Tips for Learning Vim when you want to know earlier

Source: Internet
Author: User
Tags diff thunderbird mail python list git commands

From WeChat

Since 2009, I have been working with Vim as my primary (unique) text editor. Over the years, I've learned a lot of good Vim techniques that make me feel brief encounter because they greatly improve the efficiency of my text editing. In this blog post, I would like to share with you some of the most essential parts. HJKL

The first piece of advice that new Vim users usually receive is "Use the H/J/K/L key instead of the arrow keys!" "For a long time, I ignored this piece of advice because I thought it was ridiculous: why on earth did I have to do that?" However, one day I decided to give it a try, and I tried it out. It took me a lot of days to get used to the advice, but once I started it, I realized it. H/J/K/L several keys are directly on the top, so your hands don't have to move too far away (as you would when using the arrow keys). This not only saves keyboard operation time, improves efficiency, but also makes my hands more relaxed. I believe this is one of the factors that cure my wrist pain. Another factor is that I have a wrist cushion under my hand.

If you want to learn to use the H/J/K/L key instead of the arrow keys, I suggest you either turn off the arrow keys or remap them to other more useful instructions. Another advantage of not using the arrow keys is that you will be able to adapt to better moving instructions, such as f/f/t/t,w/w/b/b,0/^/$, or search instructions. With these instructions, your input will be more efficient than simply pressing the arrow keys or the H/J/K/L key. In Vim, a single-key instruction is a reverse mode. Relative line number

Like many users, I also use the absolute line number, OK, all users use it. However, one day I stumbled upon this article, which made me think: What if the relative line number is better? I decided to use it to see. Then, as Ben said in this video, the absolute line number is a lie in my life. The authentic use of vim is to enable relative line numbers.

Before enabling the relative line number, I recommend adding the following command line to the. vimrc file:

Set number

Set Relativenumber

Together, the two command lines enable Vim to display an absolute line number for the current row, and a relative line number for the other rows.

Next, I want to explain the usefulness of the relative line number. Many Vim commands have a number as a prefix. For example, to move 10 rows below the current line, you can use 10J. To move 4 rows above the current line, use 4k. To indent the current line and the following 2 lines, use >2J. Do you understand? With the relative line number, it is clear how far the other lines (from the current line) are. If you are using an absolute line number, you need to know how many lines between the two lines must be mental arithmetic and subtract two line numbers (possibly large). This mathematical operation can be reduced by using a relative line number.

At the same time, you can still use the absolute line number. For example, you compile a source file, and the compiler tells the No. 943 line that there is a syntax error, and you can navigate to this line with 943G or:943<cr>.

A very good feature of Vim is that you can set the fold line function. Many users include I will remap the j/k key to Gj/gk so that when they are pressed, the cursor moves by the virtual line rather than by the physical line. However, this remapping affects the counting function mentioned earlier. To compensate for this shortcoming, based on the Stackoverflow.com blog post, we re-mapped the following:

Noremap <silent> <expr> J (V:count = = 0?) ' GJ ': ' J ')

Noremap <silent> <expr> k (V:count = = 0?) ' GK ': ' K ')

Then, when a row with no line number is encountered, the GJ/GK command moves the cursor to the virtual line, and when it encounters a line number, the cursor is moved by the physical line. This is a perfect match with the relative line number. Vim and Tmux

For a long time, I was using GVim, which did not involve the Vim terminal. Because it is more dazzling, with the window environment and integration higher, and so on. Later, I found Tmux, which greatly improved my workflow. In short, with it, you can open multiple separate sessions in a single terminal, open multiple Windows (window) in each session, and each window can be divided into multiple panes (pane). Look at this screenshot and feel it.

Tmux also put me in a dilemma: how to use it in conjunction with GVim? The Tmux is a terminal application, while the GVim is a standalone GUI application. Fortunately, by setting up, Vim can have almost the same function as GVim. The best plug-in is Csapprox. It makes GVim's proprietary color scheme easy to use on Vim terminals. There are many other settings that help me move to Vim terminal to work, refer to my. vimrc file.

The biggest advantage of the Tmux+vim combination is that it allows you to do almost all of the development work in one terminal. For example, you can telnet to a server via SSH and develop it there so you can seamlessly connect to the previous work in different places and even on different computers. Another benefit is that the server is typically running faster than a laptop or desktop computer. You might even develop on a server with a huge core and memory, depending on your company's budget. This experience is simply a memorable one.

If you have never used Tmux, then I suggest you try it at least. It's really a great tool. The beginning of everything is difficult, I am here to detail the Tmux configuration process, to give you a guide. Take a closer look, and maybe you can learn some tips to help you adjust and improve your workflow. For example, in this article I introduce a method for seamlessly navigating between Vim and Tmux. Operations and Actions

