Simple UNIX and VIM Tips

"Simplify, simplify, simplify"
                 

Simple Macro Recording in VIM
Split & Conquer - splitting screens in VIM
Manage your case
Match them brackets
Inserting carriage return
Save time on typing - use VIM commands at the term line
Count files in a TAR

TIP: Simple Macro Recording in VIM.

Doing it
1. Let's take the mystery out of macro recording in VIM; it is truly very simple.
In vim type in:
qa (to start recording a macro called 'a'; notice 'recording' at the bottom of the screen )
i (to switch to insert mode)
Never duplicated! [Enter] (just some text and Enter button to go to the next line.)
[ESC] (to exit the insert mode)
q (to stop recording)
2@a (to duplicate the phrase)
OUTPUT:
Never duplicated!
Never duplicated!
Never duplicated!



How does this work?
2. Using simple macros in VIM is very easy, the whole operation consist of three commands:
  • q [name of the macro] (to be technically correct it should be called a 'register') to start recording, example: 'qa'
  • q (to stop recording the macros)
  • [number of repetitions]@[name of the macro], i.e. '4@a' means "repeat macro 'a' 4 times"

  • Extra super-bonus
    3. But wait, there is more! Here is one way you could re-indent a snippet of code:
    Suppose you have inherited the following function written in PHP:

    function func_get_value( $x )
    {
    $y = 10;
    if( $x > 5 )
    {
    $y = $x * 25;
    }

    return $y;
    }

    and you would like to indent the internals of it for better readability. Here is how you can do it very quickly.
    put your cursor on the first '{' character.
    qb (start recording the macro called 'b')
    j (go to the next line)
    ^ (to get to the beginning of the line)
    2 (we are going to indent the code by 2 spaces)
    i (switch to the insert mode)
    [space] (we are using 'space', not 'tab' for indenting)
    [ESC] (done inserting, two spaces should show up in front of the '$y')
    q (stop recording)
    6@b (indent the rest of the routine, 6 lines)


    (In another example here I show how you can create a simple table using macro recording. Yes, I know, there are many rows in this example, but they are mostly very simple things you already know: moving up and down, copying (or 'yanking') and pasting.)

    You are done!
    ANfSCD
    top

    TIP: Split & Conquer - splitting screens in VIM.

    Doing it
    1. In vim type in:
  • :split [some file name] (to split the screen horizontally)
  • press CTRL-W-W (to switch between the sreens)
  • You can continue this operation ad-nauseam

  • How does this work?
    2. There are several options available for screen splitting, and :split is just one of them. Another useful option is :vsplit, which splits the window vertically. Naturally, you can split a window horizontally for two files, and then split one of them vertically for the third file.
    For example, say you have 3 files: one.html, two.html and three.html.
  • vim one.html (to open the first file)
  • :split two.html (to open the second file in the same window)
  • :vsplit three.html (to open the third file in the two.html window and split it vertically)
  • Now you can see all three files in the same window and switch between them by using:
  • CTRL-W-W

  • Extra super-bonus
    3. But wait, there is more! In fact there is wa-a-a-y too much more. But here are some basics that you probably will not forget.
    First, window resizing. To change the size of the window simply type in:
  • :res 50 (to change the size of the current window to '50')
  • :vertical res 40 (to change the vertical size of the current window to '40')

  • Second, window placing. To move windows in the screen use these simple commands:
  • CTRL-W r (to rotate windows downward for horizontal splits or to the right for the vertical splits)
  • CTRL-W R (to rotate windows upward for horizontal splits or to the left for the vertical splits), this is more of a pain however - Ctrl, Shift, upper case, lower case... I suspect CTRL-W r will serve you in most cases.
  • (There are many other window placing commands available, check them out at :help splitting if you are interested)

    Third, once you have all these windows open and split in all sorts of way, you might want to regain your sanity and close them. The easiest way to close a window is through regular:
    :q command.
    But if you want to close all windows except for the one you are in, you can use:
    :only command.

    You are done!
    ANfSCD
    top

    TIP: Manage Your Cases.

    Doing it
    1. In vim type in:

  • Type some text in vim, to set up this demo
  • v (to switch to Visual mode)
  • k or h (to select a word, a line or a phrase)
  • ~ (to switch the case)
  • The case of your selected text should change. You can perform the same operation to change it back

  • How does this work?
    2. A special case of this case-changing exercise is a case where you want to change the case to upper-case (as opposed just switching to the other case). The case switching operation is done via either u or U characters. In other words, if you want to switch a character to upper case you would use this command:
  • gU
  • and alternatively, to switch it back to lower case, just use
  • gu

  • This is good to know, but in my opinion, why bother? Just use the '~' approach.

    Extra super-bonus
    4. But wait, there is more! If you set a 'notildeop' option in vim you can then just use '~' to switch the case of character under cursor and move the curser one position to the right. Let me demonsterrate:
  • :set notildeop
  • Type in: "Deep in the hundred acre wood"
  • Ah! But we need to capitalize the Wood correctly, so...
  • 3b (to bring the cursor back to the word 'hundred')
  • ~ (to make it 'Hundred')
  • w (to bring the cursor to the next word)
  • ~ (to make the next word 'Acre')
  • w~ (you get the idea)

  • And, yes, if you want to switch the case of the entire word, or a line or the whole document you can just keep pressing '~'.
    However, a better option would be to use 'g~~' to change the case of a line, or
    just select the entire doc in visual mode and type '~' to make a global case switch.
  • You are done!

  • ANfSCD
    top

    TIP: Matching brackets in your code.

    Doing it
    1. In vim type in:

  • :set showmatch
  • This will help you to match brackets as you type code.

  • Testing it
    2. Now type in a bunch of code to test it out. Here is a PHP example (code lifted from PHP.net):
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
         echo 'You are using Internet Explorer.';
    }
    Now, if you move the curser to any bracket or a brace -"[", "(" or "{", you will notice that the cursor jumps briefly to the matchng bracket. By the way, if the cursor is out of site because the routine is to big, (kinda like this sentense) you can always match it manually by typing "%" at the bracket you are trying to match.

    Extra super-bonus
    4. But wait, there is more! Having an ability to jump to a matching bracket allows you to select entire routines very simply. For example:
  • Say you are dealing with the following code:
  • if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
         echo 'You are using Internet Explorer.';
    }

    If you want to select (to copy and paste for instance) the entire routine, you could this:
    1. Get to the first brace "{"; cursor is going to jump briefly to the matching bracket.
    2. Type v - this will switch you to the visual mode.
    3. Type % - this will select the entire routine.
    4. Now you can copy it (y) and paste it (p) later on.
    NOTE TO THE PURISTS: Yeah, I know about not copying and pasting code. It happens and sometimes it is useful.
  • You are done!

  • ANfSCD
    top

    TIP: Recalling your previous commands at the term line.

    Doing it
    1. Go to your terminal window and type in:

  • %>set -o vi

  • Testing it
    2. Now type in a bunch of UNIX commands to test it out:
  • %>ls -al
  • %>ls
  • %>clear

  • 3. Now type in j or k to test out the functionality.
    You should see "ls", "ls -a", "clear" at your term window.

    Extra super-bonus
    4. But wait, there is more! Having access to VIM commands at the terminal prompt allows you to use other VIM commands, not just "j" or "k".
    For example:
  • Say you typed in a command:
  • %>ls -r |grep mytext
  • You realized that "mytext" should be "mynum"
  • Now you can fix this command very quickly
  • recall the command: "k"
  • navigate to the offending party using a VIM commdand: "w" (5 times)
  • replace the word:"cw mynum"
  • Enter
  • You are done.


  • ANfSCD
    top

    TIP: Counting files in a TAR package without openning it.

    Doing it
    1. Suppose you have a TAR file: files.tar and you want to know how many files there are in this package.
    Go to your terminal window and type in:

  • %>tar tvf |wc -l
  • You should get a number, which will represent how many files you have in files.tar.

    How does this work?
    2. Essentially we are taking several commands and are stringing them together with "piping".
  • a) First command - tar tvf extracts the table of contents from files.tar.
  • Here is what the switches mean:
  • t - table of contents
  • v - verbose output
  • f - file name
  • b) Second command - wc -l performs a "word count", the l switch counts lines only.
  • c) Stringing commands together extracts the table of contents (a file list) and pipes it into the word count which in returns a number of lines in the file list.


  • Extra super-bonus
    3. But wait, there is more! This approach will let you count how many file of a particular type there are are in files.tar For example:
  • Say your files.tar contains .txt files, .php files and .config files.
  • All you need to do is use grep to select what type of files you would like to count
  • Say you would want to count only .txt files. Command:
  •  
  • %>tar tvf files.tar |grep *.txt |wc -l
  • will count only *.txt files.
  • You are done

  • ANfSCD
    top

    TIP: Subsituting characters for carriage returns in VIM.

    Doing it
    1. Suppose you have a file with delimited data (a CSV file for example) and you would like to arrange all data in one column.
    One way to do it is to insert a carriage return for every delimiter. Open your CSV file and type in:

  • :%s/,/^M/g
  • to actually insert ^M in the command line in VIM do this:
  • hold Control key, press V key and then M.
  • This should result in ^M displayed in the command line.

    Testing it
    2. Create a CSV file, such as:
    all,work,no joy,makes,dull
    dull,dull,dull

  • Execute a command listed in 1.
  • You should have a column of words without commas


  • Extra super-bonus
    3. But wait, there is more! Be careful when you make this change, because it is a one-way substitution.
    You'd think that like any good UNIX/VIM command this would work in reverse, but it doesn't.
    In other words, if you want to replace your carriage returns with commas, this approach will not work.
    So, if you modify your file and then want to reverse your changes, you will need to resort to something else, like sed.
    In other words, command:
    %s/^M/, /g
    will not do any magic, you will get an error: E486: Pattern not found: ^M, as sad as it sounds. So, in this case...
  • You are done

  • ANfSCD
    top