原文: https://computers.tutsplus.com/tutorials/basic-vim-configuration--cms-21498

原来,vim的配置文件,.vimrc也是一种类似于shell ,javascript 的脚本语言。叫做vimScript

Functions are very useful in the .vimrc file. Since the Vim’s configuration files use a full programing language, I will from here out refer to it’s true name: VimScript.

-------------------------------------------------------

After studying Vim for Beginners, you’ll have seen that the relative line numbering for your files do not survive a reload. Though this behaviour can be defined in the Vim configuration file.

The .vimrc File

All of Vim configuration information is in the .vimrc file found in the home directory. You can open it with the edit file command from inside Vim:

1
:e ~/.vimrc

This file is empty because it has not been used. This tutorial will show you how to use it.

Commenting Code

Before you insert any code, you should document what is done. You might know what you are doing right now, but a month from now is a different matter. Always comment the code so that when you come back to it you’ll be reminded of why you coded something.

For the .vimrc file, anything after a double quote to the end of a line is not used. Therefore, you can put anything there to help you remember what you did.

1
set number  "This turns on line numbering

Now you will always know that the set number command turns on line numbering.

Options and Variables

To turn on line numbers and relative numbering, you need to put this in to the .vimrc file:

1
2
set number          "This turns on line numbering
set relativenumber  "This turns on relative numbering

Save that and you no longer have to think about it. Every time Vim opens a file, it will now show relative line numbers. The set command sets any option that is in Vim. An option is turned off by setting the opposite option. Opposite options are the same as the option with no in front.

Use the following to turn off line numbering and relative numbering:

1
2
set nonumber            "This turns off line numbering
set norelativenumber    "This turns off relative numbering

Don’t put both sets in to the .vimrc file. That will turn it on and back off. In a little bit, I will show you how to do that more programmatically.

If you already know the state of an option, toggling the option is another way to set the option. Options are toggled by putting a ! after the option name. This toggles on/off the options:

1
2
set number!             "This toggles the value of number
set relativienumber!    "This toggles relative line numbers

If the current state of an option is needed, use a ? after the option name. In Vim, type:

1
set number?

It will return number. This enables you know the state of the option.

If you want to change the number of columns that the line number area shows, you can set the numberwidth to a value. The following will set the column width to 4:

1
set numberwidth=4       "Set the line numbers to 4 spaces

Try it out and see how many spaces you like and set that in to the .vimrc file.

If you need a variable, variables are created using the let statement. For example:

1
let name = "Richard Guay"   "Set my name in to the name variable

When you save that in the .vimrc file (but use your own name), it can displayed in command mode with :echo name.

Seeing the Variable name

Options are treated as a variable by prefixing the option with an &. Options can be printed by:

1
:echo &numberwidth

The echo command is only for variables, but the prefixing an option with an & tells Vim to treat the option as a variable. This enables you to use the option’s value in math. Therefore, to increase the line number area width by one is done by using

1
:let &numberwidth = &numberwidth + 1

An echo &numberwidth should now show 5.

All variables have their scope as well. Scope is defined by a letter, :, and the variable name. Undefined scope is treated as global scope. The different scopes are:

b: Buffer scope—Only usable from within the current buffer
w: Window scope—Only available from the current window
t: Tab page scope—Only available in the tab page
g: Global scope—available everywhere
l: Local scope—available locally to that function defined
s: Source scope—available only within the sourced file
a: Argument scope—only available within the function
v: Global scope—used to refer to a variable defined and used by Vim

The proper definition for the name variable using global scope is:

1
let g:name = "Richard Guay" "Set my name in to the name variable

Getting Information

Now that you know how to set options and variables, you might wonder how do you find out the different options. Searching the web is one option, but the information is in Vim. Type:

1
:set all

And Vim will show every option in the program. Typing the :let and an enter will show all of the variables.

The :help command is used to lookup the extensive documentation built into Vim. To get out of :help, use :q. In help mode, this does not exit the program, but puts the editor in to normal mode.

Functions

Functions are very useful in the .vimrc file. Since the Vim’s configuration files use a full programing language, I will from here out refer to it’s true name: VimScript.

In VimScript, define a function using:

1
2
3
function <function name>()
    <function body>
endfunc

I love the line numbering and relative numbering, but sometimes you do not want relative numbering. Typing the full string :set norelativenumber or even :set relativenumber! is a lot of typing. A function to turn it on and off would be good.

1
2
3
function TRelative()
    set relativenumber!
endfunc

A function is run with the :call command.

1
:call TRelative()

The function command does not allow you to overwrite an already defined function. If that function was already defined somewhere else or you tried to reload the file again, Vim will error and stop processing the file at that point. If you use the function! command, it will overwrite the function without an error. It is good programming practice in VimScript to mostly use function!.

