aboutsummaryrefslogtreecommitdiff
path: root/modules/lua/commands.lua
blob: c6a65bcbda1c8b01a6ddff63c9daab9118403bd6 (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
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.

---
-- Commands for the lua module.
module('_m.lua.commands', package.seeall)

-- Markdown:
-- ## Key Commands
--
-- + `Alt+l, m`: Open this module for editing.
-- + `Alt+l, g`: Goto file being 'require'd on the current line.
-- + `Shift+Return`: Try to autocomplete an `if`, `for`, etc. statement with
--   `end`.
-- + `.`: When to the right of a known identifier, show an autocompletion list
--   of fields.
-- + `:`: When to the right of a known identifier, show an autocompletion list
--   of functions.
-- + `Tab`: When the caret is to the right of a `(` in a known function call,
--   show a calltip with documentation for the function.
--
-- ## Autocompletion of Fields and Functions
--
-- This module parses files in the `api_files` table for LuaDoc documentation.
-- Currently all Textadept and Lua identifiers are supported.
--
-- #### Syntax
--
-- Fields are recognized as Lua line comments of the form ``-- * `field_name` ``.
-- Functions are recognized as Lua functions of the form `function func(args)`
-- or `function namespace:func(args)`. `.`-completion shows autocompletion for
-- both fields and functions using the first function syntax. `:`-completion
-- shows completions for functions only. Any LuaDoc starting with `---` and
-- including any subsequent comments up until the function declaration will be
-- shown with a calltip when requested.
--
-- In order to be recognized, all comments and functions MUST begin the line.
--
-- Syntatically valid Lua code is not necessary for parsing; only the patterns
-- described above are necessary.
--
-- For example:
--
-- In file `~/.textadept/modules/foo/foo.luadoc`:
--
--     -- * `bar`: Bar field.
--
--     --- LuaDoc for bar.
--     function baz()
--
--     ---
--     -- LuaDoc for foobar.
--     -- @param barfoo First arg.
--     function foobar(barfoo)
--
--     ---
--     -- LuaDoc for foo:barbaz.
--     -- @param foo Foo table.
--     function foo:barbaz()
--
-- In file `_HOME/modules/lua/commands.lua` below `api_files` declaration:
--
--     api_files['foo'] = _USERHOME..'/modules/foo/foo.luadoc'
--
-- In any Lua file:
--
--     foo. -- shows autocompletion list with [bar, baz, foobar].
--     foo: -- shows autocompletion list with [foobar, barbaz].

local m_editing, m_run = _m.textadept.editing, _m.textadept.run
-- Comment string tables use lexer names.
m_editing.comment_string.lua = '--'
-- Compile and Run command tables use file extensions.
m_run.run_command.lua = 'lua %(filename)'
m_run.error_detail.lua = {
  pattern = '^lua: (.-):(%d+): (.+)$',
  filename = 1, line = 2, message = 3
}

---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
  '^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
  'function%s*%b()%s*$', '^%s*local%s*function'
}

---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
  local buffer = buffer
  buffer:begin_undo_action()
  buffer:line_end()
  buffer:new_line()
  local line_num = buffer:line_from_position(buffer.current_pos)
  local line = buffer:get_line(line_num - 1)
  for _, patt in ipairs(control_structure_patterns) do
    if line:find(patt) then
      local indent = buffer.line_indentation[line_num - 1]
      buffer:add_text(patt:find('repeat') and '\nuntil' or '\nend')
      buffer.line_indentation[line_num + 1] = indent
      buffer.line_indentation[line_num] = indent + buffer.indent
      buffer:line_up()
      buffer:line_end()
      break
    end
  end
  buffer:end_undo_action()
end

---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
  local buffer = buffer
  local line = buffer:get_cur_line()
  local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
  local file
  for _, patt in ipairs(patterns) do
    file = line:match(patt)
    if file then break end
  end
  if not file then return end
  file = file:sub(2, -2):gsub('%.', '/')
  local lfs = require 'lfs'
  for path in package.path:gmatch('[^;]+') do
    path = path:gsub('?', file)
    if lfs.attributes(path) then
      io.open_file(path:iconv('UTF-8', _CHARSET))
      break
    end
  end
end

---
-- LuaDoc to load API from.
-- Keys are Lua table names with LuaDoc file values.
-- @class table
-- @name api_files
local api_files = {
  ['args'] = _HOME..'/core/args.lua',
  ['buffer'] = _HOME..'/core/.buffer.luadoc',
  ['events'] = _HOME..'/core/events.lua',
  ['gui'] = _HOME..'/core/.gui.luadoc',
  ['gui.find'] = _HOME..'/core/.find.luadoc',
  ['gui.command_entry'] = _HOME..'/core/.command_entry.luadoc',
  ['l'] = _HOME..'/lexers/lexer.lua',
  ['view'] = _HOME..'/core/.view.luadoc',
}
-- Add API for loaded textadept modules.
for p, _ in pairs(package.loaded) do
  if p:find('^_m%.textadept%.') then
    api_files[p] = _HOME..'/modules/textadept/'..p:match('[^%.]+$')..'.lua'
  end
end
-- Add Lua API
local lua = { 'coroutine', 'debug', 'io', 'math', 'os', 'string', 'table' }
for _, m in ipairs(lua) do
  api_files[m] = _HOME..'/modules/lua/api/'..m..'.luadoc'
