Archive for the 'Programming' Category

3Monkeys on Emacs: Part 5 - Replace

Thursday, July 12th, 2007

Previous in this series : Part 4 - Search

In my last post I discussed searching, frequently when searching you are looking for something to replace. As with search Emacs offers rich replace commands as well.

Unconditional and Conditional Replace

Unconditional - The command for basic replace is M-x replace-string. This command will prompt you for a target string and a destination string. When executed, it will unconditionally replace all occurrences of the target string with the destination string, from the cursor to the last occurrence of the target string. Two things should be noted. First this command does not have a reverse or backward mode. Second, a source string containing no uppercase letters will be treated as case insensitive.

Conditional - For the more paranoid and the case where only certain occurrences should be replaced, Emacs provides the command M-x query-replace or M-%. Similar to replace-string, this command prompts for a target string and a destination string. When executed the first occurrence of the target string is highlighted and the cursor is placed at its end. At this point the user has a few options to replace or not replace this occurrence, to move to the next occurrence, to unconditionally replace all remaining instance,or abort the command entirely. All of these options are specified by a single keystroke as described in the table below.

Key Effect
SPACE Replace this occurrence and move to the next
DEL Skip this occurrence and move to the next
, Replace this occurrence and do not move on
! Unconditionally replace all remaining occurrences
^ Backup to the previous matching occurrence
ESC Exit query-replace

These two commands will work for most needs, however, we can get more power from the regexp versions.

Regexp Replace

Like the non-regexp versions, the regexp versions come in both conditional, M-x query-replace-regexp and unconditional, M-x replace-regexp flavors. Regular expressions are specified in the same manner as search regular expressions covered in the previous article. What comes in handy is the ability to use prior group construct to build your destination string. For example, suppose you want to change a string such as “Name: lastname, firstname” to “Dear firstname lastname,“. This can easily be accomplished with a target regexp of

Name: +([A-Za-z]+), +([A-Za-z]+)

and a destination string of

Dear 2 1,

Bonus: Narrowing and Widening

One particular method for restricting replace is to narrow the buffer. By narrowing a buffer you limit the portion of the buffer that you can currently view and edit. This can especially be useful when performing a replace operation. For example you may want to replace a variable name with in a particular function. You would first narrow the buffer to the function in question and then perform an unconditional replace operation. This would be much safer and possibly faster than a conditional replace operation.

Narrowing a buffer is comprised of two basic steps. First mark the region you want to narrow to using the M-x set-mark-command, C-SPACE or C-@, and then repositioning the buffer to the beginning or ending of the region of interest. Once a region is defined issue the M-x narrow-to-region or C-x n n command to narrow the buffer. Now any editing actions you take will be applied to the narrowed buffer only, with the exception of M-x save-buffer and like commands which will save the entire buffer. To continue editing the full document you must widen it with the M-x widen or C-x n w command.

Next in this series: Part 6 - Some Fun

Until next time.

-3Monkeys

Popularity: 23% [?]

  • description
  • StumbleUpon
  • Technorati
  • del.icio.us
  • Slashdot
  • Digg
  • Reddit
  • NewsVine
  • SphereIt
  • e-mail
  • Facebook
  • Google
  • Live
  • Propeller

3Monkeys on Emacs: Part 4 - Search

Tuesday, July 10th, 2007

Previous in this series : Part 3 - Buffers and Windows

One of the most common editing task is searching. Emacs has a rich set of commands for searching text.

Incremental Search

The commands for basic search are M-x search-forward and M-x search-backward, however these are rarely used. Instead most Emacs users will prefer to use the incremental search commands M-x isearch-forward and M-x isearch-backward, C-s and C-r respectively. Incremental search has several advantages over normal search. The first you will notice is that as you begin typing a search string in the echo area after issuing C-s or C-r, is that the search is immediate. Consider the following three screen shots.

After typing “e”

After typing “e”

After typing “ea”

After typing “ea”

After typing “early”

After typing “early”

As you can see, with each new character added to the search string, Emacs highlights all visible occurrences of the string and repositions the cursor to the first unique occurrence. Additionally, at any point in specifying a search string issuing the C-s or C-r command will reposition the cursor to the next or previous unique occurrence of the search string.

Regexp Search

Even more powerful than the standard incremental searches, are regular expression (regexp) search. Regexp searches allow the user to use wildcards to find text patterns rather than exact or unique matches. Again these searches come in both a nonincremental and incremental form. For reference only, the commands for the nonincremental versions are M-x re-search-forward and M-x re-search-backward. The more useful incremental regular expression search commands are M-x isearch-forward-regexp or C-M-s and M-x isearch-backward-regexp which does not have a default keystroke binding.

Emacs regular expressions are almost identical to normal UNIX regular expression and those used by other tools such as vi, sed and grep. Although a thorough discussion is outside of the scope of this article, a few points about them should provide some insight. Regular expression are composed of ordinary characters such as A, b, C, 1, 2, 3, and regular expression characters. The two tables below describe both the normal regular expression characters and the set of special regular expression characters, the third table list the syntactic class characters used in the \sc and \Sc special characters.

