Monthly Archives: December 2009 - Page 2

meisterluk’s advent calendar: RegEx

RegEx is the Camel Case notation of Regular Expressions. These are a powerful way to search for strings and make replacements. For example, RegEx might be written “RegEx”, “regex” or “Regular Expressions”. With a normal string search functions you have to make three separate searches. With regex you only need to type “(RegEx|regex|Regular Expressions)”. What does those parenthesis and vertical rules mean? These are so-called metacharacters:

. Represents any symbol except Carriage-Return, Tab and so on. The not-included whitespaces depend on your configuration. “e.p” matches “exp” and “emp”
^ RegEx must be found at string starting position. “^Mail” matches “Mailer” but not “ReMail”.
$ RegEx must be found at string end position. “Mail$” matches “ReMail” but not “Mailer”.
Escape character. “.” matches a real dot and not any character. “” matches a backslash.
[ ] Characters inside the brackets define a range. For example “p[aoe]st” matches “post”, “past” and “pest”, but not “poast” and “pst”. To simplify ranges, you can simply enter [0-9] to match any number. [a-z] matches any lowercase character and [A-Z] uppercases. Two things to mention: Firstly metacharacters are unbound from their meaning (. is a dot and not any character) and secondly you have to prepend a minus symbol inside the brackets to include a real minus. For example “[-a-zA-Z0-9()!]” matches “Hello-World!”, “number4866″ and “(nothing!)”.
( ) Save match inside the brackets in a buffer. For example “(lukas) (prokop)” saves “lukas” in Buffer #0 and “prokop” in Buffer #1. These buffers can useful when using RegEx in replacement contexts.
< > Start/End of a word. A word is defined by a punctuation mark or a space. For example “<reg” matches “registry”, but not “preg_match”. “home>” matches “at home”, but not “homepage” or “homer”.
| OR-Selection. Use the term to the right or left. “(home|page)” matches “home” and “page”.

Those metacharacters can be combined to powerful RegEx’. Visit regular-expressions.info to get information about different purposes of RegEx and their implementation in programming languages.

Beside metacharacters another part of RegEx are Quantifiers: Characters which define the number of possible occurences of a characters:

* Term may occur never, 1 time or more often.
+ Term may occur 1 time or more often.
= Term may occur never or 1 time.
{n,m} Term may occur between n and m times (including m and n itself).
{n} Term may occur exactly n times.
{,m} Term may occur between 0 and m (incl. m) times.
{n,} Term may occur at least n times.

In the next session we will learn how to use regex’ in Vim :-)

meisterluk’s advent calendar: macros

Sometimes commands are really long. And sometimes you have to execute them several times. I mentioned that you can access older ex commands by using <Up> in command-line mode. This is not available for Vim commands. The solution to this problem are recorded sequences of commands: macros.

Open Vim and write plain text (make sure that noexpandtab is set)

Guido	python
Rasmus	PHP
Dennis	C

We will replace this tab-separated table with rows in HTML syntax. Frist of all, jump to the first row. To start a macro type “q” and a name for a register (eg. “q”; type “q” simply two times). Type this list of keys:

0i  <tr><td><Esc>/<Tab><Enter>xi</td> <td><Esc>$a</td></tr><Esc><Enter>

Of course <Esc>, <Tab> and <Enter> are pressed keys and <tr> is a list of characters to type. End the macros by pressing “q” (the “q” to introduce macros and not the register name) again. With this command the first line looks like this:

<tr><td>Guido</td> <td>python</td></tr>

To execute this commands to the 2 other lines, jump to the second line and type “2@q”. This executes (@) the macro in register (q) (2) times. You can use this macro now wherever you want. It will be saved over several vim sessions. You wrote your first vim macros. Have fun with it! :-)

Fazit einer Nachtschicht

Kann man so betrunken sein, dass man nicht mehr weiß in welcher Straße man wohnt?

Antwort: Ja.

meisterluk’s advent calendar: mappings

Key mappings is used to change the meaning of typed keys. In general it is used to assign the function keys to customized commands.

:map <F2> <Esc>idef ():<Left><Left><Left>

