|
| 1 | +local org = require('orgmode') |
| 2 | + |
| 3 | +local Source = {} |
| 4 | + |
| 5 | +Source.new = function() |
| 6 | + return setmetatable({}, { __index = Source }) |
| 7 | +end |
| 8 | + |
| 9 | +function Source:enabled() |
| 10 | + return vim.bo.filetype == 'org' |
| 11 | +end |
| 12 | + |
| 13 | +function Source:get_trigger_characters(_) |
| 14 | + return { '#', '+', ':', '*', '.', '/' } |
| 15 | +end |
| 16 | + |
| 17 | +function Source:get_completions(ctx, callback) |
| 18 | + local line = ctx.line:sub(1, ctx.cursor[2]) |
| 19 | + local offset = org.completion:get_start({ line = line }) + 1 |
| 20 | + local base = string.sub(line, offset) |
| 21 | + local results = org.completion:complete({ |
| 22 | + line = line, |
| 23 | + base = base, |
| 24 | + }) |
| 25 | + |
| 26 | + local cb = function(items) |
| 27 | + callback({ |
| 28 | + context = ctx, |
| 29 | + is_incomplete_forward = true, |
| 30 | + is_incomplete_backward = true, |
| 31 | + items = items, |
| 32 | + }) |
| 33 | + return function() end |
| 34 | + end |
| 35 | + |
| 36 | + if not results or #results == 0 then |
| 37 | + return cb({}) |
| 38 | + end |
| 39 | + |
| 40 | + -- Does not contain dot to avoid stopping on file paths |
| 41 | + local triggers = { '#', '+', ':', '*', '/' } |
| 42 | + |
| 43 | + local getInsertTextOffset = function(word) |
| 44 | + local word_length = #word + 1 |
| 45 | + while word_length > 0 do |
| 46 | + local char = word:sub(word_length - 1, word_length - 1) |
| 47 | + if vim.tbl_contains(triggers, char) or char:match('%s') then |
| 48 | + return word_length |
| 49 | + end |
| 50 | + word_length = word_length - 1 |
| 51 | + end |
| 52 | + return 0 |
| 53 | + end |
| 54 | + |
| 55 | + local baseOffset = getInsertTextOffset(base) |
| 56 | + local insertTextOffset = baseOffset > 0 and math.max(2, baseOffset) or 0 |
| 57 | + |
| 58 | + local items = {} |
| 59 | + |
| 60 | + for _, item in ipairs(results) do |
| 61 | + table.insert(items, { |
| 62 | + label = item.word, |
| 63 | + insertText = insertTextOffset > 0 and item.word:sub(insertTextOffset) or item.word, |
| 64 | + labelDetails = item.menu and { description = item.menu } or nil, |
| 65 | + }) |
| 66 | + end |
| 67 | + |
| 68 | + return cb(items) |
| 69 | +end |
| 70 | + |
| 71 | +return Source |
0 commit comments