Getting started with Vim.

This is a moderately-paced introduction to the Vim text editor. At the end of this post, you should not only be able to edit multiple files at once, but also use markers and execute shell commands from within Vim. The followings are links to each subsection. It might seem like a lot, but each section is pretty short.

Background
Starting up – Opening and closing files
File editing and navigation
Moving around a file
Editing a file
Markers (plus more searching and navigation)
Editing multiple files at once
Moving manipulating buffers
Using split views
Summary, and the briefest of intros to runtime configs.

Background

Vim is a text editor that traces its lineage to vi, one of the earlier programs to make its way into the Berkeley Software Distribution (back when it was 2BSD, even before it could call itself an OS). Vim’s most distinctive characteristics is its modeful (command-driven) operation, where a user must execute commands in order to enter and manipulate text. You don’t need to like Vim, but it’s still useful to know, as if you know Vim, you can get around vi, and vi comes packaged with many things Unix-like.

Starting up – Opening and closing files

The command vim <filename> opens a file named <filename> in Vim. Starting Vim without specifying a file will open an empty buffer, which is essentially a new file. Because Vim is a screen editor, the opened file will take up most of your terminal window. The last (bottom) line of your window is your command line, where you can enter commands (and receive feedback like mode info and errors).

empty buffer

Fig 1: A new Vim session starting with an empty buffer. The “–INSERT–” on the bottom line (the command line) indicates that the editor is currently in insert mode.

Vim is in command mode when it first starts up, meaning it’s expecting a command, not text. As you’ll see in the next section, there are multiple ways to begin editing a file by entering other modes. For now, just remember: if you accidentally end up in a mode you’re not sure about, hit <escape> to get out of it and back into command mode.

The following commands save and close the file:

  • :w [fname] – write (save) current open file as [fname]. If a name is omitted, the file is saved with the current name.
  • :q – quit Vim

The above two can be combined to :wq to save and close a file. Alternatively, if you don’t want to save anything, :q! will force close the file even if there are unsaved changes.

Once a Vim session is started, :e <filename> will open another file. More interestingly, creating a file named .vimrc in your home directory and adding the line

set nocp
filetype plugin on

lets you use Netrw, which, among other things, allows you to navigate/browse directories. If you open a directory in Vim (e.g. vim .) after you do this, you’ll get a directory listing:

netrw

Fig. 2: A directory opened in Vim, using Netrw.

Hitting enter when a file is highlighted will open it (or if it’s ../ , go up the directory tree). Following this logic, :e . will also open the directory with Netrw. Note, vi (or Vim without plugins enabled) will issue you a warning that the directory isn’t a regular file, and show you garble or an empty directory.

File editing and navigation

Now that we’ve gone over opening and closing files/buffers, we can edit them. As mentioned before, commands are used to manipulate both the editor and the text. For example, to begin entering text, you must hit ‘i’ first to enter insert mode, and hit <escape> before issuing more commands, e.g. to save and quit with :wq.

Before we begin, we use the following as a convention:

  • line : a string of text delimited by a newline (an enter, “\n”)
  • paragraph: a group of text delimited by two newlines
  • n[command]: a command that repeats an action n times. The default when n is omitted is once.

Moving around a file

While in command mode, you can move the cursor around with the following:

  • n[space] – n spaces
  • n[enter] – n lines
  • nh – n characters left
  • nj – n lines down
  • nk – n lines up
  • nl – n characters right
  • n{ – n paragraphs below (for n=1, to the end of the current paragraph)
  • n} – n paragraphs down (for n=1, to the beginning of the current paragraph)

Arrows should also move the cursor 1 space at a time, and can be used while in insert (editing) mode.

Editing a file

You can begin adding text i.e. go into insert mode several ways, depending on where you want to begin adding text:

  • i – before current cursor position
  • I – beginning of current line
  • a – after current cursor position
  • A – at end of current line (Append)
  • o – after the current line, as a new line
  • O – before the current line, as a new line

likewise, there are several ways to delete and cut:

  • backspace, delete – while in insert mode
  • nx – delete n characters from current cursor position
  • nX – delete n characters before current position (i.e. backspace)
  • ndd – delete or cut n lines starting from current line
  • D – delete or cut everything to the end of the current line, including current cursor position

and copy/paste:

  • nyy – yank(copy) n lines starting with the current line
  • nY – yank n lines starting with current line – same as yy
  • np – paste n copies of a yanked or deleted lines, or n copies of a string after the current cursor position. Note, if you yank n lines, and paste m, you will get m copies of the n lines.
  • nP – same as np, but before the current cursor position for strings.

and replace:

  • nr – replace n characters from current position
  • R – begin replacing text with newly typed text
  • :%s/a/b/g – replace a with b, throughout the file

undo and redo changes with:

  • nu – undo the last n changes
  • n<ctrl-r> – re-do n undone changes