One of the unique features of Vim is that it allows you to talk to it in a language. For example, the Vim command has a verb-like d (delete) or Y (copy), a noun-like B (parenthesis) or s (sentence), and an adjective-like I (internal) or a (all). You can combine them freely, so the DIB represents the deletion of all the text in parentheses, and Yap represents the copy of the current paragraph. After you learn this simple language, you don't have to think about what you need to do to delete a paragraph, simply enter DAP. Many people find vim difficult to master because they are not used to seeing vim in this way.

What's even more valuable is that the Vim language is extensible. In fact, users can create their own "verbs" and "nouns" (Actions and actions/text objects in the VIM syntax) based on the VIM syntax. Here are some of my daily necessities to use plug-ins. Operation

    • tcomment-vim--Execute code Comment action: GC. For example, for a paragraph comment, you can use GCap (go comment a paragraph), for the current line and the following 5 lines of comments, you can use the gc5j (thanks for the relative line number!). )。

    • vim-sort-motion--performs a sort operation: GS. For example, in Python, you can use GSIP (go sort inside paragraph) to sort the imports where the cursor is located.

    • replacewithregister--Perform the replacement operation: Gr. Performing the Replace text operation does not overwrite the contents of the register. For example, to replace the current word with the default register, you can use GRIW (go replace inner word). The GR operation can also be combined with the dot command (., repeating the last action), which makes it more efficient. It's one of my favorite operations.

action/Text Object
    • targets.vim--adds many useful text objects. For example, the DAA is used to delete a parameter of a function call (deletes an argument of a function called), ci$ is used to change the text between the dollar sign (very useful in LaTeX). Another feature of the plugin is that the user can use the text object, even if the cursor does not fall within the text object that you want to edit. For example, use di "(delete inside quotes) to delete the contents of the double quotation mark closest to the cursor.

    • vim-indent-object--performs an operation on the current indentation. For example, to move the current code block to the left, you can use <II (Left-shift inside indent). This is useful for Python because it uses spaces to identify blocks of code rather than curly braces.

    • vim-surround--operate on the surrounding environment. For example, CS "' means to replace the surrounding double quotation marks with single quotes, while the DSB means to delete the surrounding parentheses.

Of course, you can also use the actions and actions mentioned in the above plugin. For example, in a Python list, each item is in a separate row, in order to sort the list, you can use GSII (go sort inside indent).

Some simple text objects can even be defined without the help of a plugin. For example, to manipulate an entire file, you can add the following line of code. VIMRC:

Onoremap AF: <c-u>normal! Ggvg<cr>

Therefore, to copy the contents of the entire file (more accurately, the entire buffer), you can use YAF (Yank a file). Fuzzy Lookup

To open a file in Vim, you can open the file in either the current buffer or a new tab by using the Edit or tabnew command. One drawback of this approach is that when you open a large project with many directories and files embedded, it is very slow. For example, to edit a file frontend/scripts/js/view/viewer.js, you have to knock the entire path. Well, there has to be a better way ...

Fortunately, there is indeed! By using a fuzzy finder, such as command-t. Now just simply enable the Finder (input, T), type Fsviewer (f and S are part of the file path), and you can open the file in the current window or in a new tab instantly. Once you know the path structure or file name of your project, using a fuzzy finder can greatly improve the speed of file opening. Search

We often want to list all the files that contain a given phrase or word (such as the name of a function). When I first started using Vim, I would go to the terminal and enter Gvim grep–r FUNC | Cut–d:-f1 to open the found file in GVim. However, why not give this simple task to Vim?

You can either use Vim's built-in grep command or a more advanced plug-in, such as Vim-grepper, which allows the user to select a search tool (Grep,git grep or AG) and choose how to display the results. For example, the user can map,/to retrieve all the files that contain a word in a project, or to use,? Retrieves the file containing the word of the cursor throughout the project scope. At the end of the retrieval process, a window containing the target file pops up, and the Vim user can open the file directly. Vim as an external editor

If you're using a text editor, the most important thing is to use it as often as you can. After all, why do you want to learn another editor when you already know about Vim? For example, textarea forms on a Web page? If you use Vim everywhere in your work, you can even take advantage of it in places you couldn't imagine before.

For example, in Firefox, there is a plugin called It's All text!, which allows the user to edit the textarea element in Vim. This facilitates activities such as editing a wiki page, writing a blog post, and submitting bug reports using their favorite editor. For Vim users, this means they can enjoy their syntax highlighting, spell checking, dictionary completion, code snippets, and other features.

Also, in the Thunderbird mail client there is an It's all text! Plug - ins. Using this plugin allows you to write messages faster and more comfortably than a built-in editor.

