aboutsummaryrefslogtreecommitdiffhomepage
path: root/core/events.lua
blob: a7068dcd0ca05cacb2b0e20a32b9436ea427ac0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.

local L = _G.locale.localize

---
-- Textadept's core event structure and handlers.
module('events', package.seeall)

-- Markdown:
-- ## Overview
--
-- Textadept is very event-driven. Most of its functionality comes through event
-- handlers. Events occur when you create a new buffer, press a key, click on a
-- menu, etc. You can even make an event occur with Lua code. Instead of having
-- a single event handler however, each event can have a set of handlers. These
-- handlers are simply Lua functions that are called in the order they were
-- added to an event. This enables dynamically loaded modules to add their own
-- handlers to events.
--
-- Events themselves are nothing special. They do not have to be declared in
-- order to be used. They are simply strings containing an arbitrary event name.
-- When an event of this name occurs, either generated by Textadept or you, all
-- event handlers assigned to it are run.
--
-- Events can be given any number of arguments. These arguments will be passed
-- to the event's handler functions. If a handler returns either true or false
-- explicitly, all subsequent handlers are not called. This is useful if you
-- want to stop the propagation of an event like a keypress.
--
-- ## Textadept Events
--
-- The following is a list of all Scintilla events generated by Textadept in
-- `event_name(arguments)` format:
--
-- * **char\_added** (ch)<br />
--   Called when an ordinary text character is added to the buffer.
--       - ch: the ASCII representation of the character.
-- * **save\_point\_reached** ()<br />
--   Called when a save point is entered.
-- * **save\_point\_left** ()<br />
--   Called when a save point is left.
-- * **double\_click** (position, line)<br />
--   Called when the mouse button is double-clicked.
--       - position: the text position the click occured at.
--       - line: the line number the click occured at.
-- * **update\_ui** ()<br />
--   Called when the text or styling of the buffer has changed or the selection
--   range has changed.
-- * **margin\_click** (margin, modifiers, position)<br />
--   Called when the mouse is clicked inside a margin.
--       - margin: the margin number that was clicked.
--       - modifiers: the appropriate combination of `SCI_SHIFT`, `SCI_CTRL`,
--         and `SCI_ALT` to indicate the keys that were held down at the time of
--         the margin click.
--       - position: The position of the start of the line in the buffer that
--         corresponds to the margin click.
-- * **user\_list\_selection** (wParam, text)<br />
--   Called when the user has selected an item in a user list.
--       - wParam: the list_type parameter from
--         [`buffer:user_list_show()`][buffer_user_list_show].
--       - text: the text of the selection.
-- * **uri\_dropped** (text)<br />
--   Called when the user has dragged a URI such as a file name or web address
--   into Textadept.
--       - text: URI text.
-- * **call\_tip\_click** (position)<br />
--   Called when the user clicks on a calltip.
--       - position: 1 if the click is in an up arrow, 2 if in a down arrow, and
--         0 if elsewhere.
-- * **auto\_c\_selection** (lParam, text)<br />
--   Called when the user has selected an item in an autocompletion list.
--       - lParam: the start position of the word being completed.
--       - text: the text of the selection.
--
-- [buffer_user_list_show]: ../modules/buffer.html#buffer:user_list_show
--
-- The following is a list of all Textadept events generated in
-- `event_name(arguments)` format:
--
-- * **buffer\_new** ()<br />
--   Called when a new [buffer][buffer] is created.
-- * **buffer\_deleted** ()<br />
--   Called when a [buffer][buffer] has been deleted.
-- * **buffer\_before\_switch** ()<br />
--   Called right before another [buffer][buffer] is switched to.
-- * **buffer\_after\_switch** ()<br />
--   Called right after a [buffer][buffer] was switched to.
-- * **view\_new** ()<br />
--   Called when a new [view][view] is created.
-- * **view\_before\_switch** ()<br />
--   Called right before another [view][view] is switched to.
-- * **view\_after\_switch** ()<br />
--   Called right after [view][view] was switched to.
-- * **reset\_before()**<br />
--   Called before resetting the Lua state during a call to [`reset()`][reset].
-- * **reset\_after()**<br />
--   Called after resetting the Lua state during a call to [`reset()`][reset].
-- * **quit** ()<br />
--   Called when quitting Textadept.<br />
--   Note: Any quit handlers added must be inserted at index 1 because the
--   default quit handler in `core/events.lua` returns `true`, which ignores all
--   subsequent handlers.
-- * **keypress** (code, shift, control, alt)<br />
--   Called when a key is pressed.
--       - code: the key code (according to `<gdk/gdkkeysyms.h>`).
--       - shift: flag indicating whether or not the Shift key is pressed.
--       - control: flag indicating whether or not the Control key is pressed.
--       - alt: flag indicating whether or not the Alt/Apple key is pressed.
--   <br />
--   Note: The Alt-Option key in Mac OSX is not available.
-- * **menu\_clicked** (menu\_id)<br />
--   Called when a menu item is selected.
--       - menu\_id: the numeric ID of the menu item set in
--         [`gui.gtkmenu()`][gui_gtkmenu].
-- * **find** (text, next)<br />
--   Called when attempting to finding text via the Find dialog box.
--       - text: the text to search for.
--       - next: flat indicating whether or not the search direction is forward.
-- * **replace** (text)<br />
--   Called when the found text is selected and asked to be replaced.
--       - text: the text to replace the selected text with.
-- * **replace\_all** (find\_text, repl\_text)<br />
--   Called when all occurances of found text are to be replaced.
--       - find\_text: the text to search for.
--       - repl\_text: the text to replace found text with.
-- * **command\_entry\_keypress** (code)<br />
--   Called when a key is pressed in the Command Entry.
--       - code: the key code (according to `<gdk/gdkkeysyms.h>`).
--
-- [buffer]: ../modules/buffer.html
-- [view]: ../modules/view.html
-- [reset]: ../modules/_G.html#reset
-- [gui_gtkmenu]: ../modules/gui.html#gtkmenu
--
-- ## Example
--
-- The following Lua code generates and handles a custom `my_event` event:
--
--     function my_event_handler(message)
--       gui.print(message)
--     end
--
--     events.connect('my_event', my_event_handler)
--     events.emit('my_event', 'my message')

