LoginSignup
4
4

More than 5 years have passed since last update.

Vimのpython3で日本語表示するの面倒くさすぎワロタwww

Last updated at Posted at 2013-03-20

注:以下の内容は、KaoriYa版Vim 7.3.865 (2013/03/17版)でしか確認していません。

VimのPython 3インターフェイスで、文字列をバッファの一行目に表示する場合、"abcde" という文字列であれば、

py3 text = "abcde"
py3 import vim
py3 vim.eval('setline(1, "{}")'.format(text))

で良いのですが、日本語文字列、例えば "あいうえお" を表示する場合は、

py3 text = "\u3042\u3044\u3046\u3048\u304A"  # == "あいうえお"
py3 import vim
py3 vim_encoding = vim.eval("&encoding")
py3 vim.eval('setline(1, "{}")'.format(''.join([r"\x{:02x}".format(x) for x in text.encode(vim_encoding)])))

としなければいけませんでした。面倒くさいですね。

日本語を表示するだけでここまで手間がかかるのは、Python 3インターフェイスの vim.eval() の仕様に原因があります。

Python 3インターフェイスの vim.eval() は、引数としてPython文字列しか受け取ってくれないのですが、その文字列をUTF-8でエンコードしてからVimのエンコーディングでデコードするという謎仕様になっているのです。

そのため、日本語文字列を渡したい場合は、Python文字列(例:"あ")をVimのエンコーディングでエンコード(例:b'\x82\xa0')してから16進エスケープした文字列を作成(例:'\\x82\\xa0')した上で、ダブルクォート文字列にして vim.eval() に渡す(例:'setline(1, "\\x82\\xa0")')という手間をかける必要がありました。

ひょっとしたらもっと簡単な方法があるのかもしれませんので、もしどなたかご存知でしたら教えてください。m(__)m

4
4
1

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