Wilhel

Wilhel

vim editor

Basic Operations#

Command Mode#

  • :q Exit (close window)
  • :w Save (write)
  • :wq Save and exit
  • :e {filename} Open file for editing
  • :ls Show open buffers
  • :help {subject} Open help documentation
    • :help :w Open help documentation for :w command
    • :help w Open help documentation for w motion

Motion - Mostly in Normal Mode#

  • Basic motion: hjkl (left, down, up, right)
  • Words: w (next word), b (beginning of word), e (end of word)
  • Lines: 0 (beginning of line), ^ (first non-blank character), $ (end of line)
  • Screens: H (top of screen), M (middle of screen), L (bottom of screen)
  • Page: Ctrl-u (scroll up), Ctrl-d (scroll down)
  • File: gg (beginning of file), G (end of file)
  • Line number: :{line number}<CR> or G ({line number} is the line number)
  • Miscellaneous: % (find matching pair, e.g. parentheses or /* */ style comments)
  • Find: f{char}, t{char}, F{char}, T{char}
    • Find/to forward/backward on the current line
    • , / ; to navigate matches
  • Search: /{regex}, n / N to navigate matches

Selection - Visual Mode#

  • Visual: v
  • Visual line: V
  • Visual block: Ctrl+v

Editing#

  • i Enter insert mode
    • But for manipulation/editing text, don't just use backspace
  • O / o Insert line above/below
  • d{motion} Delete {motion}
    • e.g. dw delete word, d$ delete to end of line, d0 delete to beginning of line
  • c{motion} Change {motion}
    • e.g. cw change word
    • e.g. d{motion} then i
  • x Delete character (equivalent to dl)
  • s Substitute character (equivalent to xi)
  • Visual mode + operation
    • Select text, then d to delete or c to change
  • u Undo, <C-r> Redo
  • y Yank/copy (some commands like d also copy)
  • p Paste
  • More worth learning: e.g. ~ change case of character

Counting#

  • 3w Move forward three words
  • 5j Move down 5 lines
  • 7dw Delete 7 words

Modifiers#

You can use modifiers to change the meaning of a "noun". Modifiers are i, meaning "inside" or "in", and a, meaning "around".

  • ci( Change the contents inside the current parentheses
  • ci[ Change the contents inside the current square brackets
  • da' Delete a single-quoted string, including the surrounding single quotes

Demo#

# fizzbuzz.py
import sys

def fizz_buzz(limit):
    for i in range(1,limit+1):
        if i % 3 == 0:
            print('fizz', end="")
        if i % 5 == 0:
            print('buzz', end="")
        if i % 3 and i % 5:
            print(i)
        else:
            print()

def main():
    fizz_buzz(int(sys.argv[1]))
    
if __name__ == '__main__':
    main()
  • . Repeat the last change
  • sys.argv[1] The first argument passed in

Customizing Vim#

vim ~/.vimrc
vim /etc/vim/vimrc # debian

Extending Vim#

Commonly recommended plugins:

Instructors' open-source configuration files:

 Vim Awesome

Vim Mode in Other Programs#

Shell#

Bash set -o vi

Zsh bindkey -v

Fish fish_vi_key_bindings

Generic export EDITOR=vim

Readline#

vim ~/.inputrc
vim /etc/inputrc # debian

set editing-mode vi # Enable vi editing mode, useful for Python REPL with Vim shortcuts

Advanced Vim#

Search and Replace#

:s (substitute) command (documentation).

  • %s/foo/bar/g
    • Replace foo with bar throughout the file
  • %s/\[.*\](\(.*\))/\1/g
    • Replace named Markdown links with simple URLs

Multiple Windows#

  • Use :sp / :vsp to split windows
  • The same buffer can be displayed in multiple windows

Macros#

  • q{char} to start recording a macro in register {char}
  • q to stop recording
  • @{char} to replay the macro
  • Macros stop if an error is encountered
  • {count}@{char} to execute a macro {count} times
  • Macros can be recursive
    • Clear the macro with q{char}q
    • Record the macro, use @{char} to recursively call the macro (no operations until recording is complete)
  • Example: Convert XML to JSON (file)
    • An array of objects with "name" / "email" keys
    • With a Python program?
    • With sed / regular expressions
      • g/people/d
      • %s/<person>/{/g
      • %s/<name>\(.*\)<\/name>/"name": "\1",/g
    • Vim commands / macros
      • Gddggdd to delete the first and last lines
      • Format the last element with a macro (register e)
        • Jump to line with <name>
        • qe^r"f>s": "<ESC>f<C"<ESC>q
      • Format one with a macro
        • Jump to line with <person>
        • qpS{<ESC>j@eA,<ESC>j@ejS},<ESC>q
      • Format one tag then move to the next with a macro
        • Jump to line with <person>
        • qq@pjq
      • Execute the macro until the end of the file
        • 999@q
      • Manually remove the trailing , and add the [ and ] delimiters

Additional Resources#

Exercises#

  1. Complete vimtutor. Note: It looks best in an 80x24 (80 columns, 24 lines) terminal window.
  2. Download the provided vimrc and save it as ~/.vimrc. Read through the commented file (using Vim!) and observe the subtle differences in how Vim looks and behaves with this new configuration.
  3. Install and configure a plugin: ctrlp.vim.
    1. Create the plugin folder with mkdir -p ~/.vim/pack/vendor/start
    2. Download the plugin: cd ~/.vim/pack/vendor/start; git clone https://github.com/ctrlpvim/ctrlp.vim
      # Add the following configuration to vimrc after downloading
      set runtimepath^=~/.vim/pack/vendor/start/ctrlp.vim 
      
    3.  Read the [documentation](https://github.com/ctrlpvim/ctrlp.vim/blob/master/readme.md) for the plugin. Try using CtrlP to locate a file in a project folder by opening Vim and using the command-line command `:CtrlP`.
    4.  Customize CtrlP: Add [configuration](https://github.com/ctrlpvim/ctrlp.vim/blob/master/readme.md#basic-options) to your `~/.vimrc` to open CtrlP with Ctrl-P.
    
  4. Practice using Vim by redoing the demo on your own machine.
  5. Use Vim for all file editing for the next month. Whenever you find yourself being inefficient or thinking "there must be a better way," try searching the web—there probably is a better way. If you encounter any roadblocks, come to our office hours or send us an email.
  6. Set up Vim shortcuts in other tools (see the guide above).
  7. Further customize your ~/.vimrc and install more plugins.
    Install plugins using vim-plug:
    1. Install vim-plug
     $ curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
    
    1. Modify ~/.vimrc
     call plug#begin()
     Plug 'preservim/NERDTree' # Plugin NERDTree to be installed
     Plug 'wikitopian/hardmode'  # Install hardmode
     ..... # More plugins
     call plug#end()
    
    1. Run :PlugInstall in the vim command line
  8. (Advanced) Use a Vim macro to convert XML to JSON (example file). Try doing it on your own first, but if you get stuck, refer to the macros section above.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.