Wilhel

Wilhel

vim editor

Basic Operations#

Command Mode#

  • :q Quit (close window)
  • :w Save (write)
  • :wq Save and quit
  • :e {filename} Open file for editing
  • :ls List 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 motions: 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)
  • Paging: Ctrl-u (up), Ctrl-d (down)
  • Files: gg (beginning of file), G (end of file)
  • Line numbers: :{number}<CR> or {number}G (where {number} is a line number)
  • Miscellaneous: % (find matching pair, e.g. parentheses or /* */ comment pairs)
  • Searching: f{char}t{char}F{char}T{char}
    • Search/To forward/backward on the current line for {char}
    • , / ; for navigating matches
  • Searching: /{regex}n / N for navigating matches

Selection - Visual Mode#

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

Editing#

  • i Enter insert mode
    • But for manipulating/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 (same as dl)
  • s Substitute character (same as xi)
  • Visual mode + operation
    • Select text, then d to delete or c to change
  • u Undo, <C-r> Redo
  • y Yank/copy (also copies with some other commands like d)
  • p Paste
  • More advanced: 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 inside parentheses
  • ci[ Change inside square brackets
  • da' Delete a single-quoted string, including the surrounding 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 last change
  • sys.argv[1] First argument passed in

Customizing Vim#

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

Extending Vim#

Common 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, Python REPL supports 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 there is an error
  • {count}@{char} to execute a macro {count} times
  • Macros can be recursive
    • Clear the macro with q{char}q first
    • 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 / regex
      • 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 the line with <name>
        • qe^r"f>s": "<ESC>f<C"<ESC>q
      • Format one with a macro
        • Jump to the line with <person>
        • qpS{<ESC>j@eA,<ESC>j@ejS},<ESC>q
      • Format one tag and move to the next with a macro
        • Jump to the line with <person>
        • qq@pjq
      • Execute the macro to the end of the file
        • 999@q
      • Manually remove the trailing , and add [ and ] separators

Additional Resources#

Exercises#

  1. Complete vimtutor. Note: It looks best in an 80x24 (80 columns, 24 rows) 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 plugin's [documentation](https://github.com/ctrlpvim/ctrlp.vim/blob/master/readme.md). Try using CtrlP to locate a file within a project folder by opening Vim and using the Vim command-line to start `: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, as there likely 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, you can refer to the macros section above.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.