LoginSignup
3
3

More than 3 years have passed since last update.

VimでPythonのコードを自動整形する

Last updated at Posted at 2020-06-25

使うものリスト

今回使っているプラグインのリンクです。
各自READMEなど確認しておいてください。

autopep8のインストール

pip install autopep8

vim pluginのインストール

vimのプラグイン管理をdeinで行っている人は、plugin_lazy.tomlに以下の行をコピーして貼り付ける。(deinを使ってない人は今すぐdeinを使いましょう)

[[plugins]]
repo = 'nvie/vim-flake8'
on_ft = ['python']

[[plugins]]
repo = 'tell-k/vim-autopep8'
on_ft = ['python']

.vimrcの編集

gitにpushする前に自動で実行したりファイルを保存するときに自動で実行したりすることも可能ですが、あまり勝手に実行されても怖いのでvim上でsift+fを押したときに自動整形が実行されるように設定します。
以下を.vimrcに追記します。

"autopep8を<sift>+fで実行
function! Preserve(command)
    " Save the last search.
    let search = @/
    " Save the current cursor position.
    let cursor_position = getpos('.')
    " Save the current window position.
    normal! H
    let window_position = getpos('.')
    call setpos('.', cursor_position)
    " Execute the command.
    execute a:command
    " Restore the last search.
    let @/ = search
    " Restore the previous window position.
    call setpos('.', window_position)
    normal! zt
    " Restore the previous cursor position.
    call setpos('.', cursor_position)
endfunction
function! Autopep8()
    call Preserve(':silent %!autopep8 --ignore=E501 -')
endfunction
autocmd FileType python nnoremap <S-f> :call Autopep8()<CR>

参考

これはこちらのStackoverflowのページを参考にしています。

使い方

  • vimのノーマルモードでF7キーを押すと、Flake8が実行されてpep8に準拠していない箇所が表示される。
  • 同じくノーマルモードでsift+fキーを押すと、Autopep8が実行されて、ソースコードの自動整形が行われる。
3
3
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
3
3