owned this note
owned this note
Published
Linked with GitHub
---
title: vim
tags: editor, vim
---
[TOC]
# Setup
1. [Install the Ultimate vimrc](https://github.com/amix/vimrc)
2. plugin manager
plugin 只會愈裝愈多,因此需要一個掌管所有 plugins 的管理者
* [vundle](https://github.com/VundleVim/Vundle.vim)
* (Newer) [Minimalist Vim Plugin Manager](https://github.com/junegunn/vim-plug)
- `:PlugInstall` to install plugins.
- ~~Problem: cannot give root permission to `make`~~
```shell=
Plug 'universal-ctags/ctags', { 'dir': '~/.ctags', 'do': 'sudo make install' }
```
no need, just put the Shorthand notation:
```shell=
Plug 'universal-ctags/ctags'
```
3. IDE
[將vim打造成source insight](https://ivan7645.github.io/2016/07/12/vim_to_si/)
- **ctags**
- Build issue
> get `No pkg-config found` error on executing ./autogen.sh
Sol.: [install pkg-config package](https://github.com/universal-ctags/ctags-snap/pull/14/files)
- Setup and configuration
Ref.: [ Vim + Trinity + Source Explorer + Tag List + NERD_tree + ctags ](https://stenlyho.blogspot.com/2010/03/vim-trinity-source-explorer-tag-list.html)
- 建立程式碼的索引檔
*on terminal*:
`$ctags -R --exclude=.svn`
*in vim*:
`!ctags -R --exclude=.svn`
- Commands:
```shell
" 跳至該函式或變數定義
Ctrl + ]
" 跳回使用此函式或變數處
Ctrl + t
```
- **cscope**
*Generate database*:
- 在使用cscope前必需先建資料庫,預設cscope建立的資料庫只有*.c及*.h,如果想要其它的副檔名,則必需先產生cscope.files,如下:
`find -name '*.c' -o -name '*.cpp' -o -name '*.java' -o -name '*.h' > cscope.files`
- 產生cscope.files後, 再執行`cscope -Rbkq`去產生cscope.out, cscope.in.out, cscope.po.out這三個檔案.
其中cscope.out是基本的symbols index,後兩個檔案是-q產生的快速尋找檔.
*Commands and key mappings*
- Find locations of a given keyword
`:cstag /keyword`
- The following maps all invoke one of the following cscope search types:
```
" 's' symbol: find all references to the token under cursor
" 'g' global: find global definition(s) of the token under cursor
" 'c' calls: find all calls to the function name under cursor
" 't' text: find all instances of the text under cursor
" 'e' egrep: egrep search for the word under cursor
" 'f' file: open the filename under cursor
" 'i' includes: find files that include the filename under cursor
" 'd' called: find functions that function under cursor calls
```
:question: 使用 Source_Explorer 與 Nerd_tree 時,不時會跳回檔頭
- [ ] Try VIM's folk: NeoVIM
- https://github.com/neovim/neovim
- https://codeberg.org/Guilty/VerilogImproved
# Plugins
## [Vim Syntax Plugin for Verilog and SystemVerilog](https://github.com/vhda/verilog_systemverilog.vim)
- [Omni Completion](https://github.com/vhda/verilog_systemverilog.vim#omni-completion)
For more information on using omni completion please check the vim man page for [`i_CTRL-X_CTRL-O`](http://vimdoc.sourceforge.net/htmldoc/insert.html#i_CTRL-X_CTRL-O)
--> This option specifies a function to be used for **Insert mode** *omni completion* with `CTRL-X CTRL-O`.
- [ ] not workable
- But the `Keyword completion (^N^P)` with ctags works correctly
- [Other Vim addons helpful for Verilog/SystemVerilog](https://github.com/vhda/verilog_systemverilog.vim#other-vim-addons-helpful-for-verilogsystemverilog)
- **Matchit**
- To use:
This addon allows using `%` to jump between matching keywords as Vim already does for matching parentheses/brackets.
- **Highlight Matchit**
- [ ] 測試 `class endclass` 沒有變色
- `:HiMatch` 可以正確執行,但手動輸入 `:HiMatchOn` 仍不會變色
- **Supertab**
Configures the `<tab>` key to perform insert completion. To take full advantage of the `omni completion` functionality.
- **Tagbar**
- [x] :warning: no tag be shown
- Debugging by the command `:TagbarDebug` and got a warning from the output file located at `.`, *tagbardebug.log*:
```shell
ctags: Warning: cannot open input file "/tmp/vyi3bEE/2.c" : No such file or directory
```
:::success
> ref.: [Tagbar doesn't populate, ctags.exe can't find file /tmp/vGCKBiZ/11.cs](https://github.com/preservim/tagbar/issues/723)
--> It's a permission problem with `/tmp` directory.
Sol.: change `$TEP` or `TMPDIR` environment variable to user local directory:
- For Linux:
```shell
let $TMPDIR=$HOME . '/tmp'
```
:::
- [ ] To replace `Taglist` to `Tagbar` on the command `TriggerToggleALL`
References:
- [VIM 同时支持taglist和tagbar 插件](https://blog.csdn.net/rainysia/article/details/84861077)
- [Vim - Overwrite Plugin Scoped Function](https://stackoverflow.com/q/49443373/3401549)
- [Letting variable values be overwritten in a script](https://vim.fandom.com/wiki/Letting_variable_values_be_overwritten_in_a_script)
- **FastFold**
- [ ] The plug was added to my VIM but I'm not sure whether my VIM is improved or not.
## NerdTree
- *commands*
- Open a file as a split
> ref. [accepted answer on "MacVim+NERDTree: How to open a file as a split in furthest horizontal split"](https://stackoverflow.com/a/31094402)
- in vertical manner: press `s` on the `file name`
- in horizontal manner: press `i` on the `file name`
- Other stuff
- [ ] (TO-READ) [NERD Tree Guide](https://medium.com/usevim/nerd-tree-guide-bb22c803dcd2)
:::warning
**Run issues**
- Taglist: Exuberant ctags (http://ctags.sf.net) not found in PATH. Plugin is not loaded.
:::
## Wrapping Text In Vim
There has two kinds of `wrap` functions, Hard Wrap vs Soft Wrap:
> https://vim.works/2019/03/16/wrapping-text-in-vim/
**Automatic word wrapping**
> https://vim.fandom.com/wiki/Automatic_word_wrapping
```
set tw=80
set fo+=t
set fo-=t
```
- [x] ==NOT work on VIM version 8.2.3741==
:::info
Added a visual indicator of where that 80 character border is to instead
:::
```shell
set colorcolumn=80
" make a vertical column in the background at 80 characters
highlight ColorColumn guibg=Black
" make it black in Graphical Vims (my vim background is dark gray)
" see help gui-colors for a list of suggseted color names
" see help guibg for how to specific specific rgb / hex colors
highlight ColorColumn ctermbg=0
" make it black in terminal vims (my terminal vim looks the same as my GUI vim)
" see :help ctermbg for a list of colors that can be used in the terminal
```
:::success
Sol.: need a `space` to be added between the last two words
:::
## Set snippet by [vim-snipmate](https://github.com/garbas/vim-snipmate)
:notes: The plugin is included in [The Ultimate vimrc](https://github.com/amix/vimrc) by default
I started from [Using snipmate](https://github.com/garbas/vim-snipmate#using-snipmate) section and the command is:
> Press and try :SnipMateOpenSnippetFiles for starting. Also see doc/SnipMate.txt to learn all SnipMate
- The result:
```
1 __InputList__ X
1
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
[No Name] 100% 0:0
1 01* /home/asahsieh/.vim_runtime/sources_non_forked/vim-snippets/snippets/_.snippets
2 02: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/ack.vim/snippets/_.snippets
3 03: does not exist: /home/asahsieh/.vim/plugged/cscope/snippets/_.snippets
4 04: does not exist: /home/asahsieh/.vim/plugged/cscope-maps/snippets/_.snippets
5 05: does not exist: /home/asahsieh/.vim/plugged/taglist/snippets/_.snippets
6 06: does not exist: /home/asahsieh/.vim/plugged/nerdtree/snippets/_.snippets
7 07: does not exist: /home/asahsieh/.vim/plugged/SrcExpl/snippets/_.snippets
8 08: does not exist: /home/asahsieh/.vim/plugged/Trinity/snippets/_.snippets
9 09: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/ale/snippets/_.snippets
10 10: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/auto-pairs/snippets/_.snippets
11 11: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/bufexplorer/snippets/_.snippet
12 12: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/ctrlp.vim/snippets/_.snippets
13 13: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/dracula/snippets/_.snippets
14 14: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/editorconfig-vim/snippets/_.sn
15 15: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/gist-vim/snippets/_.snippets
16 16: does not exist: /home/asahsieh/.vim_runtime/sources_non_forked/goyo.vim/snippets/_.snippets
NORMAL master __InputList__ 1% 1:3
```
> at `line 1` on the buttom split, there has a `_.snippet` file as default in the *copied* (sourced_non_forked) git repo, and the file could be opened by press `Enter` on the `line 1`
And, it constains some pre-defined snippets which are folded:
```shell
1 _.snippets X
+ 1 +-- 2 lines: Global snippets-------------------------------------------------------------------
- 3 # (c) holds no legal value ;)
+ 4 +-- 2 lines: snippet c)------------------------------------------------------------------------
+ 6 +-- 2 lines: snippet date----------------------------------------------------------------------
+ 8 +-- 2 lines: snippet ddate---------------------------------------------------------------------
+ 10 +-- 2 lines: snippet diso----------------------------------------------------------------------
+ 12 +-- 2 lines: snippet time----------------------------------------------------------------------
+ 14 +-- 2 lines: snippet datetime------------------------------------------------------------------
+ 16 +-- 2 lines: snippet lorem---------------------------------------------------------------------
+ 18 +-- 17 lines: snippet GPL2----------------------------------------------------------------------
+ 35 +-- 17 lines: snippet LGPL2---------------------------------------------------------------------
+ 52 +-- 17 lines: snippet GPL3----------------------------------------------------------------------
+ 69 +-- 17 lines: snippet LGPL3---------------------------------------------------------------------
+ 86 +-- 17 lines: snippet AGPL3---------------------------------------------------------------------
+103 +-- 9 lines: snippet GMGPL linking exception---------------------------------------------------
+112 +-- 28 lines: snippet BSD2----------------------------------------------------------------------
NORMAL master _.snippets 1% 3:29
```
Use `:zo` command to open a snippet, use `3 # (c) holds no legal value ;)` as example:
```shell
- 4 snippet c)
| 5 Copyright `&enc[:2] == "utf" ? "©" : "(c)"` `strftime("%Y")` ${1:`g:snips_author`}. All Rights Reserved.
```
:question: Then, How to use it?
- From the description in the [introduction](https://github.com/garbas/vim-snipmate#snipmate):
For example, in C, typing `for<tab>` could be expanded to
```c
for (i = 0; i < count; i++) {
/* code */
}
```
with successive presses of tab jumping around the snippet.
- I typed `c)<tab>`, and it was successfully expended to the copyright:
```
1 test + X
1 Copyright © 2022 Me. All Rights Reserved.
```
Now we know that how to use the `vim-snippet`, then, we are going to ==add own snippets==:
- An intuitive way is adding snippet to the default file mentioned before, but the repository is a copied version. We want to create a new snippets file maintained by ourself (e.g. upload it to Github).
:notes: From the previous result of command `SnipMateOpenSnippetFiles`, we can observe that it searches `_.snippets` on several pathes
- *which pathes will be searched?*
I found a related explaination in [FAQ](https://github.com/garbas/vim-snipmate#faq) which is for the question `SnipMate doesn't work / My snippets aren't triggering`
- Check that your snippets file is located inside a `foo/snippets` directory, where `foo` is a path listed in your `runtimepath`
The `runtimepath` in our vim setting (i.e. in *.vimrc*) is at `~/.vim_runtime`, as the *line 5* in the following scratch:
```shell=
.vimrc
" DO NOT EDIT THIS FILE
" Add your own customizations in ~/.vim_runtime/my_configs.vim
set runtimepath+=~/.vim_runtime
```
The plugin will search "./snippets/\_.snippets" under pathes in `runtimepath`
此外掛程式沒有提及如何[編寫](https://terms.naer.edu.tw/detail/18683879/?index=5)*snippet*,點擊此外掛程式於開頭介紹的其他類似的外掛程式,如[UltiSnips](https://github.com/sirver/ultisnips), 於*Screencast* section的[Episode 2: Creating Basic Snippets](http://www.sirver.net/blog/2012/01/08/second-episode-of-ultisnips-screencast/)有列出幾個範例;我想編寫`Linux kernel coding style`中的[Comment](https://www.kernel.org/doc/html/latest/process/coding-style.html#commenting)的snippet, 需要*plaintext*的語法,故參考了最接近的範例,`Complete Scripts in Shell Interpolation`。編寫如下:
```
[15:47] asahsieh@asahsieh-MacBookAir:~/Documents/Git_DBs/my-os-home-dir/dotfiles/general/.vim_ 1 _.snippets X
- 1 snippet c-long-comm
- 2 /*
- 3 * This is the preferred style for multi-line
- 4 * comments in the Linux kernel source code.
- 5 * Please use it consistently.
- 6 *
- 7 * Description: A column of asterisks on the left side,
- 8 * with beginning and ending almost-blank lines.
- 9 */
```
接著,在VIM的insertion mode底下使用該snippet, 輸入內容如下:
- `c-long-comm<tab>`
會遇到以下warning message:
:::warning
```shell
Error detected while processing function snipMate#TriggerSnippet[43]..<SNR>145_state_jump_stop[4]..<SNR>145_state_update_changes:
line 1:
E716: Key not present in Dictionary: "prev_len"
```
:::
> 從error message, `Key not present in Dictionary`, 看起來是沒有找到新增的snippet;亦有嘗試輸入預設的*snippets*, 沒有出現此error message。故回頭檢查`c-long-comm` snippet的syntax, 與預設的*snippets*仔細比較後,發現snippet內容有用\<tab\>作為prefix;比較如下(分成上下兩個splits):
```
1 _.snippets X
- 1 snippet c-long-comm
- 2 /*
- 3 * This is the preferred style for multi-line
- 4 * comments in the Linux kernel source code.
- 5 * Please use it consistently.
- 6 *
- 7 * Description: A column of asterisks on the left side,
- 8 * with beginning and ending almost-blank lines.
- 9 */
NORMAL master _.snippets 100% 9:1
- 1 snippet c)
| 2 Copyright `&enc[:2] == "utf" ? "©" : "(c)"` `strftime("%Y")` ${1:`g:snips_author`}. All Rights Reserved.
- 3 snippet date
| 4 `strftime("%Y-%m-%d")`
- 5 snippet ddate
| 6 `strftime("%B %d, %Y")`
```
修正後的內容,請參考[\_.snippets](https://raw.githubusercontent.com/asahsieh/my-os-home-dir/master/dotfiles/general/.vim_runtime/snippets/_.snippets)
> 更多語法,請參考vim-snipmate於vim的manual,vim命令為: `help snippet-syntax`
## Ctags
### Shortcuts
> https://stackoverflow.com/a/563992
```
Ctrl+] - go to definition
Ctrl+T - Jump back from the definition.
Ctrl+W Ctrl+] - Open the definition in a horizontal split
Add these lines in vimrc
map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>
map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>
Ctrl+\ - Open the definition in a new tab
Alt+] - Open the definition in a vertical split
After the tags are generated. You can use the following keys to tag into and tag out of functions:
Ctrl+Left MouseClick - Go to definition
Ctrl+Right MouseClick - Jump back from definition
```
# Operations
## [Paste the copied words before cursor](https://stackoverflow.com/questions/4073731/how-to-paste-before-the-cursor-after-selecting-a-vertical-block)
--> Press `P`
## [Gvim/Vim open file without souring .vimrc file](https://linuxtutorials.org/gvim-open-without-vimrc/)
- for Vim
`$vim -u NONE myfile`
## Remove unwanted spaces
> [Remove unwanted spaces](https://vim.fandom.com/wiki/Remove_unwanted_spaces)
> [Highlight unwanted spaces](https://vim.fandom.com/wiki/Highlight_unwanted_spaces)
- Delete trailing whitespace on each end of line:
```
:%s/\s\+\n/\r/gc
```
- The following deletes any leading whitespace at the beginning of each line.
```
:%s/^\\s\\+//e
" Same thing (:le = :left = left-align given range; % = all lines):
:%le
```
- :accept: Automatically removing all trailing whitespace
--> 利用vim `autocmd BufWritePre`於存檔時透過呼叫移除`trailing white space`的function, 如下:
```
" 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
" Automatically removing all trailing whitespace:
autocmd BufWritePre *.h,*.hpp,*.c,*.cc,*.cpp call CleanExtraSpaces()
```
## Create a new file or foloder in the directory of the open file in vim?
## [Switch between opened files in history](https://www.tumblr.com/dailyvim/6826612086/ctrl-o-and-ctrl-i-or-the-jumplist-or-friggin-vim)
By **jumplist**
Jumps are remembered in a jump list. With the `CTRL-O` and `CTRL-I` command you can go to cursor positions before older jumps, and back again.
### by `Nerdtree`
:::info
References
- [vim nerdtree copy paste search and replace](https://gist.github.com/todgru/4497708)
- [Create a new file in the directory of the open file in vim?](https://stackoverflow.com/questions/13239464/create-a-new-file-in-the-directory-of-the-open-file-in-vim)
:::
press `m` on the node you want to then select (m)ove the current node. Moving is the same as renaming.
```shell
NERDTree Menu. Use j/k/enter and the shortcuts indicated
==========================================================
> (a)dd a childnode
(m)ove the curent node
(d)elete the curent node
(c)copy the current node
```
- Ref.: https://stackoverflow.com/a/2442130/3401549
### by `Netrw`
> [Using Netrw, vim's builtin file explorer](https://vonheikemen.github.io/devlog/tools/using-netrw-vim-builtin-file-explorer/)
## Split related commands
`Ctrl-w h` or `Ctrl-w ←`: Shift focus to split on left of current
`Ctrl-w l` or `Ctrl-w →`: Shift focus to split on right of current
`Ctrl-w j` or `Ctrl-w ↓`: Shift focus to split below the current
`Ctrl-w k` or `Ctrl-w ↑`: Shift focus to split above the current
## Open file under cursor to Tab
- in `NerdTree` window
Press `T`
- in VIM window
```
:help tab-page-commands
CTRL-W gf Open a new tab page and edit the file name under the cursor.
See CTRL-W_gf.
```
- In NERDTree, press`m` +`c` to copy a file (node)
## Fast search
Open ack.vim for fast search:
```map <leader>g :Ack ```
## Access to the terminal while you are on Vim
> [The reference](https://askubuntu.com/questions/496822/access-to-the-terminal-while-you-are-on-vim)
Since recent vim you can now do:
`:terminal`
This was initially added in ==Vim 8.0.693==, but with lots of bugs. See `:help terminal:`
> this message is 8 years ago, the bugs should be fixed. [name=asahsieh]
## How to search highlighted text in Vim
> [link text](https://codeyarns.com/tech/2020-03-21-how-to-search-highlighted-text-in-vim.html#gsc.tab=0)
```
- Visually highlight the text you want to search using v and the cursor motion commands.
- Yank the visually highlighted text using y.
- Type /, then Ctrl+R, then ". This pastes the highlighted text at the search /.
- Press Enter to search for that text.
```
# [Regular expression](https://en.wikipedia.org/wiki/Regular_expression)
# TO-LEARN
- [ ] [Mapping keys in Vim - Tutorial (Part 1)](https://vim.fandom.com/wiki/Mapping_keys_in_Vim_-_Tutorial_(Part_1))
# References
[Learn Vimscript the Hard Way](https://learnvimscriptthehardway.stevelosh.com/)