Difference between revisions of "Emacs"
m (→Customization: use setq for setting things)
|(One intermediate revision by the same user not shown)|
|Line 395:||Line 395:|
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.
== Resources ==
== Resources ==
Revision as of 18:25, 5 April 2012
Emacs is the extensible, customizable, self-documenting real-time display editor. At the core of Emacs lies an Emacs Lisp interpreter, the language in which the majority of Emacs' built-in functionality and extensions are implemented. GTK is the default X toolkit used as of GNU Emacs 22, though it functions equally well within a CLI environment. The text-editing capabilities of Emacs are often compared to that of vim.
- 1 Installation
- 2 Quick Start
- 3 Tips and tricks
- 4 Troubleshooting
- 5 Alternatives
- 6 Resources
Emacs comes in several variants (sometimes referred to as emacsen). The most common of these is GNU Emacs, which can be installed (as root) via:
# pacman -S emacs
Another common variant is xemacs, which is also available for installation via pacman.
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting Help->Emacs Tutorial from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.
Emacs also includes a set of reference cards, useful for beginners and experts alike, see
/usr/share/emacs/<version>/etc/refcards/ (substitute <version> for your version of emacs).
To start Emacs run:
or, to use it from the console:
$ emacs -nw
A file name can also be provided to open that file immediately:
$ emacs filename.txt
As a daemon
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:
$ emacs --daemon
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect both graphical and console clients to the daemon at the same time and make the GUI to start quickly.
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):
$ emacsclient -c
If you still want a console client no matter you are in a graphical environment then use:
$ emacsclient -t
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line
$ Exec=emacs %f
$ Exec=emacsclient -c
This way, a client will be called each time you open up a file and so be very fast!
Basic terminology and convention
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.
The one piece of terminology which must be introduced early is the concept of buffers. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.
The convention for key sequences in Emacs may be unfamiliar. Namely:
C-x refers to Control-x
M-x refers to Meta-x
For example, to exit Emacs use the following key sequence: C-x C-c. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as point in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use C-f and to move one character backward, C-b. C-n and C-p can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. M-f moves forward one word and M-b will move point one word backward. Similarly, M-e moves point one sentence forward and M-a one sentence backward.
Until now, all of the movement commands introduced have been relative to point. M-< can be used to move point to the beginning of the buffer, with its counterpart, M->, moving to the end of the buffer. To move point to a specific line number, use M-g g. M-g g will prompt for the desired line number. Also, to move to the start or end of the current line, use C-a or C-e, respectively.
Files and buffers
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. C-x C-f is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. C-x C-s can be used to save a buffer. To save a buffer with a different filename, use C-x C-w (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with C-x s, which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the minibuffer. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. <TAB> can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the Up Arrow or C-p.
To exit the minibuffer at any time, press C-g.
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides C-x b, which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.
A list of all open buffers can be displayed using C-x C-b. Should a buffer no longer be required, it can be removed with C-x k.
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via C-_ or C-/. Movement commands generally also have a corresponding delete command. For example, M-<backspace> can be used to delete a word backwards, and M-d to delete a word forwards. To delete to the end of the line, or the end of the sentence, use C-k or M-k, respectively.
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as filling in Emacs. A paragraph can be filled using M-q.
Characters and words can be transposed using C-t and M-t, respectively. For example:
Hello World! →
The case of words is also readily adjustable. M-l downcases a word from point (
hello); M-u upcases a word from point (
HELLO) and M-c capitalizes the first character of a word from point while downcasing the remainder (
Killing, yanking and regions
A region is a section of text between two positions. One of those positions is referred to as mark, and the other is point. C-<SPC> is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are killing commands.
In Emacs, cut and paste are referred to as kill and yank, respectively. Many commands which delete more than one character (including many of those in the above section, such as C-k and M-d) actually cut the text and append it to what is known as the kill-ring. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.
C-w and M-w can be used to kill and copy a region, respectively.
To insert killed text into a buffer (known as 'yanking'), use C-y. C-y can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however C-y only retrieves the first of them. The earlier kills can be accessed via M-y. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. M-y must be used immediately following C-y and can be used in many times succession to cycle through the kill-ring.
Search and replace
Searching for a string is common practise in text-editing. This can be performed using C-s (to search forward) or C-r (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press C-s or C-r again, respectively. Once a match has been found, <RET> can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use C-g.
Once a search is completed (i.e., was not aborted with C-g or similar), the string which was searched for will be the default for any following search. To make use of this, press C-s C-s or C-r C-r to search forward or backward again, respectively.
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use C-M-s or C-M-r to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, C-s and C-r can be used to search forward or backward, just as with string searches.
In addition to searching, it is also possible to perform string and regular expression replacement (via M-% and C-M-%, respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing ?), the most commonly used are y, to perform replacement, n, to skip this match, and ! to replace this, and all following matches.
Indentation and prefix arguments
Indentation is usually performed with either <TAB>, to indent a single line, or with C-M-\, to indent a region.
Exactly how text is indented usually depends on the major-mode which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See Modes for more information.)
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see Killing, yanking and regions) then perform indentation with C-u <n> C-x <TAB> (where '<n>' is the number of columns which the text within the region should be indented). For example:
Increase the region's indentation by four columns:
C-u 4 C-x <TAB>
Decrease the region's indentation by two columns.
C-u -2 C-x <TAB>
Windows and frames
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as windows and frames.
A window is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a mode-line, which displays information for that buffer.
A frame is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').
From now on the definition of these terms as they exist in Emacs will be used.
To split the window vertically or horizontally, use C-x 2 or C-x 3, respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use C-x o.
The opposite of splitting a window, is deleting it. To delete the current window, use C-x 0 and C-x 1 to delete all windows except the current.
As with windows, it is also possible to create and delete frames. C-x 5 2 creates a frame. With C-x 5 0 to delete the current frame and C-x 5 1 to delete all except the current frame.
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:
C-h t Start the Emacs tutorial C-h b List all active keybindings C-h k Find which command a key is bound to C-h w Find which key(s) a command is bound to C-h a Find a command matching a description C-h m Display information regarding the currently active modes C-h f Describe the given function
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:
M-x sh-mode <RET>
M-x column-number-mode <RET>
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:
M-x line-number-mode <RET>
sh-mode is a major-mode. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:
C-c ( Insert a function definition C-c C-f Insert a 'for' loop C-c TAB Insert an 'if' statement C-c C-w Insert a 'while' loop C-c C-l Insert an indexed loop from 1 to n
'line-number-mode' and 'column-number-mode', are minor-modes. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.
Tips and tricks
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:
To prompt for the root password before opening /etc/hosts with root permissions:
C-x C-f /su::/etc/hosts
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:
C-x C-f /ssh:myuser@myhost:~/example.txt
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.
Keyboard macros and registers
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, keyboard macros and registers.
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.
The first feature which will be introduced is registers. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.
The other which will be demonstrated is keyboard macros. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.
Starting with a buffer containing our set of characters:
Prepare a register by invoking the `number-to-register' command (C-x r n) then storing the number '0' in register 'k':
C-x r n k
With point at the beginning of the buffer, start a keyboard macro (C-x () and begin to format the characters:
C-x ( C-f M-4 .
Insert (C-x r i) and increment (C-x r +) the register 'k'. The prefix argument (C-u) is used to leave point positioned after the inserted text:
C-u C-x r i k C-x r + k
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. C-x e completes then invokes the keyboard macro. The prefix argument, M-0, causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.
<RET> M-0 C-x e
A....0 B....1 C....2 [...] x....49 y....50 z....51
From the Emacs Manual: "A regular expression, or regexp for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See Regular Expressions section in the Emacs Manual for further reading.
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see Keyboard macros and registers). Again, starting with a buffer containing.
At the beginning of the buffer, use C-M-% (if the key-sequence is difficult to perform, it may be more comfortable to use M-x query-replace-regexp). At the prompt:
which simply matches one character. Then, when prompted for the replacement:
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.
Finally, press ! to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.
Emacs can configured by editing '~/.emacs' or using M-x customize. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:
C-M-x with point anywhere within the expression.
C-x C-e with point following the last ')'
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:
(defalias 'yes-or-no-p 'y-or-n-p)
To stop the cursor blinking, use:
Similarly, to enable column-number-mode, as discussed in the previous section:
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.
(scroll-bar-mode -1) (menu-bar-mode -1) (tool-bar-mode -1)
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.
(setq auto-mode-alist (append '(("\\.tut$" . text-mode) ("\\.req$" . text-mode)) auto-mode-alist))
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a hook. For example, to force indentation to use spaces instead of tabs, but only in text-mode:
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))
Similarly, to only use spaces for indentation everywhere:
(setq-default indent-tabs-mode nil)
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make F8 delete any whitespace from the end of each line of a 'text-mode' buffer:
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' (C-M-%) to '<f7>'.
(global-set-key (kbd "<f7>") 'query-replace-regexp)
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both F7 and C-M-% after the above example.
Almost anything within Emacs can be configured. Browsing through the Emacs Wiki should give a solid place to start.
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the AUR. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the Emacs Wiki, which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.
You can also use the Emacs Lisp Package Archive (ELPA) to automatically install packages. See the website for instructions. ELPA will be included with Emacs 24 (the next version of Emacs); it is an accepted part of the Emacs ecosystem.
Colored output issues
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.
Including the following into
~/.emacs amends the problem:
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
Menus appear empty
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding Debian bug report contains a workaround.
Problems displaying characters in X Windows
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install xorg-fonts-75dpi and/or xorg-fonts-100dpi and restart X windows.
Slow startup times are often caused by one of two things.
To determine which it might be, run Emacs with:
$ emacs -q
Incorrect network configuration
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to 'set the hostname' in the network configuration guide for information.
Init file loads slowly
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:
you might use:
(autoload 'anything "anything" "Select anything" t)
Cannot open load file: ...
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:
(add-to-list 'load-path "/path/to/directory/")
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:
(add-to-list 'load-path "/usr/share/emacs/site-lisp")
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular.
Lighter Emacs compatibile alternatives can be found in Arch repositories or in AUR.
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.
It's possible to install mg right away from
# pacman -S mg
or download source from official page.
According to the offical web page "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".
zile can be found in
# pacman -S zile
the latest taballs can be found at official GNU mirrors.