Regular Expresion Character
Character What it Matches
. Any single character except newline
^ Start of line
$ End of linr
* Zero or more of the previous ordinary character
+ One or more of the previous ordinary character
? Zero or One of the previous ordinary character
[ range ] Any character specified by range
[^ range ] Any charcter not specified by range
\ Used to escape or remove any special meaning from a character

-

Special Characters
Character What it Matches
\t Tab
\n Newline
\\ Backslash
\b Empty string at the begining or end of a word
\< Empty string at the begining of a word
\> Empty string at the end of a word
\` Empty string at the beginning of the buffer
Empty string at the end of the buffer
\w Any character considered part of a word
\W Any character not considered part of a word
\| Seperates multiple regular expressions
\( group \) Treats group as a group of characters to be treated as a single entity
\sc A character of a syntactic class denoted by c
\Sc A character not of a syntactic class denoted by c

-

Syntactic Class Characters
Character Syntactic Class
SPACE Whitespace
w Words
- Symbol names
. Punctuation
( Open balanced expression
) Close balanced expression
String delimiter
< Comment start
> Comment end

An additional construct of regular expression is the prior group reference, which allows you to substitute a prior matching portion to the regular expression. For example the regular expresion \([0123456789]\)\1 would match any occurrences of two identical digets, such as 11, 22, 33 and so on. Emacs regular expressions are greedy, or in other words, tend to try to match as much as possible. So be sure to construct your regular expression with this in mind. One final point, search terms can be reused in later searches by using the M-p and M-n commands when prompted for a search term in the echo area.

Next in this series: Part 5 - Replace

Until next time.

-3Monkeys

Popularity: 20% [?]

  • description
  • StumbleUpon
  • Technorati
  • del.icio.us
  • Slashdot
  • Digg
  • Reddit
  • NewsVine
  • SphereIt
  • e-mail
  • Facebook
  • Google
  • Live
  • Propeller

3Monkeys on Emacs: Part 3 - Buffers and Windows

Friday, July 6th, 2007

Previous in this series : Part 2 - Basic Navigation and Editing

Buffers and Windows

All editing in Emacs occurs within one or more buffers. The key to that statement is “one or more“. It is possible, and usually likely, that multiple editing buffers will be available in a given emacs session. There are other types of buffers, such as the scratch, completion, and shell buffers which serve different purposes other than editing. Let us consider the case of % emacs foo.txt bar.csv, that was introduced in Part 1 of this series. When emacs is started two buffers are created, foo.txt and bar.csv, if those files exist on disk then the contents of those files are populated to their respective buffers. In most implementations of Emacs, the result will be an instance of Emacs with two windows, one for each buffer being displayed, as shown below.

Two windows, Two Buffers
We notice each window contains its own mode line however, there remains only one echo area.

Windows

Windows can be created, removed and navigated with a few simple commands. If you wish to remove the current window use the C-x 0 command. To remove all windows except the current one, use C-x 1. C-x o will shift the focus from window to window in the order they were created. Want to create a window? Use C-x 2 to split the current window horizontally, and C-x 3 to split it vertically. To shrink or enlarge the current window you can use the commands shrink-window, shrink-window-horizontally, enlarge-window, enlarge-window-horizontally. To enter a verbose command use M-x then type with possible tab-completion the command name. If you find yourself using commands frequently, such as these you can bind them to a keystroke command sequence. Binding keystrokes will be covered in a later article.

Buffers

It is not uncommon to have many editing buffers open in a single Emacs session. Consider if you were programming in C, you will likely want to edit both a .c and a .h file concurrently. I have dozens of buffer (files) open at any given time when working on anything but the simplest project. Using windows it is easy to display a class definition while coding its implementation. Switching buffers is a common task when editing in this type of environment.

To switch the current window to another buffer, there are two basic methods, the direct method and the select method. In the direct method use the C-x b command and type the name of the buffer in the echo area. By default the target buffer is the last visited buffer, press return to visit this buffer. Tab-completion, as in most input cases, is supported. If you tab-complete and the buffer name is incomplete a completion buffer is displayed to either help you narrow your choices or allow you to select from. The completion buffer is a subset of the select method. In the select method, use the command C-x C-b, this will open a buffer list buffer. You can navigate to the buffer list window using the C-x o command described above. Navigate to the buffer you wish to visit and press return. The buffer list shows additional information regarding the buffers, such as its modification status, size, mode and associated file.

Buffer List

Finally, you will want to remove buffers or kill them. Use the command C-x k, to kill a buffer. The default buffer is the currently selected buffer, otherwise you can specify another buffer in the echo area. When you kill a buffer associated with a file and it has been modified, Emacs will prompt you to save it or not.

Quiting Emacs

Well it is now the third article in this series, you maybe wondering how to quit emacs. The command C-x C-c will cause Emacs to terminate, it will inform you of any modified buffers and allow you to save them on your way out if you wish.

Next in this series: Part 4 - Search

Until next time.

-3Monkeys

Popularity: 15% [?]

  • description
  • StumbleUpon
  • Technorati
  • del.icio.us
  • Slashdot
  • Digg
  • Reddit
  • NewsVine
  • SphereIt
  • e-mail
  • Facebook
  • Google
  • Live
  • Propeller