… this would create a function definition and set the cursor to the position of the function name for python programs. Like abbreviations, mappings can be mode-dependent. (:map itself is active for all modes)

  • (i) insert
  • (n) normal
  • (v) visual
  • (o) operator
  • (c) command-line

One mode might not be self-explained: the operator-mode is used whenever you type something like “d” (in normal mode) and Vim is waiting for any other inputs. A small list of special characters:

<Enter> <CR> Enter / Carriage-Return
<C-R> General syntax for any Ctrl key: here Ctrl + R
<Up> <Down> <Left> <Right> The cursor keys
<F2> Function key 2

Back to mappings: There are a lot of special cases. What happens if the mappings “aa” and “aaa” exist? How can I work with the buffer? How can I make mappings file-type-dependent? Sorry, but this would be too much for a blog entry. Use :help mappings to get more information about that.

The stroke unit game

the_stroke_unit_game

via funtasticus

meisterluk’s advent calendar: diff, patch and abbreviate

This is some kind of off-topic, but it’s very useful for texttool lovers. Vim users might want to use it. “diff” shows the differences between files. “patch” can get these differences and update the original file to these patched version. Vim users might want to apply these changes to backup files. The following code is meant to be executed at shell:

echo "#!/usr/bin/env pythonnnprint 'Hello World'" > original.py
vim original.py
    # execute:
    # :set backup
    # :wq
    # :3d
    # oprint 'Hallo Welt!'
   # :wq
diff -u original.py original.py~ > patch.diff
patch -p0 -i patch.diff

The old version (of the first shell command line) was recovered using the backup file.
The last two lines are interesting. See “man diff” and “man patch” for more information. With these tools you can handle small source revision control. But if you want to have an optimized system look for any of the SCMs (Source Control Management) like git, hg or subversion.

Topic-change. Vim tries to minimize the number of typed keys to write a text. Another useful vim feature is abbreviation.

:abbreviate vim Vim " abbr. ab

Whenever you type vim right now you, it will be replaced with Vim. You can prepend a character to enable the abbreviation only in one mode:

  • (i) insert
  • (c) command-line
  • (!) both

:cab vim Vim

This will only replace vim in command-line mode (for example while writing ex commands). In general the replacements are only useful to avoid spelling mistakes:
:iab hte the

meisterluk’s advent calendar: backups

Vim has several mechanisms to prevent data loss. In the last lesson we have learned about swap files. They are create as “.filename.swp” and when exiting Vim, they will be deleted. If Vim is interrupted, Vim cannot exit normally and does not delete “.filename.swp”. As a result an existing “.filename.swp” means, Vim was interrupted the last time during work. Basically it is useful to “set dir” to set path for swp files.

Another feature is writing a copy of the opened file, before overwriting it.

set writebackup " abbr. wb

Create a backup file, before overwriting the current one. The backup file will be removed after writing the original file successfully except the backup option is set.

set backup " abbr. bk

Create a backup file, before overwriting the current one. The backup file will remain after writing the original file. Per default off (set nobackup).

set backupdir " abbr. bdir

A list of directories to use for backup file storage. The first directory with writing permissions will be used. Per default “.,~/tmp/,~/”.

set backupext " abbr. bex

The file extension to append to the filename to mark backup files. Per default “~”. As a result, after modifying “filename.txt”, a backup file “filename.txt~” will remain.

With these options it possible to create your own backup settings.

meisterluk’s advent calendar: settings 3

set background=dark " abbr. bg

Use colors looking good with $background background. Valid values are “dark” and “light”. I prefer “dark”, because I use dark background colors in Vim which are better for my eyes.

set directory " abbr. dir

Write a swap file of the current modified file to this directory. If Vim crashes, you can recover the file. Typcially the swap file is named “.filename.swp” with the original filename replaced with “filename”. The option can also contain a list of directories separated by commas and Vim will write the swap file to the first directory where it is possible to write the file. Per default the option is set to “.,~/tmp,/tmp”.

set fileformat " abbr. ff

