Vim操作方法

Pythonプログラミングを快適にするVim環境の作り方 [Windows 10/dein編]

VimでPythonプログラミングを快適にするWindows環境の作り方 [gVim/Windows10編]
記事内に広告が含まれています。
スポンサードリンク

VimをWindows 10で利用したいが、なかなか苦労しているというユーザーは多いのでは無いでしょうか。

本記事で、Windows 10 上で gVim を使った快適なプログラミング環境を構築する方法について、ご紹介します。

スポンサードリンク

VimでPythonプログラミングを快適にする構成

下記の構成を前提とした構築します。

OS & Python

  • Windows 10 Professional(執筆時点では バージョン 1903)
  • Python 2.7.16
  • Python 3.7.2

なお、Anaconda を活用しても良いとは思います。

ただ、Python 2.7 環境があった方が良いケースがあるようなので、そちらは順番注意です。

Vim

本体&プラグインマネージャー

  • gVim (KaoriYa版がおすすめ)
  • プラグインマネージャー:dein

vim.org の vim もアリですが、Kaoriya版の方が色々な組み込みがされているので便利です。

プラグインマネージャーは好みですが、dein が高速でメンテナンスも細やかなので人気があるようです。

プラグイン

プラグインはかなり好みがあると思いますが、今回は下記のようなオーソドックスな構成としています。(それでも数は多いですが…)

deoplete.nvim 入力補完
nvim-yarp フレームワーク deoplete.nvim利用のため
vim-hug-neovim-rpcフレームワーク deoplete.nvim利用のため
denite.nvim検索ツール
defx.nvimファイルマネージャー
vim-quickrun簡易実行
tagbar概要表示
mru.vimファイル履歴表示
vim-fugitive.gitGit 操作
vim-gitgutterGit 差分表示
vim-surround テキスト囲み補完
vimdoc-jaヘルプ日本語化
vim-auto-save自動保存
molokaiカラースキーマ
indentLineインデント表示
lightline.vimステータスバー表示
neosnippet.vimスニペットツール
neosnippet-snippetsスニペット集
vim-tomlTOMLハイライトVimプラグイン設定用途
vim-gitignoregitignoreハイライト
vim-jsonJSONハイライトPythonでJSONファイルはよく扱う
blackPythonフォーマッタ
vim-flake8Pythonコードチェッカー
jedi-vimPython入力支援
syntasticPythonシンタックスチェッカー
auto-ctags.vim タグ生成 プログラミング時のみ利用

こちらのサイトを参考に、さらに欲しいプラグインを加えると良いでしょう。

Vim Awesome
Awesome Vim plugins from across the universe

注意

今回はあくまで gVim 、Windows上の1つのウインドウアプリケーションとして利用する上での構成となります。

そのため、コマンドプロンプトやPowerShellで利用するには、不自由があります。

そちらで利用するには、それに合わせた設定が必要になる点をご理解ください。

Vim環境構築1.前提環境の準備

python2系インストール

必ず先に Python2 系をインストールする必要があります。

こちらからダウンロードして、インストールしましょう。

Python Release Python 2.7.15
The official home of the Python Programming Language

python3系インストール

次に Python3 系のインストールが必要になります。

こちらからダウンロードして、インストールしましょう。

Python Release Python 3.7.2
The official home of the Python Programming Language

必ず Python2 系とは異なるディレクトリにしましょう。

Pythonにパスを通す

詳しい手順は省略しますが、Python3 および Python(2系) のフォルダにパスを通します。

環境変数は ユーザー変数でもシステム変数でもOK

インストーラで設定するなら、そちらでも構いません。必ず設定内容は確認しましょう。

Pythonモジュールのインストール

下記のコマンドで、gVimで利用するモジュールをインストールします。

pip install --upgrade black flake8 flake8-docstrings flake8-import-order hacking flake8-pytest jedi nvim pynvim

コマンドプロンプトは、管理者権限で実行することに注意してください。

Gitインストール

こちらからインストーラを使って、指示通りにインストールします。

Git

バージョンは最新版で構いませんが、こちらも環境変数のPATHには必ず追加しておきましょう。

Vim環境構築2.Vimインストール

