Emacs notes

From Helpful
(Redirected from Emacs)
Jump to navigation Jump to search

Introduction

Emacs is a multi-document, windowable editor with widely scriptable functionality (although most people don't, since LISP isn't for everyone).

(When adding things: try to separate the stuff you've consistently used for a long time from the stuff you know about and might be useful. This just in an effort to keep this a quick overview rather than something to surf away from. You can link to complex stuff or cheat sheets for completism)


Some of its jargon

A buffer is, in practice, often a document/file. Buffers are also used to display temporary feedback, output, shells, mail clients if you use it, or anything else that needs to query or inform you using more than one line.


The Minibuffer is the bottom-most line on the screen that shows messages, and where the occasional question is asked and answered. Things like which file to open, what to save as, which function to call via M-x command

You can often use tab completion (commands, filenames, more).


Notation used here, shortcuts vs. commands

In key-combo references, the M refers to Meta, almost always Alt. If for some reason Alt doesn't work for you (for example because of a mismatched remote shell setup), you can emulate M-x by pressing escape, then x.


C-a b specifies that you should hold Control only while you press a, then hit b. These are case-sensitive, so eg. (the nonexistant) C-@ A would in real-button terms mean Control-Shift-2 Shift-A.


Most everything in emacs can be done via M-x command. Key shortcuts tend to just run these commands, which is why there is often more than one way to do something. For example:

  • M-x save-buffer, which saves a file. Of course, most people just uses the...
  • C-x C-s shortcut because it's shorter.


Before I forget:

  • C-g terminates a current action. Three presses of Esc often also works, but may have side effects in some circumstances, such as minibuffer key/text input that accepts escapes.

Looking around the tutorial (C-h t) to learn various controls.

Help

Finding commands and their according key shortcuts can be done with:

  • C-h a which allows you to search descriptions of functions.
  • C-h m gives you help for the mode(s), including key shorcuts it introduces, and a basic descriptionl
  • C-h C-h, help about using the help system
  • C-h k followed by some key combination displays the meaning of that key combination.


Files and buffers

There are more file functions, but this is what I use almost all of the time:

  • C-x f opens a file (in a new buffer)
  • C-x s save a buffer (with current pathname, if any, otherwise acts as save as)
  • C-x w write buffer as... (queries for filename to save as)
  • C-x k closes ('kills') current buffer. (Asks for save if changed.)


When you have more than one file open, you'll have one buffer for each and some extra ones besides. Switching to what you want is probably best done via:

  • C-x b

By default this will show the last buffer you were in, allowing you to quickly switch between two buffers. Pressing tab will give a temporary window with the list of all buffers. You can use tab completion.

(In the X version of emacs you can get and immediately choose in the buffer list with C-left-mouse-hold .)


Modes

Many types of files have a mode and a command to get into them (via Meta-x). The main thing for many is that TAB-indentation and syntax highlighting of code (you often still have to do a Meta-x font-lock-mode for that) is automatically done this way, but there are often other benefits. Some modes are quite advanced, such as nxml-mode, which includes a XML validator.

For example, you often have most of php-mode, python-mode, nxml-mode, html-mode, c++-mode, prolog-mode, latex-mode, fundamental-mode (no special behaviour).

From within teach of these you can get basic description and help with Control-h m, which also lists key shortcuts the mode introduces, which can be useful for people who code in a language a lot.

You can get a list via the command search (C-h a and search for -mode). Actually, there are modes for more than files, as you'll see.


Navigation

The arrow keys work. Their key-combo analogues:

  • C-f: Move cursor forward one character
  • C-b: Move cursor back one character
  • C-p: Move cursor up one line to previous line
  • C-n: Move cursor down one line to next line
  • C-a or Home: Move cursor to start of line
  • C-e or End: Move cursor to end of line


  • M-f - move forward a word (also C-rightarrow, but only in the X variants)
  • M-b - move back a word (also C-leftarrow, but only in the X variants)


Cutting, copying and pasting -- marking and moving

Kill and yank - Most people know the following two:

  • C-k takes the line right of the cursor and puts it in the killring.
  • C-y yanks the killring and puts it where the cursor is.

Note: Direct successions of C-k take the next lines and append it to the killring. (separation by movement/and or time will make the next kill overwrite the killring)


Mark and region - There is a concept of a region (what you might think of as a selection) which is the text between the cursor and the mark (which is really just a remembered position), when the mark is active.

  • C-space set the mark to the current cursor position (also C-2 and C-@, which may be useful in strange terminals).
  • C-w cuts: it moves the text between the mark and the cursor into the killring.

There are other things you can do with the region, such as letting the mode reformat it with proper indents, converting tabs to spaces in it, and any other command which works on the region. Something I use occasionally is:

  • C-x C-x exchanges the cursor and the mark. (can be useful for jumping between two points quickly)

Possibly useful:

  • M-h puts region around current paragraph (sets cursor and mark)
  • C-M-h puts region around current function definition (various modes)
  • M-@ selects the next word


(See what registers are)

Editing tricks

  • C-_ is undo. C-x u is redo, but note that this will remove your undo history(verify)
  • M-/ autocompletes document text. This is based on frequency counts of all open documents(verify), so this works great on long variable names.

Searching and replacing

Search:

  • C-s string (repeat Control-s for next match. Press enter to put cursor at current match position)
  • C-M-s regexp Regexp search
  • C-r string search, backwards
  • C-M-r regexp ...backwards

Replace:

  • Interactive: M-%
  • Noninteractive: M-x string-replace
  • regexp, interactive: C-M-%
  • regexp, noninteractive: M-x replace-regexp


See also slightly longer summary [1].


In replace-regexp:

  • You need to do some non-trivial escaping. (I need to summarize this)
  • \& refers to the whole match (regardless of groups) so mostly useful to append things.
  • \1, \2, etc. refer to bracketed groups (starts at 1)
  • \# means the number of replacements done so far (starts at 0)


Note that a number of things must be escaped, including () and \\. For example, to rewrite =Introduction= as \section{Introduction} (mediawiki style headers to LaTeX), try:

M-x replace-regexp RET ^=\([^=]+\)+=$ RET \\section{\1}


You can enter a literal newline in the minibuffer with C-q C-j. (C-q avoids other possible interpretations, which is also interesting with e.g. C-q Tab, also in regular editing.

Sectioning the interface

I tend to like looking at data and code, or potentially code and command line executing that code. The sections are windows on your code (not related to buffers; doesn't close them)

  • C-x 2 adds a window via a vertical split
  • C-x 3 adds a window via a horizontal split
  • C-x 1 makes the current window fullscreen (the only one)
  • C-x 0 removes the current window from the current split

Switching can be done via:

  • C-x o moves to the next window.


Running a shell:

  • M-x shell runs a shell in the current window (dumb terminal, though). This can save you another xterm, although in my experience it takes too many keypresses to get to it unless it's in one of a two-window split.

(resizing windows nicely?)


Common problems

"I'd like to use a literal newline in searches. How?"

You can enter a literal newline in the minibuffer with C-q C-j.

C-q allows other special characters, including C-q Tab


File exists: /home/username/.emacs.d/

...and, if you specified a filename to open, it isn't loaded.

Typically means that that directory exists but the user can't access it:

# ls -la ~ | grep emacs.d
drwx------  3 root  root  4096 okt  2 16:42 .emacs.d

A chown should fix it. If that's too much bother and you never had any custom config, you can remove it instead.

Inserting special strings

This can mean various things, such as:

  • binding keys to output a particular string (Unicode char, code template) -- see basic key shortcuts
  • inserting unicode via configurable names, such as an alpha character when you type "alpha". See abbrev-mode)


See also:

"emacs: Cannot connect to X server localhost:10.0." Huh?

This is because you have a DISPLAY set, but either there is no X server on the other end, or you're not allowed to use it.

This can happen when you have a remote connection and have DISPLAY set without good reason. This includes cases in which you told the client to always enable X forwarding but (currently) have no X server. The error specifically mentioning localhost:10.0 suggests you have PuTTY's X forwarder on. You should disable the X forwarding it if you usually don't have an X server for it to go to.

You can also force emacs to be purely text-mode and ignore X by using emacs -nw (short for --no-windows, which doesn't use X and ignores $DISPLAY'')

"Pasted code gets indented up the wahoo. Why?"

That's your active mode trying to be smart about indenting what you type.

The underlying problem is that there is no good way to distinguish between you typing and you pasting text.


You can avoid having to re-indent everything you pasted by switching to fundamental-mode for the paste, and back to the mode you were in afterward.

Configurable behaviour

The easiest way to have behaviour in all your sessions is to figure out what to place in your ~/.emacs file. Create it if it doesn't exist. There is no required header or wrapping structure - most of the below can be just pasted in it, as separate chunks.

"I always want pretty colors."

You can force fontification for all modes that support it using:

(global-font-lock-mode 1)


Configurable colors

"How do I remove the startup message?"

(setq inhibit-startup-message t)

"I want the mode (and highlighting) to be set based on the file extension."

Assuming you have the mode, emacs usually does this already, since package installation of the respective modes usually alters the global emacs configuration to hook these in.

You may well want to add extensions, like:

(setq auto-mode-alist (cons '("\\.java$" . java-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("\\.cxx$" . c++-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("\\.hxx$" . c++-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("\\.txt$" . text-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("\\.wsgi$" . python-mode) auto-mode-alist))

"Damn those tabs, I want spaces."

Emacs by default uses a combination of tabs and spaces, which can really come to bite you with things like python, where indent is syntactic and semantic rather than just aesthetic (or, for some coders, far from it).

To globally prefers spaces over tabs:

(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)

setq-default is preferred over setq as the former applies as a global default, but is overridden by the buffer's mode if it has its own ide.

(I assume that setq default-tab-width has the same effect as setq-default tab-width)(verify)


Note that you can convert tabs in the current region to spaces with M-x untabify. (you may sometimes wish to change tab-width first)


"I want to see the region (selection)."

In transient mark mode[2], the space between the mark and the cursor is highlight (in X and on color capable terminals).

Note that enabling this will change the way you think of the mark. When visible, you will probably treat it as a a selection that something needs to be done with fairly immediately - you won't leave it around since it's visually disturbing; you'll find some way to disable a set mark (e.g. C-g), and you probably won't use it for tricks like C-x C-x (switch mark and cursor positions, to quickly go back and forth between two positions in the buffer).

Use M-x transient-mark-mode to try it, or set it in .emacs:

(transient-mark-mode t)

If you want this out of "I just started using emacs and it's all different and icky," I suggest you give regular (invisible) regions a try. You get used to it.

"How do I install a mode as a user?"

Not sure as to the details, but something like:

(setq load-path (cons "/home/myaccount/myemacsstuff/python-mode/" load-path))
(autoload 'python-mode "python-mode" "" t)

worked for me. (where python-mode is the directory with, in this case, python-mode.el in it)

Adding and removing keyboard shortcuts

It's probably not a brilliant idea to alter the common workings so that uncustomized emacses will confuse you and yours will confuse others.


On the other hand, all C-c singleletter combinations are intentionally left undefined (by emacs and most modes and packages) for your own functionality.


To add a keyboard shortcut, you usually use (global-set-key keyspec 'functionname)

I personally like to hook in interactive regexp search (isearch-forward-regexp). The following example replaces C-t, 'transpose characters' (which puts it next to C-r, search backwards)

(global-set-key [(control t)] 'isearch-forward-regexp)


You can also remove keybindings. For example, a lot of people have some other or past key combo they hit out of habit. For me this is Control-T, firefox for 'new tab', which in emacs transposes two caracters, which I have never needed, but have frequently done and not noticed until they turn out to be syntax errors. I added the following to my .emacs file:

(global-unset-key "\C-t")


See also:


specifying keys

There are multiple ways/levels to specify a key shortcut, and various emacses may have slightly varying interpretations (know that that can be the cause of problems, and that you may need to tweak things a bit).

The three major ways are:

  • (kbd "C-5") and (kbd "M-<f7>"), which seems generally handiest as it allows some things that are otherwise hard to specify
  • "\C-t" seems shortest for simple combinations
  • [(control /)] and [(meta shift h)] can be clearer to read


kbd knows names like

  • the Fn keys (e.g. "<f2>")
  • keypad specifics (e.g. "<kp-2>" for the 2 on the keypad)
  • "<tab>"
  • "<insert>", "<delete>", "<home>", "<end>"
  • page up, page down: ("<prior>", "<next>")
  • arrow keys ("<left>", "<right>", "<up>", "<down>")
  • Return/Enter ("RET"), space ("SPC")
  • mouse buttons


If you want to figure out what a key is bound to, for example which of the various search functions C-s is bound to, you can use M-x describe-key (also available under C-h k).


You can use special keys such as the windows, menu, the Mac option, command and such keys, given that your X configuration maps them to super, hyper, or possibly meta.

This may involve a little work on each computer, which can sometimes vary between computers, but can be worth it.


key arrival (text mode, X)

Text-mode emacs (as in emacs -nw) is a special case. In X, emacs listens to the X keyboard interface, but in terminals, most things arrive as escape sequences instead. It is generally easiest to figure this out on the emacs side.

You can also reconfigure X's keyboard model, for example to map caps lock, command/option/windows/menu keys to modifiers (see [3] and various online resources).


Since both these things change the way you should configure emacs, you will probably appreciate M-x view-lossage, which shows how recent keyboard input has arrived (and whether it has at all - can be useful to see whether (remote) shells choose to filter certain things out).


For example, the way F3 arrives via my remote shell led me to add:

(global-set-key (kbd "ESC [ 1 3 ~") 'isearch-forward-regexp)  ; interactive regexp search

...and them some experiments:

; F5, F8: navigate between paragraphs.  
;         I also have a variation that skips between functions; see below
; F6, F7: navigate between words
(global-set-key (kbd "ESC [ 1 5 ~") 'backward-paragraph) 
(global-set-key (kbd "ESC [ 1 7 ~") 'backward-word)
(global-set-key (kbd "ESC [ 1 8 ~") 'forward-word)
(global-set-key (kbd "ESC [ 1 9 ~") 'forward-paragraph)
</code>
<syntaxhighlight lang="lisp">
;F1, F2: instant switch to previous and next buffer
; download bubble-buffer.el to get these commands
(when (require 'bubble-buffer nil t)
  (global-set-key (kbd "ESC [ 1 1 ~") 'bubble-buffer-previous)
  (global-set-key (kbd "ESC [ 1 2 ~") 'bubble-buffer-next)
  ;or leave it at:
  ;(global-set-key [f11] 'bubble-buffer-next)
  ;(global-set-key [(shift f11)] 'bubble-buffer-previous)
)
;F4: switch to other window (when using window splitting)
(global-set-key (kbd "ESC [ 1 4 ~") 'other-window)   ; shorter than M-x o
</code>


===Binding your own functions===
...is not a special case as such -- besides having to write or at least creatively copy-paste LISP, and and getting mode-specifics right. Simple example functions {{comment|(and note that these are similar the already existing <tt>py-beginning-of-def-or-class</tt> and <tt>py-end-of-def-or-class</tt> functions normally bound to ESC C-a and ESC C-e)}}:
<syntaxhighlight lang="lisp">
(defun find-previous-python-function ()
  " move to previous python function "
  (interactive)
  (re-search-backward "^[\\s]*def ")
)

(defun find-next-python-function ()
  " move to next python function "
  (interactive)
  (re-search-forward "^[\\s]*def ")
)

To add bindings for only a specific mode (so that you e.g. generally get paragraph jumping but function jumping in python-mode), you use define-key for a specific mode's keymap. That mode map reference may not be defined when your .emacs file is loaded, though. For python, you work around this by adding the registrations in a hook, for example:

(add-hook 'python-mode-hook
  '(lambda ()
     (define-key py-mode-map (kbd "ESC [ 1 5 ~") 'find-previous-python-function)
     (define-key py-mode-map (kbd "ESC [ 1 9 ~") 'find-next-python-function)
   )
)

See also

Keyboard macros

Keyboard macros record series of actions (usually keyboard commands) that you can quickly replay. Can be used as a 'give one example of how to change, then repeat many times' thing.

  • C-x ( starts recording
  • C-x ) stops recording
  • C-x e executes the just recorded macro
  • C-x C-k edits the just recorded macro (how? append?(verify))

You can use the 'repeat the following command so-many times (C-u <number> command) to repeat it a number of times.

You should consider consider exception cases. For more robust macros you will generally find the more semantic movement commands useful, such as:

  • M-f, M-b: forward or back a word (Also Esc, f, Esc, b)
  • C-a, C-e: start, end of this line

And perhaps:

  • C-f, C-b: forward or back a character
  • C-n, C-p: next, previous line

Example: I have ISBN registrar ranges per prefix (copy-pasted from a pdf, cleaned up with some simple string replaces), e.g.

0 0 19
0 200 699
0 7000 8499
0 85000 89999
0 900000 949999
0 9500000 9999999
1 0 9
1 100 399

And want to transform this into code that creates an array, perhaps:

prefix['0'].append( ( 0, 19 ) )
prefix['0'].append( ( 200, 699 ) )


This comes down to something like C-x ( prefix[' M-f '].append( ( M-f , M-f ) ) C-n C-a C-x ). That C-a C-n near the end puts the cursor on the first character of the next line so that the macro can immediately be applied again, for example in batches like C-u 5 0 C-x e to apply it fifty times.


See also


Semi-sorted

Character codings, unicode

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.

In general

Viewing

One simple way you can check whether your setup can show Unicode is to run

view-hello-file

This should show the most interesting scripts. Can also be useful in picking a font.


On remote

First make sure you can unicode shows in general (view-hello-file).

If you don't see non-ASCII characters at all, you probably want to check your client / terminal emulator.

For example, in the case of PuTTY you want to tell it to use UTF-8.


On the text console

First make sure unicode shows in general.

In this case, you rely on the locale as well as the console font. And systems may have defaults that avoid unicode fonts (verify)


Loading and saving

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.

Apparently emacs's in-memory representation is (a superset of?) unicode, which means you mistly care about:

  • the conversion that happen when loading
  • what coding emacs thinks the buffer is in (as that controls what it does to the contents when you edit it)
  • the conversion that happens when saving

(There's more, of course, for example the default for new files, and the way it handles IO)


You can see what codings apply to the current buffer with C-h C or describe-current-coding-system

When emacs is not showing unicode characters but octal escapes like \304 (and characters pasted in that way are shown like that too) then that command likely shows the buffer coding as something like raw-text.


Forcing a coding

If emacs guesses wrong, you probably want to force the file coding. Some of the most relevant commands:


  • C-x <RET> r coding or M-x revert-buffer-with-coding-system

Revisit the current file using using the specified coding. Useful when you know the file's coding, but emacs did not.

(If you want to load a file without interpretation, you can use M-x find-file-literally)


  • C-x <RET> f coding or M-x set-buffer-file-coding-system

Set the coding with which to save (or revisit?). (for ascii, this can e.g. be useful to convert between dos and unix style newlines)

Will not change the current interpretation. If you want that for the whole file, see revert-buffer-with-coding-system. If you want it for part of the contents, see recode-region.


  • M-x recode-region

Converts a region. Can be helpful when the file was edited using the wrong coding system.


  • C-x <RET> c coding

The next command will be done with this coding.

For example:

C-x <RET> c utf8 C-x C-f will open a file as utf8.

For many commands this is somewhat redundant (assuming your current coding is set properly)


Less force

Ideally, a file will be opened with the coding it actually contains.

Emacs has autodetection, but I've not figured it out yet.


There are a few ways to tell emacs how to interpret a file.

emacs file variables] to a file.

-*- coding: utf-8 -*-

(this is the single-line variant. You'ld add it within whatever style of commenting is relevant).

  • If you want to avoid doing this in the content, but don't mind changing filenames, you can get in the habit of naming things like file.txt.utf8 or file.utf8.txt, and add lines to your emacs config like:
(modify-coding-system-alist 'file "\\.utf8" 'utf-8)


See also:


emacs freezes on startup

Can be a few different things.


One is that emacs is trying to look up your FQDN, and it helps to put this in your /etc/hosts so that it won't need internet access to do so.


If it's specific to text-mode emacs and using strace on the process shows a lot of SIGIO signals, (may or may not be a bug interacting with a glib update) ...then you probably want to upgrade emacs (from 23 to 24?(verify)).