summaryrefslogtreecommitdiff
path: root/runtime/lua/core/motion.lua
blob: a6bcb807358db6a1d39ef66990930c4f556b0156 (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
local M = {}

local function is_word_char(ch)
  if ch == "" then
    return false
  end
  local byte = string.byte(ch)
  if not byte then
    return false
  end

  if byte >= string.byte("a") and byte <= string.byte("z") then
    return true
  end
  if byte >= string.byte("A") and byte <= string.byte("Z") then
    return true
  end
  if byte >= string.byte("0") and byte <= string.byte("9") then
    return true
  end
  return ch == "_"
end

function M.forward_word()
  local len = editor.buffer_length()
  local point = editor.point()
  if point >= len then
    return
  end

  local ch = editor.char_at(point)
  if is_word_char(ch) then
    while point < len and is_word_char(editor.char_at(point)) do
      point = point + 1
    end
  else
    while point < len and not is_word_char(editor.char_at(point)) do
      point = point + 1
    end
    while point < len and is_word_char(editor.char_at(point)) do
      point = point + 1
    end
  end

  editor.set_point(point)
end

function M.backward_word()
  local point = editor.point()
  if point <= 0 then
    return
  end

  point = point - 1
  while point >= 0 and not is_word_char(editor.char_at(point)) do
    point = point - 1
  end

  while point >= 0 and is_word_char(editor.char_at(point)) do
    point = point - 1
  end

  editor.set_point(point + 1)
end

return M