将vim打造成代码阅读利器(for mac and ubuntu)

需要用到的工具:
NERDTree
Cscope
ctags
vundle
homebrew(for mac)

目录:

文章目录

  • linux内核代码阅读神技
  • 软件介绍
    • NERDTree
    • Cscope
    • ctags
    • vundle
    • homebrew
  • mac安装
  • ubuntu安装
    • 直接使用现成工具
    • ubuntu使用vundle
    • vim-airline
    • 让vim记忆上次编辑的位置
    • Barry Song的配置

linux内核代码阅读神技

make cscope tags ARCH=arm

软件介绍

NERDTree

NERDTree是一款vim插件,可以显示树形目录:
将vim打造成代码阅读利器(for mac and ubuntu)_第1张图片

进入当前目录的树形界面,通过小键盘"上下"键,能移动选中的目录或文件。目录前面有"+“号,按Enter会展开目录,文件前面是”-"号,按Enter会在右侧窗口展现该文件的内容,并光标的焦点focus右侧。“ctr+w+h"光标focus左侧树形目录,“ctrl+w+l"光标focus右侧文件显示窗口。按"ctrl+w+w”,光标自动在左右侧窗口切换。光标focus左侧树形窗口,按”?“弹出NERDTree的帮助,再次按”?“关闭帮助显示。输入”:q"回车,关闭光标所在窗口。

NERDTree更详细的快捷键可以参考:
https://www.linuxidc.com/Linux/2017-03/141699.htm
(在NERDTree中输入?也能查看帮助)

Cscope

Cscope是VIM适用的工具和插件,通过Cscope可以方便的获取某个函数的定义以及被那些函数调用 。

cscope使用之前需要生成缓存文件,cscope -R之后就可以看到有名为cscope.out的文件,vim中执行

:cs add cscope.out

就可以加载这个文件。另外也可以在脚本中指定预加载缓存文件。
将vim打造成代码阅读利器(for mac and ubuntu)_第2张图片

功能演示:
将vim打造成代码阅读利器(for mac and ubuntu)_第3张图片
(使用f/b/q等快捷键可以快速移动,可以在函数中进行选择,输入对应数字序号后就可以跳转到相应位置。)

在命令行输入

:cs -h

可以查看帮助文件:
将vim打造成代码阅读利器(for mac and ubuntu)_第4张图片

ctags

ctags是一款方便函数跳转的插件,在功能上比不过cscope,但胜在使用方便。
生成tags文件后就可以使用快捷键ctrl+]和ctrl+t进行跳转和返回。

详细的使用可以参考:
https://blog.csdn.net/gangyanliang/article/details/6889860

vundle

Vim本身能够满足开发人员的很多需求,但是它的可扩展性也极强,并且已经有一些杀手级的扩展,可以让Vim拥有“现代”集成开发环境的特性。所以,你所需要的第一件东西就是一个好用的扩展管理器。

虽说有其他很多方式对vim进行扩展,Vim也有多个插件管理器,但是我们强烈推荐Vundle,它能够搜索、安装、更新和移除vim插件,再也不需要手动管理vim插件,你可以把它想象成Vim的pip。有了Vundle,安装和更新包这种事情不费吹灰之力。

下载vundle:

git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim

修改配置文件使vundle生效(vim ~/.vimrc),把这段话粘贴到顶部:

set nocompatible              " required
filetype off                  " required
 
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
 
" Add all your plugins here (note older versions of Vundle used Bundle instead of Plugin)
" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

homebrew

homebrew是一个mac软件,通过Homebrew可以安装Apple没有预装但需要的东西。

官方网址:
https://brew.sh/index_zh-cn

使用方法:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

然后就可以通过它安装卸载软件了:

brew install xxx
brew uninstall xxx

mac安装

mac搭建vim环境基于homebrew和vundle,按上文说明安装好这两个软件。
1.通过homebrew安装软件

brew install ctags
brew install cscope

2.通过vundle安装插件及配置

安装vim插件的一般步骤可归结为:

1.在配置文件~/.vimrc中,将希望安装的插件写入call vundle#begin()和call vundle#end()行之间:Plugin '插件名'

