// call dbus_watch_handle is a must, it uses internal predefined
// watch handler to do some thing, but i am not quite sure what
// it is right now.
for (l = watchlist; l != NULL; l = l->next) {
fd = dbus_watch_get_fd(l->watch);

Emacs Tips n Tricks for Everybody

This web-page is not yet complete. Several pieces of LISP-code require explanations — I'll add them as I get time.

To try out a code snippet, just add it to your .emacs, re-start emacs and see if any error messages appear (visit the *messages* window in emacs. Alternately, if you're familiar with the basic syntax of LISP, you could position your cursor after a closing parenthesis (the end of a LISP expression) and press C-x C-e (ctrl-x followed by ctrl-e). This would "evaluate" the expression, thereby "executing" the command. Of course, to execute the command automatically every time you start emacs, you would have to add it to your .emacs.

Removing Annoyances

(setq inhibit-startup-message t) will inhibit startup messages.

(setq require-final-newline t) will make the last line end in a carriage return.

(fset 'yes-or-no-p 'y-or-n-p) will allow you to type just "y" instead of "yes" when you exit.

(setq next-line-add-newlines nil) will disallow creation of new lines when you press the "arrow-down key" at end of the buffer.

General Embellishments

(setq modifier-keys-are-sticky t) will make ctrl, shift, alt "sticky" in xemacs. (Does anybody know how to do this in emacs?) With sticky-keys, you dont have to hold down the ctrl/shift/alt key and another key simultaneosly. For example, to type ctrl-a, you'd have to tap on the 'ctrl'-key, followed by a tap on the 'a'-key. This feature is useful for folks with sore wrists/hands.

(setq message-log-max 512) will reduce the number of messages that appear in the "*Messages*" window to 512.

(setq display-time-day-and-date t) (display-time) will make the display of date and time persistent.

With the above global key-bindings, it is possible to press 'f12' (you could change this to any other key you want) and automagically, a partial string gets expanded. For example, if you have typed "mylon" and press 'F12', "mylon" will get replaced by "MyLongIdentifierName" if that string exists somewhere in your set of buffers.

The above function "swaps" the numeric keys with the respective characters (e.g., '*' with '8' and '(' with '9'). Why? It appears to me that the upper row of characters is used more often in C/C++. So we need fewer key-strokes (the 'Shift' is avoided) with the swappings in place. 'F10' and 'Shift-F10' allow u to toggle between these key-swaps.

The function above is funky but useful. Having swapped the pairs ('[', '{'), ('-', '_') and (']', '}'), in order to type "->", we need to type four characters ('Shift' followed by '-' followed by 'Shift' followed by '>'). With the above code, all you need to type is two underscores: '__'). Automagically, they are converted into '->'). Similarly, two successive dots '..' are translated into '[]' (for array indexing). I find that these combinations improve my code-typing speed significantly.

shell-mode Improvements

