Skip to content

Commit a2394cd

Browse files
authored
feat: 以词定字长句输入支持 (#1252)
close #1251
1 parent 89a7aba commit a2394cd

File tree

1 file changed

+30
-20
lines changed

1 file changed

+30
-20
lines changed

lua/select_character.lua

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
-- 20230526195910 不再错误地获取commit_text,而是直接获取get_selected_candidate().text
55
-- 20240128141207 重写:将读取设置移动到 init 方法中;简化中文取字方法;预先判断候选存在与否,无候选取 input
66
-- 20240508111725 当候选字数为 1 时,快捷键使该字上屏
7-
7+
-- 20250515093039 以词定字支持长句输入
8+
-- 20250516231523 当候选字数为 1 且还有未处理的输入时,快捷键使该字上屏, 保留未处理部分
9+
-- 20250524151149 当光标位置不在 input 末尾时,保留光标右侧部分
810
local select = {}
911

1012
function select.init(env)
@@ -22,27 +24,35 @@ function select.func(key, env)
2224
and (context:is_composing() or context:has_menu())
2325
and (env.first_key or env.last_key)
2426
then
25-
local text = context.input
26-
if context:get_selected_candidate() then
27-
text = context:get_selected_candidate().text
28-
end
29-
if utf8.len(text) > 1 then
30-
if (key:repr() == env.first_key) then
31-
engine:commit_text(text:sub(1, utf8.offset(text, 2) - 1))
32-
context:clear()
33-
return 1
34-
elseif (key:repr() == env.last_key) then
35-
engine:commit_text(text:sub(utf8.offset(text, -1)))
36-
context:clear()
37-
return 1
38-
end
27+
local input = context.input
28+
local selected_candidate = context:get_selected_candidate()
29+
selected_candidate = selected_candidate and selected_candidate.text or input
30+
31+
local selected_char = ""
32+
if (key:repr() == env.first_key) then
33+
selected_char = selected_candidate:sub(1, utf8.offset(selected_candidate, 2) - 1)
34+
elseif (key:repr() == env.last_key) then
35+
selected_char = selected_candidate:sub(utf8.offset(selected_candidate, -1))
3936
else
40-
if key:repr() == env.first_key or key:repr() == env.last_key then
41-
engine:commit_text(text)
42-
context:clear()
43-
return 1
44-
end
37+
return 2
38+
end
39+
40+
local commit_text = context:get_commit_text()
41+
local _, end_pos = commit_text:find(selected_candidate)
42+
local caret_pos = context.caret_pos
43+
44+
local part1 = commit_text:sub(1, end_pos):gsub(selected_candidate, selected_char)
45+
local part2 = commit_text:sub(end_pos + 1)
46+
47+
engine:commit_text(part1)
48+
context:clear()
49+
if caret_pos ~= #input then
50+
part2 = part2 .. input:sub(caret_pos + 1)
51+
end
52+
if part2 ~= "" then
53+
context:push_input(part2)
4554
end
55+
return 1
4656
end
4757
return 2
4858
end

0 commit comments

Comments
 (0)