vim 配置——manjaro xfce4環境

爲vim添加系統剪貼板

https://vi.stackexchange.com/questions/3076/how-do-i-use-the-system-clipboard-with-vim-in-arch-linux
總結:刪除vim安裝gvim但不使用gvim。只是讓vim建立與libx的連接

sudo pacman -S gvim

capslock映射爲ctrl

參考:https://blog.yxwang.me/2009/05/caps-lock-to-ctrl/
總結:使用xmodmap這個工具
修改前記得先備份當前的鍵位映射,

xmodmap -pke > xmodmap.backup

接下來運行

xmodmap -e 'keycode 66 = Control_L'
xmodmap -e 'clear Lock'
xmodmap -e 'add Control = Control_L'

這樣就修改了Caps Lock的鍵位映射而不需要重啓x,如果要在每次啓動時自動修改Caps Lock鍵的映射,可以新建/修改一個.Xmodmap或者.xmodmap的文件,

vim .xmodmap

在裏面加入

keycode 66 = Control_L
clear Lock
add Control = Control_L

在.zshrc中加入:

xmodmap /home/yszc/.xmodmap 

終端啓動時出現問題:xmodmap: please release the following keys within 2 seconds: Control_L (...
參考:https://bbs.deepin.org/forum.php?mod=viewthread&tid=43109&extra=page%3D1
錯誤出現原因:
你是不是在你的rc文件加入了xmodmap的操作?,比如.bashrc如果是bash的話,可能你在裏面加了xmodmap ~/.Xmodmap? 如果你加了的話,你每次在開啓一個bash的時候,xmodmap的命令都會被執行,好的做法是加到profile文件中去,如.bash_profile等。

再參考:https://blog.csdn.net/thisishenryzhang/article/details/77892630 刪除.zshrc中的xmodmap… 在/etc/zsh/zprofile 中加入xmodmap /home/yszc/.xmodmap 效果待檢驗。失敗。 再再參考:https://forum.manjaro.org/t/how-to-execute-a-command-at-the-system-startup/1972 將該命令加入到 /etc/profile 中,檢驗效果:失敗 再來:選項->會話和啓動->應用程序自啓動 添加 xmodmap /home/yszc/.xmodmap 再再再參考:https://blog.csdn.net/u014717036/article/details/57082204 失敗 再參考:https://bbs.archlinux.org/viewtopic.php?id=67363 再參考:https://askubuntu.com/questions/1083637/file-xmodmap-is-not-sourced-on-startup-in-18-04 再來:https://wiki.archlinux.org/index.php/Xmodmap_(簡體中文) 受不了:https://askubuntu.com/questions/54157/how-do-i-set-xmodmap-on-login 終於解決:
解決方法:參考(https://askubuntu.com/questions/54157/how-do-i-set-xmodmap-on-login

Please note: if you are on Xfce, it is noted on the official Xfce FAQ
that you may have to create a startup item instead of using
~/.xinitrc, and that you might have to delay the execution so the
xmodmap changes are not overwritten by setxkbmap. You can use a delay
to achieve this in your startup entry:

/bin/bash -c "sleep 20; /usr/bin/xmodmap /home/$USER/.Xmodmap"

選項->會話和啓動->應用程序自啓動
添加 /bin/bash -c “sleep 20; /usr/bin/xmodmap /home/$USER/.Xmodmap”

3.新建.vimrc輸入下面的代碼: (暫時不用鼠標功能,翻頁用n模式下c-j c-k,具體定位用EasyMotion)

" 基本設置----------------{{{
" 不兼容vi模式 必須放在第一行
set nocompatible
" 開啓語法高亮
syntax on
" 高亮當前行
set cursorline
" 開啓搜索高亮
set incsearch
" 設定歷史記錄數
set history =50
" 設定爲系統剪貼板
set clipboard=unnamedplus
" 消除~後綴備份文件
set nobackup
" 消除un後綴備份文件
set noundofile
" 顯示行號
set number
" 高亮搜索項
set hlsearch
" 用空格代替tab鍵
" 設置tab寬度,爲了符合google c++標準將4空格換位2空格節省橫向空間
set tabstop=2
" 設置縮進寬度
set shiftwidth=2
" 用空格代替tab,問題:用空格代替tab會導致一些快捷鍵無法使用
" 可以嘗試用 c-j/k 來選擇
set expandtab
" 設置mapleader爲逗號
let mapleader=","
" 設置編碼
set encoding=utf-8
language messages zh_CN.utf-8
"}}}

" 全局變量------------------{{{
let g:author="yszc"
" }}}

 " 映射-------------------{{{
" C-W +j/k/l/h可以移動窗口光標,不用按多次w
" CTRL-A 是全選
nnoremap <c-a> ggvG
" 高亮開關
nnoremap <leader>hl :set hlsearch!<cr>
" 定義快速打開加載.vimrc和.vimrc.vundle文件
nnoremap <leader>ev :split $MYVIMRC<cr>
nnoremap <leader>sv :source $MYVIMRC<cr>
nnoremap <leader>ep :split $HOME/.vimrc.vundle<cr>
" nnoremap <c-e> :echo "hi"<cr>
" insert 模式括號匹配
" inoremap < <><esc>i
inoremap [ []<esc>i
inoremap { {}<esc>i
inoremap ( ()<esc>i
inoremap ' ''<esc>i
inoremap " ""<esc>i

" c-j/k映射成翻頁鍵
nnoremap <c-j> <c-f>
nnoremap <c-k> <c-b>

" H映射爲0,L映射爲$
nnoremap 0 <nop>
nnoremap $ <nop>
nnoremap H 0
nnoremap L $
vnoremap H 0
vnoremap L $
" 操作符號重映射
onoremap H 0
onoremap L $

" J/K向上/下移動一段?一頁?還是easymotion
" 方向鍵習慣改掉
nnoremap <Left> <nop>
nnoremap <Up> <nop>
nnoremap <Right> <nop>
nnoremap <Down> <nop>
inoremap <Left> <nop>
inoremap <Up> <nop>
inoremap <Right> <nop>
inoremap <Down> <nop>
" insert模式下方向鍵
inoremap <C-H> <Left>
inoremap <C-L> <Right>
inoremap <C-J> <Down>
inoremap <C-K> <Up>
" insert模式jk代替<esc>
" 將inoremap模式下的<esc>映射爲空導致了方向鍵和翻頁鍵亂碼的情況
inoremap <esc> <nop>
inoremap jk <esc>
" 快速保存,退出
nnoremap <C-S> :w<cr>
nnoremap <C-Q> :q<cr>
" 不能映射normal模式下的esc鍵,因爲方向鍵和翻頁鍵的前綴是esc
" 這會導致在鍵入方向鍵或翻頁鍵時退出,並且失靈
" nnoremap <esc> :q
"}}}

修改zsh和vim光標樣式(zsh改爲豎線,vim改爲方塊豎線切換):

參考:
https://blog.csdn.net/xiaohui5319/article/details/7507042
https://unix.stackexchange.com/questions/433273/changing-cursor-style-based-on-mode-in-both-zsh-and-vim
總結:
.zshrc中加入:

# 改變光標樣式爲豎線
echo -ne '\e[5 q'

.vimrc中加入:

" 自動命令組----------------{{{
" 光標切換
augroup cursor_switch
    autocmd!
    au InsertLeave * silent exec "! echo -ne '\e[1 q'"
    au InsertEnter * silent exec "! echo -ne '\e[5 q'" 
    au VimLeave * silent exec "! echo -ne '\e[1 q'"
    au VimEnter * silent exec "! echo -ne '\e[1 q'"
augroup END
" }}}

安裝並配置vundle(插件配置見下文)

新建.vimrc.vundle,粘貼下面的文本:(注意set rtp += 要包含正確的目錄)

   set nocompatible              " be iMproved, required
filetype off                  " required

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

" let Vundle manage Vundle, required
" 刪除或添加插件後要重新加載vimrc後執行vundle纔有效果
Plugin 'VundleVim/Vundle.vim'

Plugin 'morhetz/gruvbox'

Plugin 'scrooloose/nerdtree'

Plugin 'vim-airline/vim-airline'

Plugin 'Valloric/YouCompleteMe'

Plugin 'majutsushi/tagbar'

Plugin 'easymotion/vim-easymotion'

Plugin 'junegunn/fzf.vim'

Plugin 'yianwillis/vimcdoc'

Plugin 'SirVer/ultisnips'

Plugin 'scrooloose/nerdcommenter'

Plugin 'Chiel92/vim-autoformat'

Plugin 'Yggdroot/indentLine'
" Plugin 'haya14busa/incsearch.vim'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" 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

在.vimrc開頭加入下面代碼:

" 加載vundle配置文件
source $HOME/.vimrc.vundle

在vim執行

:PluginInstall

初步配置一些插件、主題和字體

下載DejaVu字體,將下載下來的ttf文件放入/usr/share/fonts中

字體下載參考:https://blog.csdn.net/devil_pull/article/details/17206377
vimrc寫法參考:https://stackoverflow.com/questions/20015138/how-to-set-font-to-be-dejavu-sans-mono-in-vim-for-xp

.vimrc中加入:

" 插件配置---------------{{{

" 主題字體----------------------------{{{
colorscheme gruvbox
set background=dark
set guifont=DejaVu\ Sans\ Mono:h12
" }}}


" nerdtree-------------------{{{
" q是退出
" F1觸發
nnoremap <F1> :NERDTreeToggle<cr>
" 打開文件時退出
let g:NERDTreeQuitOnOpen = 1
" }}}


"}}}

安裝youcompleteme

先用vundle安裝youcompleteme

Plugin 'Valloric/YouCompleteMe'

安裝過程參考官方教程 https://github.com/Valloric/YouCompleteMe#linux-64-bit

安裝過程總結:
我安裝了cmake llvm clang

sudo pacman -S cmake llvm clang

但是build-essential和python3-dev manjaro沒有,裝不了,(但沒發現有什麼影響)。
然後進入ycm目錄

   cd .vim/bundle/YouCompleteMe  

執行(我需要c++補全):

python3 install.py --clangd-completer

打開vim沒有出現ycm報錯信息,安裝成功

問題: 在vim中:PluginInstall 發現錯誤:no module named future 解決:
子模塊未安裝完整導致。進入YouCompleteMe目錄

cd .vim/bundle/YouCompleteMe   

使用以下命令可以更新所有子模塊。

git submodule update --init --recursive 

見文章http://www.jianshu.com/p/d908ce81017a?nomobile=yes

ycm C++配置(重點是.ycm_extra_config)

參考:
先完整閱讀官方user’s guide:https://github.com/Valloric/YouCompleteMe#option-2-provide-the-flags-manually
整體參考:https://blog.csdn.net/yangcs2009/article/details/45506749
整體參考:https://www.hahack.com/codes/cmake/
.ycm_extra_conf配置參考:https://www.jianshu.com/p/5aaae8f036c1
輸出編譯器默認包含目錄:https://blog.csdn.net/jing35030401/article/details/17303971
默認包含目錄的讀法:https://blog.csdn.net/yasi_xi/article/details/8833094

總結:
先配置ycm_conf文件以及vimrc,後期熟悉cmake再用cmake生成的database補全。
參考上文ycm.conf配置參考,將clang的默認包含目錄放到ycm.conf中,

具體步驟:
1.複製官網的.ycm_extra_conf示例文件到家目錄中,修改.ycm_extra_conf,添加 clang++的基本包含路徑(clang++的路徑與clang一樣)
修改後的.ycm_extra_conf:

from distutils.sysconfig import get_python_inc
import platform
import os
import subprocess
import ycm_core

DIR_OF_THIS_SCRIPT = os.path.abspath( os.path.dirname( __file__ ) )
# 注意爲了用vim打開.py文件時讀取到家目錄中的此文件導致第三方庫目錄錯誤的情況,並保證python complete調用的正確性,用絕對路徑來確定第三方庫目錄
DIR_OF_THIRD_PARTY = os.path.join('/home/yszc/.vim/bundle/YouCompleteMe/third_party' )
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]

# 下面的flag會在找不到compilation database時使用
# 根據具體情況來改變下面的flag
flags = [
# 編譯後顯示所有警告
'-Wall', 
# 顯示額外警告信息
'-Wextra',
# 所有的警告變爲錯誤,出現警告時也停止編譯
# '-Werror',
# 關閉long long警告
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
# 禁止assert()函數
'-DNDEBUG',
# You 100% do NOT need -DUSE_CLANG_COMPLETER and/or -DYCM_EXPORT in your flags;
# only the YCM source code needs it.
'-DUSE_CLANG_COMPLETER',
'-DYCM_EXPORT=',
# THIS IS IMPORTANT! Without the '-x' flag, Clang won't know which language to
# use when compiling headers. So it will guess. Badly. So C++ headers will be
# compiled as C headers. You don't want that so ALWAYS specify the '-x' flag.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
# 包含clang++所包含的include文件夾
'-isystem',
'/usr/include',
'-isystem',
'/usr/local/include',
'-isystem',
'/usr/lib/clang/8.0.0/include',
'-isystem',
'/usr/include/c++/8.3.0',
'-isystem',
'/usr/include/c++/8.3.0/x86_64-pc-linux-gnu',
'-isystem',
'/usr/include/c++/8.3.0/backward'
# 下面包含的是當前項目include目錄
# 包含當前目錄
'-I',
'.',
# ...
]

# Clang automatically sets the '-std=' flag to 'c++14' for MSVC 2015 or later,
# which is required for compiling the standard library, and to 'c++11' for older
# versions.
if platform.system() != 'Windows':
  flags.append( '-std=c++11' )


# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# You can get CMake to generate this file for you by adding:
#   set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''

if os.path.exists( compilation_database_folder ):
  database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
  database = None


def IsHeaderFile( filename ):
  extension = os.path.splitext( filename )[ 1 ]
  return extension in [ '.h', '.hxx', '.hpp', '.hh' ]


def FindCorrespondingSourceFile( filename ):
  if IsHeaderFile( filename ):
    basename = os.path.splitext( filename )[ 0 ]
    for extension in SOURCE_EXTENSIONS:
      replacement_file = basename + extension
      if os.path.exists( replacement_file ):
        return replacement_file
  return filename


def Settings( **kwargs ):
  if kwargs[ 'language' ] == 'cfamily':
    # If the file is a header, try to find the corresponding source file and
    # retrieve its flags from the compilation database if using one. This is
    # necessary since compilation databases don't have entries for header files.
    # In addition, use this source file as the translation unit. This makes it
    # possible to jump from a declaration in the header file to its definition
    # in the corresponding source file.
    filename = FindCorrespondingSourceFile( kwargs[ 'filename' ] )

    if not database:
      return {
        'flags': flags,
        'include_paths_relative_to_dir': DIR_OF_THIS_SCRIPT,
        'override_filename': filename
      }

    compilation_info = database.GetCompilationInfoForFile( filename )
    if not compilation_info.compiler_flags_:
      return {}

    # Bear in mind that compilation_info.compiler_flags_ does NOT return a
    # python list, but a "list-like" StringVec object.
    final_flags = list( compilation_info.compiler_flags_ )

    # NOTE: This is just for YouCompleteMe; it's highly likely that your project
    # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
    # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
    try:
      final_flags.remove( '-stdlib=libc++' )
    except ValueError:
      pass

    return {
      'flags': final_flags,
      'include_paths_relative_to_dir': compilation_info.compiler_working_dir_,
      'override_filename': filename
    }
  return {}


def GetStandardLibraryIndexInSysPath( sys_path ):
  for path in sys_path:
    if os.path.isfile( os.path.join( path, 'os.py' ) ):
      return sys_path.index( path )
  raise RuntimeError( 'Could not find standard library path in Python path.' )


def PythonSysPath( **kwargs ):
  sys_path = kwargs[ 'sys_path' ]
  for folder in os.listdir( DIR_OF_THIRD_PARTY ):
    if folder == 'python-future':
      folder = os.path.join( folder, 'src' )
      sys_path.insert( GetStandardLibraryIndexInSysPath( sys_path ) + 1,
                       os.path.realpath( os.path.join( DIR_OF_THIRD_PARTY,
                                                       folder ) ) )
      continue

    if folder == 'cregex':
      interpreter_path = kwargs[ 'interpreter_path' ]
      major_version = subprocess.check_output( [
        interpreter_path, '-c', 'import sys; print( sys.version_info[ 0 ] )' ]
      ).rstrip().decode( 'utf8' )
      folder = os.path.join( folder, 'regex_{}'.format( major_version ) )

    sys_path.insert( 0, os.path.realpath( os.path.join( DIR_OF_THIRD_PARTY,
                                                        folder ) ) )
  return sys_path

2.在vimrc中添加ycm配置

" youcompleteme---------------{{{
" C語義補全
let g:ycm_global_ycm_extra_conf = '~/.ycm_extra_conf.py'
" python語義補全
let g:ycm_python_binary_path = '/usr/bin/python3'
" GoTo映射
nnoremap <leader>g :YcmCompleter GoToDefinitionElseDeclaration<cr>
" 停止提示是否載入本地ycm_extra_conf文件
let g:ycm_confirm_extra_conf = 0
" 語法關鍵字補全
let g:ycm_seed_identifiers_with_syntax = 1
" 開啓 YCM 基於標籤引擎
let g:ycm_collect_identifiers_from_tags_files = 1
" 從第2個鍵入字符就開始羅列匹配項
let g:ycm_min_num_of_chars_for_completion=2
" 在註釋輸入中也能補全
let g:ycm_complete_in_comments = 1
" 在字符串輸入中也能補全
let g:ycm_complete_in_strings = 1
" 註釋和字符串中的文字也會被收入補全
let g:ycm_collect_identifiers_from_comments_and_strings = 1
" 錯誤和警告符號
let g:ycm_error_symbol = '✘'
let g:ycm_warning_symbol = '►'
" 打開錯誤和警告表
noremap <F4> : YcmDiags<CR>
"}}}

安裝過程中的問題:編輯.py文件時報錯找不到/home/yszc/third_party的情況,通過:YcmDebugInfo看到錯誤報告在/tmp/中,查之,發現在我主目錄中的.ycm_extra_conf.py報錯,原來python補全器需要調用.ycm_extra_conf中的PythonSysPath函數而該函數需要一個第三方庫路徑,但是該路徑是通過當前腳本路徑+/third_path來讀取的,這導致在打開python文件時,ycm會發現/home/user/third_party目錄不存在,爲防止此問題,將家目錄中的庫目錄改爲ycm內的絕對路徑,(該文件就是從ycm目錄裏拷貝出來的),修改家目錄中的.ycm_extra_conf.py中第8行如下:

# 注意爲了防止子目錄用vim打開.py文件時讀取到家目錄中的此文件導致第三方庫目錄錯誤的情況,爲保證python complete調用的正確性,用絕對目錄來確定第三方庫目錄
    DIR_OF_THIRD_PARTY = os.path.join('/home/yszc/.vim/bundle/YouCompleteMe/third_party' )

ycm python配置

.py文件中輸入:YcmShowDetailedDiagnostic
出現:

NoDiagnosticSupport: YCM has no diagnostics support for this filetype; refer to Syntastic docs
 if using Syntastic.

參考:https://groups.google.com/forum/#!topic/ycm-users/feF1hauaJ14
ycm沒有提供python診斷的功能

ycm python第三方庫補全:
參考:https://github.com/Valloric/YouCompleteMe#python-semantic-completion
~/.ycm_extra_config.py中的:

def Settings(**kwargs):

函數中的return中加入:(注意是最後一個return不是if中的return!)

return {
        # 第三方庫添加
        'sys_path': ['/home/yszc/.local/lib/python3.7/site-packages']
    }

第三方庫目錄位置的查找用

pip show yourpackage

來查找

ctags tagbar 安裝與配置

安裝ctags:

sudo pacman -S ctags

安裝tagbar:

Plugin 'majutsushi/tagbar'

vimrc添加:

" tagbar-----------------------{{{
" tagbar的q是退出
" 設置觸發按鍵
noremap <F2> : TagbarToggle<cr>
" 設置tagbar要使用的ctags路徑
let g:tarbar_ctags_bin = '/usr/bin/ctags'
" 設置窗口寬度
let g:tarbar_width = 30
" 顯示在窗口右邊
let g:tarbar_right = 1
" 開啓自動預覽
let g:tagbar_autopreview = 1
" 光標自動切換到tagbar中
let g:tagbar_autoclose = 1
" }}}

安裝快速移動插件EasyMotion

介紹
EasyMotion在觸發時,會爲附近的單詞。。。隨機標上符號,只要按下對應的符號就能跳轉到對應的位置,教程參考:https://github.com/easymotion/vim-easymotion , http://www.wklken.me/posts/2015/06/07/vim-plugin-easymotion.html#yong-fa-1-tiao-zhuan-dao-dang-qian-guang-biao-qian-hou-de-wei-zhi-wb

步驟:

 Plugin 'easymotion/vim-easymotion'

默認雙leader鍵觸發,改爲單leader鍵,vimrc中加入:

map <Leader> <Plug>(easymotion-prefix)
nmap J <Plug>(easymotion-j)
nmap K <plug>(easymotion-k)
nmap W <Plug>(easymotion-w)
nmap B <Plug>(easymotion-b)

vim設置ctrl-s保存 ctrl-q退出:

ctrl-s是終端默認鎖屏鍵,要禁止掉。
參考:http://ju.outofmemory.cn/entry/42007
在.zshrc中加入:

stty -ixon

在vimrc中加入:

nnoremap <C-S> :w<cr>
nnoremap <C-Q> :q<cr>

模糊搜索神器fzf安裝:

參考:https://segmentfault.com/a/1190000011328080
配置參見: https://blog.csdn.net/Demorngel/article/details/85464796
步驟:
下載安裝fzf:

git clone https://github.com/junegunn/fzf.git 
./install

安裝後發現無法使用(E121 E117),所以刪除:

./uninstall

使用pacman下載:

sudo pacman -S fzf

vim下載安裝fzf.vim,在.vimrc.bundle中配置:

set rtp+=/home/username/.fzf/
    Plugin 'junegunn/fzf.vim'

教程介紹參考:https://segmentfault.com/a/1190000016186540?utm_source=tag-newest#articleHeader2
總結:
1。 :Files 遞歸搜索當前目錄中的文件名
2。 :Buffers 搜索Buffer中的文件名,常用於標籤切換
3。 :Lines 搜索Buffer文件中的行內容
4。:BLines搜索當前Buffer中的行內容
5。爲了能在當前目錄中搜索行內容,採用ripgrep加腳本的形式:
先下載ripgrep:

sudo pacman -S ripgrep

vimrc寫入:

" fzf-----------------------{{{
" esc是退出
"雙<Leader>f在當前目錄搜索文件
nnoremap <silent> <Leader><Leader>f :Files<CR>
"雙<Leader>b切換Buffer中的文件
nnoremap <silent> <Leader><Leader>b :Buffers<CR>
"雙<Leader>p在當前所有加載的Buffer中搜索包含目標詞的所有行,:BLines只在當前Buffer中搜索
nnoremap <silent> <Leader><Leader>l :Lines<CR>
"雙<Leader>h在Vim打開的歷史文件中搜索,相當於是在MRU中搜索,:History:命令歷史查找
nnoremap <silent> <Leader><Leader>h :History<CR>
"雙<Leader>r利用ripgrep搜索當前文檔中的行
nnoremap <silent> <Leader><Leader>r :Rg<CR>
"調用Rg進行搜索,包含隱藏文件
"command! -bang -nargs=* Rg
  \ call fzf#vim#grep(
  \   'rg --column --line-number --no-heading --color=always --smart-case --hidden '.shellescape(<q-args>), 1,
  \   <bang>0 ? fzf#vim#with_preview('up:60%')
  \           : fzf#vim#with_preview('right:50%:hidden', '?'),
  \   <bang>0)
" }}}

控制檯分屏tmux安裝

sudo pacman -S tmux

Oh My Tmux主題安裝:

$ cd
$ git clone https://github.com/gpakosz/.tmux.git
$ ln -s -f .tmux/.tmux.conf
$ cp .tmux/.tmux.conf.local .

然後閱讀~/.tmux.conf 瞭解各快捷鍵的用處。

配置教程參考:https://www.cnblogs.com/cherishry/p/5674518.html
學習教程:https://www.cnblogs.com/maoxiaolv/p/5526602.html
更好的教材:https://www.cnblogs.com/oxspirt/p/10218284.html

學習總結:
快捷鍵:
1。創建會話:

tmux new -s <name-of-my-session>

在tmux中按下 prefix 加冒號(:)
輸入:

new -s <name-of-my-new-session>

從而再創建一個新的會話。

prefix+s可以瀏覽已經創建的會話
若tmux會話已經創建但tmux尚未執行,使用:

  tmux attach    

可以進入之前創建的會話。

2.創建窗口
prefix+c 創建新窗口
prefix+number 切換到指定編號的窗口
prefix+%或"在窗口中分割出窗格
(窗口是個窗格容器,你可以將多個窗格放置在窗口中)
總之,一個tmux會話包含多個窗口,一個窗口可以包含多個窗格

vim中文文檔

參考:https://github.com/yianwillis/vimcdoc
查看vim編碼:

:set enc?

發現是utf-8.
在.vimrc.vundle中加入

Plugin 'yianwillis/vimcdoc'

:PluginInstall即可。

安裝UltiSnips,代碼塊插入神器

參考:https://blog.csdn.net/solomonxiewise/article/details/85916085
安裝配置步驟:
vundle寫入:

Plugin 'SirVer/ultisnips'

vimrc寫入:

 " ultisnips-----------------{{{
" 指定snipper存儲文件夾
let g:UltiSnipsSnippetDirectories=['UltiSnips']
" 此鍵默認爲tab,會導致you_complete_me混亂,一定要改
let g:UltiSnipsExpandTrigger="<c-e>"
" 展開可用snips表
let g:UltiSnipsListSnippet="<c-i>"
" 只會在打開時映射下面的跳轉鍵,應該不會影響之前的映射
let g:UltiSnipsJumpForwardTrigger="<c-j>"
let g:UltiSnipsJumpBackwardTrigger="<c-k>"
" 指定python版本,py2.7 或者 py3.6
let g:UltiSnipsUsePythonVersion = 3
" 編輯snips窗口以分割窗口打開,此操作會在當前目錄創建UltiSnips文件夾並新建.snippets文件
let g:UltiSnipsEditSplit="vertical"
" }}}

出現問題:ExpandTrigger無效
參考:http://www.itboth.com/d/aYBfAr/python-snippet-youcompleteme-vim
參考:https://blog.csdn.net/solomonxiewise/article/details/85916085 解決:

必須在ultisnips文件夾下創建一個UltiSnips文件夾,將所有自定義代碼都放在這裏。

如何自定義請見:https://github.com/SirVer/ultisnips 裏面的視頻教材(kxsw)
snips教程:https://blog.51cto.com/10245818/2167828
高級snips需要python和正則表達式知識,後面要看看基本python語法和snips正則表達式

但目前就先從honza/vim-snippet項目複製一些代碼配置一些基本的snippet:

自定義總結:
首先:

cd ~/.vim/bundle/ultisnips/
mkdir UltiSnips
cd UltiSnips
vim snippets.snippets

加入

   # snippet代碼塊
    snippet usnip "ultisnips snippet definition" b
    `!p snip.rv = "snippet"` ${1:trigger} "${2:description}" ${3:b}
    ${0:${VISUAL}}
    `!p snip.rv = "endsnippet"`
    endsnippet

用於快速擴展snippet定義代碼塊

1.創建c++補全文件:

vim cpp.snippets

(目前cpp.snippets可以正確的匹配.cc .cpp .h文件,但cc.snippets不行)
加入:(參考了google c++ 編碼規範和honza/vim-snippet的代碼)

# python函數配置
global !p
def get_args(arglist):
	args = [arg.strip() for arg in arglist.split(',') if arg]
	return args

def write_docstring_args(arglist, snip):
	args = str(arglist).split(',')

	if len(args) > 1:
		c = 0
		for arg in args:
			if c == 0:
				snip.rv += arg
				c = 1
			else:
				snip += '*       : %s' % arg.strip()
	else:
		snip.rv = args[0]
endglobal

# 代碼塊

#文件頭作者信息
snippet head "file header" b
/*
* File:             `!p snip.rv = fn`
*
* Author:           `echo $USER`  
* Created:          `date +%m/%d/%y` 
* Description:      ${4:${VISUAL}}
* Encoding:			    `!v &fileencoding`
*
*/
${0}
endsnippet

#函數定義與實現
snippet fun "Function Header" 
/*
* Description:      ${4:${VISUAL}}
*/
${1:ReturnType} ${2:FunctionName}(${3:param}){
	${0}
}
endsnippet

#main函數
snippet main "main() (main)"
int main(int argc, char *argv[])
{
	${VISUAL}$0
	return 0;
}
endsnippet

# 頭文件保護
snippet #ifndef "#ifndef ... #define ... #endif"
#ifndef ${1/([A-Za-z0-9_]+).*/$1/}
#define ${1:SYMBOL_H_} 
$2
#endif /* ifndef $1 */
endsnippet

# 頭文件註釋
snippet include_order "include order tip" b
//本類聲明

//C系統文件

//C++系統文件

//外部庫頭文件

//本項目頭文件

endsnippet

# 讀取文件名構造類的頭文件,文件名,以下劃線讀取文件名稱並整合到類名上
snippet h_p "An entire .h generator" b
/*
* File:             `!p snip.rv = fn`
*
* Author:           `echo $USER`  
* Created:          `date +%m/%d/%y` 
* Description:      ${1:None}
* Encoding:			    `!v &fileencoding`
*/

//確保header guard宏名永不重複
#ifndef ${3:`!v substitute(Vim_snippets_filename('$1_H_','ClassName'),'.*','\U&\E','')`}
#define $3

//C系統文件

//C++系統文件

//外部庫頭文件

//本項目頭文件

//前置聲明


class ${2:`!v substitute(substitute(Vim_snippets_filename('$1','ClassName'),'^.','\u&',''), '_\(\w\)', '\u\1', 'g')`}
{
 private:
	$4

 public:
	$2();
	virtual ~$2();
};

#endif /* $3 */
endsnippet

snippet class "a single class" b
class $1
{
 private:
	$2

 public:
	$1();
	virtual ~$1();
}
endsnippet

# 存取函數 默認類成員變量以下劃線結尾
snippet set "set template 小寫" b
void set_${1:param_name}(${2:type} $1){ this->$1_ = $1; }
endsnippet

snippet get "get template 小寫" b
${1:type} get_${2:param_name} const (){ return this->$2_; }
endsnippet

# 類函數定義
snippet cla_fun_dec "class function declare 大寫" b
/*
* @brief: ${5:功能概述:輸入輸出(功能)、是否分配了需要調用者釋放的空間、是否會修改或釋放引用參數}
*/
${1:ReturnType} ${2:FunctionName}(${3:param})
{
	${0:FunctionBody}
}
endsnippet

# .cc預編碼
snippet cc_p "cc precode" b
//本類聲明
#include "${1:Header}.h"
//C系統文件

//C++系統文件

//外部庫頭文件

//本項目頭文件


namespace{
$2
}
endsnippet

# .cc類函數定義
snippet cla_fun_def "class function define" b
/**
* @brief: ${5:實現概述}
*/
${1:ReturnType} ${4:`!v substitute(substitute(Vim_snippets_filename('$1','ClassName'),'^.','\u&',''), '_\(\w\)', '\u\1', 'g')`}::${2:FunctionName}(${3:param})
{
	${0:FunctionBody}
}
endsnippet


# to do
snippet todo "todo 註釋" b
//TODO(yszc):$1
endsnippet

# if
snippet if "單獨一個if" b
if (${1}) {
	${2}
} 
endsnippet

# ifel
snippet ifel "if else" b
if (${1}) {
	${2}
} else {
	${3}
} 
endsnippet

# elif
snippet elif "else if" w
else if ($1) {
	$2
} 
endsnippet

# else
snippet else "else" w
else {
	$1
} 
endsnippet

# while
snippet while "while" b
while ($1) {
	$2
} 
endsnippet

# for
snippet for "for" b
for (${1: }; ${2: }; ${3: }) {
	$4
}
endsnippet

# switch
snippet switch "switch" b
switch ($1) {
	case $2: {
		$3
	break;
	}
	default: {
		$4
	}
}
endsnippet

然後隨便新建一個.h或.cc .cpp後綴的文件,ycm會自動顯示ultisnip選擇,按下ctrl-e就可擴展

2.python代碼塊以後再配置:

nerdcommenter 代碼註釋插件

.vimrc.vundle中添加:

Plugin 'scrooloose/nerdcommenter'

:PluginInstall
用法:
緊靠着添加註釋

 <leader>cc

最左側添加註釋

<leader>cb

取消註釋

<leader>cu

vimrc中加入:

" nerdcommenter-------------------{{{
" <leader>cc 緊貼當前行添加註釋
" <leader>cb 緊貼左側行添加註釋
" <leader>cu 取消註釋
" 註釋自動添加空格
let g:NERDSpaceDelims=1
" }}}

自動格式化插件 vim-autoformat

參考:https://blog.csdn.net/demorngel/article/details/69053613
參考:https://blog.csdn.net/SimpleForest/article/details/77429744
參考:https://github.com/Chiel92/vim-autoformat
步驟:
.vimrc.vundle加入:

Plugin 'Chiel92/vim-autoformat'

:PluginInstall
下載astyle(c c++ java)和autopep8(python)

sudo pacman -S astyle
sudo pacman -S autopep8

vimrc中加入:

" vim-autoformat-------------------{{{
" 定義astyle c++代碼格式化風格
" 對指定後綴的文件名,使用指定的c++格式化工具,設置c++代碼風格爲google,縮進設爲2空格,節省橫向空間。
let g:formatdef_my_cpp = '"astyle --style=google --indent=spaces=2"'
let g:formatters_cpp = ['my_cpp']
" F12觸發自動格式化
noremap <F12> :Autoformat<cr>

augroup autoformat
  autocmd!
" 最好不要將所有文件都進行保存格式化,比如.snippets文件不能格式化,不然你的代碼塊會亂掉
    au BufWrite *.h,*.cpp,*.cc,*.cxx,*.py :Autoformat
augroup END
" }}}

indentLine顯示縮進線

參考:https://segmentfault.com/a/1190000014560645
.vimrc.vimrc加入

Plugin 'Yggdroot/indentLine'

.vimrc加入:

" indentLine-----------------{{{
let g:indentLine_noConcealCursor = 1
" 這個顏色正好是灰色,0就看不見了
let g:indentLine_color_term = 239
let g:indentLine_char = '|'
" }}}

以後待研究。

airline配置安裝

安裝:

Plugin 'vim-airline/vim-airline'

問題:出現亂碼,且沒有箭頭。
試了試官網的解決方案:

The powerline font symbols are partially messed up
You are likely
using the fontconfig method. If that is the case, you need to override
the space character like so:

if !exists('g:airline_symbols')
  let g:airline_symbols = {}
endif
let g:airline_symbols.space = "\ua0"

The powerline font symbols are not showing up Adding let
g:airline_powerline_fonts = 1 to your vimrc will automatically
populate the g:airline_symbols dictionary with the proper font glyphs
for various symbols.

The powerline font is not perfectly lined up, or there a bit of
whitespace in between symbols, or they are cut off(和字體有關)

If you are using fontconfig, make sure bitmap fonts are not disabled.
That rule, if exists, is usually under
/etc/fonts/conf.d/70-no-bitmaps.conf for linux users, which might be a
symbolic link. If that’s the case, remove that link so that bitmap
fonts are available system-wide.
(參考這裏,我將70-no-bitmaps.conf做了備份然後刪掉了,沒啥改觀)

Also make sure Terminal uses the same font style (e.g. Meslo) as
specified in your vimrc. (參考這裏,我將終端字體改成了和vim相同的DejaVu字體)

結果:出現了箭頭,但還是有些奇怪的亂碼。箭頭有小空隙但無傷大雅。

安裝autopairs

Plugin 'jiangmiao/auto-pairs'

:PluginInstall

附錄:閱讀過程中提出的問題:
參考插件大全:https://blog.csdn.net/u010826976/article/details/38659541
註釋鍵

用cmake管理compilation database:
先學一邊cmake教程:https://cmake.org/cmake-tutorial/

c++代碼規範空格

tab鍵要不要改?要:tab鍵不變,c-j c-k改爲上下翻動
錯誤提示欄常顯示:
視頻網站:http://vimcasts.org/
goto :

診斷:

git:

以src爲截斷點提供.cc頭文件

baskspace有4個空格一次退四格,先找插件

vim自動規範代碼加空格,先找插件

vim撤銷的太多了

系統時間還是有問題

vim括號高亮太噁心了

括號相關的操作

vim搜索,輸入時無法自動高亮

g:ycm_collect_identifiers_from_tags_files的意思

g:ycm_seed_identifiers_with_syntax的意思

EasyMotion特性探索

fzf特性探索

能否讓ycm左側的錯誤提示欄一直顯示,錯誤提示能不能是下劃線

vim語句沒顏色

EasyMotion 雙leader改單leader,其他鍵換成ctrl開頭

vimrc example研讀

終端粘貼快捷鍵盤

研讀vim help中文文檔

rm功能太垃圾要改!!!

vim cmdline 按下tab沒有補全表提示

ycm tab鍵,c-j c-k 同模式

python+正則 ultsnip進階

在插入模式下也可以c-s

.cc文件按照源代碼目錄樹截斷

fzf example研讀:https://github.com/junegunn/fzf/wiki/examples

參考以下配置:https://segmentfault.com/a/1190000002662054

好用vim插件參考:https://vimawesome.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章