To turn off all numbering, a function can be created to do that and it’s opposite. Add this to the .vimrc:

1
2
3
4
5
6
7
8
9
function! NoNumber()
    set nonumber
    set norelativenumber
endfunc
 
function! Numbers()
    set number
    set relativenumber
endfunc

To pass parameters to a function, you place a variable name inside the parenthesis. For example:

1
2
3
function! Hi( name )
    echo "Hello" a:name
endfunc

As you see, you have to scope variables that are arguments of a function. When you call the function now with a name, you will get

1
2
:call Hi( "Richard" )
Hello Richard

Basic Key Mapping

One of the most important uses for the configuration file is to setup key mappings. For example, you toggle relative numbers on and off a whole lot. Instead of typing :call TRelative all the time, a hotkey is much faster. To do that, the map command will help.

1
map <c-t> :call TRelative()<cr>

With this line in the .vimrc file, you can now type Control-T and the relative numbering will toggle on and off. Try it out by making a mapping for toggling all line numbering.

Key maps are not just for normal mode, but for every mode. If you prefix the command with the first letter of a mode, it will map the key for that mode. nmap also maps for normal modevmap maps for visual modeimap maps for insert mode.

Now that you know these command, forget them. These commands can be dangerous. If you remap a key again, it will use the new mapping and can create an infinite loop in the mappings.

To prevent that happening, you need to add nore after the mode and before the map. Therefore, nmap is nnoremapvmap is vnoremap, and imap is inoremap. These use the default mapping for any key command you reference in the macro. These are much safer to use in the configuration file.

Conclusion

In this tutorial I have shown you the basics of creating a Vim configuration file. I have shown you how to: comment the configuration file, set/unset options and variables, create basic functions, and mapping keyboard shortcuts. The best way to remember is by practicing.

------------------------------------------------------------------------------------------------------------

Install and setup vim on Ubuntu 14.04

<note> I have upgraded to Ubuntu 16.04 and wrote another post about setting up vim, this time using vundle instead of pathogen. Checkout the new post– vim and vundle on Ubuntu 16.04 – if that sounds interesting to you. </note>

Vim is a powerful editor that can be used on your laptop/desktop and is also typically found of any Linux server you might encounter. As a result, I started using vim as my main editor. The Ubuntu install is simple:

$ sudo apt-get install vim
 

That’s it, you’re ready to edit. A good place to start if you need to learn more about vim is the main website: vim . Also be sure to check out the vim tutorials.

Pathogen

My next step is to add a variety of vim plugins that make (my) life easier. To do this I use pathogen a wonderful vim package manager. Installation is accomplished with the following lines:

$ mkdir -p ~/.vim/autoload ~/.vim/bundle;
$ curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim

If you don’t have curl installed, use:

$ sudo apt-get install curl

and try the second line again. Finally, if you don’t have a ~/.vimrc file create the following minimal example:

" contents of minimal .vimrc
execute pathogen#infect()
syntax on
filetype plugin indent on

NERDTree

NERDTree is a plugin the provides a nice file browser with bookmarks. With pathogen available, getting NERDTree installed is as simple as:

$ cd ~/.vim/bundle
$ git clone https://github.com/scrooloose/nerdtree.git

After installing, start vim and type:

:NERDTreeToggle

to toggle the file browser open or closed. Use up and down arrows to select files and press enter to open file in current tab. To open in a new tab, select the file and press t.

To bookmark, select a directory and type:

:Bookmark bookmarkname

to assign bookmarkname to the desired directory. To toggle the bookmarks open or closed (while in the NERDTree window) press shift-b. Finally, to open a bookmark, select the bookmark using up/down arrows and press enter when the desired bookmark is highlighted.

Tagbar

Tagbar does a nice job of showing code outlines– class, methods, etc and allows for jumping to different parts of the code using the outline. I’ve mainly used this with Python, where the results are very nice.

First, we have to install exuberant ctags , which Tagbar uses to do its parsing. Luckily, there is version in the Ubuntu repository:

$ sudo apt-get install exuberant-ctags

Next, install the vim plugin using pathogen, as before:

$ cd ~/.vim/bundle
$ git clone git://github.com/majutsushi/tagbar

Thanks to pathogen, we can now start vim and type:

:TagbarToggle

to toggle the code outline open or closed. To get to the code outline window press Cntrl-w and then l – this is a general vim command to move to the right window. Use up and down arrows to move through the code outline. When the desired class or function is highlighted press enter and vim will jump to the desired code. This is very nice for larger files!

jedi-vim

Next we install the jedi-vim plugin which allows for auto-complete and documentation search for Python projects. First, we install the Python package jedi

$ pip install --user jedi

I use this command assuming that you are installing all python packages as a user. Otherwise you will have install with $ sudo pip install jedi (global install), or activate the desired virtual environment and use$ pip install jedi.