Defines the fileformat. Only the newline-symbol is effected:

  • “dos” inserts “rn” for a newline
  • “unix” inserts “n” for a newline
  • “mac” inserts “r” for a newline

Per default Vim auto-detects the fileformat.

set fileformats " abbr. ffs

List of fileformat values, that might occur. “dos,unix” will auto-detect dos- and unix-format, but not mac-format. “dos,unix” is the default.

set hlsearch " abbr. hls

Highlight search matches. “set nohls” is the default.

set history " abbr. hi

On command line you can lookup commands from the past (by pressing <Up>). How much commands shall be stored in the buffer? Per default 20.

set makeprg " abbr. mp

Name of program to use whenever executing “:make” command. Per default “make”.

set makeef " abbr. mef

If “:make” results in an error, unix systems try to write an error file. The option tells the path to this error file. “##” will be replaced by an ID. Per default “/tmp/vim##.err”

set mouse

Enable mouse usage in non-GUI versions of vim. Only works with some terminals like MS-DOS, Win32 and xterm. “:help mouse” tells the possible values:

n
Normal mode
v
Visual mode
i
Insert mode
c
command-line mode
h
all previous modes when editing a help file
a
all previous modes
r
for |hit-enter| and |more-prompt| prompt

set showmode

Show current mode information in bottom line. For example “– INSERT –” for insert mode. The information appears at any of the three modes insert, replace and visual.

This was the last blog entry about Vim’s settings. For any other (which are more system-based) see “:set all” and “:set”.

meisterluk’s advent calendar: settings 2

set autoindent " abbr. ai

If you start a new line with 4 empty spaces, write your text and press Enter to break the line, the new line already starts with 4 empty spaces. So you don’t need to indent for each line, Vim does it for you. If you remove the empty spaces, Vim will do it so on the next line.

set nosmartindent " abbr. nosi

if you write a line with no indentation and end this line with {, the next line will start with indentation, because a code block is expected (C code). Inserting } will auto-remove the indentation in the current line. This optimizes writing C-like code. But also works for files starting single-line comments with #.

set expandtab " abbr. et

Expand tab always to spaces.

set tabstop=4 " abbr. ts

If expandtab is set, this value is used as the number of spaces. So expandtab and tabstop=4 will replace a tab with 4 spaces.

set number " abbr. nu

Add line numbers on the left side of screen. Useful for writing commands with ranges.

set shiftwidth=4

Number of spaces to use for each step of autoindent.

set showmatch " abbr. sm

If you start a block of code with a bracket { and end it with a bracket }, the cursor will jump for a short time to the other symbol (starting or ending bracket) and highlight it. Very useful whenever having a lot of nested brackets.

set matchtime=4 " abbr. mat

Option of showmatch. The time the cursor should jump to the other bracket.

set matchpairs=(:),{:},[:] " abbr. mps

Option of showmatch. Contains all brackets, where the shotmatch takes effect.

set backspace=2 " abbr. bs

2 is the compatible version of “indent,eol,start”. This allows you to treat newlines, indentations and insertion from buffers like normal text, which can be deleted with the backspace key. Value 0 is set per default and compatible to vi.

set wrapmargin=20 " abbr. wm

Vim will auto-break between words if number of characters to the right window border reaches this value.

set textwidth=80 " abbr. tw

The number of characters in one line. Vim auto-breaks if one line has reached this length. 80 is the programming default coding style recommendation. Value 0 disables this feature.

set showcmd " abbr. sc

Show (partial) command in the last line of the screen. With this feature you will get further information about selections in visual mode (especially the number of selected lines)

set ruler " abbr. ru

Like showcmd this adds additional information to the bottom line. The ruler shows information about the current cursor position.

This is only very small documentation of Vim settings. Simply use :help keyword to get further information. Only :help backspace will lead to information about the backspace key (on the keyboard). Use :help backspace? to get information about the command. Vim’s huge documentation files are really nice.

Ins Krankenhaus bitte!

Manche Filme sind natürlich super:

Steigt der Hauptdarsteller in den Krankenwagen ein und meint “Ins Krankenhaus.”

:-D
via “Stirb langsam 4.0″