and finally, select text with:

  • ctrl-V – visual line mode
  • ctrl-v – visual block mode

Text can be selected my moving the cursor around; selected text in either mode are highlighted. Line mode selects whole lines at a time, whereas block mode selects n rows and m columns of text starting from the current position of the cursor. Block mode is useful for selecting rows of formatted text e.g. the contents of a table. Once you select a chunk of text, you can enter a command to apply it just to the selection.

A pretty typical use for line mode is for indenting a block of code. After selecting some lines:

  • n> – indents the selected lines by n tabs
  • n< – un-indents the selected lines by n tabs
  • = – matches the indentation of the selected lines up to that of the last un-selected line

Markers (plus more searching and navigation)

Only moving one space or line at a time, or scrolling through your files to look for things is annoying at best, and unmanageable with large files.

  • G – jump to last line
  • gg – jump to first line
  • :[n] – jump to line [n]
  • $ – jump to end of the line
  • ^ – jump to beginning of the line
  • /<word> – search for <word> (there is much more to this i.e. regular expressions, but that’s for another post).

  • n – jump to the next appearance of the searched word

If your cursor is on a word that you want to look for:

  • # – jump to the previous appearance of word
  • * – jump to the next appearance of word

Marks are user-defined points within files that you can create and later jump to. The characters a-z and A-Z can be used as marks. In specific, a-z are marks within a single file, akin to HTML anchors, whereas A-Z are global, akin to hyperlinks between files. Because of this, you can have, say, a mark ‘b’ in each file, but you can only have one mark ‘B’ amongst your marked files.

  • ma – mark the current position with marker ‘a’
  • 'a – jump to beginning of line marked with ‘a’
  • `a – jump to the exact position of marker ‘a’
  • :marks – list all currently used markers
  • :delmarks ab – delete markers a and b

Editing multiple files at once

What if you want to edit/reference multiple files at once? You can use :e to open more files while you have one already open. If you had not made any changes to the durrent file, Vim will oblige. However, Opening another file while you are editing one will cause vim to display an error:

`E37: No write since last change (add ! to override)`

You can either proceed after saving the file, or do :e! to forcibly open a new buffer. In either case, once you open the second file, you now have two buffers, one per file. :buffers displays all of the buffers you currently have open. Which brings us to:

Moving manipulating buffers

The following commands let you switch between buffers:

  • :bn – switch to the next buffer
  • :bp – switch to the previous buffer

Vim also assigns numeric IDs to each buffer, which are shown if you list all buffers with :buffers. :b[ID] jumps directly to the buffer with ID [ID].

Finally, :bd closes just the current buffer. A word of caution: if you issue :wq while you have multiple buffers open, it will close all of them, along with Vim. issuing :bd when you have one file open will leave you with an empty buffer.

Using split views

Sometimes it’s easier to work with an extra large file when you can view different parts of it at once. :sp lets you split the window to view two parts of a file one on top of another. Or if you prefer, :vsp can split the window vertically so you can view them side-by-side. ctrl-w<arrowkey> lets you move between the split panes, and :q closes the pane your cursor is on. You can repeat the process and split already-split windows. You can also tile multiple files by splitting the window and opening different files in each, using the aforementioned methods e.g. :e or switching to a different buffer.

splitbuf

Fig. 3: An empty buffer split into three panes with :vsp and :sp.

Running scripts

You can execute shell commands while still in Vim by doing :! . For example, to list all of your files in the current directory, you can do

:! ls

Hitting <enter> will return you to your file. This is pretty useful if you are working on, say, a Python script that you might want to test out frequently while editing. Instead of saving, exiting, testing, and re-launching Vim, you might do this:

:! python %

If you need to repeat a command, regular shell tricks like :!! also work here. :<arrow keys> also lets you scroll through past commands.

Summary, and the briefest of intros to runtime configs.

Finally, as we have done to enable the use of Netrw, Vim’s user configurations can stored in a file named .vimrc in the user’s home directory. Some examples are:

  • syntax on/off – turn on/turn off syntax highlighting
  • set (no)number – add (or remove) line numbers
  • set tw=n – wrap text at n characters
  • set bg=light/dark – change highlighting colors for light or dark terminal backgrounds

syntax on plus different bg settings

Fig. 4: A comparison of sessions with setting syntax on (syntax highlighting) on a dark background. Top is bg=dark and bottom is bg=light. Default is bg=light (bottom)

These settings can also be tried from command mode by prepending them with a colon e.g. :set bg=dark. Maybe someday there will be a more complete post – but for now, hopefully this is/was a good starting point.


References:

Open Sources: Voices from the Open Source Revolution (Section by McKusick)
www.freebsd.org : vi(1) man page
vim.wikia.com : Vim marks (in general, a good reference)


Advertisements

A generic intro to switchwork.

This post introduces switchwork in a very general way; specifically, it’s aimed at people attempting to configure/administer their first switches. The takeaway from this post, hopefully, is a modus operandi for switch configuration, and a handful of keywords that might come in handy when searching for more information.

Background

I was asked the following question: “Given very little to begin with, how do I go about configuring/administering a switch? What is actually involved in switch work, and what are some keywords to look for?”

The scenario is this: You have just a basic knowledge of networking (e.g what OSI layers are), and the Linux command line. The switch staring back at you is the first of the (many makes and models of) “serious” network device you’re about to mess with. It is a layer 2/3 switch with a CLI, serial management interface, and at least a dozen ports. The switch has a wide range of features from STP to port mirroring and even a DHCP sever – Given that you know the features exist, and you know how to enable them. Which brings us to…

The Problem

You’ve found a manual, but it’s written under the assumption that the reader already knows a thing or two about administering networks, knows what needs to be done, and is just looking for the “how”. Manuals can be pretty useless until you have a knowledge base of what the options are and why they are there. Even when you have a high-level idea of what needs to be done, searching a manual can still be a pain when you aren’t aware of certain keywords or general procedures.

Bridging (some) gaps

After thinking a bit, I came up with this list of steps/notes on how to begin configuring a typical switch. Note, this answer was put together with the idea of exposing the various aspects of switchwork without focusing on just one make or model.

  1. Many switches don’t come with networked services enabled. You’ll likely have to connect to the switch using a serial (RS-232) cable and a client program supporting serial communication, such as HyperTerminal, Minicom, or C-Kermit. There is usually a labeled console port (RJ-45 or DB-9) on the front faceplate of a switch that you can hook a cable to.

  2. To actually connect via serial, expect to configure some settings on your client. Switches seem to favor:
    • baud rate: either 9600 or 115200 bps (e.g if one garbles output, try the other). 9600 seems to be more popular.
    • carrier detection off
    • no parity bits
    • 8 data 1 stop bit (8N1)

    You’ll likely have to specify a serial port, usually something like /dev/ttyS0 on Linux  or /dev/cuau0 on FreeBSD. Using C-kermit, the commands at your terminal prompt might amount to (for a Quanta LB9A):

        kermit -l /dev/ttyS0
        set carrier-watch off
        set baud 115200
        connect

  3. Some switches (e.g. some Netgear models) may not use a serial interface, but rather, auto-configure itself with a static IP. In this case, you can hook an Ethernet cable to your switch, and even likely, point a browser to its GUI.

  4. Once you’re connected, you’ll either have to enter a default username/password to get to, or be dropped straight into, the CLI. Sadly little can be said about the CLI that is generic:
    • There are usually various modes for various administration tasks. The default is a non-privelaged read-only mode that lets you see a limited set of system status and configurations. An ‘enabled’ mode with more privilege (similar to becoming root) may exist to allow you to configure a switch. From this enabled mode you can enter a configuration mode that actually lets you change things, such as enabling non-serial access methods, such as SSH or Telnet.
    • Considering the dozens, if not hundreds, of ports that these things can have, many CLIs (but not all) have a range syntax for configuring multiple ports at once. An example is the range keyword used by Cisco IOS and the firmware for NEC’s IP8800 series L2/L3 switches.
    • Often times, configuration changes have to be explicitly saved with a command before exiting “enabled” mode. Some CLIs will give you a visual hint (like an exclamation point) indicating there are changes that need saving.

    For example, on the IP8800/S3640, logging in, turning multiple ports into trunk ports, saving the settings, and logging off involves the following steps:

        login: operator

        > enable
        # configure
        (config)# interface range gi 0/45-48
        (config-if-range)# switchport mode trunk
        !(config-if-range)# save
        (config-if-range)# exit
        (config)# exit
        # disable
        > exit

  5. Management-wise, many switches and routers can be thought of as a *nix box with a bunch of network interfaces. For example, Quanta’s LB9A, NEC’s IP8800-series, and Juniper’s MX-80 run firmwares that are based on, or incorporate, Linux, NetBSD, and FreeBSD, respectively. Some may even give you the option to drop into a shell from the CLI or at boot up, or execute UNIX-flavored commands (The IP8800 even came with ed, a minimal text editor!).

  6. A part of configuration/maintenance will include updating or installing new firmware on (“flashing”) the switch. The procedures vary wildly with make and model. Some switches may be updated from the CLI (e.g. the IP8800, with its ‘ppupdate’ command), but some will require more invasive measures such as updating and configuring the boot loader. For example, enabling OpenFlow on the LB9A involves copying the new firmware to its CF Card (via FTP, from its Linux shell) and pointing its boot loader (in this case, U Boot) to the image location manually upon reboot.

  7. An improperly flashed/updated switch may potentially be rendered nonfunctional (“bricked”), so it is important to keep interruption of this process to an absolute minimum.