gVim(Kaoriya版)のインストール

こちらから有り難くダウンロードさせていただいて、インストールしましょう。

Vim — KaoriYa
VimのWindows向けコンパイル済みバイナリを配布しています。

インストーラも無く、解凍して配置するだけで簡単です。

配置場所はどちらでも構いませんが、下記へインストールするのが無難ですね。

C:\Program Files\vim

環境変数のPATHに追加しておくと、かなり便利です。

ctags のインストール

タグファイルを作成するプログラムもインストールしておきます。

ctags日本語対応版

こちらも インストーラも無く、解凍して配置するだけです。

PATHが通っていないといけないので、 環境変数のPATHにあるフォルダに配置するのがオススメです。

フォントのインストール

かなり好みの激しいところですが、今回はフォントは次を利用しています。

GitHub - yuru7/HackGen: Hack と源柔ゴシックを合成したプログラミングフォント 白源 (はくげん/HackGen)
Hack と源柔ゴシックを合成したプログラミングフォント 白源 (はくげん/HackGen). Contribute to yuru7/HackGen development by creating an account on GitHub...

文字が読みやすくて非常に良いですね。こちらの記事で好きになってしまいました。

Ricty を神フォントだと崇める僕が、フリーライセンスのプログラミングフォント「白源」を作った話 - Qiita
誰もが知る(?)プログラミングフォントこと Ricty にインスパイアされ、Ricty のように英文フォントと和文フォントを合成したプログラミングフォントを作りました。その名も、プログラミングフォ…

関連フォルダの作成

下記のコマンドでフォルダを作成しましょう。

mkdir %USERPROFILE%\.vim\backup
mkdir %USERPROFILE%\.vim\dein
mkdir %USERPROFILE%\.vim\session
mkdir %USERPROFILE%\.vim\swap
mkdir %USERPROFILE%\.vim\undo

プラグインマネージャーのインストール

プラグインマネージャーだけは手動インストールしなければ、他のプラグインのインストールが機能しません。

そのため、下記のコマンドを実行して下さい。

git clone https://github.com/Shougo/dein.vim.git %USERPROFILE%\.vim\dein

シンプルにするために標準のフォルダとは変更している点は注意です。

Vim環境構築3.Vim設定

配置場所

各設定ファイルの配置場所は下記の通りです。

%USERPROFILE% (ホームフォルダ)
|
+--- .vimrc
+--- .gvimrc
+--- .vim/
   |
   +--- plugins.toml
   +--- lazy.toml
   +--- backup/
   +--- session/
   +--- swap
   +--- undo
   +--- dein

設定ファイル1. .vimrc

こちらを元にさせてもらって、カスタマイズするのが良いですね。

GitHub - amix/vimrc: The ultimate Vim configuration (vimrc)
The ultimate Vim configuration (vimrc). Contribute to amix/vimrc development by creating an account on GitHub.

.vimrc は0から構築するのは辞めた方が良いですね。手間がかかりすぎる上に設定漏れが多くなってしまいますので。

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sections:
"    -> General
"    -> VIM user interface
"    -> Colors and Fonts
"    -> Files and backups
"    -> Text, tab and indent related
"    -> Visual mode related
"    -> Moving around, tabs and buffers
"    -> Status line
"    -> Editing mappings
"    -> vimgrep searching and cope displaying
"    -> Spell checking
"    -> Misc
"    -> Helper functions
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=500
" Enable filetype plugins
filetype plugin on
filetype indent on
" Set to auto read when a file is changed from the outside
set autoread
" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","
" Fast saving
nmap <leader>w :w!<cr>
" :W sudo saves the file 
" (useful for handling the permission-denied error)
command W w !sudo tee % > /dev/null
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the cursor - when moving vertically using j/k
set so=7
" Avoid garbled characters in Chinese language windows OS
let $LANG='ja' 
set langmenu=ja
source $VIMRUNTIME/delmenu.vim
source $VIMRUNTIME/menu.vim
" Turn on the Wild menu
set wildmenu
" Ignore compiled files
set wildignore=*.o,*~,*.pyc
if has("win16") || has("win32")
    set wildignore+=.git\*,.hg\*,.svn\*