2.然后打开Vim编辑器,运行下面的命令::PluginInstall,Vundle就会自动下载安装对应的插件

3.在.vimrc中对插件进一步做详细配置

将vim打造成代码阅读利器(for mac and ubuntu)_第5张图片

~/.vimrc杂项配置:
将vim打造成代码阅读利器(for mac and ubuntu)_第6张图片

其他如NERDTree、Tlist等太长不截图了,直接贴上整个~/.vimrc文件:

set nocompatible              " required
filetype off                  " required
 
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'

"frank vim plugin to be installed
Plugin 'scrooloose/nerdtree'
Plugin 'Xuyuanp/nerdtree-git-plugin'
Plugin 'taglist.vim'
Plugin 'Yggdroot/indentLine'
 
" Add all your plugins here (note older versions of Vundle used Bundle instead of Plugin)
" All of your Plugins must be added before the following line
call vundle#end()            	" required
filetype plugin indent on    	" required

"cscope config
if has("cscope")
    if filereadable("cscope.out")
        cs add cscope.out
    endif
endif

syntax on		     	"语法高亮
colorscheme zellner	     	"主题
set nu!                      	"显示行号
set hlsearch			"查找高亮显示
set incsearch			"查找时跳转
set mouse=a  			"always use mouse 

" frank mvim plugin config
" -------- pulgin NERDTree 
"使用F12键快速调出和隐藏它
map  :NERDTreeToggle
let NERDTreeChDirMode=1
"显示书签"
let NERDTreeShowBookmarks=1
"设置忽略文件类型"
let NERDTreeIgnore=['\~$', '\.pyc$', '\.swp$']
"窗口大小"
let NERDTreeWinSize=20 "25
" 修改默认箭头
let g:NERDTreeDirArrowExpandable = '▸'
let g:NERDTreeDirArrowCollapsible = '▾'
 
"How can I open a NERDTree automatically when vim starts up if no files were specified?
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif
" 打开vim时自动打开NERDTree
"autocmd vimenter * NERDTree           
 
"How can I open NERDTree automatically when vim starts up on opening a directory?
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | endif
" 关闭vim时,如果打开的文件除了NERDTree没有其他文件时,它自动关闭,减少多次按:q!
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
 
" 开发的过程中,我们希望git信息直接在NERDTree中显示出来, 和Eclipse一样,修改的文件和增加的文件都给出相应的标注, 这时需要安装的插件就是 nerdtree-git-plugin,配置信息如下
let g:NERDTreeIndicatorMapCustom = {
    \ "Modified"  : "✹",
    \ "Staged"    : "✚",
    \ "Untracked" : "✭",
    \ "Renamed"   : "➜",
    \ "Unmerged"  : "═",
    \ "Deleted"   : "✖",
    \ "Dirty"     : "✗",
    \ "Clean"     : "✔︎",
    \ "Unknown"   : "?"
    \ }
" 显示行号
let NERDTreeShowLineNumbers=1
let NERDTreeAutoCenter=1
 
" 在终端启动vim时,共享NERDTree
let g:nerdtree_tabs_open_on_console_startup=1

" 显示在右边
let NERDTreeWinPos=1

" -------- plugin Tlist
"let Tlist_Use_Right_Window = 1          "让taglist窗口出现在Vim的右边
let Tlist_File_Fold_Auto_Close = 1      "当同时显示多个文件中的tag时,设置为1,可使taglist只显示当前文件
					"tag,其它文件的tag都被折叠起来。

let Tlist_Show_One_File = 1             "只显示一个文件中的tag,默认为显示多个
let Tlist_Sort_Type ='name'             "Tag的排序规则,以名字排序。默认是以在文件中出现的顺序排序

let Tlist_GainFocus_On_ToggleOpen = 1       "Taglist窗口打开时,立刻切换为有焦点状态
let Tlist_Exit_OnlyWindow = 1           "如果taglist窗口是最后一个窗口,则退出vim

let Tlist_WinWidth = 23             "设置窗体宽度为32,可以根据自己喜好设置
let Tlist_Ctags_Cmd='/usr/local/bin/ctags'  "这里比较重要了,设置ctags的位置,不是指向MacOS自带的那个,>而是我们用homebrew安装的那个

