VIM的使用手册
VIM的四种模式
正常模式:
进入VIM后默认的状态是正常模式。
命令模式:
一般是执行ex命令,在正常模式下输入“:”, “/” ,”?”等字符进入命令模式。
插入模式:
编辑命令就可以进入插入模式,如在正常模式下输入i、a、o、I、O、P等字符进入插入模式。
可视模式:
用于选择文本块,如在正常模式下输入v, 按字符选择;输入V,按行选择;按Ctrl+V,按块选择。按两次Esc退出可视模式。
VIM的操作
打开、进入
指令 | 作用 |
---|---|
vim file | 创建file文件 |
vim file1 file2 … | 创建多个文件 |
vim + file | 打开文件file,将光标定位到文件最后一行 |
vim +n file | 打开文件file,将光标定位到第n行 |
vim +/pattern file | 打开文件file,将光标定位到第一个匹配的pattern的行 |
退出、保存文件
指令 | 作用 |
---|---|
:wq ZZ :x | 保存文件、退出vim |
:w :w! | 保存当前文件,!表示忽略写保护 |
:w newfile | 将文件另存为newfile |
:20,100w newfile | 将当前文件的20-100行的内容存到新文件newfile中 |
:20,100>>newfile | 将当前文件的20-100行的内容追加到文件newfile中 |
:q :q! | 不保存退出文件,!表示不保存强行退出 |
Q | 退出vim,进入Ex模式 |
:e newfile | 不离开vim,直接编辑newfile新文件 |
:n | 切换到下一个文件进行编辑(多文件编辑的情况) |
移动光标
指令 | 功能 |
---|---|
h,j,k,l | 光标分别向左、下、上、右移动一个字符,而:5h光标向左移动5个字符 |
3h | 表示光标向左移动3个字符 |
w,W,b,B | w,W移动到下一个单词,b,B移动到前一个单词 |
3w,3b | 3w向后移动3个单词,3b向前移动3个单词 |
),( | “)” 移动到下一句的句尾, “(” 移动到上句的句首 |
:n | 光标移动到第n行 |
nG | 光标移动到第n行 |
gg | 移动到文件的开始 |
G | 移动到文件的末尾 |
[Ctrl + G] | 显示文件的总行数、当前行号、列号信息 |
Enter | 向下移动一行 |
0,$ | 光标移动到当前行首,行尾 |
编辑
命令 | 功能 |
---|---|
插入 | |
i, a | 光标之前,之后插入文字 |
I, A | 在当前行的行首、行尾插入文字 |
o, O | 在当前行之下,之上新建一行,插入文字 |
修改 | |
r | 替代单个字符 |
R | 替代文字 |
cw | 修改单词,如:3cw修改3个单词 |
cc | 修改当前行 |
s | 替代:删除当前字符,插入新的字符 |
S | 替代:删除当前行,插入新内容 |
删除 | |
x, X | 删除光标所在的位置,光标之前的字符:而:5x删除5个字符 |
dw | 删除光标所在的位置的单词,而:2dw或d2w删除2个单词 |
dd | 删除当前行,而:5dd或d5d删除5行 |
D | 删除光标所在的位置到行尾的所有内容 |
复制(yank) | |
yw | 复制单词,而:3yw或y3w复制3个单词 |
yy | 复制当前行,而:2yy或y2y复制2行 |
粘贴 | |
p(小写) | 将删除、复制的内容插入到光标所在的位置之后 |
P(大写) | 将删除、复制的内容插入到光标所在的位置之前 |
其他命令 | |
. | 重复上一次的编译命令 |
u, U | 撤销上一次操作,恢复当前行 |
样式匹配及替换
命令 | 功能 |
---|---|
当前行匹配 | |
:s/pattern/new-str/ | 将当前一行中的第一个匹配的pattern字符串替换为new-str |
:s/pattern/new-str/g | 将当前行中所有匹配pattern的字符串替换为new-str |
指定范围匹配 | |
:5,26s/pattern/new-str/g | 将5-26行中所有匹配的pattern的字符串替换为new-str |
全局范围匹配 | |
:%s/pattern/new-str/g | 将整个文件中所有匹配pattern的字符串替换为new-str,%代表所有行 |
:g/pattern/s/old/new/g | 在整个文件中,将匹配的pattern的行中所有的old替换为new |
显示所有匹配 | |
:g/pattern/p | 显示所有匹配到的样式,g表示全局,p代表打印 |
与shell的交互
命令 | 功能 |
---|---|
:sh | 切换到shell |
Ctrl+D | 在shell环境中按Ctrl+D返回vim |
:! command | 在vim中临时执行shell命令 |
VIM配置文件的优化
配置 | 功能 |
---|---|
set nu | “显示行号 |
color asmaniana | “设置背景主题 |
syntax on | “语法高亮 |
set background=dark | “背景使用黑色 |
set encoding=utf-8 | “设置编码方式 |
set tabstop=4 | “设置tab键的宽度为4 |
set softtabsstop=4 | “统一缩进宽度为4 |
set wrap | “自动换行 |
set autoindent | “自动对齐 |
set smartindent | “智能对齐 |
set showmatch | “设置显示匹配 |
set mouse=a | “在GUI坏境中允许鼠标操作 |
set smartcase | |
set expandtab | “用space 来代替 tab |
set backspace=eol,start,indent | “设置退格键 |
VIM安装插件
示例:安装YouCompleteMe插件
Linux Ubuntu X64安装方法
准备环境
确保vim的版本高于7.3.598,并且支持python2和python3。
补充: 使用vim -version查看版本号,在vim编辑器中使用:echo
has(“python”)的Ex命令,显示1则标志支持Python,显示0则不支持。
安装Vundle
在普通用户下使用命令:
$ git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle
/Vundle.vim
配置.vimrc文件
如果.vimrc文件没有,则在自己用户目录下新建一个.vimrc。
然后在.vimrc里面新增加一条:
Plugin ‘Valloric/YouCompleteMe’
安装YouCompleteMe插件
在Bash下输入vim +PluginInstall +qall 或者进入vim,输入:PluginInstall
这个时候我们可以开始看见在VIM中正在处理YouCompleteMe插件。
安装工具
$ sudo apt-get install build-essential cmake
$ sudo apt-get install python-dev python3-dev
编译YCM支持C系列语言
$ cd ~/.vim/bundle/YouCompleteMe
$ .install.sh –clang-completer
这个过程会自动安装clang,时间稍微有点长。
补充: 如果图简单,那么可以直接./install.sh -all,这样所有的语言支持都安装上了。
配置.vimrc文件
let g:ycm_global_ycm_extra_conf='~/.ycm_extra_conf.py'
let g:ycm_collect_identifiers_from_tag_files = 1
let g:ycm_seed_identifiers_with_syntax = 1
let g:ycm_confirm_extra_conf=0
let g:ycm_key_invoke_completion = '<C-/>'
nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>
拷贝到.ycm_extra_conf.py文件
拷贝一下内容,到普通用户目录的.ycm_extrea_conf.py
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
# You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM
# source code needs it.
'-DUSE_CLANG_COMPLETER',
# THIS IS IMPORTANT! Without a "-std=<something>" 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
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++11',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-isystem',
'../BoostParts',
'-isystem',
# This path will only work on OS X, but extra paths that don't exist are not
# harmful
'/System/Library/Frameworks/Python.framework/Headers',
'-isystem',
'../llvm/include',
'-isystem',
'../llvm/tools/clang/include',
'-I',
'.',
'-I',
'./ClangCompleter',
'-isystem',
'./tests/gmock/gtest',
'-isystem',
'./tests/gmock/gtest/include',
'-isystem',
'./tests/gmock',
'-isystem',
'./tests/gmock/include',
]
# 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
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
if not working_directory:
return list( flags )
new_flags = []
make_next_absolute = False
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith( '/' ):
new_flag = os.path.join( working_directory, flag )
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompilationInfoForFile( filename ):
# The compilation_commands.json file generated by CMake does not have entries
# for header files. So we do our best by asking the db for flags for a
# corresponding source file, if any. If one exists, the flags for that file
# should be good enough.
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists( replacement_file ):
compilation_info = database.GetCompilationInfoForFile(
replacement_file )
if compilation_info.compiler_flags_:
return compilation_info
return None
return database.GetCompilationInfoForFile( filename )
def FlagsForFile( filename, **kwargs ):
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object
compilation_info = GetCompilationInfoForFile( filename )
if not compilation_info:
return None
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ )
# 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
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
return {
'flags': final_flags,
'do_cache': True
}
VIM常见问题
在Vim中保存修改后的只能写的文件
使用:w !sudo tee %
w 写文件
!sudo 调用shell指令sudo
tee 将写输出(vim :w)重定向,%代表当前文件
在Vim中Insert模式下,退格键不删除字符
在Vim中,backspace有几种工作模式,默认是vi兼容的。
可以使用set backspace=indent,eol,start
indent 退格键可以删除字段缩进
eol 插入模式下,backspace将两行合并
start 要删除此次插入前的输入