else
    set wildignore+=*/.git/*,*/.hg/*,*/.svn/*,*/.DS_Store
endif
"Always show current position
set ruler
" Height of the command bar
set cmdheight=2
" A buffer becomes hidden when it is abandoned
set hid
" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
" Ignore case when searching
set ignorecase
" When searching try to be smart about cases 
set smartcase
" Highlight search results
set hlsearch
" Makes search act like search in modern browsers
set incsearch 
" Don't redraw while executing macros (good performance config)
set lazyredraw 
" For regular expressions turn magic on
set magic
" Show matching brackets when text indicator is over them
set showmatch 
" How many tenths of a second to blink when matching brackets
set mat=2
" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500
" Properly disable sound on errors on MacVim
if has("gui_macvim")
    autocmd GUIEnter * set vb t_vb=
endif
" Add a bit extra margin to the left
set foldcolumn=1
" === Add Settings ==
set belloff=all
set vb t_vb=
set showcmd
set wrapscan
set matchtime=3
set list
set autoindent
set hidden
set ttyfast
set number
set mousemodel=popup
set mouse=a
if has("win16") || has("win32")
    set clipboard&
    set clipboard=unnamed
else
    set clipboard&
    set clipboard^=unnamedplus
endif
set cursorline
" ファイルを開くと、ファイルがあるディレクトリに移動する
augroup grlcd
    autocmd!
    autocmd BufEnter * if &buftype !=# 'terminal' | lcd %:p:h | endif
augroup END
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax highlighting
syntax enable 
" Enable 256 colors palette in Gnome Terminal
if $COLORTERM == 'gnome-terminal'
    set t_Co=256
endif
try
    colorscheme evening
catch
endtry
set background=dark
" Set extra options when running in GUI mode
if has("gui_running")
    "set guioptions-=T
    "set guioptions-=e
    " === Add: Display: toolbar and menubar ===
    set guioptions=egmrtiT
    set t_Co=256
    set guitablabel=%M\ %t
endif
" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8
" Use Unix as the standard file type
set ffs=unix,dos,mac
" === Add: file encodings ===
set fileencoding=utf-8
set fileencodings=utf-8,iso-2022-jp,euc-jp,sjis
" === Add: Colorcolum ===
set colorcolumn=80
" 
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git et.c anyway...
set nobackup
set nowb
set noswapfile
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use spaces instead of tabs
set expandtab
" Be smart when using tabs ;)
set smarttab
" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4
" === Add:
set softtabstop=0
" Linebreak on 500 characters
set lbr
set tw=500
set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines
""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Visual mode pressing * or # searches for the current selection
" Super useful! From an idea by Michael Naumann
vnoremap <silent> * :<C-u>call VisualSelection('', '')<CR>/<C-R>=@/<CR><CR>
vnoremap <silent> # :<C-u>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs, windows and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Map <Space> to / (search) and Ctrl-<Space> to ? (backwards search)
map <space> /
map <c-space> ?
" Disable highlight when <leader><cr> is pressed
map <silent> <leader><cr> :noh<cr>
" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Close the current buffer
map <leader>bd :Bclose<cr>:tabclose<cr>gT
" Close all the buffers
map <leader>ba :bufdo bd<cr>
map <leader>l :bnext<cr>
map <leader>h :bprevious<cr>
" Useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove 
map <leader>t<leader> :tabnext 
" Let 'tl' toggle between this and the last accessed tab
let g:lasttab = 1
nmap <Leader>tl :exe "tabn ".g:lasttab<CR>
au TabLeave * let g:lasttab = tabpagenr()
" Opens a new tab with the current buffer's path
" Super useful when editing files in the same directory
map <leader>te :tabedit <c-r>=expand("%:p:h")<cr>/
" Switch CWD to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>:pwd<cr>
" Specify the behavior when switching between buffers 
try
  set switchbuf=useopen,usetab,newtab
  set stal=2