"自动打开Tlist
autocmd vimenter * TlistToggle

"使用F10键快速调出和隐藏它
map  :TlistToggle

"map t :TlistToggle              "热键设置,我设置成Leader+t来呼出和关闭Taglist

" -------- plugin indentline
"" 支持任意ASCII码,也可以使用特殊字符:¦, ┆, or │ ,但只在utf-8编码下有效
let g:indentLine_char='¦'
" 使indentline生效
let g:indentLine_enabled = 1

最终效果:
将vim打造成代码阅读利器(for mac and ubuntu)_第7张图片
F9和F11可以开启和关闭侧栏。


ubuntu安装

直接使用现成工具

ubuntu可以直接使用现成的工具:
https://download.csdn.net/download/qq_33160790/10556797

这三个文件移动到~/目录下:
这里写图片描述

将vim.7z中vim文件夹也移动到~/目录下,并重命名为.vim。
这里写图片描述

最终效果:
将vim打造成代码阅读利器(for mac and ubuntu)_第8张图片
(按F1和F2可以控制侧栏)

ubuntu使用vundle

ubuntu上也可以使用vundle来安装插件。

1.使用git下载项目

git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim 

2.修改~/.vimrc文件,这里我们使用和mac一样的配置.

set nocompatible              " required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'

"frank vim plugin to be installed
Plugin 'scrooloose/nerdtree'
Plugin 'Xuyuanp/nerdtree-git-plugin'
Plugin 'taglist.vim'
Plugin 'Yggdroot/indentLine'

" Add all your plugins here (note older versions of Vundle used Bundle instead of Plugin)
" All of your Plugins must be added before the following line
call vundle#end()               " required
filetype plugin indent on       " required

"cscope config
if has("cscope")
    if filereadable("cscope.out")
        cs add cscope.out
    endif
endif

syntax on               "语法高亮
colorscheme darkblue    "主题
set nu!                 "显示行号
set hlsearch            "查找高亮显示
set incsearch           "查找时跳转
"set mouse=a            "always use mouse 

" frank mvim plugin config
" -------- pulgin NERDTree 
"使用F2键快速调出和隐藏它
map  :NERDTreeToggle
let NERDTreeChDirMode=1
"显示书签"
let NERDTreeShowBookmarks=1
"设置忽略文件类型"
let NERDTreeIgnore=['\~$', '\.pyc$', '\.swp$']
"窗口大小"
let NERDTreeWinSize=20 "25
" 修改默认箭头
let g:NERDTreeDirArrowExpandable = '▸'
let g:NERDTreeDirArrowCollapsible = '▾'

"How can I open a NERDTree automatically when vim starts up if no files were specified?
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif
" 打开vim时自动打开NERDTree
"autocmd vimenter * NERDTree           

"How can I open NERDTree automatically when vim starts up on opening a directory?
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | endif
" 关闭vim时,如果打开的文件除了NERDTree没有其他文件时,它自动关闭,减少多次按:q!
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif

" 开发的过程中,我们希望git信息直接在NERDTree中显示出来, 和Eclipse一样,修改的文件和增加的文件都给出相应的标注, 这时需要安装的插件就是 nerdtree-git-plugin,配置信息如下
let g:NERDTreeIndicatorMapCustom = {
    \ "Modified"  : "✹",
    \ "Staged"    : "✚",
    \ "Untracked" : "✭",
    \ "Renamed"   : "➜",
    \ "Unmerged"  : "═",
    \ "Deleted"   : "✖",
    \ "Dirty"     : "✗",
    \ "Clean"     : "✔︎",
    \ "Unknown"   : "?"
    \ }
" 显示行号
let NERDTreeShowLineNumbers=1
let NERDTreeAutoCenter=1

" 在终端启动vim时,共享NERDTree
let g:nerdtree_tabs_open_on_console_startup=1

" 显示在右边
let NERDTreeWinPos=1

