Skip to content
Update vim authored by umaumax's avatar umaumax
[[_TOC_]] [[_TOC_]]
## 💡how to update plugins ## :bulb:how to update plugins
``` bash ```bash
brew upgrade nvim brew upgrade nvim
``` pip install pynvi
pip install neovim
``` vim ```
:PlugUpdate
:TSInstall all ```vim
:TSUpdate :PlugUpdate
:checkhealth :TSInstall all
:checkhealth nvim-treesitter :TSUpdate
``` :checkhealth
:checkhealth nvim-treesitter
* エラーが発生した場合は、GitHubで該当するpluginのissueを探す ```
* pluginのon/offを試してみる
* エラーが発生した場合は、GitHubで該当するpluginのissueを探す
e.g. * pluginのon/offを試してみる
* [nvim-treesitterで「query: invalid node type at...」エラーが出た #neovim - Qiita]( https://qiita.com/ZOI_dayo/items/3c39252c729dd27393f3 )
* [Highlights broken after update with `query: invalid structure` · Issue #3092 · nvim-treesitter/nvim-treesitter]( https://github.com/nvim-treesitter/nvim-treesitter/issues/3092 ) e.g.
## オレオレコードリーディングチートシート * [nvim-treesitterで「query: invalid node type at...」エラーが出た #neovim - Qiita](https://qiita.com/ZOI_dayo/items/3c39252c729dd27393f3)
マッピング * [Highlights broken after update with `query: invalid structure` · Issue #3092 · nvim-treesitter/nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter/issues/3092)
* S: 関数やシンボルなどの一覧を表示して飛ぶ
* _: 型の定義へ飛ぶ ## オレオレコードリーディングチートシート
* H: 型やメソッドの情報を表示
* K: 定義へ飛ぶ マッピング
* R: 利用されている箇所の一覧して飛ぶ
* S: 関数やシンボルなどの一覧を表示して飛ぶ
コマンド * \_: 型の定義へ飛ぶ
* FZFbuffers: バッファ一覧を表示して切り替え * H: 型やメソッドの情報を表示
* RenameRefactor: 変数名などを一括変更する * K: 定義へ飛ぶ
* R: 利用されている箇所の一覧して飛ぶ
fzf
* L: 行を検索する コマンド
### マークダウン * FZFbuffers: バッファ一覧を表示して切り替え
* `:Unite outline`: 見出しジャンプ * RenameRefactor: 変数名などを一括変更する
### 移動 fzf
* `g<space>` + 2文字入力: 画面内移動
* `[`,`]`: 関数ごとにジャンプ * L: 行を検索する
* `{`,`}`: ブロック?ごとにジャンプ
* [stevearc/aerial.nvim: Neovim plugin for a code outline window]( https://github.com/stevearc/aerial.nvim#keymaps ) ### マークダウン
* `AerialToggle`: 関数などのシンボルを一覧表示してジャンプ可能
* 自作ショートカットでは`<Leader>A``AerialOpen` * `:Unite outline`: 見出しジャンプ
### ショートカットメモ ### 移動
* [tpope/vim-abolish: abolish.vim: easily search for, substitute, and abbreviate multiple variants of a word]( https://github.com/tpope/vim-abolish )
``` vim * `g<space>` + 2文字入力: 画面内移動
" crs "SnakeCase" -> "snake_case" * `[`,`]`: 関数ごとにジャンプ
" crm "mixed_case" -> "MixedCase" * `{`,`}`: ブロック?ごとにジャンプ
" crc "camel_case" -> "camelCase" * [stevearc/aerial.nvim: Neovim plugin for a code outline window](https://github.com/stevearc/aerial.nvim#keymaps)
" cru "upper_case" -> "UPPER_CASE" * `AerialToggle`: 関数などのシンボルを一覧表示してジャンプ可能
* 自作ショートカットでは`<Leader>A``AerialOpen`
call extend(Abolish.Coercions, { 'c': Abolish.camelcase,
\ 'm': Abolish.mixedcase, ### ショートカットメモ
\ 's': Abolish.snakecase,
\ '_': Abolish.snakecase, * [tpope/vim-abolish: abolish.vim: easily search for, substitute, and abbreviate multiple variants of a word](https://github.com/tpope/vim-abolish)
\ 'u': Abolish.uppercase,
\ 'U': Abolish.uppercase, ```vim
\ '-': Abolish.dashcase, " crs "SnakeCase" -> "snake_case"
\ 'k': Abolish.dashcase, " crm "mixed_case" -> "MixedCase"
\ '.': Abolish.dotcase, " crc "camel_case" -> "camelCase"
\ ' ': Abolish.spacecase, " cru "upper_case" -> "UPPER_CASE"
\ 't': Abolish.titlecase,
\ "function missing": s:function("s:unknown_coercion") call extend(Abolish.Coercions, { 'c': Abolish.camelcase,
\}, "keep") \ 'm': Abolish.mixedcase,
``` \ 's': Abolish.snakecase,
\ '_': Abolish.snakecase,
## how to build vim \ 'u': Abolish.uppercase,
\ 'U': Abolish.uppercase,
[vim\-jp » Linuxでのビルド方法]( https://vim-jp.org/docs/build_linux.html ) \ '-': Abolish.dashcase,
\ 'k': Abolish.dashcase,
<details> \ '.': Abolish.dotcase,
<summary>how to build</summary> \ ' ': Abolish.spacecase,
<!-- you must insert blank line --> \ 't': Abolish.titlecase,
``` bash \ "function missing": s:function("s:unknown_coercion")
$ git clone https://github.com/vim/vim.git \}, "keep")
$ cd vim ```
$ ./configure --with-features=huge \
--enable-multibyte \ ## how to build vim
--enable-fontset \
--enable-fail-if-missing \ [vim-jp » Linuxでのビルド方法](https://vim-jp.org/docs/build_linux.html)
--prefix=$HOME/local \
--enable-pythoninterp=yes \ <details>
--enable-python3interp=yes <summary>how to build</summary>
$ make -j8
$ ./src/vim --version <!--you must insert blank line-->
VIM - Vi IMproved 8.2 (2019 xxx, compiled xxx)
Included patches: 1-19 \`\`\` bash $ git clone https://github.com/vim/vim.git $ cd vim $ ./configure --with-features=huge \\ --enable-multibyte \\ --enable-fontset \\ --enable-fail-if-missing \\ --prefix=$HOME/local \\ --enable-pythoninterp=yes \\ --enable-python3interp=yes $ make -j8 $ ./src/vim --version VIM - Vi IMproved 8.2 (2019 xxx, compiled xxx) Included patches: 1-19 Compiled by xxx Huge version with GTK2 GUI. Features included (+) or not (-): +acl -farsi -mouse_sysmouse -tag_old_static +arabic +file_in_path +mouse_urxvt -tag_any_white +autocmd +find_in_path +mouse_xterm -tcl +autochdir +float +multi_byte +termguicolors -autoservername +folding +multi_lang +terminal +balloon_eval -footer -mzscheme +terminfo +balloon_eval_term +fork() +netbeans_intg +termresponse +browse +gettext +num64 +textobjects ++builtin_terms -hangul_input +packages +textprop +byte_offset +iconv +path_extra +timers +channel +insert_expand -perl +title +cindent +job +persistent_undo +toolbar +clientserver +jumplist +popupwin +user_commands +clipboard +keymap +postscript +vartabs +cmdline_compl +lambda +printer +vertsplit +cmdline_hist +langmap +profile +virtualedit +cmdline_info +libcall +python/dyn +visual +comments +linebreak +python3/dyn +visualextra +conceal +lispindent +quickfix +viminfo +cryptv +listcmds +reltime +vreplace +cscope +localmap +rightleft +wildignore +cursorbind -lua -ruby +wildmenu +cursorshape +menu +scrollbind +windows +dialog_con_gui +mksession +signs +writebackup +diff +modify_fname +smartindent +X11 +digraphs +mouse -sound -xfontset +dnd +mouseshape +spell +xim -ebcdic +mouse_dec +startuptime -xpm +emacs_tags -mouse_gpm +statusline +xsmp_interact +eval -mouse_jsbterm -sun_workshop +xterm_clipboard +ex_extra +mouse_netterm +syntax -xterm_save +extra_search +mouse_sgr +tag_binary system vimrc file: "$VIM/vimrc" user vimrc file: "$HOME/.vimrc" 2nd user vimrc file: "\~/.vim/vimrc" user exrc file: "$HOME/.exrc" system gvimrc file: "$VIM/gvimrc" user gvimrc file: "$HOME/.gvimrc" 2nd user gvimrc file: "\~/.vim/gvimrc" defaults file: "$VIMRUNTIME/defaults.vim" system menu file: "$VIMRUNTIME/menu.vim" fall-back for $VIM: "\~/local/share/vim" Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK -pthread -I\~/.linuxbrew/Cellar/pcre/8.42/include -I\~/.linuxbrew/Cellar/expat/2.2.6/include -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/gio-unix-2.0/ -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/include/libpng12 -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/libpng12 -I/usr/include/pango-1.0 -I/usr/include/harfbuzz -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/freetype2 -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 Linking: gcc -L/usr/local/lib -Wl,--as-needed -o vim -lgtk-x11-2.0 -lgdk-x11-2.0 -lpangocairo-1.0 -latk-1.0 -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lpangoft2-1.0 -lpango-1.0 -lgobject-2.0 -lglib-2.0 -lfontconfig -lfreetype -lSM -lICE -lXt -lX11 -lXdmcp -lSM -lICE -lm -ltinfo -lnsl -lacl -lattr -ldl \`\`\`
Compiled by xxx </details>
Huge version with GTK2 GUI. Features included (+) or not (-):
+acl -farsi -mouse_sysmouse -tag_old_static ## how to name plugins
+arabic +file_in_path +mouse_urxvt -tag_any_white
+autocmd +find_in_path +mouse_xterm -tcl * `*.vim`
+autochdir +float +multi_byte +termguicolors * `vim-*`
-autoservername +folding +multi_lang +terminal
+balloon_eval -footer -mzscheme +terminfo ## Vim script
+balloon_eval_term +fork() +netbeans_intg +termresponse
+browse +gettext +num64 +textobjects ### snippet
++builtin_terms -hangul_input +packages +textprop
+byte_offset +iconv +path_extra +timers #### visualモードで選択しているテキスト操作
+channel +insert_expand -perl +title
+cindent +job +persistent_undo +toolbar [vim - How to get visually selected text in VimScript - Stack Overflow](https://stackoverflow.com/questions/1533565/how-to-get-visually-selected-text-in-vimscript)
+clientserver +jumplist +popupwin +user_commands
+clipboard +keymap +postscript +vartabs ```vim
+cmdline_compl +lambda +printer +vertsplit function! s:get_visual_selection()
+cmdline_hist +langmap +profile +virtualedit " Why is this not a built-in Vim script function?!
+cmdline_info +libcall +python/dyn +visual let [line_start, column_start] = getpos("'<")[1:2]
+comments +linebreak +python3/dyn +visualextra let [line_end, column_end] = getpos("'>")[1:2]
+conceal +lispindent +quickfix +viminfo let lines = getline(line_start, line_end)
+cryptv +listcmds +reltime +vreplace if len(lines) == 0
+cscope +localmap +rightleft +wildignore return ''
+cursorbind -lua -ruby +wildmenu endif
+cursorshape +menu +scrollbind +windows let lines[-1] = lines[-1][: column_end - (&selection == 'inclusive' ? 1 : 2)]
+dialog_con_gui +mksession +signs +writebackup let lines[0] = lines[0][column_start - 1:]
+diff +modify_fname +smartindent +X11 return join(lines, "\n")
+digraphs +mouse -sound -xfontset endfunction
+dnd +mouseshape +spell +xim
-ebcdic +mouse_dec +startuptime -xpm function! s:delete_visual_selection()
+emacs_tags -mouse_gpm +statusline +xsmp_interact let selected = s:get_visual_selection()
+eval -mouse_jsbterm -sun_workshop +xterm_clipboard call setpos('.', getpos("'<"))
+ex_extra +mouse_netterm +syntax -xterm_save let Mlen = { s -> strlen(substitute(s, ".", "x", "g"))}
+extra_search +mouse_sgr +tag_binary let l = Mlen(selected)
system vimrc file: "$VIM/vimrc" if l > 0
user vimrc file: "$HOME/.vimrc" execute "normal! v".(l-1)."\<Right>\"_x"
2nd user vimrc file: "~/.vim/vimrc" endif
user exrc file: "$HOME/.exrc" return selected
system gvimrc file: "$VIM/gvimrc" endfunction
user gvimrc file: "$HOME/.gvimrc" ```
2nd user gvimrc file: "~/.vim/gvimrc"
defaults file: "$VIMRUNTIME/defaults.vim" #### 特定行に内容をセットする
system menu file: "$VIMRUNTIME/menu.vim"
fall-back for $VIM: "~/local/share/vim" ```vim
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK -pthread -I~/.linuxbrew/Cellar/pcre/8.42/include -I~/.linuxbrew/Cellar/expat/2.2.6/include -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/gio-unix-2.0/ -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/include/libpng12 -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/libpng12 -I/usr/include/pango-1.0 -I/usr/include/harfbuzz -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/freetype2 -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 function! s:setlines(pos, lines)
Linking: gcc -L/usr/local/lib -Wl,--as-needed -o vim -lgtk-x11-2.0 -lgdk-x11-2.0 -lpangocairo-1.0 -latk-1.0 -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lpangoft2-1.0 -lpango-1.0 -lgobject-2.0 -lglib-2.0 -lfontconfig -lfreetype -lSM -lICE -lXt -lX11 -lXdmcp -lSM -lICE -lm -ltinfo -lnsl -lacl -lattr -ldl if len(a:lines)==0
``` execute ':'.a:pos.'d'
</details> return
endif
## how to name plugins call setline(a:pos, a:lines[0])
* `*.vim` call append(a:pos, a:lines[1:])
* `vim-*` endfunction
```
## Vim script
### snippet #### 範囲選択コマンド
#### visualモードで選択しているテキスト操作
[vim \- How to get visually selected text in VimScript \- Stack Overflow]( https://stackoverflow.com/questions/1533565/how-to-get-visually-selected-text-in-vimscript ) ```vim
function! XXX() range
``` vim for n in range(a:firstline, a:lastline)
function! s:get_visual_selection() let line = getline(n)
" Why is this not a built-in Vim script function?! endfor
let [line_start, column_start] = getpos("'<")[1:2] endfunction
let [line_end, column_end] = getpos("'>")[1:2] command! -range XXX <line1>,<line2>call XXX()
let lines = getline(line_start, line_end) ```
if len(lines) == 0
return '' #### 外部コマンド
endif
let lines[-1] = lines[-1][: column_end - (&selection == 'inclusive' ? 1 : 2)] [vim-clang-format/clang_format.vim at master · rhysd/vim-clang-format](https://github.com/rhysd/vim-clang-format/blob/master/autoload/clang_format.vim#L14)
let lines[0] = lines[0][column_start - 1:]
return join(lines, "\n") ```vim
endfunction function! s:has_vimproc() abort
if !exists('s:exists_vimproc')
function! s:delete_visual_selection() try
let selected = s:get_visual_selection() silent call vimproc#version()
call setpos('.', getpos("'<")) let s:exists_vimproc = 1
let Mlen = { s -> strlen(substitute(s, ".", "x", "g"))} catch
let l = Mlen(selected) let s:exists_vimproc = 0
if l > 0 endtry
execute "normal! v".(l-1)."\<Right>\"_x" endif
endif return s:exists_vimproc
return selected endfunction
endfunction function! s:success() abort
``` let l:exit_success = (s:has_vimproc() ? vimproc#get_last_status() : v:shell_error) == 0
return l:exit_success
#### 特定行に内容をセットする endfunction
``` vim
function! s:setlines(pos, lines) function! s:error_message(result) abort
if len(a:lines)==0 echohl ErrorMsg
execute ':'.a:pos.'d' echomsg 'xxx has failed to yyy.'
return for l:line in split(a:result, "\n")[0:1]
endif echomsg l:line
call setline(a:pos, a:lines[0]) endfor
call append(a:pos, a:lines[1:]) echohl None
endfunction endfunction
``` ```
#### 範囲選択コマンド ### 行継続時のコメント
``` vim
function! XXX() range ```vim
for n in range(a:firstline, a:lastline) let hoge = {
let line = getline(n) \ "a": 1,
endfor "\ comment \の後に必ずスペースを入れること
endfunction \ "b": 2
command! -range XXX <line1>,<line2>call XXX() \ }
``` ```
#### 外部コマンド [Twitter](https://twitter.com/Bakudankun/status/1334618416951463937)
[vim-clang-format/clang_format.vim at master · rhysd/vim-clang-format]( https://github.com/rhysd/vim-clang-format/blob/master/autoload/clang_format.vim#L14 )
### [実は必要のないset nocompatible](https://github.com/vim-jp/reading-vimrc/wiki/vimrc%E3%82%A2%E3%83%B3%E3%83%81%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3#%E5%AE%9F%E3%81%AF%E5%BF%85%E8%A6%81%E3%81%AE%E3%81%AA%E3%81%84set-nocompatible)
``` vim
function! s:has_vimproc() abort ### 他のバッファの行数のみを知りたいが,vim単体では行全体を取得してから長さ取得となる
if !exists('s:exists_vimproc')
try [Is there a way to get the number of lines of a buffer in Vim Script? - Stack Overflow](https://stackoverflow.com/questions/14544618/is-there-a-way-to-get-the-number-of-lines-of-a-buffer-in-vim-script)
silent call vimproc#version()
let s:exists_vimproc = 1 ### sortしたい
catch
let s:exists_vimproc = 0 ```vim
endtry # builtin command
endif :{range}sort
return s:exists_vimproc
endfunction # unix command
function! s:success() abort :{range}!sort
let l:exit_success = (s:has_vimproc() ? vimproc#get_last_status() : v:shell_error) == 0 ```
return l:exit_success
endfunction ### expand - スクリプトのディレクトリ自体を取得する
function! s:error_message(result) abort [Vimスクリプトでスクリプトのディレクトリを取得する -- ぺけみさお](https://www.xmisao.com/2014/05/28/vim-get-script-path.html)
echohl ErrorMsg
echomsg 'xxx has failed to yyy.' ### match, 2match, 3match
for l:line in split(a:result, "\n")[0:1]
echomsg l:line [pattern - Vim日本語ドキュメント](https://vim-jp.org/vimdoc-ja/pattern.html#:2match)
endfor
echohl None prefixがつくと別々の独立したマッチを行う
endfunction
``` [nvim-treesitter/nvim-treesitter: Nvim Treesitter configurations and abstraction layer](https://github.com/nvim-treesitter/nvim-treesitter)有効時には`2match``3match`で設定しないとハイライトされないことに注意
### 行継続時のコメント `matchadd`関数を利用すると各ウィンドウごとに確実にシンタックスハイライトが可能となる
``` vim ### visual mode
let hoge = {
\ "a": 1, #### 矩形選択(ctrl-v)
"\ comment \の後に必ずスペースを入れること
\ "b": 2 [visual - Vim日本語ドキュメント](https://vim-jp.org/vimdoc-ja/visual.html#CTRL-V)
\ }
``` > WindowsではCTRL-Vはテキストの貼り付けにマップされることがあり、その際にはビジュアルモードを開始できない。[CTRL-V-alternative](https://vim-jp.org/vimdoc-ja/gui_w32.html#CTRL-V-alternative) を参照。
[Twitter]( https://twitter.com/Bakudankun/status/1334618416951463937 ) > CTRL-Vがペーストに使われてしまうので、矩形ビジュアル選択を開始することができな い。これにはCTRL-Qを代用できる。
### [実は必要のないset nocompatible]( https://github.com/vim-jp/reading-vimrc/wiki/vimrc%E3%82%A2%E3%83%B3%E3%83%81%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3#%E5%AE%9F%E3%81%AF%E5%BF%85%E8%A6%81%E3%81%AE%E3%81%AA%E3%81%84set-nocompatible ) #### `'<,'>` range機能
### 他のバッファの行数のみを知りたいが,vim単体では行全体を取得してから長さ取得となる 行単位(~~文字単~~)
[Is there a way to get the number of lines of a buffer in Vim Script? \- Stack Overflow]( https://stackoverflow.com/questions/14544618/is-there-a-way-to-get-the-number-of-lines-of-a-buffer-in-vim-script ) #### [visualモードで選択した範囲に含まれる「行」ではなく、選択した「テキスト」にだけ置換処理を適用する。 — 名無しのvim使い](http://nanasi.jp/articles/howto/editing/replace-selecttext.html)
### sortしたい 置換対象の先頭に`\%V`を付加する
``` vim ### visual modeの種類を判定したい
# builtin command
:{range}sort `visualmode()` `v`,`V`,`^V`?
# unix command #### [ビジュアルモードの選択情報の取得 — 名無しのvim使い](http://nanasi.jp/articles/code/screen/visual.html)
:{range}!sort
``` ```vim
:let tmp = @@
### expand - スクリプトのディレクトリ自体を取得する :silent normal gvy
[Vimスクリプトでスクリプトのディレクトリを取得する -- ぺけみさお]( https://www.xmisao.com/2014/05/28/vim-get-script-path.html ) :let selected = @@
:let @@ = tmp
### match, 2match, 3match :echo selected
[pattern \- Vim日本語ドキュメント]( https://vim-jp.org/vimdoc-ja/pattern.html#:2match ) ```
prefixがつくと別々の独立したマッチを行う #### visual mode時に関数を呼びたい
[nvim\-treesitter/nvim\-treesitter: Nvim Treesitter configurations and abstraction layer]( https://github.com/nvim-treesitter/nvim-treesitter )有効時には`2match``3match`で設定しないとハイライトされないことに注意 ```vim
vnoremap :<C-u>call xxx<CR>
`matchadd`関数を利用すると各ウィンドウごとに確実にシンタックスハイライトが可能となる ```
### visual mode `<C-u>`でrangeを無効化
#### 矩形選択(ctrl-v)
[visual \- Vim日本語ドキュメント]( https://vim-jp.org/vimdoc-ja/visual.html#CTRL-V ) [vimrcでのキーマッピングの際の意味 - e_v_e’s blog](http://e-v-e.hatenablog.com/entry/20150101/1420067539)
> WindowsではCTRL-Vはテキストの貼り付けにマップされることがあり、その際にはビジュアルモードを開始できない。[CTRL-V-alternative]( https://vim-jp.org/vimdoc-ja/gui_w32.html#CTRL-V-alternative ) ### cmdline mode判定
を参照。
`getcmdtype()`
> CTRL-Vがペーストに使われてしまうので、矩形ビジュアル選択を開始することができな
い。これにはCTRL-Qを代用できる。 ```
> debug mode command |debug-mode|
#### `'<,'>` range機能 / forward search command
行単位(~~文字単~~) ? backward search command
@ |input()| command
#### [visualモードで選択した範囲に含まれる「行」ではなく、選択した「テキスト」にだけ置換処理を適用する。 — 名無しのvim使い]( http://nanasi.jp/articles/howto/editing/replace-selecttext.html ) - |:insert| or |:append| command
置換対象の先頭に`\%V`を付加する = |i_CTRL-R_=|
```
### visual modeの種類を判定したい
`visualmode()` ### 無名バッファを開いてpasteしたい
`v`,`V`,`^V`?
e.g. paste z regster
#### [ビジュアルモードの選択情報の取得 — 名無しのvim使い]( http://nanasi.jp/articles/code/screen/visual.html )
``` vim ```vim
:let tmp = @@ tabnew | exe "normal! \"zp"
:silent normal gvy ```
:let selected = @@
:let @@ = tmp ### 編集しても:qで警告なしに終了可能なバッファにしたい
:echo selected
``` ```vim
:setlocal buftype=nofile
#### visual mode時に関数を呼びたい ```
``` vim
vnoremap :<C-u>call xxx<CR> ### get window width
```
[Get "usable" window width in vim script - Stack Overflow](https://stackoverflow.com/questions/26315925/get-usable-window-width-in-vim-script)
`<C-u>`でrangeを無効化
```vim
[vimrcでのキーマッピングの際の意味 \- e\_v\_e’s blog]( http://e-v-e.hatenablog.com/entry/20150101/1420067539 ) :set virtualedit=all
:norm! g$
### cmdline mode判定 :echo virtcol('.')
`getcmdtype()` ```
``` ### original commandに`-bar`オプションがない場合
> debug mode command |debug-mode|
/ forward search command wrapperを定義すれば良い
? backward search command
@ |input()| command ```vim
- |:insert| or |:append| command autocmd BufWritePre *.go if IsAutoFormat() | :GoFmtWrapper | endif
= |i_CTRL-R_=| " NOTE: original GoFmt has no '-bar' option
``` command! -bar GoFmtWrapper :GoFmt
```
### 無名バッファを開いてpasteしたい
e.g. paste z regster ### `range`なfunctionを他のcommandとしてではなくfunctionとして呼びたい
``` vim
tabnew | exe "normal! \"zp" [vimscript - Run global with range from within function - Vi and Vim Stack Exchange](https://vi.stackexchange.com/questions/9037/run-global-with-range-from-within-function)
```
```vim
### 編集しても:qで警告なしに終了可能なバッファにしたい 4,8call Function()
``` vim ```
:setlocal buftype=nofile
``` ### メッセージに出力する形式での変数の値確認
### get window width `echom string(xxx)`とすると`echo`のように任意の型に対して利用できる
[Get "usable" window width in vim script \- Stack Overflow]( https://stackoverflow.com/questions/26315925/get-usable-window-width-in-vim-script )
``` vim ### コマンドのログ付き実行
:set virtualedit=all
:norm! g$ `:99verbose COMMAND`
:echo virtcol('.')
``` ### 行操作
### original commandに`-bar`オプションがない場合 ```vim
wrapperを定義すれば良い setline()
``` vim append()
autocmd BufWritePre *.go if IsAutoFormat() | :GoFmtWrapper | endif " NOTE: 対象がfoldされているとすべて消える
" NOTE: original GoFmt has no '-bar' option execute 'normal! "_dd'
command! -bar GoFmtWrapper :GoFmt
``` # 現在の見ている範囲
let topline = line("w0")
### `range`なfunctionを他のcommandとしてではなくfunctionとして呼びたい let bottomline = line("w$")
[vimscript \- Run global with range from within function \- Vi and Vim Stack Exchange]( https://vi.stackexchange.com/questions/9037/run-global-with-range-from-within-function )
let lastline = line("$")
``` vim ```
4,8call Function()
``` #### 現在位置に挿入
### メッセージに出力する形式での変数の値確認 ```vim
`echom string(xxx)`とすると`echo`のように任意の型に対して利用できる call setline('.', line[:col('.')-1] . repeat(' ', &tabstop) . line[col('.'):])
call cursor('.', col('.')+&tabstop)
### コマンドのログ付き実行 ```
`:99verbose COMMAND`
[vimscript - How can I append text to the current line? - Vi and Vim Stack Exchange](https://vi.stackexchange.com/questions/12445/how-can-i-append-text-to-the-current-line)
### 行操作
``` vim ### source
setline()
append() #### 実はURLを指定してファイルを読み込むことができる
" NOTE: 対象がfoldされているとすべて消える
execute 'normal! "_dd' とある環境の内部では`wget`が実行されていた
# 現在の見ている範囲 e.g. `source https://raw.githubusercontent.com/mhinz/vim-galore/master/static/minimal-vimrc.vim`
let topline = line("w0")
let bottomline = line("w$") #### sourceしたvimファイル中での早期return
let lastline = line("$") `finish`
```
### 関数内で関数定義可能
#### 現在位置に挿入
``` vim e.g. [vim-codefmt/yapf.vim at 5ede026bb3582cb3ca18fd4875bec76b98ce9a12 · google/vim-codefmt](https://github.com/google/vim-codefmt/blob/5ede026bb3582cb3ca18fd4875bec76b98ce9a12/autoload/codefmt/yapf.vim#L28)
call setline('.', line[:col('.')-1] . repeat(' ', &tabstop) . line[col('.'):])
call cursor('.', col('.')+&tabstop) ### コマンド
```
#### `<Plug>`なキーマップをコマンドから呼びたい
[vimscript - How can I append text to the current line? - Vi and Vim Stack Exchange]( https://vi.stackexchange.com/questions/12445/how-can-i-append-text-to-the-current-line )
[Vim の \<Plug\> ってなんだ? - Qiita](https://qiita.com/domodomodomo/items/043e1f8d0f2a08ad0c53)
### source
#### 実はURLを指定してファイルを読み込むことができる `command! PreviewGitDiff call feedkeys("\<Plug>(GitGutterPreviewHunk)")`
とある環境の内部では`wget`が実行されていた
### キーマップ
e.g. `source https://raw.githubusercontent.com/mhinz/vim-galore/master/static/minimal-vimrc.vim`
[Mapping keys in Vim - Tutorial (Part 1) | Vim Tips Wiki | FANDOM powered by Wikia](http://vim.wikia.com/wiki/Mapping_keys_in_Vim\_-\_Tutorial\_(Part_1)) `<sciprt>`を付加すると意図しない上書きを禁止しやすい
#### sourceしたvimファイル中での早期return
`finish` > The following characters may be displayed before the {rhs} of the map:
### 関数内で関数定義可能 ```
e.g. [vim\-codefmt/yapf\.vim at 5ede026bb3582cb3ca18fd4875bec76b98ce9a12 · google/vim\-codefmt]( https://github.com/google/vim-codefmt/blob/5ede026bb3582cb3ca18fd4875bec76b98ce9a12/autoload/codefmt/yapf.vim#L28 ) * The {rhs} of the map is not re-mappable. Defined using the
':noremap' or ':nnoremap' or ':inoremap', etc. commands.
### コマンド & Only script local mappings are re-mappable in the {rhs} of the
#### `<Plug>`なキーマップをコマンドから呼びたい map. The map command has the <script> attribute.
@ A buffer local map command with the <buffer> attribute.
[Vim の \<Plug> ってなんだ? - Qiita]( https://qiita.com/domodomodomo/items/043e1f8d0f2a08ad0c53 ) ```
`command! PreviewGitDiff call feedkeys("\<Plug>(GitGutterPreviewHunk)")` #### 割当不可
### キーマップ * `ctrl-;`,`ctrl-:`
[Mapping keys in Vim \- Tutorial \(Part 1\) \| Vim Tips Wiki \| FANDOM powered by Wikia]( http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_(Part_1) ) * `ctrl-,`,`ctrl-.`
`<sciprt>`を付加すると意図しない上書きを禁止しやすい * `<S-Space>`
* `<C-S-xxx>`
> The following characters may be displayed before the {rhs} of the map:
`inoremap``<ESC>`をマッピングすると、矢印移動でABCDが入力される問題が発生する
```
* The {rhs} of the map is not re-mappable. Defined using the #### `<C-u>`
':noremap' or ':nnoremap' or ':inoremap', etc. commands.
& Only script local mappings are re-mappable in the {rhs} of the `nnoremap <Space>w :<C-u>w<CR>``<C-u>`は範囲指定の数字を削除するため
map. The map command has the <script> attribute.
@ A buffer local map command with the <buffer> attribute. #### 特定のキーがマッピングされているかどうか
```
```vim
#### 割当不可 maparg('hoge')
* `ctrl-;`,`ctrl-:` maparg('<S-Tab>', 'i')
* `ctrl-,`,`ctrl-.` !empty(maparg('hoge'))
* `<S-Space>` ```
* `<C-S-xxx>`
### 判定
`inoremap``<ESC>`をマッピングすると、矢印移動でABCDが入力される問題が発生する
#### 関数の存在判定
#### `<C-u>`
`nnoremap <Space>w :<C-u>w<CR>``<C-u>`は範囲指定の数字を削除するため [vim - VimL: Checking if function exists - Stack Overflow](https://stackoverflow.com/questions/13710364/viml-checking-if-function-exists)
#### 特定のキーがマッピングされているかどうか * `"`で囲むこと
``` vim * `*`を付加すること
maparg('hoge')
maparg('<S-Tab>', 'i') ```vim
!empty(maparg('hoge')) if exists("*GitBranchInfoString")
``` " do stuff here
endif
### 判定 ```
#### 関数の存在判定
[vim \- VimL: Checking if function exists \- Stack Overflow]( https://stackoverflow.com/questions/13710364/viml-checking-if-function-exists ) #### 関数が定義されているファイルを調べる
* `"`で囲むこと `:verbose function /FunctionNameRegex/`
* `*`を付加すること
#### vimコマンドの判定
``` vim
if exists("*GitBranchInfoString") `exists(":HogeCommand")`
" do stuff here
endif 注意点: help existsより、完全一致の場合は2が返されるが、完全一致せずに、`:HogeCommandPlus`にマッチした場合は1となる
```
```
#### 関数が定義されているファイルを調べる 1 for match with start of a command
`:verbose function /FunctionNameRegex/` 2 full match with a command
3 matches several user commands
#### vimコマンドの判定 To check for a supported command always check the return value to be 2.
`exists(":HogeCommand")` ```
注意点: help existsより、完全一致の場合は2が返されるが、完全一致せずに、`:HogeCommandPlus`にマッチした場合は1となる #### プラグインの読み込み判定
```
1 for match with start of a command ```vim
2 full match with a command if &rtp =~ 'plugin-name'
3 matches several user commands ...
To check for a supported command always check the return value to be 2. endif
``` ```
#### プラグインの読み込み判定 ```vim
``` vim if &rtp !~ 'non-exist-plugin-name'
if &rtp =~ 'plugin-name' ...
... endif
endif ```
```
[Vim script の exists で autoload の関数は判定してはいけない - C++でゲームプログラミング](http://d.hatena.ne.jp/osyo-manga/20120412/1334158849)
``` vim
if &rtp !~ 'non-exist-plugin-name' #### 変数の存在判定
...
endif `exists('v:t_number')`
```
#### type detection
[Vim script の exists で autoload の関数は判定してはいけない \- C\+\+でゲームプログラミング]( http://d.hatena.ne.jp/osyo-manga/20120412/1334158849 )
`:h type()`
#### 変数の存在判定
`exists('v:t_number')` ### autocmd
#### type detection * [autocmd-once](https://vim-jp.org/vimdoc-en/autocmd.html#autocmd-once)
`:h type()` * one-shotなイベント向け
* [autocmd-nested](https://vim-jp.org/vimdoc-en/autocmd.html#autocmd-nested)
### autocmd * autocmdトリガー中に他のautocmdのトリガー向けに意図的にイベントの発生を許容してネストさせる
* [autocmd-once]( https://vim-jp.org/vimdoc-en/autocmd.html#autocmd-once )
* one-shotなイベント向け ### runtime
* [autocmd-nested]( https://vim-jp.org/vimdoc-en/autocmd.html#autocmd-nested )
* autocmdトリガー中に他のautocmdのトリガー向けに意図的にイベントの発生を許容してネストさせる ```vim
runtime! xxx/yyy/zzz/*.vim
### runtime ```
``` vim
runtime! xxx/yyy/zzz/*.vim ではパスが適切でなくともエラーが表示されないので注意
```
ではパスが適切でなくともエラーが表示されないので注意 ### execute
### execute * `call execute("echo 42")`: 出力されない
* `call execute("echo 42")`: 出力されない * `echo execute("echo 42")`: 出力される
* `echo execute("echo 42")`: 出力される * `call execute("echo 42", "")`: 出力される
* `call execute("echo 42", "")`: 出力される
### 変数のプリフィックス
### 変数のプリフィックス
* `l:`: ローカル変数(関数内部のデフォルト接頭辞であるので、省略可) * `l:`: ローカル変数(関数内部のデフォルト接頭辞であるので、省略可)
* `g:`: グローバル変数(関数外の場合のデフォルト) * `g:`: グローバル変数(関数外の場合のデフォルト)
* `v:`: 特殊な変数のみ * `v:`: 特殊な変数のみ
* `b:`: バッファローカル * `b:`: バッファローカル
* 新規バッファになったときに,autocmd系から呼ばれるときにも初期化された状態となる * 新規バッファになったときに,autocmd系から呼ばれるときにも初期化された状態となる
* `w:`: ウィンドウローカル * `w:`: ウィンドウローカル
* `t:`: タブローカル * `t:`: タブローカル
* `s:`: スクリプトローカル * `s:`: スクリプトローカル
#### バッファローカルな変数を利用して状態を保持したい #### バッファローカルな変数を利用して状態を保持したい
単純に`.vimrc`に定義を書いた場合には、単に最初のバッファのみに実体が生成されるだけで、他のバッファを開いたときにその変数の値を読み込もうとするとエラーとなるので、その変数を利用する関数内の先頭などで下記のようにデフォルト値を設定する必要がある
``` vim 単純に`.vimrc`に定義を書いた場合には、単に最初のバッファのみに実体が生成されるだけで、他のバッファを開いたときにその変数の値を読み込もうとするとエラーとなるので、その変数を利用する関数内の先頭などで下記のようにデフォルト値を設定する必要がある
let b:hoge = get(b:, 'hoge', 'default value')
``` ```vim
let b:hoge = get(b:, 'hoge', 'default value')
### 正規表現 ```
* `\+`
* `\(`,`\)` ### 正規表現
* `^`,`$`,`.`
* `*`:最長マッチ * `\+`
* `\{-}`:最短マッチ * `\(`,`\)`
* `\zs`:どこにでもマッチしてマッチの開始地点を設定する * `^`,`$`,`.`
* `*`:最長マッチ
### for * `\{-}`:最短マッチ
``` vim * `\zs`:どこにでもマッチしてマッチの開始地点を設定する
for l:n in range(0, 10)
### for
endfor
``` ```vim
for l:n in range(0, 10)
``` vim
for l:val in l:list endfor
endfor ```
```
```vim
``` vim for l:val in l:list
for l:key in keys(l:map) endfor
let l:val = l:map[l:key] ```
endfor
``` ```vim
for l:key in keys(l:map)
### filename let l:val = l:map[l:key]
* 現在のファイルを対象:`expand` endfor
* 変数を対象:`fnamemodify` ```
### save & restore settings ### filename
#### cursor
``` * 現在のファイルを対象:`expand`
let l:view = winsaveview() * 変数を対象:`fnamemodify`
...
silent call winrestview(l:view) ### save & restore settings
```
#### cursor
#### window
``` ```
let save_winnr = winnr() let l:view = winsaveview()
... ...
exe save_winnr. 'wincmd w' silent call winrestview(l:view)
``` ```
#### user setting #### window
```
" push user setting ```
let s:save_cpo = &cpo let save_winnr = winnr()
set cpo&vim ...
exe save_winnr. 'wincmd w'
" write plugin script here ```
" pop user setting #### user setting
let &cpo = s:save_cpo
unlet s:save_cpo ```
``` " push user setting
let s:save_cpo = &cpo
### insert modeからcommand line modeへ移動する例 set cpo&vim
* `<ESC>:xxx<CR>i`:カーソルがずれる
* `<C-o>:xxx<CR>`:カーソルがずれない " write plugin script here
### vimscriptの実行結果を変数に格納して、その変数を外部コマンドへパイプする例 " pop user setting
``` let &cpo = s:save_cpo
silent! redir => commands unlet s:save_cpo
silent! scriptnames ```
silent! redir END
### insert modeからcommand line modeへ移動する例
echo(system('grep ".vim"', commands))
``` * `<ESC>:xxx<CR>i`:カーソルがずれる
* `<C-o>:xxx<CR>`:カーソルがずれない
### multiple filetype
通常,使えない ### vimscriptの実行結果を変数に格納して、その変数を外部コマンドへパイプする例
[Multiple file types in vim \- Stack Overflow]( https://stackoverflow.com/questions/2601403/multiple-file-types-in-vim )
```
> ou can specify to use multiple filetypes at the same time. For example: silent! redir => commands
> :setfiletype html.php silent! scriptnames
> But most of filetype plugings and syntax files are not designed for such cases. See also :help 'filetype' silent! redir END
[複数の'filetype'を扱いたい · Issue \#1034 · vim\-jp/issues]( https://github.com/vim-jp/issues/issues/1034 ) echo(system('grep ".vim"', commands))
```
### exit code
`v:shell_error` ### multiple filetype
### 文字列処理 通常,使えない [Multiple file types in vim - Stack Overflow](https://stackoverflow.com/questions/2601403/multiple-file-types-in-vim)
#### 文字列の文字を配列の要素とする
e.g. `"abc" -> ['a', 'b', 'c']` > ou can specify to use multiple filetypes at the same time. For example: :setfiletype html.php But most of filetype plugings and syntax files are not designed for such cases. See also :help 'filetype'
```
let l:key_mapping = "asdfghjklzxcvbnmqwertyuiop" [複数の'filetype'を扱いたい · Issue #1034 · vim-jp/issues](https://github.com/vim-jp/issues/issues/1034)
let g:key_mapping_list = map(range(len(l:key_mapping)), { index, val -> l:key_mapping[val] })
``` ### exit code
#### 1文字ずつ処理 `v:shell_error`
```
for c in split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.", '\zs') ### 文字列処理
...
endfor #### 文字列の文字を配列の要素とする
```
e.g. `"abc" -> ['a', 'b', 'c']`
#### slice
最初から最後の1文字手前まで ```
``` let l:key_mapping = "asdfghjklzxcvbnmqwertyuiop"
'sample'[:-2] let g:key_mapping_list = map(range(len(l:key_mapping)), { index, val -> l:key_mapping[val] })
``` ```
最後の文字のみを取得 #### 1文字ずつ処理
```
'sample'[-1:] ```
``` for c in split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.", '\zs')
...
#### 繰り返し文字連結 endfor
`repeat(char, num)` ```
#### マルチバイトな文字列の長さ #### slice
[文字列型 — 名無しのvim使い]( http://nanasi.jp/articles/code/variable/string.html )
``` vim 最初から最後の1文字手前まで
strlen(substitute("マルチバイトな日本語文字列", ".", "x", "g"))
```
# lambda function for multi bytes string 'sample'[:-2]
let Mlen = { s -> strlen(substitute(s, ".", "x", "g"))} ```
```
最後の文字のみを取得
### mapの注意点
`map`を使用すると第一引数のlistの中身自体が書き換わる(`+[]`でコピーを作成することができる) ```
``` vim 'sample'[-1:]
let include_dirs=['a','b','c'] ```
echo include_dirs
let include_dirs_opts=map(include_dirs+[], {k,v -> '-I'.v}) #### 繰り返し文字連結
echo include_dirs
``` `repeat(char, num)`
### 検索 #### マルチバイトな文字列の長さ
last searched pattern
``` [文字列型 — 名無しのvim使い](http://nanasi.jp/articles/code/variable/string.html)
@/
``` ```vim
strlen(substitute("マルチバイトな日本語文字列", ".", "x", "g"))
### 以前に開いたときのファイルのカーソル位置取得
``` vim # lambda function for multi bytes string
getpos("'`") let Mlen = { s -> strlen(substitute(s, ".", "x", "g"))}
``` ```
### 禁止行為 ### mapの注意点
`<expr>`指定時に`setline()`を呼んではならない
``` vim `map`を使用すると第一引数のlistの中身自体が書き換わる(`+[]`でコピーを作成することができる)
function! s:UnTab()
let line = getline('.') ```vim
if line[0] == "\t" let include_dirs=['a','b','c']
echom 'success' echo include_dirs
let line = line[1:] let include_dirs_opts=map(include_dirs+[], {k,v -> '-I'.v})
call setline('.', line) echo include_dirs
endif ```
return ''
endfunction ### 検索
inoremap <expr><S-Tab> pumvisible() ? "\<C-p>" : <SID>UnTab()
``` last searched pattern
`<C-o>`の影響で`pumvisible()`は常にゼロ ```
``` vim @/
# ng ```
inoremap <S-Tab> <C-o>:echo pumvisible()<CR>
# ok ### 以前に開いたときのファイルのカーソル位置取得
inoremap <S-Tab> <C-r>=<SID>UnTab()<CR>
``` ```vim
getpos("'`")
`:normal` in `<expr>` is NG ```
## lua ### 禁止行為
[nvim-lua-guide-ja/README.ja.md at master · willelz/nvim-lua-guide-ja]( https://github.com/willelz/nvim-lua-guide-ja/blob/master/README.ja.md )
`<expr>`指定時に`setline()`を呼んではならない
### luaからvimの変数を参照する
[nvim-lua-guide-ja/README.ja.md at master · willelz/nvim-lua-guide-ja]( https://github.com/willelz/nvim-lua-guide-ja/blob/master/README.ja.md#%E3%83%A1%E3%82%BF%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B5%E3%83%BC%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B-1 ) ```vim
function! s:UnTab()
## リモート let line = getline('.')
### scpプロトコルでのリモートファイル編集 if line[0] == "\t"
`:e scp://x.x.x.x//Users/xxx/tmp/README.md` echom 'success'
let line = line[1:]
* `~`は使えない call setline('.', line)
* リモートのファイル編集時に無理やりsudoして保存する方法は使えないことに注意 endif
* ホームディレクトリからの相対パスとする場合は`/`を先頭につける必要がない return ''
endfunction
## Neovim inoremap <expr><S-Tab> pumvisible() ? "\<C-p>" : <SID>UnTab()
### Vim scriptでのバージョン確認 ```
``` vim
:echo has('nvim') `<C-o>`の影響で`pumvisible()`は常にゼロ
:echo has('nvim-0.1')
:echo has('nvim-0.1.6') ```vim
``` # ng
inoremap <S-Tab> <C-o>:echo pumvisible()<CR>
### 色付きのメッセージを簡単に出力する # ok
``` vim inoremap <S-Tab> <C-r>=<SID>UnTab()<CR>
lua vim.api.nvim_echo({{"This is a "}, {"warning", "WarningMsg"}, {" message.\n"}, {"NOTE: This is a comment.", "Comment"}, }, true, {}) ```
call nvim_echo([["This is a "], ["warning", "WarningMsg"], [" message.\n"], ["NOTE: This is a comment.", "Comment"], ], v:true, {}) `:normal` in `<expr>` is NG
```
## lua
## Plugin
### 誰かのライブラリを拡張(ハック)する [nvim-lua-guide-ja/README.ja.md at master · willelz/nvim-lua-guide-ja](https://github.com/willelz/nvim-lua-guide-ja/blob/master/README.ja.md)
[Big Sky :: 他人が作ったVimScriptを一切触らず拡張する]( https://mattn.kaoriya.net/software/vim/20110728094347.htm )
### luaからvimの変数を参照する
### 多重ロード防止
`plugin`ディレクトリ:`!`あり [nvim-lua-guide-ja/README.ja.md at master · willelz/nvim-lua-guide-ja](https://github.com/willelz/nvim-lua-guide-ja/blob/master/README.ja.md#%E3%83%A1%E3%82%BF%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B5%E3%83%BC%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B-1)
``` vim
if !exists('g:loaded_hoge') ## リモート
finish
endif ### scpプロトコルでのリモートファイル編集
let g:loaded_hoge = 1
``` `:e scp://x.x.x.x//Users/xxx/tmp/README.md`
`autoload`ディレクトリ:`!`なし * `~`は使えない
``` vim * リモートのファイル編集時に無理やりsudoして保存する方法は使えないことに注意
if exists('g:loaded_hoge') * ホームディレクトリからの相対パスとする場合は`/`を先頭につける必要がない
finish
endif ## Neovim
let g:loaded_hoge = 1
``` ### Vim scriptでのバージョン確認
### [fatih/vim\-go: Go development plugin for Vim]( https://github.com/fatih/vim-go ) ```vim
* `:GoFillStruct`: 構造体のフィールドを自動生成する :echo has('nvim')
:echo has('nvim-0.1')
### [ripxorip/aerojump\.nvim: Aerojump is a fuzzy\-match searcher/jumper for Neovim with the goal of quick keyboard navigation]( https://github.com/ripxorip/aerojump.nvim ) :echo has('nvim-0.1.6')
入力文字を利用して、コードの移動を容易にする ```
### [Shougo/neosnippet\.vim: neo\-snippet plugin]( https://github.com/Shougo/neosnippet.vim ) ### 色付きのメッセージを簡単に出力する
* [記号の後ろだと補完が出来ない · Issue \#444 · Shougo/neosnippet\.vim]( https://github.com/Shougo/neosnippet.vim/issues/444 )
* 仕様である ```vim
lua vim.api.nvim_echo({{"This is a "}, {"warning", "WarningMsg"}, {" message.\n"}, {"NOTE: This is a comment.", "Comment"}, }, true, {})
### [nvim\-treesitter/nvim\-treesitter: Nvim Treesitter configurations and abstraction layer]( https://github.com/nvim-treesitter/nvim-treesitter )
call nvim_echo([["This is a "], ["warning", "WarningMsg"], [" message.\n"], ["NOTE: This is a comment.", "Comment"], ], v:true, {})
* Neovimには[neovim/runtime/lua/vim/treesitter]( https://github.com/neovim/neovim/tree/bb7ed42089e77feebe26b94f4cb46c72254b55e6/runtime/lua/vim/treesitter )にて、Tree-sitterのランタイムを制御するコードが組み込まれているが、パーサーなどの制御のためにこのプラグインが必要となる ```
* カラースキームをこのプラグインに対応しているものに変更しないと恩恵を受けることができないことに注意
## Plugin
また、[airblade/vim\-gitgutter: A Vim plugin which shows git diff markers in the sign column and stages/previews/undoes hunks and partial hunks\.]( https://github.com/airblade/vim-gitgutter )と組み合わせた際に、例えば、`GitGutterAddLine`などは`DiffAdd`へひも付くので、その行の背景色がすべて上書きされてしまうので、独自に設定を上書きする必要があることに注意
### 誰かのライブラリを拡張(ハック)する
## デバッグ
エラー発生時に`v:exception`, `v:throwpoint`を確認するとよい [Big Sky :: 他人が作ったVimScriptを一切触らず拡張する](https://mattn.kaoriya.net/software/vim/20110728094347.htm)
## Tips ### 多重ロード防止
### 検索
`:set smartcase`利用時でも`\C`を先頭に付与すると、厳密に大文字小文字を区別するようになる `plugin`ディレクトリ:`!`あり
### visual mode ```vim
`gv`: reselect the last block if !exists('g:loaded_hoge')
finish
### insert modeから素早くvisual modeへ移動 endif
`<C-o>v` let g:loaded_hoge = 1
```
### visual modeのカーソル位置
* `o`: toggle `autoload`ディレクトリ:`!`なし
* `` `< ``: 先頭
* `` `> ``: 末尾 ```vim
if exists('g:loaded_hoge')
### 繰り返し文字列挿入 finish
* normal modeで`数字i入力したい文字列`+`Esc`とすると入力できるが,多少タイムラグがある endif
* insert modeで文字を入力してから,normal modeになり,`数字.`の方はタイムラグがない let g:loaded_hoge = 1
```
### エラーコードで終了
例えば、gitのcommit message用のエディタとして起動している時に利用する ### [fatih/vim-go: Go development plugin for Vim](https://github.com/fatih/vim-go)
``` * `:GoFillStruct`: 構造体のフィールドを自動生成する
:cq[uit]
``` ### [ripxorip/aerojump.nvim: Aerojump is a fuzzy-match searcher/jumper for Neovim with the goal of quick keyboard navigation](https://github.com/ripxorip/aerojump.nvim)
## トラブルシューティング 入力文字を利用して、コードの移動を容易にする
### golangの補完が機能しない
[fatih/vim\-go: Go development plugin for Vim]( https://github.com/fatih/vim-go ) ### [Shougo/neosnippet.vim: neo-snippet plugin](https://github.com/Shougo/neosnippet.vim)
`:GoUpdateBinaries`を実行する * [記号の後ろだと補完が出来ない · Issue #444 · Shougo/neosnippet.vim](https://github.com/Shougo/neosnippet.vim/issues/444)
* 仕様である
### rustの補完が機能しない
``` bash ### [nvim-treesitter/nvim-treesitter: Nvim Treesitter configurations and abstraction layer](https://github.com/nvim-treesitter/nvim-treesitter)
rustup update
rustup component add rls-preview --toolchain nightly * Neovimには[neovim/runtime/lua/vim/treesitter](https://github.com/neovim/neovim/tree/bb7ed42089e77feebe26b94f4cb46c72254b55e6/runtime/lua/vim/treesitter)にて、Tree-sitterのランタイムを制御するコードが組み込まれているが、パーサーなどの制御のためにこのプラグインが必要となる
rustup component add rust-analysis --toolchain nightly * カラースキームをこのプラグインに対応しているものに変更しないと恩恵を受けることができないことに注意
rustup component add rust-src --toolchain nightly
``` また、[airblade/vim-gitgutter: A Vim plugin which shows git diff markers in the sign column and stages/previews/undoes hunks and partial hunks.](https://github.com/airblade/vim-gitgutter)と組み合わせた際に、例えば、`GitGutterAddLine`などは`DiffAdd`へひも付くので、その行の背景色がすべて上書きされてしまうので、独自に設定を上書きする必要があることに注意
### kotlinの補完が機能しない ## デバッグ
一度、該当のリポジトリでビルドをしておくこと
``` bash エラー発生時に`v:exception`, `v:throwpoint`を確認するとよい
./gradlew build
``` ## Tips
### vimのフォーマッターがない ### 検索
現時点でまともなものは存在しない
`:set smartcase`利用時でも`\C`を先頭に付与すると、厳密に大文字小文字を区別するようになる
[Vim Script Parser written in Go \- haya14busa \- Medium]( https://medium.com/@haya14busa/vim-script-parser-written-in-go-4d0296782a14 )
### visual mode
> I’ll try to develop vimfmt, Vim script version of gofmt, by using go-vimlparser.
`gv`: reselect the last block
[add a formatter for vimscript · Issue \#23 · google/vim\-codefmt]( https://github.com/google/vim-codefmt/issues/23 )
### insert modeから素早くvisual modeへ移動
### 🔥autocmdでトリガーされた処理で他のautocmdがトリガーされない
[++nested]( https://vim-jp.org/vimdoc-ja/autocmd.html#autocmd-nested ) `<C-o>v`
> 既定では、自動コマンドはネストしない (入れ子にならない)。例えば、自動コマンド ### visual modeのカーソル位置
内で ":e" や ":w" を使っても、これらに対してはイベント BufRead や BufWrite に
よる自動コマンドは実行されない。もしこれを実行してほしいなら、ネストしてほしい * `o`: toggle
コマンド内でフラグ "nested" を使うこと。 * `` `< ``: 先頭
\ No newline at end of file * `` `> ``: 末尾
### 繰り返し文字列挿入
* normal modeで`数字i入力したい文字列`+`Esc`とすると入力できるが,多少タイムラグがある
* insert modeで文字を入力してから,normal modeになり,`数字.`の方はタイムラグがない
### エラーコードで終了
例えば、gitのcommit message用のエディタとして起動している時に利用する
```
:cq[uit]
```
## トラブルシューティング
### golangの補完が機能しない
[fatih/vim-go: Go development plugin for Vim](https://github.com/fatih/vim-go)
`:GoUpdateBinaries`を実行する
### rustの補完が機能しない
```bash
rustup update
rustup component add rls-preview --toolchain nightly
rustup component add rust-analysis --toolchain nightly
rustup component add rust-src --toolchain nightly
```
### kotlinの補完が機能しない
一度、該当のリポジトリでビルドをしておくこと
```bash
./gradlew build
```
### vimのフォーマッターがない
現時点でまともなものは存在しない
[Vim Script Parser written in Go - haya14busa - Medium](https://medium.com/@haya14busa/vim-script-parser-written-in-go-4d0296782a14)
> I’ll try to develop vimfmt, Vim script version of gofmt, by using go-vimlparser.
[add a formatter for vimscript · Issue #23 · google/vim-codefmt](https://github.com/google/vim-codefmt/issues/23)
### :fire:autocmdでトリガーされた処理で他のautocmdがトリガーされない
[++nested](https://vim-jp.org/vimdoc-ja/autocmd.html#autocmd-nested)
> 既定では、自動コマンドはネストしない (入れ子にならない)。例えば、自動コマンド 内で ":e" や ":w" を使っても、これらに対してはイベント BufRead や BufWrite に よる自動コマンドは実行されない。もしこれを実行してほしいなら、ネストしてほしい コマンド内でフラグ "nested" を使うこと。
\ No newline at end of file