catch
endtry
" Return to last edit position when opening files (You want this!)
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
""""""""""""""""""""""""""""""
" => Status line
""""""""""""""""""""""""""""""
" Always show the status line
set laststatus=2
" Format the status line
" set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l\ \ Column:\ %c
set laststatus=2
set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remap VIM 0 to first non-blank character
map 0 ^
" Move a line of text using ALT+[jk] or Command+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z
if has("mac") || has("macunix")
  nmap <D-j> <M-j>
  nmap <D-k> <M-k>
  vmap <D-j> <M-j>
  vmap <D-k> <M-k>
endif
" Delete trailing white space on save, useful for some filetypes ;)
fun! CleanExtraSpaces()
    let save_cursor = getpos(".")
    let old_query = getreg('/')
    silent! %s/\s\+$//e
    call setpos('.', save_cursor)
    call setreg('/', old_query)
endfun
if has("autocmd")
    autocmd BufWritePre *.txt,*.js,*.py,*.wiki,*.sh,*.coffee :call CleanExtraSpaces()
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Spell checking
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>
" Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Misc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
" Quickly open a buffer for scribble
map <leader>q :e ~/buffer<cr>
" Quickly open a markdown buffer for scribble
map <leader>x :e ~/buffer.md<cr>
" Toggle paste mode on and off
map <leader>pp :setlocal paste!<cr>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Helper functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Returns true if paste mode is enabled
function! HasPaste()
    if &paste
        return 'PASTE MODE  '
    endif
    return ''
endfunction
" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
    let l:currentBufNum = bufnr("%")
    let l:alternateBufNum = bufnr("#")
    if buflisted(l:alternateBufNum)
        buffer #
    else
        bnext
    endif
    if bufnr("%") == l:currentBufNum
        new
    endif
    if buflisted(l:currentBufNum)
        execute("bdelete! ".l:currentBufNum)
    endif
endfunction
function! CmdLine(str)
    call feedkeys(":" . a:str)
