home icon indicating copy to clipboard operation
home copied to clipboard

是否可以实现“当光标在英文区域时”自动切换到英文输入模式,“当在中文区域时”,自动切换到中文输入模式?

Open Explorer-cc opened this issue 3 months ago • 2 comments

如题,希望可以指个路。听闻rime-lua可以实现类似的功能。

Explorer-cc avatar Sep 15 '25 18:09 Explorer-cc

gemini2.5pro给的方案,但似乎不生效😢

-- context_switcher.lua

--[[
  功能:根据光标两侧的字符类型,自动切换中/英文输入模式。
  规则:
  1. 当光标两侧都是西文(字母、数字)时,切换到英文模式 (ascii_mode)。
  2. 当光标两侧都是中文(汉字)时,切换到中文模式。
--]]

-- 辅助函数:判断字符是否为中文汉字 (CJK Unified Ideographs)
local function is_cjk(char)
  if not char then return false end
  -- 使用 Unicode 范围匹配中日韩统一表意文字
  return char:match("[\u{4e00}-\u{9fa5}]")
end

-- 辅助函数:判断字符是否为西文(这里定义为 ASCII 字母和数字)
local function is_western(char)
  if not char then return false end
  -- 匹配 a-z, A-Z, 0-9
  return char:match("[a-zA-Z0-9]")
end

-- 创建一个 processor 函数
local function context_aware_switcher(key, env)
  -- 1. 我们只在光标移动时触发这个逻辑,以避免在输入时产生干扰
  --    常见的方向键 keycode:Left(0xff51), Right(0xff53), Up(0xff52), Down(0xff54), Home(0xff50), End(0xff57)
  local keycode = key.keycode
  if keycode >= 0xff50 and keycode <= 0xff57 then
    local engine = env.engine
    local context = engine.context

    -- 2. 获取光标前后的文本
    local before, after = context:get_surrounding_text()

    -- 3. 检查两侧是否有内容
    if not before or #before == 0 or not after or #after == 0 then
      return 1 -- kAccepted: 让 Rime 继续处理按键
    end

    -- 4. 获取紧邻光标的左右两个字符
    --    使用 utf8 库来正确处理多字节字符
    local left_char = utf8.sub(before, -1)
    local right_char = utf8.sub(after, 1, 1)

    -- 5. 获取当前的输入模式状态
    local is_ascii_mode = context:get_option("ascii_mode")

    -- 6. 应用切换规则
    -- 规则一:两侧均为西文,且当前不是西文模式,则切换到西文模式
    if is_western(left_char) and is_western(right_char) then
      if not is_ascii_mode then
        engine:set_option("ascii_mode", true)
        -- print("Switched to ASCII mode.") -- 调试用
      end
    -- 规则二:两侧均为中文,且当前是西文模式,则切换到中文模式
    elseif is_cjk(left_char) and is_cjk(right_char) then
      if is_ascii_mode then
        engine:set_option("ascii_mode", false)
        -- print("Switched to Chinese mode.") -- 调试用
      end
    end
  end

  -- 总是返回 kAccepted,确保光标移动键本身的功能不受影响
  return 1 -- kAccepted
end

-- 将函数导出,以便 Rime 可以调用
return context_aware_switcher

Explorer-cc avatar Sep 15 '25 19:09 Explorer-cc

不能實現。打聽不到光標外面的內容。

lotem avatar Sep 16 '25 14:09 lotem