0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VSCode: エンコーディングの誤判定対策(ショートカットキー一発で開き直す。Karabiner-Elements利用)

Posted at

問題

VSCodeでCP932 (Shift_JIS)のファイルを開くとWindows 1252などと誤判定されてしまうことがある。
コマンドパレットから Change File Encoding でエンコーディングを指定して開き直せるが、エンコーディングを選択するのが面倒だ。

対策

Karabiner-Elements(Mac用アプリ)を援用し、ショートカットキー一発でShift_JIS指定で開き直せるようにする。
Windowsの人もAutoHotkeyなどのキーボードマクロツールを使えば同じことができると思う。

設定手順

VSCodeで Change File Encoding にキーバインドを定義しておく。
ここでは Cmd+g Cmd+e にしたが、なんでも良い。

  { "key": "cmd+g cmd+e", "command": "workbench.action.editor.changeEncoding", "when": "editorFocus" },

~/.config/karabiner/karabiner.json に下記のComplex Modificationを定義:

{
  "description": "VSCode: Ctrl+Cmd+Shift+sでShift_JISで開き直す",
  "manipulators": [
    {
      "from": {
        "key_code": "s",
        "modifiers": {"mandatory": ["control", "command", "shift"]}
      },
      "to": [
          { "key_code": "g", "modifiers": ["command"], "hold_down_milliseconds": 100 },
          { "key_code": "e", "modifiers": ["command"], "hold_down_milliseconds": 100 },
          { "key_code": "return_or_enter", "hold_down_milliseconds": 100 },
          { "key_code": "s" },
          { "key_code": "h" },
          { "key_code": "i" },
          { "key_code": "f" },
          { "key_code": "t" },
          { "key_code": "return_or_enter" }
      ],
      "type": "basic"
    }
  ]
}

見ての通り、Cmd+g Cmd+e を押し、ReturnReopen with Encodingを選択、shiftと入力して絞り込み、としている。

これでCtrl+Cmd+Shift+sを押せばShift_JISで開き直されるようになった。

余談

この問題には多くの人が悩まされているようで、「vscode エンコーディング 誤判定」でググると色々出てくる。ソースファイルを書き換えるという方法もあるようだ。
VSCodeの文字コード自動判定を改善する - 7cc@はてなブログ

VSCodeのソースを見るとChange File Encodingの実装は下記になっていて、これを真似てエンコーディング変更する拡張を作れないかと考えたが、IEncodingSupportを得る方法が分からなかった。APIが提供されていないということなのかもしれない。
https://github.com/microsoft/vscode/blob/1eabca550153e1502de582d1d6aa44ecc636f1c8/src/vs/workbench/browser/parts/editor/editorStatus.ts#L1437

そもそも自動判定の候補リストをユーザーが定義できるようにしておけば誤判定確率を下げられるはず。VSCode本体で改善してもらいたいところだ。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?