(setq comint-buffer-maximum-size 10240) set maximum-buffer size for shell-mode (useful if some program that you're debugging spews out large amounts of output).

(add-hook 'comint-output-filter-functions 'comint-watch-for-password-prompt) will disalllow passwords to be shown in clear text (this is useful, for example, if you use the shell and then, login/telnet/ftp/scp etc. to other machines).

The above code will split the Emacs window into two, and start the shell in one of them. The last line invokes (my-key-swap my-key-pairs) which toggles some keys (search for "my-key-swap" on this page to locate its definition).

Basic Tips & Tricks

Emacs initialization

When Emacs is launched, a specific initialization file is read. The initialization file can contain Emacs personal preferences like the functions and key bindings examples in this document. In addition it can contain default state settings for Emacs variables. Some examples are given below.

In the MS-Windows environment the initialization file should be called _EMACS and should be put in the root directory. In UNIX based systems the file should be called .emacs and should be put in the personal home directory.

Key bindings

For maximum typing and editing efficiency, as many keyboard keys as possible should be bound directly to Emacs functions. Some are already bound when Emacs is installed, but the great variety of keyboards and operating systems available makes it difficult for the Emacs team to pre bind functions in general.

To bind a function to a key, include a statement of the form

(global-set-key key-name 'function-name)

in the initialization file. key-name is either given as an actual name within brackets like [f1] for the F1 function key, or as "\C-q" or "\M-q" for a Control-key or Escape-key sequence respectively.

Remember that function that are not bound to a specific key or key sequence (actually this includes most functions) can always be accessed by typing

Esc-x function-name

This document gives many examples of possible Emacs key bindings. Since the name of the keys may differ between keyboards and operating systems, the following approach can be used to find the name of a specific key. Enter

Esc-x describe-key

and hit the key (or key combination) in question. This will reveal the name of the key as well as the function it is currently bound to.

Complete word

Emacs includes a very useful concept called complete word. Whenever in the minibuffer, it is always possible to hit the space bar to let Emacs try to complete the current input. This can save many key strokes and a lot of time.

For instance when looking for a file one can give one letter of a directory or a file name and, in case it is unique, Emacs will fill in the rest automatically. If it is not unique, Emacs will fill in as much as possible and return the different possible completions to let you choose between them.

The Emacs region

Emacs includes a powerful concept called a region. A region is like a marked area in a conventional word processor, but more useful in the way Emacs functions can be applied to it directly, for instance for sorting just a few lines of a file, or for printing a portion of a file.

A region is set implicitly by many Emacs functions, but can be set manually as well using Ctrl-Space. This specifies the current cursor position as one end of the region, called the mark. The cursor can then be moved around and its position will specify the other end of the region.

Cut, copy and paste key bindings

Based on the description of a region above, defining the common functions Cut, Copy and Paste on the region becomes very useful. The functions should be bound to keys for easy access, for instance like:

An element that is cut or copied this way is put into something called the kill-ring. Calling the yank function always pastes the last entry from the kill-ring. However, after the yank function as called, it is possible to replace the pasted text by the second last entry in the ring and so on by calling the yank-pop (by default boud to the Esc-y key) function repeatedly. In effect, all cut/copy operations of the session is registered, and are easily accessible through this simple sequence of key strokes.

Column handling

A feature that are missing in most editors and word processors is the possibility to cut/copy and paste a vertical region of a file. In Emacs this is simple. The column to cut or copy is marked as a region as described above. It can then be cut calling the function kill-rectangle and re-pasted by yank-rectangle

Navigation key bindings

These are the basic navigation keys. Many keyboard come with two sets of these keys, so each function is bound once for each key. Some of these functions are usually already bound when Emacs is installed.

Undo

Emacs has the most amazing undo facility. Anything you have typed since your session began is registered and can be undone. Since this obviously is a very useful function it should be bound directly to a key. Using the keypad [-] (subtraction) key for this purpose is convenient since it indicates the nature of the operation as well as being located so far away that it isn't easily accessed by accident.

(global-set-key [kp-subtract] 'undo) ; [Undo]

Insert/overwrite mode

By default Emacs run in insert mode. This state can be toggled with overwrite mode, and is best bound to the Insert key(s) on the keyboard.

Goto line

To go to a specific line can be useful, especially when Emacs is used for programming. This common function can be bound to Ctrl-L by:

(global-set-key "\C-l" 'goto-line) ; [Ctrl]-[L]

Window splitting

The Emacs window can be split so that is can display two or more buffers at the same time. This can be useful when comparing two files, or when editing two files simultaneously. Functions for managing window splits:

Frames

As well as displaying more than one buffer in a window, Emacs can also display more than one window (or frames as it is called in Emacs terminology). Creating and deleting frames can conveniently be done by binding the the functions as follows:

Getting information

Emacs contains lots of features and possibilities and it can be difficult to comprehend and utilize it all. However, Emacs comes with full documentation included. One of the more useful functions is apropos:

[ESC]-x apropos

This command prompts for a name or a concept and will return list of all functions or variables that relates to the entry given. This is a very useful approach for getting to know Emacs and the possibilities it contains.

Given an Emacs function or a variable it can sometimes be difficult to know exactly what it does. An explanation of a function or a variable can be obtained by:

[ESC]-x describe-function
[ESC]-x describe-variable

They will prompt for a name and return a comprehensive description of it.

Similarly, as described above

[ESC]-x describe-key

prompts for a key and returns the name of the key and the function it is currently bound to.

File Finder

This extension to the powerful Emacs complete-word facility is the major time saver for the frequent Emacs user. It is used within the find-file function and makes it possible to enter a given directory in the minibuffer by just entering a predefined two- to four letter sequence followed by the space key. Three different paths are given in the example below. The list can however be extended indefinetly.

Buffer Switcher

After a file has been loaded once, it is available in an Emacs buffer. Emacs is installed with lots of clever functions for fast retrieval of buffers. The function below is different however. It makes it possible to browse through the buffer list by single key-strokes only. It is also clever in its handling of the buffer stack in the way that the most frequent visited buffers (i.e. files) always are at the top of the stack.

When you are definitely done with a buffer (i.e. a file) it can be convinient to remove it from the buffer stack. To silently remove the current buffer from the stack (and retrieve the next one on the stack), bind the following function to the Ctrl-Del key.

Navigator

For fast navigation within an Emacs buffer it is necessary to be able to move swiftly between words. The functions below change the default Emacs behavour on this point slightly, to make them a lot more usable.

Note the way that the underscore character is treated. This is convinient behaviour in programming. Other domains may have different requirements, and these functions should be easy to modify in this respect.

Emacs for Programmers

Modes

During editing Emacs can be set in different modes. The mode has some knowledge about the structure of the document the user is working on, and can assist on the organization, formatting and editing of this.

This is particularly helpful when Emacs is used for programming, since programming languages in general has rigid sets of restrictions regarding document structure. For instance, programming statements are normally indented according to specific rules, and if the mode know the rules, it can do the indentation for the user automatically.

There exists modes for all major and minor programming languages and most types of documents such as HTML, Perl scripts, shell scripts, Unix Makefiles, CSS etc. The mode is automatically set by Emacs based on the name or the extension of the file edited.

Color coding

A very useful feature is Emacs' ability to render text with different colors and fonts. Emacs packages for color coding analyse the structure of the text and color the text according to the structure. For instance can programming comments get one color, reserved words a different color, function definitions yet another and so on.

A popular color coding package that comes with the standard Emacs distribution is hilite. To use it, include the following statement in the initialization file:

(load "hilit19")

During editing, it is in general impossible for the color coding package to color the text since the structure of the edited part of the document may not yet be complete. Beacuase of this, it is handy to be able to refresh the color coding manually. This is done with the function hilit-highlight-buffer which can be bound to a key combination for convenience.

Including predefined element skeletons

Many of the text elements that are used in programming has a standard form based on common skeletons. The ability to include skeletons like these with a single keystroke can be very useful and time efficient.

For instance, declaration and documentation comments in Java follow the rules dictated by the javadoc automatic documentation system. A typical javadoc method comment will look something like this:

/**
*
* Returns the character at the specified index. An index
* ranges from <code>0</code> to <code>length()-1&</code>
*
* @param index of the desired character
* @return the desired character
* @exeption StringIndexOutOfRangeExeption
* if the index is not in the range <code>0</code>
* to <code>length()-1&</code>.
* @see java.lang.Character#charValue()
*/ public char charAt(int index) {
...
}

To create a skeleton that can be included directly into a java source file, include the following LISP function in the Emacs initialization file:

So hitting F9 will in effect include a javadoc method comment skeleton at the cursor position and move the cursor to the position within the comment where the description should start.

Along the same lines it is easy to predefine a large number of code elements, for instance while loops, if-then-else constructions, file headers etc. and make them available by single key strokes or key combinations.

110 Restart marker reply. In this case, the text is exact and not left to the particular implementation; it must read: MARK yyyy = mmmm where yyyy is User-process data stream marker, and mmmm server's equivalent marker (note the spaces between markers and "=").
重新启动标志回应。这种情况下，信息是精确的并且不用特别的处理；可以这样看：标记 yyyy = mmm 中 yyyy是 用户进程数据流标记，mmmm是服务器端相应的标记（注意在标记和等号间的空格）

120 Service ready in nnn minutes.
服务在NNN时间内可用

125 Data connection already open; transfer starting.
数据连接已经打开，开始传送数据.

150 File status okay; about to open data connection.
文件状态正确，正在打开数据连接.

200 Command okay.
命令执行正常结束.

202 Command not implemented, superfluous at this site.
命令未被执行，此站点不支持此命令.

211 System status, or system help reply.
系统状态或系统帮助信息回应.

212 Directory status.
目录状态信息.

213 File status.
文件状态信息.

214 Help message.On how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user. 帮助信息。关于如何使用本服务器或特殊的非标准命令。此回复只对人有用。

215 NAME system type. Where NAME is an official system name from the list in the Assigned Numbers document.
NAME系统类型。