zoukankan      html  css  js  c++  java
  • 快速搭建你的编程环境:VIM + dotfiles

    目录

    前文列表

    Openstack 实现技术分解 (1) 开发环境 — Devstack 部署案例详解
    Openstack 实现技术分解 (2) 虚拟机初始化工具 — Cloud-Init & metadata & userdata

    扩展阅读

    跟我一起学习VIM - vim插件合集
    很全面的vimrc配置技巧
    VIM set 指令

    VIM

    VIM is the God of editors, EMACS is God’s editor. —— 这是一句非常经典的万县,可以看出 VIM 在 editors 圈的地位。首先需要声明,本人不参与任何 IDE 战争,IDE 的本质追求是提高开发效率,能够称心如意撸代码就是你最好的选择。但就 OpenStack 开发而言,我仍会极力推荐使用 VIM,因为绝大多数紧急的救火环境中,往往只有 VIM。而 VIM + dotfiles 就是能够快速搭建或者说同步自己的 VIM 编程环境的最佳组合。

    这里写图片描述

    Vundle,VIM 插件管理器

    is short for Vim bundle and is a Vim plugin manager.

    当前被统计的 VIM 扩展插件多达 4900 多种,能够满足开发者们各种各样合理或奇葩的要求。 Vundle 是一个 VIM 插件管理工具,帮助你简易的完成这些插件的应用。

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

    在介绍 Vundle 之前,还需要了解一个 .vimrc 文件。.vimrc 是 VIM 的配置文件,绝对路径为 ~/.vimrc,是 VIM 的灵魂,拥有非常强大的自定义能力。Vundle 首先会读取 .vimrc 中以关键字 Plugin 开始的语句,这条语句的值实际上就是插件项目在 Github 上的名称,然后再实现对插件的安装、卸载或更新。

    这里给出 Vundle 的官方 .vimrc 配置样例

    set nocompatible              " 关闭兼容 vi 模式, 必须
    filetype off                  " 必须
    
    " 指定 Vundle 的源码路径
    " 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 安装 Vundle 插件
    Plugin 'VundleVim/Vundle.vim'
    
    " 下列列出了你所希望管理的 VIM 插件的样例
    " The following are examples of different formats supported. 
    " Keep Plugin commands between vundle#begin/end.
    
    " plugin on GitHub repo
    Plugin 'tpope/vim-fugitive'
    " plugin from http://vim-scripts.org/vim/scripts.html
    Plugin 'L9'
    " Git plugin not hosted on GitHub
    Plugin 'git://git.wincent.com/command-t.git'
    " git repos on your local machine (i.e. when working on your own plugin)
    Plugin 'file:///home/gmarik/path/to/plugin'
    " The sparkup vim script is in a subdirectory of this repo called vim.
    " Pass the path to set the runtimepath properly.
    Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
    " Install L9 and avoid a Naming conflict if you've already installed a
    " different version somewhere else.
    Plugin 'ascenator/L9', {'name': 'newL9'}
    
    " All of your Plugins must be added before the following line
    call vundle#end()            " 必须
    
    filetype plugin indent on    " 开启插件, 必须
    " To ignore plugin indent changes, instead use:
    "filetype plugin on
    
    " 插件管理类型
    " Brief help 
    " :PluginList       - lists configured plugins
    " :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
    " :PluginSearch foo - searches for foo; append `!` to refresh local cache
    " :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
    
    " 查看帮助手册
    " see :h vundle for more details or wiki for FAQ
    " Put your non-Plugin stuff after this line

    可以看出在语句 call vundle#begin()call vundle#end() 之间就定义了需要安装的插件列表。在定义好需要安装的插件列表之后,只需要执行下面的指令就可以自动的完成所有插件的安装。

    vim +PluginInstall +qall

    下面继续推荐几个常用的 VIM 插件。

    Solarized 主题

    这里写图片描述

    Solarized 具有阴阳(light/dark)两种风格鲜明的主题和灵活的自定义配色能力,是最受欢迎的主题插件之一。安装它只需要对 .vimrc 进行如下编辑:

    ...
    " 添加 Solarized 主题插件
    Plugin 'altercation/vim-colors-solarized'
    ...
    
    " Solarized 配置
    " Solarized =================================================
    syntax enable                                                                   
    set background=dark                 " 使用阴主题                 
    let g:solarized_termcolors=16                                                   
    let g:solarized_visibility='high'                                               
    let g:solarized_contrast='high'                                                 
    try                                                                             
      colorscheme solarized   " 设定配色方案                                                      
    catch /^Vim\%((a+))=:E185/                                                  
    endtry

    微调你喜欢的 Terminal 配色:
    这里写图片描述

    效果:
    这里写图片描述

    Nerdtree 项目目录结构

    Nerdtree 提供的项目目录结构浏览功能,极大的加强了开发者对整个项目目录结构的辨识和把控。

    ...
    Plugin 'scrooloose/nerdtree'
    ...
    
    
    " NERD Tree =================================================
    let NERDChristmasTree=0                                                            
    let NERDTreeWinSize=35                                                             
    let NERDTreeChDirMode=2                                                            
    let NERDTreeIgnore=['~$', '.pyc$', '.swp$']                                     
    let NERDTreeShowBookmarks=1                                                        
    let NERDTreeWinPos="left"                                                          
    " Automatically open a NERDTree if no files where specified                        
    autocmd vimenter * if !argc() | NERDTree | endif                                   
    " Close vim if the only window left open is a NERDTree                             
    autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
    " Open a NERDTree                                                                  
    nmap <F2> :NERDTreeToggle<CR>

    效果:
    这里写图片描述

    Tagbar 符号窗口

    符号(Symbol)窗口列出了当前文件中的宏、全局变量、函数、类等信息,使用光标选择就能够跳转相应源代码的位置,非常便捷。

    ...
    Plugin 'majutsushi/tagbar'
    ...
    
    " Tagbar =================================================
    let g:tagbar_width=35                                                           
    let g:tagbar_autofocus=1                                                        
    nmap <F3> :TagbarToggle<CR>

    安装 ctags:因各人环境不同,很可能需要手动安装 ctags

    sudo apt-get install exuberant-ctags

    效果:
    这里写图片描述

    Ctags 函数跳转

    Ctags(Generate tag files for source code)是 Linux 的下源码分析利器,默认以及安装在 VIM 中了,但也有可能需要手动安装。

    1. 在源代码的上级目录,通常是项目的顶级目录执行指令:
    ctags -R *
    1. 上述指令会生成 tags 文件,记录了所有函数的记录信息。
    2. 在 tags 文件所在的路径下打开源码文件,光标移至函数名处,快捷键 CTRL+] 进入函数。
    3. 快捷键 CTRL+t 退出函数,返回进入原点。

    也可以在指令行中使用 Ctags,同样需要在 tags 文件所在的路径下执行:

    $ vim -t <func_name>

    原理:ctags –R * 中的 -R 表示递归创建,包括源代码根目录(当前目录)下的所有子目录。这条命令会在当前目录下产生一个 tags 文件,当用户在当前目录中运行 vi/vim 时,就会自动载入此 tags 文件。tags 文件中包括以下对象:

    • 枚举型变量的值
    • 函数的定义、原型和声明
    • 命名空间(namespace)
    • 类型定义(typedefs)
    • 变量(包括定义和声明)
    • 类(class)、结构(struct)、枚举类型(enum)和联合(union)
    • 类、结构和联合中的成员变量

    注意,运行 vim 时,必须在 tags 文件所在的目录下运行,否则在 vim 启动后执行指令 :settags=<tags_path>。显然,这样并不方便,所以可以通过修改 vimrc 来解决这一问题:

    "=============================================== Ctags =================================================
    set tags+=/root/workspace/<project_name>/tags

    Ctags 的 VIM 指令:

    • ts(tags list)
    • tp(tags preview)
    • tn(tags next)
    • ta(tags access,访问指定函数)

    CtrlP 文件模糊查询

    CtrlP 文件模糊查询插件,让你在项目的文件海中自由穿梭。

    ...
    Plugin 'kien/ctrlp.vim'
    ...
    
    " Ctrlp =================================================
    set wildignore+=*/tmp/*,*.so,*.swp,*.zip,*.png,*.jpg,*.jpeg,*.gif  " Ignore for MacOSX/Linux
    let g:ctrlp_custom_ignore = {                                                   
         'dir':  'v[/].(git|hg|svn|rvm)$',                                      
         'file': 'v.(exe|so|dll|zip|tar|tar.gz|pyc)$',                           
         }                                                                         
    let g:ctrlp_match_window = 'bottom,order:btt,min:1,max:10,results:20'           
    let g:ctrlp_max_height = 30                                                     
    "let g:ctrlp_user_command = [                                                   
    "     '.git', 'cd %s && git ls-files . -co --exclude-standard',                
    "     'find %s -type f'                                                        
    "     ]                                                                        
    if executable('ag')                                                             
      " Use Ag over Grep                                                            
      set grepprg=ag --nogroup --nocolor                                          
      " Use ag in CtrlP for listing files.                                          
      let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'                         
      " Ag is fast enough that CtrlP doesn't need to cache                          
      let g:ctrlp_use_caching = 0                                                   
    endif                                                                           
    let g:ctrlp_working_path_mode=0                                                 
    let g:ctrlp_match_window_bottom=1                                               
    let g:ctrlp_max_height=15                                                       
    let g:ctrlp_match_window_reversed=0                                             
    let g:ctrlp_mruf_max=500                                                        
    let g:ctrlp_follow_symlinks=1                                                   
    let g:ctrlp_map = '<leader>p'                                                   
    let g:ctrlp_cmd = 'CtrlP'                                                       
    nmap <leader>f :CtrlPMRU<CR>

    NOTE 1:这里使用了 ag 搜索来代替 find 指令搜索,更加高效。
    NOTE 2:设置了 leader+f 快捷键来 Open/Close CtrlP。
    NOTE 3:leader 键类似于 Home 键,是组合快捷键的基础, 一般设置为 , 号,后文会给出该键的设置方法。

    效果:
    这里写图片描述

    YouCompleteMe 代码补全

    ...
    Plugin 'Valloric/YouCompleteMe'
    ...
    
    " YouCompleteMe =================================================
    let g:ycm_autoclose_preview_window_after_completion=1

    Syntastic 语法检查

    ...
    Plugin 'scrooloose/syntastic'
    ...
    
    " Syntastic =================================================
    " configure syntastic syntax checking to check on open as well as save          
    let g:syntastic_check_on_open=1                                                 
    let g:syntastic_html_tidy_ignore_errors=[" proprietary attribute "ng-"]        
    let g:syntastic_always_populate_loc_list = 1                                    
    let g:syntastic_auto_loc_list = 1                                               
    let g:syntastic_check_on_wq = 0                                                 
    set statusline+=%#warningmsg#                                                   
    set statusline+=%{SyntasticStatuslineFlag()}                                    
    set statusline+=%*

    官方效果图:
    这里写图片描述

    vimrc 通用配置

    VIM 的通用配置数不胜数,这里列出常见的一些作为参考:

    " General Config =================================================
    set nocompatible                          " be iMproved, required               
    filetype off                              " required                            
    set number                                " 显示行号             
    set ruler                                 " 打开状态栏标尺 
    set backspace=indent,eol,start            " Allow backspace in insert mode      
    set fileencodings=utf-8,gbk               " Set encoding of files               
    set history=1000                          " Number of things to remember in history
    set showcmd                               " Show incomplete cmds down the bottom
    set showmode                              " Show current mode down the bottom   
    set showmatch                             " 输入 )/} 时,光标会暂时的回到相匹配的 (/{              
    set gcr=a:blinkon0                        " Disable cursor blink                
    set novisualbell                          " No sounds                           
    set noerrorbells                          " No noise                            
    set autoread                              " Reload files changed outside vim    
    set laststatus=2                          " 显示状态栏            
    set statusline+=%{fugitive#statusline()}  " Git Hotness                         
    set list listchars=tab:>.,trail:.         " Display tabs and trailing spaces visually
    set linebreak                             " Wrap lines at convenient points     
    set nobackup                                                                    
    set nowb                                                                        
    set tabstop=4                                                                   
    set shiftwidth=4                                                                
    set textwidth=80                          " Make it obvious where 80 characters is
    highlight ColorColumn ctermbg=gray                                              
    set colorcolumn=80                                                              
    set numberwidth=4                                                               
    set fileformat=unix                                                             
    set expandtab                                                                   
    set t_Co=256                                                                    
    set list                                                                        
    "set ignorecase                                                                 
    set incsearch                                   " 输入搜索内容时就显示搜索结果            
    au WinLeave * set nocursorline nocursorcolumn   " Highlight current line 
    
    au WinEnter * set cursorline cursorcolumn                                       
    set cursorline cursorcolumn                     " 突出当前行和列                                           
    " Persistent Undo                                                               
    set undodir=~/.vim/backups                                                      
    set undofile                                                                    
                                                                                    
    " Search Options                                                                
    set incsearch                   " Find the next match as we type the search     
    set hlsearch                    " 搜索时高亮显示被找到的文本                   
    set viminfo='100,f1             " Save up to 100 marks, enable capital marks    
                                                                                    
    " Indentation                                                                   
    set autoindent                                                                  
    set smartindent    " 开启新行时使用智能自动缩进                                        
    set smarttab                                                                    
    set shiftwidth=4   " 设定 << 和 >> 命令移动时的宽度为 4                              
    set softtabstop=4  " 使得按退格键时可以一次删掉 4 个空格                             
    set tabstop=4      " 设定 tab 长度为 4                             
    set expandtab                                                                   
                                                                                    
    " Folds                                                                         
    set foldmethod=indent           " Fold based on indent                          
    set foldnestmax=3               " Deepest fold is 3 levels                      
    set nofoldenable                " Dont fold by default                          
                                                                                    
    " Leader setting                                                                
    let mapleader = ","             " Rebind <Leader> key                           
                                                                                    
    " Syntax Highlight                                                              
    syntax on                                                                       
                                                                                    
    " Run commands that require an interactive shell                                
    nnoremap <Leader>r :RunInInteractiveShell<space>

    最终效果:
    这里写图片描述

    NOTE:完整的 .vimrc 文件非常长,感兴趣的小伙伴移步到 JMilkFan’s Github

    dotfiles

    dotfiles(点文件)顾名思义就是文件名前缀带 . 的文件,因为这类文件在 Linux 中一般为与系统环境相关的隐藏文件,例如:.vimrc/.bashrc/.profile/.bash_profile,所以在一定程度上 ditfiles 代表了 Linux 系统环境的个性化配置。简而言之就是,如果在另外一台计算机中同步了这些 dotfils 就能拥有与你自己的计算机一致的环境设置。而且 dotfiles + Github 就能够实现只要有网络,那么所有的计算机都能够变成自己熟悉且习惯的样子。

    工作原理:

    • 收集相关的 “dotfiles”。
    • 将这些 “dotfiles” 都放置到同一个目录 dotfiles 中。
    • 将 dotfiles 目录上传到 Github 或者任意网络存储设备上。
    • 在另外一台计算机上拉下 dotfiles 目录,并以软链接的方式将 dotfiles 目录中对应的 "dotfiles"文件链接到系统中相应路径中。

    安装示例

    git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    git clone https://github.com/JmilkFan/dotfiles.git
    ln -s dotfiles/.vimrc ~/.vimrc
    vim +PluginInstall +qall

    NOTE:这里只是一个仅含有 .vimrc 文件的 dotfiles,实际上会含有更多的文件,那么就需要使用到 Bash 来为我们快速的建立软链接了。

    问题

    vim 版本不满足

    $ vim ~/.vimrc
    YouCompleteMe unavailable: requires Vim 7.4.1578+.

    解决:需要安装最新的 vim 版本。

    to Ubuntu:

    sudo add-apt-repository ppa:jonathonf/vim 
    sudo apt update 
    sudo apt install vim

    to CentOS

    cd /etc/yum.repos.d/
    wget  https://copr.fedorainfracloud.org/coprs/mcepl/vim8/repo/epel-7/mcepl-vim8-epel-7.repo
    rpm --import  https://copr-be.cloud.fedoraproject.org/results/mcepl/vim8/pubkey.gpg
    yum erase vim-minimal
    yum update vim

    to CentOS7

    rpm -Uvh http://mirror.ghettoforge.org/distributions/gf/gf-release-latest.gf.el7.noarch.rpm
    rpm --import http://mirror.ghettoforge.org/distributions/gf/RPM-GPG-KEY-gf.el7
    yum -y remove vim-minimal vim-common vim-enhanced sudo
    yum -y --enablerepo=gf-plus install vim-enhanced sudo

    to MAC Pro

    brew install vim
    
    # 重新打开终端即可
    # 会连带着安装 Python3、pip3 但需要手动配置 PATH

    YouCompleteMe unavailable: unable to load Python. VIM 不支持 Python3

    $ vim ~/.vimrc
    YouCompleteMe unavailable: unable to load Python.
    
    $ vim --version | grep python
    +cryptv          +linebreak       +python/dyn      +vreplace
    +cscope          +lispindent      -python3         +wildignore

    安装支持 Python3 的 VIM8:

    yum remove vim-*
    yum install git -y
    yum install gcc gcc-c++ -y
    yum install ncurses-devel -y
    yum install python3 python3-devel -y
    
    git clone --depth 1 https://github.com/vim/vim ~/vim
    cd ~/vim
    ./configure --with-features=huge 
                --enable-multibyte 
                --enable-python3interp=yes 
                --with-python3-config-dir=/usr/lib64/python3.6/config-3.6m-x86_64-linux-gnu 
                --enable-gui=gtk2 
                --enable-cscope 
                --prefix=/usr/local/vim
    make
    sudo make install
    rm -rf ~/vim

    修改环境变量:

    $ /usr/local/vim/bin/vim ~/.bashrc
    export PATH=$PATH:/usr/local/vim/bin

    The ycmd server SHUT DOWN (restart with ‘:YcmRestartServer’). YCM core library not detected; you need to compile YCM before using it.

    解决:YCM 核心库未检测到,需要重新编译 YCM
    to Ubuntu

    sudo apt-get install gcc gcc-c++ cmake g++  python3-dev
    python3 ~/.vim/bundle/YouCompleteMe/install.py --clang-completer

    to CentOS

    yum install gcc gcc-c++ cmake g++ python3-devel
    python3 ~/.vim/bundle/YouCompleteMe/install.py --clang-completer

    to MAC Pro

    brew install cmake
    
    cd ~/.vim/bundle/YouCompleteMe
    ./install.py --clang-completer --tern-completer

    Tagbar: Exuberant ctags not found at ‘/usr/local/bin/ctags’

    to Ubuntu:

    sudo apt-get install exuberant-ctags

    to CentOS:

    yum install ctags-etags

    to MAC Pro

    brew install ctags-exuberant
    brew link ctags
    $ find / -name ctags
    /etc/alternatives/ctags
    /var/lib/dpkg/alternatives/ctags
    /usr/bin/ctags
    
    $ ln -s /usr/bin/ctags /usr/local/bin/ctags

    相关阅读:

  • 相关阅读:
    Hello,cnblogs!
    本地搭建IIS服务器
    thinkPHP相关
    网页中经常用到的<hr / >标签的样式
    JS三元表达式
    ZUI开发人员选项
    XWindow、Server、Client和QT、GTK之间的关系
    深度桌面操作系统架构设计
    关于linux图形界面的基本知识
    linux各发行版之间的区别
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13310656.html
Copyright © 2011-2022 走看看