---
-- Adds a handler function to an event.
-- @param event The string event name. It is arbitrary and need not be defined
--   anywhere.
-- @param f The Lua function to add.
-- @param index Optional index to insert the handler into.
-- @return Index of handler.
-- @see disconnect
function connect(event, f, index)
  local plural = event..'s'
  if not _M[plural] then _M[plural] = {} end
  local handlers = _M[plural]
  if index then
    table.insert(handlers, index, f)
  else
    handlers[#handlers + 1] = f
  end
  return index or #handlers
end

---
-- Disconnects a handler function from an event.
-- @param event The string event name.
-- @param index Index of the handler (returned by events.connect).
-- @see connect
function disconnect(event, index)
  local plural = event..'s'
  if not events[plural] then return end
  local handlers = events[plural]
  table.remove(handlers, index)
end

---
-- Calls all handlers for the given event in sequence (effectively "generating"
-- the event).
-- If true or false is explicitly returned by any handler, the event is not
-- propagated any further; iteration ceases.
-- @param event The string event name.
-- @param ... Arguments passed to the handler.
-- @return true or false if any handler explicitly returned such; nil otherwise.
function emit(event, ...)
  local plural = event..'s'
  local handlers = _M[plural]
  if not handlers then return end
  for _, f in ipairs(handlers) do
    local result = f(unpack{...})
    if type(result) == 'boolean' then return result end
  end
end

local connect = connect
local emit = emit

--- Map of Scintilla notifications to their handlers.
local c = _SCINTILLA.constants
local scnnotifications = {
  [c.SCN_CHARADDED] = { 'char_added', 'ch' },
  [c.SCN_SAVEPOINTREACHED] = { 'save_point_reached' },
  [c.SCN_SAVEPOINTLEFT] = { 'save_point_left' },
  [c.SCN_DOUBLECLICK] = { 'double_click', 'position', 'line' },
  [c.SCN_UPDATEUI] = { 'update_ui' },
  [c.SCN_MARGINCLICK] = { 'margin_click', 'margin', 'modifiers', 'position' },
  [c.SCN_USERLISTSELECTION] = { 'user_list_selection', 'wParam', 'text' },
  [c.SCN_URIDROPPED] = { 'uri_dropped', 'text' },
  [c.SCN_CALLTIPCLICK] = { 'call_tip_click', 'position' },
  [c.SCN_AUTOCSELECTION] = { 'auto_c_selection', 'lParam', 'text' }
}

---
-- Handles Scintilla notifications.
-- @param n The Scintilla notification structure as a Lua table.
-- @return true or false if any handler explicitly returned such; nil otherwise.
function notification(n)
  local f = scnnotifications[n.code]
  if f then
    local args = { unpack(f, 2) }
    for k, v in ipairs(args) do args[k] = n[v] end
    return emit(f[1], unpack(args))
  end
end

-- Default handlers to follow.

connect('view_new',
  function() -- sets default properties for a Scintilla window
    local buffer = buffer
    local c = _SCINTILLA.constants

    -- allow redefinitions of these Scintilla key commands
    local ctrl_keys = {
      '[', ']', '/', '\\', 'Z', 'Y', 'X', 'C', 'V', 'A', 'L', 'T', 'D', 'U'
    }
    local ctrl_shift_keys = { 'L', 'T', 'U' }
    for _, key in ipairs(ctrl_keys) do
      buffer:clear_cmd_key(string.byte(key), c.SCMOD_CTRL)
    end
    for _, key in ipairs(ctrl_shift_keys) do
      buffer:clear_cmd_key(string.byte(key), c.SCMOD_CTRL + c.SCMOD_SHIFT)
    end

    if _THEME and #_THEME > 0 then
      local ret, errmsg = pcall(dofile, _THEME..'/view.lua')
      if ret then return end
      io.stderr:write(errmsg)
    end
  end)

local SETDIRECTFUNCTION = _SCINTILLA.properties.direct_function[1]
local SETDIRECTPOINTER = _SCINTILLA.properties.doc_pointer[2]
local SETLEXERLANGUAGE = _SCINTILLA.functions.set_lexer_language[1]
connect('buffer_new',
  function() -- sets default properties for a Scintilla document
    local function run()
      local buffer = buffer

      -- lexer
      buffer:set_lexer_language('lpeg')
      buffer:private_lexer_call(SETDIRECTFUNCTION, buffer.direct_function)
      buffer:private_lexer_call(SETDIRECTPOINTER, buffer.direct_pointer)
      buffer:private_lexer_call(SETLEXERLANGUAGE, 'container')
      buffer.style_bits = 8

      -- properties
      buffer.property['textadept.home'] = _HOME
      buffer.property['lexer.lpeg.home'] = _LEXERPATH
      buffer.property['lexer.lpeg.script'] = _HOME..'/lexers/lexer.lua'
      if _THEME and #_THEME > 0 then
        buffer.property['lexer.lpeg.color.theme'] = _THEME..'/lexer.lua'
      end

      -- buffer
      buffer.code_page = _SCINTILLA.constants.SC_CP_UTF8

      if _THEME and #_THEME > 0 then
        local ret, errmsg = pcall(dofile, _THEME..'/buffer.lua')
        if ret then return end
        io.stderr:write(errmsg)
      end
    end
    -- normally when an error occurs, a new buffer is created with the error
    -- message, but if an error occurs here, this event would be called again
    -- and again, erroring each time resulting in an infinite loop; print error
    -- to stderr instead
    local ret, errmsg = pcall(run)
    if not ret then io.stderr:write(errmsg) end
  end)

-- Sets the title of the Textadept window to the buffer's filename.
-- @param buffer The currently focused buffer.
local function set_title(buffer)
  local buffer = buffer
  local filename = buffer.filename or buffer._type or L('Untitled')
  local dirty = buffer.dirty and '*' or '-'
  gui.title = string.format('%s %s Textadept (%s)', filename:match('[^/\\]+$'),
                            dirty, filename)
end

connect('save_point_reached',
  function() -- changes Textadept title to show 'clean' buffer
    buffer.dirty = false
    set_title(buffer)
  end)

connect('save_point_left',
  function() -- changes Textadept title to show 'dirty' buffer
    buffer.dirty = true
    set_title(buffer)
  end)

connect('uri_dropped',
  function(utf8_uris)
    local lfs = require 'lfs'
    for utf8_uri in utf8_uris:gmatch('[^\r\n\f]+') do
      if utf8_uri:find('^file://') then
        utf8_uri = utf8_uri:match('^file://([^\r\n\f]+)')
        utf8_uri = utf8_uri:gsub('%%(%x%x)',
          function(hex) return string.char(tonumber(hex, 16)) end)
        if WIN32 then
          utf8_uri = utf8_uri:sub(2, -1) -- ignore leading '/'
          utf8_uri = utf8_uri:gsub('/', '\\')
        end
        local uri = utf8_uri:iconv(_CHARSET, 'UTF-8')
        if lfs.attributes(uri).mode ~= 'directory' then
          io.open_file(utf8_uri)
        end
      end
    end
  end)

local string_format = string.format
local EOLs = { L('CRLF'), L('CR'), L('LF') }
local GETLEXERLANGUAGE = _SCINTILLA.functions.get_lexer_language[1]
connect('update_ui',
  function() -- sets docstatusbar text
    local buffer = buffer
    local pos = buffer.current_pos
    local line, max = buffer:line_from_position(pos) + 1, buffer.line_count
    local col = buffer.column[pos] + 1
    local lexer = buffer:private_lexer_call(GETLEXERLANGUAGE)
    local eol = EOLs[buffer.eol_mode + 1]
    local tabs = string_format('%s %d', buffer.use_tabs and L('Tabs:') or
                               L('Spaces:'), buffer.indent)
    local enc = buffer.encoding or ''
    gui.docstatusbar_text =
      string_format('%s %d/%d    %s %d    %s    %s    %s    %s', L('Line:'),
                    line, max, L('Col:'), col, lexer, eol, tabs, enc)
  end)

connect('margin_click',
  function(margin, modifiers, position) -- toggles folding
    local line = buffer:line_from_position(position)
    buffer:toggle_fold(line)
  end)

connect('buffer_new', function() set_title(buffer) end)

connect('buffer_before_switch',
  function() -- save buffer properties
    local buffer = buffer
    -- Save view state.
    buffer._anchor = buffer.anchor
    buffer._current_pos = buffer.current_pos
    buffer._first_visible_line = buffer.first_visible_line
    -- Save fold state.
    buffer._folds = {}
    local folds = buffer._folds
    local i = buffer:contracted_fold_next(0)
    while i >= 0 do
      folds[#folds + 1] = i
      i = buffer:contracted_fold_next(i + 1)
    end
  end)

connect('buffer_after_switch',
  function() -- restore buffer properties
    local buffer = buffer
    if not buffer._folds then return end
    -- Restore fold state.
    for _, i in ipairs(buffer._folds) do buffer:toggle_fold(i) end
    -- Restore view state.
    buffer:set_sel(buffer._anchor, buffer._current_pos)
    buffer:line_scroll(0,
      buffer:visible_from_doc_line(buffer._first_visible_line) -
        buffer.first_visible_line)
  end)

connect('buffer_after_switch',
  function() -- updates titlebar and statusbar
    set_title(buffer)
    emit('update_ui')
  end)

connect('view_after_switch',
  function() -- updates titlebar and statusbar
    set_title(buffer)
    emit('update_ui')
  end)

connect('reset_after', function() gui.statusbar_text = 'Lua reset' end)

connect('quit',
  function() -- prompts for confirmation if any buffers are dirty
    local any = false
    local list = {}
    for _, buffer in ipairs(_BUFFERS) do
      if buffer.dirty then
        list[#list + 1] = buffer.filename or buffer._type or L('Untitled')
        any = true
      end
    end
    if any and
       gui.dialog('msgbox',
                  '--title', L('Quit without saving?'),
                  '--text', L('The following buffers are unsaved:'),
                  '--informative-text',
                  string.format('%s', table.concat(list, '\n')),
                  '--button1', 'gtk-cancel',
                  '--button2', L('Quit _without saving'),
                  '--no-newline') ~= '2' then
      return false
    end
    return true
  end)

if MAC then
  connect('appleevent_odoc',
    function(uri) return emit('uri_dropped', 'file://'..uri) end)

  connect('buffer_new',
    function() -- GTK-OSX has clipboard problems
      buffer.paste = function()
        local clipboard_text = gui.clipboard_text
        if #clipboard_text > 0 then buffer:replace_sel(clipboard_text) end
      end
    end)
end

connect('error', function(...) gui._print(L('[Error Buffer]'), ...) end)