" -------- plugin Tlist
"let Tlist_Use_Right_Window = 1         "让taglist窗口出现在Vim的右边
let Tlist_File_Fold_Auto_Close = 1      "当同时显示多个文件中的tag时,设置为1,可使taglist只显示当前文件
                                        "tag,其它文件的tag都被折叠起来。

let Tlist_Show_One_File = 1             "只显示一个文件中的tag,默认为显示多个
let Tlist_Sort_Type ='name'             "Tag的排序规则,以名字排序。默认是以在文件中出现的顺序排序

"let Tlist_GainFocus_On_ToggleOpen = 1   "Taglist窗口打开时,立刻切换为有焦点状态
let Tlist_Exit_OnlyWindow = 1           "如果taglist窗口是最后一个窗口,则退出vim

let Tlist_WinWidth = 32                 "设置窗体宽度为32,可以根据自己喜好设置

"自动打开Tlist
autocmd vimenter * TlistToggle

"使用F1键快速调出和隐藏它
map  :TlistToggle

" -------- plugin indentline
"" 支持任意ASCII码,也可以使用特殊字符:¦, ┆, or │ ,但只在utf-8编码下有效
let g:indentLine_char='¦'
" 使indentline生效
let g:indentLine_enabled = 1

"让vim记忆上次编辑的位置
autocmd BufReadPost *
            \ if line("'\"")>0&&line("'\"")<=line("$") |
            \   exe "normal g'\"" |
            \ endif
"内核使用的缩进
set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab


3.开始安装

在vim中输入

:PluginInstall 

vim-airline

这是一个状态栏增强功能。

1.修改~/.vimrc文件,增加
	Bundle 'bling/vim-airline'
2.然后输入vim中输入:PluginInstall
3.如果想美化图标的话

"airline
"安装字体后必须设置
let g:airline_powerline_fonts = 1
"关闭tabline
let g:airline#extensions#tabline#enabled = 0
let g:airline#extensions#tabline#buffer_nr_show = 1
if !exists('g:airline_symbols')
  let g:airline_symbols = {}
endif
"unicode symbols
let g:airline_left_sep = '▶'
let g:airline_left_alt_sep = '❯'
let g:airline_right_sep = '◀'
let g:airline_right_alt_sep = '❮'
let g:airline_symbols.linenr = '¶'
let g:airline_symbols.branch = '⎇' 

让vim记忆上次编辑的位置

修改~/.vimrc文件

"让vim记忆上次编辑的位置
autocmd BufReadPost *
			\ if line("'\"")>0&&line("'\"")<=line("$") |
			\	exe "normal g'\"" |
			\ endif
"让vim记忆上次编辑的位置

PS:如果taglist无法显示


1、打开文件: vi ~/.vim/bundle/taglist.vim/plugin/taglist.vim
2、在taglist.vim中查找 /loaded_taglist;
3、然后在if !exists('loaded_taglist') 前面添加下面语句:
     let Tlist_Ctags_Cmd="/usr/bin/ctags"   
4、然后在文件夹目录中重新执行执行ctags -R  ,taglist就显示正常了。
     
原因分析:
可能是在ubuntu中安装了eclipse,倒是taglist默认不再使用ctags了,然后
 let Tlist_Ctags_Cmd="/usr/bin/ctags" 来使能ctags。

Barry Song的配置

set wildmenu
set number
set nocompatible
set autoindent
set history=50
set ruler
set showcmd
set incsearch
set ai
set showmatch
set showmode
set hlsearch

set t_Co=8
set cino=:0
set cindent