endfunction 
function! VisualSelection(direction, extra_filter) range
    let l:saved_reg = @"
    execute "normal! vgvy"
    let l:pattern = escape(@", "\\/.*'$^~[]")
    let l:pattern = substitute(l:pattern, "\n$", "", "")
    if a:direction == 'gv'
        call CmdLine("Ack '" . l:pattern . "' " )
    elseif a:direction == 'replace'
        call CmdLine("%s" . '/'. l:pattern . '/')
    endif
    let @/ = l:pattern
    let @" = l:saved_reg
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Directory Settings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Valuable definition
let g:vimdir = $HOME . '\.vim'
let g:bundledir = vimdir . '\bundle'
let g:session_directory = vimdir . '\session'
let g:vimproc#download_windows_dll = 1
let $VIMDIR = vimdir
set backupdir=$VIMDIR/backup
set directory=$VIMDIR/swap
set undodir=$VIMDIR/undo
set updatetime=60000
" session management
let g:session_autoload = "no"
let g:session_autosave = "no"
let g:session_command_aliases = 1
let g:python3_host_prog = 'C:\Program Files\Python37\python.exe'
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"" dein Settings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if &compatible
  set nocompatible
endif
" dein directories
"let s:dein_dir = expand($VIMDIR . '\dein')
let g:dein_dir = $VIMDIR . '\dein'
let g:dein_repo_dir = g:dein_dir
let g:dein#cache_directory = g:dein_dir
set runtimepath+=$VIMDIR\dein
" Required:
if dein#load_state(g:dein_dir)
    call dein#begin(g:dein_dir)
    call dein#add('$HOME')
    call dein#add('Shougo/deoplete.nvim')
    if !has('nvim')
      call dein#add('roxma/nvim-yarp')
      call dein#add('roxma/vim-hug-neovim-rpc')
    endif
    let g:deoplete#enable_at_startup = 1
    "let g:config_dir  = expand('~\.cache\nvim')
    let g:config_dir  = $VIMDIR
    let s:toml        = g:config_dir . '\plugins.toml'
    let s:lazy_toml   = g:config_dir . '\lazy.toml'
    call dein#load_toml(s:toml,      {'lazy': 0})
    call dein#load_toml(s:lazy_toml, {'lazy': 1})
    call dein#end()
    call dein#save_state()
endif
" If you want to install not installed plugins on startup.
if dein#check_install()
    call dein#install()
endif
filetype plugin indent on
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"" Key Mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Like windows keymapping
inoremap <C-v>                  <C-r>*
inoremap <C-e>                  <End>
nnoremap <C-c>                  "+y
vnoremap <C-C>                  "+y
nnoremap <C-a>                  ggVG
" Tab control
nnoremap <C-t>                  :tabe<cr>
nnoremap <C-tab>                :tabnext<cr>
nnoremap <C-S-tab>              :tabprevious<cr>
" Edit / source setting files
nnoremap <F5>                   :source $MYVIMRC<CR>
nnoremap <C-F7>                 :<C-u>split $MYVIMRC<CR>
nnoremap <C-F8>                 :<C-u>split $HOME\.vim\plugins.toml<CR>
nnoremap <C-F9>                 :<C-u>split $HOME\.vim\lazy.toml<CR>
nnoremap <S-F7>                 :<C-u>edit $MYVIMRC<CR>
nnoremap <S-F8>                 :<C-u>edit $HOME\.vim\plugins.toml<CR>
nnoremap <S-F9>                 :<C-u>edit $HOME\.vim\lazy.toml<CR>
" Programmings
nnoremap <C-F5>                 :bo terminal<CR>
nnoremap <C-A-F5>               :QuickRun<CR>
nnoremap <C-e>                  <End>
" Launch Plugins
nnoremap <F1>                   :MRU<CR>
nnoremap <F2>                   :Denite buffer<CR>
nnoremap <F3>                   :Denite file/rec<CR>
nnoremap <F4>                   :Denite file/rec -input=
nnoremap <F7>                   :Defx -split -columns=icons:indent:filename:type<CR>
nnoremap <F8>                   :Defx -split=vertical -winwidth=30<CR>
nnoremap <F9>                   :TagbarToggle<CR>
" deoplete
inoremap <expr><tab> pumvisible() ? "\<C-n>" :
        \ neosnippet#expandable_or_jumpable() ?
        \    "\<Plug>(neosnippet_expand_or_jump)" : "\<tab>"

それぞれの詳しい説明は、各プラグインの説明ページに譲ります。

ただ、Windows らしいキー操作を残しつつ、Denite や Defx などの頻繁に使う機能はファンクションキーに割り当てたのは拘りのポイントです。

また、deoplete.nvim はプラグインの設定ファイルに記載すると競合するみたいなので、コチラに記載することにしました。ちょっと格好悪いですが…

設定ファイル2. .gvimrc

gVimを利用するときだけの設定ファイルで、主にGUI周りの設定のみ切り出しています。

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"" Visual Settings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Window
set columns=80             " ウインドウ幅
set lines=52               " ウインドウ高
if has("gui")
    winpos  0  0           " ウインドウ位置
endif
source $VIMRUNTIME/delmenu.vim
set langmenu=ja_jp.utf-8
source $VIMRUNTIME/menu.vim
set guifont=HackGen:h12
colorscheme molokai

このファイルが無いと、Windowsでは動作してくれないところがあるため、やむなく .vimrc と併用して利用することになります。

設定ファイル3. plugin.toml(プラグイン)

gVim起動時に一緒に読み込むプラグインを設定します。

ポイントは、denite と defx のキーバインド設定と indentLine の設定です。

特に、前者は設定しないと正常にりようできないので最低限といえる内容です。

[[plugins]]
repo = 'Shougo/denite.nvim'
on_cmd = 'Denite'
hook_add = '''
    " Define mappings
    autocmd FileType denite call s:denite_my_settings()
    function! s:denite_my_settings() abort
      nnoremap <silent><buffer><expr> <CR>
      \ denite#do_map('do_action')
      nnoremap <silent><buffer><expr> d
      \ denite#do_map('do_action', 'delete')
      nnoremap <silent><buffer><expr> p
      \ denite#do_map('do_action', 'preview')
      nnoremap <silent><buffer><expr> q
      \ denite#do_map('quit')
      nnoremap <silent><buffer><expr> i
      \ denite#do_map('open_filter_buffer')
      nnoremap <silent><buffer><expr> <Space>
      \ denite#do_map('toggle_select').'j'
    endfunction
    autocmd FileType denite-filter call s:denite_filter_my_settings()
    function! s:denite_filter_my_settings() abort
      imap <silent><buffer> <C-o> <Plug>(denite_filter_quit)
    endfunction
'''
[[plugins]]
repo = 'Shougo/defx.nvim'
on_cmd = 'Defx'
hook_add = '''
    set runtimepath+=~/.vim/dein/repos/github.com/Shougo/defx.nvim/
    autocmd FileType defx call s:defx_my_settings()
    function! s:defx_my_settings() abort
      " Define mappings
      nnoremap <silent><buffer><expr> <CR>
      \ defx#do_action('open')
      nnoremap <silent><buffer><expr> c
      \ defx#do_action('copy')
      nnoremap <silent><buffer><expr> m
      \ defx#do_action('move')
      nnoremap <silent><buffer><expr> p
      \ defx#do_action('paste')
      nnoremap <silent><buffer><expr> l
      \ defx#do_action('open')
      nnoremap <silent><buffer><expr> E
      \ defx#do_action('open', 'vsplit')
      nnoremap <silent><buffer><expr> P
      \ defx#do_action('open', 'pedit')
      nnoremap <silent><buffer><expr> o
      \ defx#do_action('open_or_close_tree')
      nnoremap <silent><buffer><expr> K
      \ defx#do_action('new_directory')
      nnoremap <silent><buffer><expr> N
      \ defx#do_action('new_file')
      nnoremap <silent><buffer><expr> M
      \ defx#do_action('new_multiple_files')
      nnoremap <silent><buffer><expr> C
      \ defx#do_action('toggle_columns',
      \                'mark:indent:icon:filename:type:size:time')
      nnoremap <silent><buffer><expr> S
      \ defx#do_action('toggle_sort', 'time')
      nnoremap <silent><buffer><expr> d
      \ defx#do_action('remove')
      nnoremap <silent><buffer><expr> r
      \ defx#do_action('rename')
      nnoremap <silent><buffer><expr> !
      \ defx#do_action('execute_command')
      nnoremap <silent><buffer><expr> x
      \ defx#do_action('execute_system')
      nnoremap <silent><buffer><expr> yy
      \ defx#do_action('yank_path')
      nnoremap <silent><buffer><expr> .
      \ defx#do_action('toggle_ignored_files')
      nnoremap <silent><buffer><expr> ;
      \ defx#do_action('repeat')
      nnoremap <silent><buffer><expr> h
      \ defx#do_action('cd', ['..'])
      nnoremap <silent><buffer><expr> ~
      \ defx#do_action('cd')
      nnoremap <silent><buffer><expr> q
      \ defx#do_action('quit')
      nnoremap <silent><buffer><expr> <Space>
      \ defx#do_action('toggle_select') . 'j'
      nnoremap <silent><buffer><expr> *
      \ defx#do_action('toggle_select_all')
      nnoremap <silent><buffer><expr> j
      \ line('.') == line('$') ? 'gg' : 'j'
      nnoremap <silent><buffer><expr> k
      \ line('.') == 1 ? 'G' : 'k'
      nnoremap <silent><buffer><expr> <C-l>
      \ defx#do_action('redraw')
      nnoremap <silent><buffer><expr> <C-g>
      \ defx#do_action('print')
      nnoremap <silent><buffer><expr> cd
      \ defx#do_action('change_vim_cwd')
    endfunction
'''
[[plugins]]
repo = 'thinca/vim-quickrun'
[[plugins]]
repo = 'majutsushi/tagbar'
[[plugins]]
repo = 'vim-scripts/mru.vim'
[[plugins]]
repo = 'tpope/vim-fugitive.git'
[[plugins]]
repo = 'airblade/vim-gitgutter'
hook_add = '''
    let g:gitgutter_git_executable = 'C:\Program Files\Git\cmd\git.exe'
'''
[[plugins]]
repo = 'tpope/vim-surround'
[[plugins]]
repo = 'vim-jp/vimdoc-ja'
[[plugins]]
repo = 'vim-scripts/vim-auto-save'
[[plugins]]
repo = 'tomasr/molokai'
hook_add = '''
    colorscheme molokai
    set t_Co=256
    let g:molokai_original = 1
    let g:rehash256 = 1
    if has('gui_running')
        set background=dark
    else
        set background=light
    endif
'''
[[plugins]]
repo = 'Yggdroot/indentLine'
hook_add = '''
    let g:indent_guides_enable_on_vim_startup = 1
    let g:indent_guides_start_level = 2
    let g:indent_guides_guide_size = 1
    let g:indent_guides_exclude_filetypes = ['help', 'nerdtree', 'tagbar', 'unite']
'''
[[plugins]]
repo = 'itchyny/lightline.vim'

設定ファイル4. lazy.toml(遅延読み込みプラグイン)

プラグインの機能を使いたいときだけ読み込む設定です。

可能な限り、こちらに移せば gVim の起動動作が速くなるので良いですが、機能を使うときには都度読み込みが発生します。

主にプログラミング作業に使用するプラグインなど、使う場面が特定できそうなものを中心に設定しています。

[[plugins]]
repo = 'Shougo/neosnippet.vim'
on_i  = 1
on_ft = ['snippet']
depends = ['neosnippet-snippets']
hook_add = '''
    let g:neosnippet#snippets_directory = '$HOME/.vim/snippets/'
    imap <C-K>     <Plug>(neosnippet_expand_or_jump)
    smap <C-K>     <Plug>(neosnippet_expand_or_jump)
    xmap <C-K>     <Plug>(neosnippet_expand_target)
    if has('conceal')
        set conceallevel=2 concealcursor=niv
    endif
'''
[[plugins]]
repo = 'Shougo/neosnippet-snippets'
[[plugins]]
repo = 'cespare/vim-toml'
on_ft = ['toml']
[[plugins]]
repo = 'gisphm/vim-gitignore'
on_ft = ['gitignore']
[[plugins]]
repo = 'elzr/vim-json'
on_ft = ['json']
hook_add = '''
    let g:vim_json_syntax_conceal = 0
    au! BufRead,BufNewFile *.json set filetype=json
    augroup json_autocmd
        autocmd!
        autocmd FileType json set autoindent
        autocmd FileType json set formatoptions=tcq2l
        autocmd FileType json set textwidth=78 shiftwidth=2
        autocmd FileType json set softtabstop=2 tabstop=8
        autocmd FileType json set expandtab
        autocmd FileType json set foldmethod=syntax
    augroup END
'''
# Python plugins """"""""""""""""""""""""""""""""""""""""""""""
[[plugins]]
repo = 'psf/black'
on_ft = ['python']
hook_add = '''
    autocmd BufWritePost *.py Black
'''
[[plugins]]
repo = 'nvie/vim-flake8'
on_ft = ['python']
hook_add = '''
    autocmd BufWritePost *.py call Flake8()
    let g:flake8_show_in_gutter=1
    let g:flake8_show_in_file=1
'''
[[plugins]]
repo = 'davidhalter/jedi-vim'
on_ft = ['python']
[[plugins]]
repo = 'vim-scripts/syntastic'
on_ft = ['python']
[[plugins]]
repo = 'soramugi/auto-ctags.vim'
on_ft = ['python']
hook_add = '''
    let g:auto_ctags = 1
    let g:auto_ctags_directory_list = ['.git', '.']
'''

これまでの手順がすべて完了していれば、次回の gVim 起動時に必要なプラグインが git によってインストールされます。

その際は、少し gVimの起動に時間がかかる点は注意してください。

以上で、インストールおよび初期設定は完了です。

gVim で Python スクリプトを快適に開発する Windows 10 環境
Python スクリプトをチェッカーでチェックした様子

しかし、Windows環境で快適に使うなら、あと一工夫が必要です。

Windows環境で素早くVimを利用するために

スタートメニュー/タスクバー

Windows の基本ですが、gVim をスタートメニューやタスクバーに登録しましょう。

gVim(kaoriya版)にはインストーラーが無いため、手動で登録する必要がある点は注意です。

ショートカットキーの設定

とっさにパッと起動したいことがあり得ます。そんな時にはショートカットキーを使うと便利です。

VimをWindowsのショートカットキーに登録する

こちらの画像をご覧いただくと分かりますが、gVim のショートカットのプロパティに設定します。

タスクバーに登録した gVim のショートカットのプロパティに設定したりすると良いですね。

右クリックメニュー

こちらの手順の通り、Windowsの右クリックメニューに追加すると、さらにgVimを利用しやすくなりますので、オススメです。

GVim/neovimの右クリックメニュー登録方法 [Windows 10]
この記事では、GVim / neovim を Windows 10 の右クリックメニューへ登録する方法をご紹介します。

「送る」への追加

右クリックメニューの「送る」に登録する手もあります。

レジストリを操作しなくて良いので安全ですが、選ぶためには1つステップが増えます。

もしこちらを設定する場合は、窓キー+Rキーを押した後に下記のコマンドを実行してください。

shell:sendto

コマンドプロンプトからは実行できないので要注意。


以上で gVim を Windows環境に馴染ませて、Python開発ができる環境が整いました。

動作確認としては、下記をやってみると良いと思います。

  • Terminal モードで Python を起動する
  • QuickRun で Pythonスクリプトを実行する
  • :py または py3 でそれぞれスクリプトを実行する(バージョン注意)
  • :!python % または :!python3 % でスクリプトを実行する (バージョン注意)
  • Pythonスクリプトを保存する(各チェッカーやフォーマッターが機能するはず)

既知の問題

この手順で設定した gVim には下記の問題があります。ご理解ください。

  • TOMLファイルを読み込んだ際、ハイライトが機能しない。(その後、source $MYVIMRC するとハイライトが機能します)
  • 同じ設定ファイルで、コマンドプロンプトから Vim を起動すると、ステータスバーの設定など正常に機能しません。
  • Pythonスクリプトを保存する際、jedi や フォーマッター、チェッカーがエラーを起こすことがあります。

また、解決法が分かる方は、お問い合わせフォームもしくはTwitterでメンションいただけると助かります。

Pythonプログラミングのレベルアップには

Python プログラミングを学びたい Vimmer は、次のようなオンラインスクールを活用するのが良いでしょう。通いのスクールが難しい人に最適です。

Udemy

有名オンラインレッスンサービスです。コンテンツが非常に充実しており、プログラミングに限らないバリエーションの豊富さが特徴です。

プログラミング言語 Python 3 入門 プログラミング初心者でも安心、Python/Django入門講座 【4日で体験!】 TensorFlow, Keras, Python 3 で学ぶディープラーニング体験講座 Python 3 : Web スクレイピング 超入門 - Python で通販サイトの最低価格を比較するアプリを作る

日本語以外ができるのであれば、より選択肢が多いサイトといえます。

質の高い動画での学習は、多くのエンジニアに好評を得ていますね。

TechAcademy

国内のプログラミングスクールでは、定評のあるサービスの1つです。

オンラインブートキャンプをうたっているだけあって、かなりミッチリなカリキュラムが評判です。

また、パーソナルメンターがつくなど、挫折しにくく、徹底的なサポートが魅力です。

Pythonコースなら「機械学習プログラムを開発することがゴール」とされているのも面白いですね。

無料レッスンもやっているようなので、機械学習を学びたい人をはじめ、Pythonプログラミングを覚えたい人は、ぜひ試してみると良いでしょう。

CodeCamp

国内のプログラミングスクールでは、定評のあるサービスの1つです。

講師陣が現役エンジニアであることや、講師との1on1レッスンが好評です。

プログラミングのオンライン家庭教師と表するサービスは、なかなか魅力的ではないでしょうか。

また、「Pythonデータサイエンスコース」では、Pythonで業務タスクを自動化する方法も学べるようです。

こちらも無料レッスンもやっているようなのですので、ぜひ試してみると良いでしょう。

プロフィール
管理人
Vim太郎

Vim力アップして、そろそろ上級 Vimmer の仲間入りしたいIT系エンジニアの端くれです。読んでくる訪問者の皆様と一緒に、Vim力を上げていくことができる記事が書ければと考えています。

\フォローする/
スポンサードリンク
関連記事
Vim入門