Finally, use pathogen to install jedi-vim in the usual way:

$ cd ~/.vim/bundle/
$ git clone https://github.com/davidhalter/jedi-vim.git

The two command I use most with jedi are:

  • cntrl-space : auto-complete
  • shift-k : get documentation (must be in command-mode and put cursor on function of class of interest)

vim-template

vim-template is a plugin that provides nice file templates for new files. Using pathogen the installation is simple:

$ cd ~/.vim/bundle
$ git clone git://github.com/aperezdc/vim-template.git

Now, try:

$ vim test.py

or,

$ vim test.sh

to see the standard templates for Python files and bash scripts, respectively.

There are a variety of customizations that can be made (see the link above), but I like to add the following defaults to my .~/vimrc file:

" Customize the settings for vim-template plugin
let g:email = "desiredemail@gmail.com"
let g:user = "Desired Name"
let g:license = "Desired License"

That’s it for my basic vim and vim-plugins setup. Questions and comments are always welcome.

Posted by Chris Strelioff

Basic Vim Configuration的更多相关文章

  1. Cisco IOS Basic CLI Configuration : Switch Port Command

    Cisco IOS Basic CLI Configuration : Switch Port Command 1.  Basic Switch>en Switch#conf t Enter c ...

  2. Cisco IOS Basic CLI Configuration:Access Security 01

    1.  Telnet Switch Config: Switch>en Switch#conf t Enter configuration commands, one per line.  En ...

  3. Vim Configuration

    安装原生态的Vim之后,界面是这样的: 行号,没有:自动缩进,没有:括号匹配,没有~ 为了我们使用的方便,进行一些基本的配置: sudo vim /etc/vim/vimrc 进入配置界面: 如下图进 ...

  4. 2. Basic environment configuration

    网卡设置: Controller Node # The loopback network interface auto lo iface lo inet loopback   # The primar ...

  5. (转) 共享个很棒的vim配置

    发现了一个很棒的vim配置方法,现在共享给大家. https://github.com/kepbod/ivim   ivim - The Vim Distribution of Xiao-Ou Zha ...

  6. vim 设置

    TL;DR: $ git clone https://github.com/sontek/dotfiles.git $ cd dotfiles $ ./install.sh vim Download  ...

  7. vim的配置与使用

    经历了一次source insight 一言不合就崩溃之后,决定还是花点时间好好配置和学习以下vim 于是找到大神的配置 https://github.com/humiaozuzu/dot-vimrc ...

  8. install vim

    常用命令: [0]安装vim: oee@copener:~$ sudo apt-get install vim vim-scripts vim-doc 刚安装完$HOME目录下只有两个文件:.vim/ ...

  9. vim does not map customized key?

    it is a long time confusing me that why my customized key map in vim does not work? Some vim configu ...

随机推荐

  1. Python 前端 js基础

    Javascript 概述 JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的 ...

  2. 在线安装ipa,超链接下载ipa

    在线安装ipa包其实是OTA实现,先粘一下OTA解释 OTA OTA即Over-the-Air,简单来说就是通过无线的方式发送指令给设备,具体针对iOS的设备,比如iphone .ipad等,让开发者 ...

  3. Tensorflow 笔记 -- tensorboard 的使用

    Tensorflow 笔记 -- tensorboard 的使用 TensorFlow提供非常方便的可视化命令Tensorboard,先上代码 import tensorflow as tf a = ...

  4. [python 函数学习篇] 关键字参数

    函数可以通过 关键字参数 的形式来调用,形如 keyword = value .例如,以下的函数: def parrot(voltage, state='a stiff', action='voom' ...

  5. 以前刷过的数位dp

    TOJ1688: Round Numbers Description The cows, as you know, have no fingers or thumbs and thus are una ...

  6. [错误解决]UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

    python2内容无法写入csv,报错:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordin ...

  7. 2.启动ABP ASP.NET ZERO

    1.使用VS2017打开项目,等待自动还原程序包结束 2.生成项目,确保项目全部生成成功 3.生成数据库 (1).将项目“MyCompanyName.AbpZeroTemplate.EntityFra ...

  8. HDU——1874畅通工程续(Dijkstra与SPFA)

    畅通工程续 Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submiss ...

  9. 算法复习——数位dp

    开头由于不知道讲啥依然搬讲义 对于引入的这个问题,讲义里已经很清楚了,我更喜欢用那个建树的理解···· 相当于先预处理f,然后从起点开始在树上走··记录目前已经找到了多少个满足题意的数k,如果枚举到第 ...

  10. zygote的分裂

    1 zygote的分裂 前面已经讲了zygote分裂出了长子system_server,然后SS(system_server)就通过initAndLoop进行消息循环处理了.那么谁会向zygote发送 ...