colo ron
syntax on

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" CSCOPE settings for vim           
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"
" This file contains some boilerplate settings for vim's cscope interface,
" plus some keyboard mappings that I've found useful.
"
" USAGE: 
" -- vim 6:     Stick this file in your ~/.vim/plugin directory (or in a
"               'plugin' directory in some other directory that is in your
"               'runtimepath'.
"
" -- vim 5:     Stick this file somewhere and 'source cscope.vim' it from
"               your ~/.vimrc file (or cut and paste it into your .vimrc).
"
" NOTE: 
" These key maps use multiple keystrokes (2 or 3 keys).  If you find that vim
" keeps timing you out before you can complete them, try changing your timeout
" settings, as explained below.
"
" Happy cscoping,
"
" Jason Duell       [email protected]     2002/3/7
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" This tests to see if vim was configured with the '--enable-cscope' option
" when it was compiled.  If it wasn't, time to recompile vim... 

    """"""""""""" Standard cscope/vim boilerplate

    " use both cscope and ctag for 'ctrl-]', ':ta', and 'vim -t'
    " set cscopetag

    " check cscope for definition of a symbol before checking ctags: set to 1
    " if you want the reverse search order.
    set csto=0

    " add any cscope database in current directory
    if filereadable("cscope.out")
    	cs add cscope.out  
    "else add the database pointed to by environment variable 
    elseif $CSCOPE_DB != ""
       cs add $CSCOPE_DB
    endif

    " show msg when any other cscope db added
    set cscopeverbose  


    """"""""""""" My cscope/vim key mappings
    "
    " 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
    "
    " Below are three sets of the maps: one set that just jumps to your
    " search result, one that splits the existing vim window horizontally and
    " diplays your search result in the new window, and one that does the same
    " thing, but does a vertical split instead (vim 6 only).
    "
    " I've used CTRL-\ and CTRL-@ as the starting keys for these maps, as it's
    " unlikely that you need their default mappings (CTRL-\'s default use is
    " as part of CTRL-\ CTRL-N typemap, which basically just does the same
    " thing as hitting 'escape': CTRL-@ doesn't seem to have any default use).
    " If you don't like using 'CTRL-@' or CTRL-\, , you can change some or all
    " of these maps to use other keys.  One likely candidate is 'CTRL-_'
    " (which also maps to CTRL-/, which is easier to type).  By default it is
    " used to switch between Hebrew and English keyboard mode.
    "
    " All of the maps involving the  macro use '^$': this is so
    " that searches over '#include " return only references to
    " 'time.h', and not 'sys/time.h', etc. (by default cscope will return all
    " files that contain 'time.h' as part of their name).


    " To do the first type of search, hit 'CTRL-\', followed by one of the
    " cscope search types above (s,g,c,t,e,f,i,d).  The result of your cscope
    " search will be displayed in the current window.  You can use CTRL-T to
    " go back to where you were before the search.  
    "

    nmap s :cs find s =expand("")	
    nmap g :cs find g =expand("")	
    nmap c :cs find c =expand("")	
    nmap t :cs find t =expand("")	
    nmap e :cs find e =expand("")	
    nmap f :cs find f =expand("")	
    nmap i :cs find i ^=expand("")$
    nmap d :cs find d =expand("")	


    " Using 'CTRL-spacebar' (intepreted as CTRL-@ by vim) then a search type
    " makes the vim window split horizontally, with search result displayed in
    " the new window.
    "
    " (Note: earlier versions of vim may not have the :scs command, but it
    " can be simulated roughly via:
    "    nmap s  :cs find s =expand("")	

    nmap s :scs find s =expand("")	
    nmap g :scs find g =expand("")	
    nmap c :scs find c =expand("")	
    nmap t :scs find t =expand("")	
    nmap e :scs find e =expand("")	
    nmap f :scs find f =expand("")	
    nmap i :scs find i ^=expand("")$	
    nmap d :scs find d =expand("")	


    " Hitting CTRL-space *twice* before the search type does a vertical 
    " split instead of a horizontal one (vim 6 and up only)
    "
    " (Note: you may wish to put a 'set splitright' in your .vimrc
    " if you prefer the new window on the right instead of the left

    nmap s :vert scs find s =expand("")
    nmap g :vert scs find g =expand("")
    nmap c :vert scs find c =expand("")
    nmap t :vert scs find t =expand("")
    nmap e :vert scs find e =expand("")
    nmap f :vert scs find f =expand("")	
    nmap i :vert scs find i ^=expand("")$	
    nmap d :vert scs find d =expand("")

    " replace string
    nmap r :%s/ostr/nstr/g

参考文章:
https://blog.csdn.net/weixin_40539892/article/details/79252927

你可能感兴趣的:(Ubuntu)