end
api_files[''] = _HOME..'/modules/lua/api/_G.luadoc'

local lfs = require 'lfs'

-- Load API.
local apis = {}
local current_doc = ''
local f_args = {}
for word, api_file in pairs(api_files) do
  if lfs.attributes(api_file) then
    apis[word] = { fields = {}, funcs = {} }
    for line in io.lines(api_file) do
      if line:match('^%-%- %* `([^`]+)`') then -- field
        local fields = apis[word].fields
        fields[#fields + 1] = line:match('^%-%- %* `([^`]+)`')..'?2'
      elseif line:match('^function ') then -- function
        local f, n = line:match('^function [%w_]+:(([%w_]+)%([^)]*%))')
        if not f then
          f, n = line:match('^function (([%w_]+)%([^)]*%))')
          local fields = apis[word].fields
          fields[#fields + 1] = n..'?1'
        end
        local funcs = apis[word].funcs
        funcs[#funcs + 1] = n..'?1'
        if f and #current_doc > 0 then
          f = f..current_doc
          current_doc = ''
        end
        local c = line:find(':') and ':' or '.'
        if word == '' then c = '' end
        f_args[word..c..n] = f
      elseif line:match('^%-%-%-? (.+)$') then
        current_doc = current_doc..'\n'..line:match('^%-%-%-? (.+)$')
      elseif #current_doc > 0 then
        current_doc = ''
      end
    end
    table.sort(apis[word].fields)
    table.sort(apis[word].funcs)
  end
end

local f_xpm = '/* XPM */\nstatic char *function[] = {\n/* columns rows colors chars-per-pixel */\n"16 16 5 1",\n"  c black",\n". c #E0BC38",\n"X c #F0DC5C",\n"o c #FCFC80",\n"O c None",\n/* pixels */\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOO  OOOO",\n"OOOOOOOOO oo  OO",\n"OOOOOOOO ooooo O",\n"OOOOOOO ooooo. O",\n"OOOO  O XXoo.. O",\n"OOO oo  XXX... O",\n"OO ooooo XX.. OO",\n"O ooooo.  X. OOO",\n"O XXoo.. O  OOOO",\n"O XXX... OOOOOOO",\n"O XXX.. OOOOOOOO",\n"OO  X. OOOOOOOOO",\n"OOOO  OOOOOOOOOO"\n};'
local v_xpm = '/* XPM */\nstatic char *field[] = {\n/* columns rows colors chars-per-pixel */\n"16 16 5 1",\n"  c black",\n". c #8C748C",\n"X c #9C94A4",\n"o c #ACB4C0",\n"O c None",\n/* pixels */\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOOOOOOOOO",\n"OOOOOOOOO  OOOOO",\n"OOOOOOOO oo  OOO",\n"OOOOOOO ooooo OO",\n"OOOOOO ooooo. OO",\n"OOOOOO XXoo.. OO",\n"OOOOOO XXX... OO",\n"OOOOOO XXX.. OOO",\n"OOOOOOO  X. OOOO",\n"OOOOOOOOO  OOOOO",\n"OOOOOOOOOOOOOOOO"\n};'

-- Returns word specified by patt behind the caret.
-- @param patt Lua pattern containing word characters.
-- @param pos Optional position to start from.
-- @return word.
local function prev_word(patt, pos)
  local e = pos or buffer.current_pos - 1
  local s = e - 1
  while s >= 0 and string.char(buffer.char_at[s]):find(patt) do s = s - 1 end
  return buffer:text_range(s + 1, e)
end

-- Shows autocompletion list.
-- @param len Length passed to buffer:auto_c_show.
-- @param completions Table of completions.
-- @see buffer:auto_c_show.
local function auto_c_show(len, completions)
  buffer:clear_registered_images()
  buffer:register_image(1, f_xpm)
  buffer:register_image(2, v_xpm)
  buffer:auto_c_show(len, table.concat(completions, ' '))
end

events.connect('char_added',
  function(c) -- show autocomplete list or calltip
    if c == 46 or c == 58 then -- '.' or ':'
      if buffer:get_lexer() ~= 'lua' then return end
      local word = prev_word('[%w_%.]')
      if word == '' or not apis[word] then return end
      auto_c_show(0, c == 46 and apis[word].fields or apis[word].funcs)
    end
  end)

-- Lua-specific key commands.
local keys = _G.keys
if type(keys) == 'table' then
  keys.lua = {
    al = {
      m = { io.open_file,
            (_HOME..'/modules/lua/init.lua'):iconv('UTF-8', _CHARSET) },
      g = { goto_required },
    },
    ['s\n'] = { try_to_autocomplete_end },
    [not OSX and 'c\n' or 'esc'] = { function() -- complete API
      local part = prev_word('[%w_]', buffer.current_pos)
      local pos = buffer.current_pos - #part - 1
      if pos > 0 then
        local word = prev_word('[%w_%.]', pos)
        if word == '' or not apis[word] then return false end -- handle normally
        local c = buffer.char_at[pos]
        auto_c_show(#part, c == 46 and apis[word].fields or apis[word].funcs)
      end
    end },
    ['\t'] = { function() -- show API calltip
      local func = prev_word('[%w_%.:]')
      if not f_args[func] then return false end -- handle normally
      buffer:call_tip_show(buffer.current_pos, f_args[func])
    end },
  }
end