ふかふかブログ

興味のあることについてゆる~く書きます

Jupyter notebookでもVim scriptが書きたい!

この記事は、Vim Advent Calendar 2018 その2 1日目の記事です。

Vim その2 Advent Calendar 2018 - Qiita

皆さん、Jupyter notebookでVim scriptが書きたくなる時があると思います。

Jupyter notebookはKernelと呼ばれるものを差し替えることでPython以外も動作させることができます。

というわけで、Vim script kernel作ってみました。

動作確認はWindows10でのみ行っていますが、ほかのOSでも動くと思います。

完成図

f:id:nohararc:20181130234158p:plain

実装

json(connection)ファイル

{"argv":["python","-m","vim-kernel", "-f", "{connection_file}"],
 "display_name":"Vim"
}

python(kernel)ファイル

from ipykernel.kernelbase import Kernel
from subprocess import Popen, STDOUT, PIPE


class Vim(Kernel):
    implementation = 'Vim'
    implementation_version = '0.1'
    language = 'no-op'
    language_version = '0.1'
    language_info = {'name': 'Vim', 'mimetype': 'text/plain'}
    banner = 'Vim script'
    _d = {}
    def do_execute(self, code, silent, store_history=True,
             user_expressions=None, allow_stdin=False):

        with open('prog.vim', 'w') as f:
            f.write("\n".join(code.splitlines()))

        p = Popen(['vim', '-X', '-N', '-u', 'NONE', '-i', 'NONE', '-V1', '-e', '-s', '-S', 'prog.vim', '+qall!'], stdout=PIPE, stderr=STDOUT, shell=True)
        p.wait()
        exitcode = p.returncode
        output = p.communicate()[0].decode()
        self.send_response(self.iopub_socket, 'stream', {'name': 'stdout', 'text': output})
        return {'status': 'ok',
                'execution_count': self.execution_count,
                'payload': [],
                'user_expressions': {},
               }

if __name__ == '__main__':
    from ipykernel.kernelapp import IPKernelApp
    IPKernelApp.launch_instance(kernel_class=Vim)

2018/01/08追記

なんとあのmattnさんが改良版を作ってくださいました。

Vim scriptカーネルのインストール方法も詳細に記載されいているので試したい方はこちらを参照ください

Vim script で機械学習 - Qiita

まとめ

意外と簡単にJupyter kernelを作ることができました。

このkernelがVIm script普及拡大の一助となれば幸いです。

以下参考にしたもの

jupyter kernel作り方

Making kernels for Jupyter — jupyter_client 6.0.0.dev documentation

Vim script

Vimスクリプト基礎文法最速マスター - 永遠に未完成

vimのコマンド

$ vim -X -N -u NONE -i NONE -V1 -e -s -S prog.vim +qall!

wandboxから拝借