Many end applications also support the use of Vim as an external editor. For example, you can set midnight Commander to open files from Vim. Another valuable point of Vim is in the use of version control systems, such as Git, when writing the submission instructions. Are you tired of typographical errors? Then set the spelling checker in Vim. Do you want to make the words that appear in the diff file auto-complete by using CTRL + N? Then submit it with the-verbose parameter. It can copy the entire diff file into Vim, so you can use the dictionary completion function, just like the function name. The boss no longer has to worry about you writing the submission instructions.

Finally, I want to mention is another Firefox browser plugin, Vimperator. It allows users to browse the Web page can also use the principle of vim, so that the browser to use like Vim. For example, you can quickly open a connection on a webpage, copy text, or make a bookmark to return later, without having to move the mouse. Vimperator even allows you to configure Firefox in a file similar to. vimrc. This is my version. running external Commands

Suppose you are writing Pyhton code, and you want to perform unit tests in the current file. Or, suppose you are writing a Latex document and you have to compile it in order to see the results. One way to do this is to open a terminal and then perform the test or compile it. However, this is not an efficient approach because it causes disruption to your workflow.

A better approach is to use Vim to perform the characteristics of external commands. For example, with the following automatic commands, you can simply press F9 to save and perform the currently edited unit test for your Python code:

Au FileType python nnoremap <buffer> <F9>:wa<cr>:!clear; Nosetests%<cr>

Another benefit of running Vim in Tmux is that it makes it possible to execute external commands in the Tmux pane or window. For example, you can divide the current Tmux window into two panes, one for editing the file and the other for performing the test without having to switch between them. To give you a taste of my workflow, here's a demonstration. I used a dual monitor in my work and set it up accordingly. For a project, I opened two terminals in which a TMUX console was opened, and then a terminal was displayed in each display separately. At this point, I can write the code on the first Tmux console, and if I want to run a test, generate a document, or check the code with a tool similar to lint, I simply send a command through Vim to the second Tmux console, and the test will be on the second display. This allows me to write code and test documents in the split window of the first display, run GIT commands on the second display, perform tests, and so on. I also set the Fluxbox so that I can switch between the two monitors with the ctrl+alt+h/l. This is my configuration file. In addition, there are more exciting parts Oh! That is, the workflow described above even applies to running Tmux on a remote server via SSH. configuration options and Mappings

Vim is highly scalable. You can configure it according to your preferences, and you can add maps and commands to the actions you use frequently. In the past time, I gradually perfected my own. vimrc file, which contains a lot of useful settings, mappings. Here are some of them, but I suggest you finish reading my entire. vimrc file.

"Quickly Select the text that is just pasted. This allows, e.g.,

"Indent it after pasting.

Noremap GV ' [v ']

"Stay in visual mode when indenting. You'll never has to run GV after

"Performing an indentation.

Vnoremap < <GV

Vnoremap > >GV

Make Y yank everything from the cursor to the end of the line. This makes Y

"Act more like C or D because by default and Y yanks the current line (i.e. the

"Same as yy").

Noremap Y y$

"Make ctrl-e jump to the end of the" the "on the" insert mode. This is

"Handy when" is in the middle of a line and would like to go to its end

"Without switching to the normal mode.

Inoremap <C-e> <c-o>$

"Allows easily replace the current word with all its occurrences.

Nnoremap <LEADER>RC:%s/<<c-r><c-w>>/

Vnoremap <LEADER>RC y:%s/<c-r> "/

"Allows easily change the current word and all occurrences to something

"Else. The difference between this and the previous mapping are that the mapping

"Below pre-fills the current word for your change.

Nnoremap <LEADER>CC:%s/<<c-r><c-w>>/<c-r><c-w>

Vnoremap <leader>cc y:%s/<c-r> "/<c-r>"

Replace tabs with the four spaces. Make sure, there is a tab character between

"The first pair of slashes when you copy this mapping into your. vimrc!

Nnoremap <leader>rts:%s///g<cr>

"Remove ANSI color Escape codes for the edited file. This was handy when

"Piping colored text into Vim.

Nnoremap <leader>rac:%s/<c-v><esc>[(d{1,2} (;d {) {0,2})? [ m| K]//g<cr>

parameter Folding

Finally this is also very important, I want to mention the Vim-argwrap plugin. It lets you quickly collapse or expand function parameters (tables), lists, or dictionaries. For example, you can use it to put the following code

Decompiler = Decompiler (Api_url=args.api_url, Api_key=args.api_key)

Converted to

Decompiler = Decompiler (

Api_url=args.api_url,

Api_key=args.api_key

)

And vice versa, you only need to make a simple mapping.

0 jump to the beginning of the line,^ (shift 6 + F (forward) Ctrl + B (backward) respectively downwards/+ D (down) Ctrl + U (UP) respectively down/rolled half screen

Tips for Learning Vim when you want to know earlier

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.