aboutsummaryrefslogtreecommitdiff
path: root/spellcheck.lua
blob: 0c5aca90146d37207ea41a5d2a458b6e031906c0 (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
local core = require "core"
local style = require "core.style"
local config = require "core.config"
local command = require "core.command"
local DocView = require "core.docview"

config.spellcheck_files = { "%.txt$", "%.md$", "%.markdown$" }
config.dictionary_file = "/usr/share/dict/words"

local inited = false
local words

local function init_words()
  if inited then return end
  inited = true
  core.add_thread(function()
    local t = {}
    local i = 0
    for line in io.lines(config.dictionary_file) do
      for word in line:gmatch("%a+") do
        t[word:lower()] = true
      end
      i = i + 1
      if i % 1000 == 0 then coroutine.yield() end
    end
    core.log_quiet("Finished loading dictionary file: %s", config.dictionary_file)
    words = t
    core.redraw = true
  end)
end


local function matches_any(filename, ptns)
  for _, ptn in ipairs(ptns) do
    if filename:find(ptn) then return true end
  end
end


local draw_line_text = DocView.draw_line_text

function DocView:draw_line_text(idx, x, y)
  draw_line_text(self, idx, x, y)

  init_words()
  if not words
  or not matches_any(self.doc.filename or "", config.spellcheck_files) then
    return
  end

  local s, e = 0, 0
  local text = self.doc.lines[idx]
  local l, c = self.doc:get_selection()

  while true do
    s, e = text:find("%a+", e + 1)
    if not s then break end
    local word = text:sub(s, e):lower()
    if not words[word] and not (l == idx and c == e + 1) then
      local color = style.spellcheck_error or style.syntax.keyword2
      local x1 = x + self:get_col_x_offset(idx, s)
      local x2 = x + self:get_col_x_offset(idx, e + 1)
      local h = style.divider_size
      renderer.draw_rect(x1, y + self:get_line_height() - h, x2 - x1, h, color)
    end
  end
end