1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Linux] neovimで日本語入力を快適にするスクリプト

Last updated at Posted at 2025-05-29

はじめに

日本語ユーザにとって和文の書類を作成する($\LaTeX$やmarkdownなど)際,最も面倒くさいのが,入力メソッド(input method)の切り替えである.ノーマルモードでjkを押した時に全角の「j」とか「k」が出てきてカーソルが動かなかったときには深いため息をつきたくなるだろう.そこで私はLinuxターミナル上で以下の仕様のスクリプト(lua)を作成した:

  • 挿入モード終了時の入力メソッドを記憶
  • ノーマルモードでの入力メソッドの自動オフ
  • 挿入モード開始時の入力メソッドの自動オン(終了時にオンになっていれば)

日本語環境

日本語入力環境はfcitx5-mozcであるため,別の日本語入力メソッドを使っている方は正常に動作しないことに注意されたい.

Luaスクリプト

仕様の説明は二の次で内容物がほしい人は,以下のスクリプトを init.lua に貼り付けてほしい.

local function trim(s)
    return s:match("^%s*(.-)%s*$")
end

local function GetFcitxStatus()
    local handle = io.popen('fcitx5-remote -n')
    local result = handle:read("*a")
    handle:close()
    return trim(result)
end

local function OnInsertLeave()
    -- Save fcitx status when leaving insert mode
    vim.g.fcitx_status = GetFcitxStatus()
    -- Disable (Japanese) input method 
    os.execute('fcitx5-remote -c')
end

local function Enable(status)
    if status ~= 'keyboard-us' then
        os.execute('fcitx5-remote -o')
    end
end

vim.g.fcitx_status = GetFcitxStatus()

-- Autocmd for InsertLeave and InsertEnter
vim.api.nvim_create_autocmd("InsertLeave", {
    callback = OnInsertLeave
})
vim.api.nvim_create_autocmd("InsertEnter", {
    callback = function()
        Enable(vim.g.fcitx_status)
    end
})

仕様

原理としてはじめににも書いたが以下の通り:

  • 起動時にGetFcitxStatus()で現在fcitx5がオンかオフかを検知し,fcitx_statusに代入
  • 挿入モード終了InsertLeaveをトリガーにOnInsertLeaveが動き,escキーを押した直前の入力モードをfcitx_statusに保存し,入力メソッドをオフにする
  • 挿入モード開始InsertEnterをトリガーに,前の挿入モード時のステータスfcitx_statusを使って,入力メソッドを切り替え

おわりに

WindowsのVSCodeはzenhanという便利なツールがある一方,macOSやLinuxは整備が十分でないようである.これを機にたくさんの方がこのスクリプトを使用してくれることを願う.

また,私は約半年前にvimrcから脱却し,luaへの移行作業を済ませた.そこまでハードコアなvimmerでない人はluaを使っていないだろう.そのため,今後は vimrc でも普及できるように務める次第である.

また余力があればlua引っ越しのすゝめ的な記事も書いてみたい.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?