Emacs Tips

Table of Contents

Ben Maughan, Room 4.19, Physics. Full contact information.

This page summarises tips and notes on using emacs sent to the phys-emacs@sympa.bristol.ac.uk mailing list. A new tip is added each week. Most of the tips should work for a standard emacs installation, but some may require additional packages (see this tip). My recommended emacs configuration is described here.

The tips are aimed at people who have learned the basics of emacs (i.e. moving around, opening, editing, saving files) and are starting to explore how to do more than basic editing. If you want a more complete overview, see this tutorial.

I use the standard emacs notation for commands, so C-x C-s means hold control and press x then s, while C-x s means hold control and press x then release control and press s. M- means the meta key (generally the ALT key), SPACE, RET, ESC mean space, return, and escape respectively.

Table of Contents

1 Editing

1.1 Mark or highlight text using the keyboard

To mark or highlight a region using the keyboard, press C-SPACE to set a mark and the move the cursor as normal (with e.g. arrow keys, or any other navigation commands).

You can then cut, copy or run other commands on the selected region, or press C-RET to turn the region into a rectangle (more on rectangles later).

1.2 Recenter display on current line

Use C-l to recenter the display on the current line. Pressing C-l several times moves the display so the current line is at the top, centre, or bottom of the window.

Here is an example - note that ^L indicates C-l

emacs-cl.gif

1.3 Delete whole words

Use M-<DEL> to delete back to the start of a word, and M-d to delete up to the end of a word.

1.4 Delete whole line

You can use C-k to delete up to the end of the current line from the current cursor position, but this does not include the newline character at the end of the line.

I find it more useful to use C-S-backspace which deletes the whole line including the newline, regardless of where the cursor is.

In either case, the line(s) that you deleted are in your clipboard (kill-ring in emacs terminology) and can be pasted elsewhere (yanked in emacs terminology). See the previous post on paste history

Even more useful, if you add the following code to your emacs config file, then pressing C-w (which usually kills a highlighted region) when no region is highlighted, will kill the current line instead.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; kill line if no region active                                          ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http://emacs-fu.blogspot.co.uk/2009/11/copying-lines-without-selecting-them.html
(defadvice kill-region (before slick-cut activate compile)
  "When called interactively with no active region, kill a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
           (line-beginning-position 2)))))

1.5 Select all text in buffer

To select all text in a buffer, use C-x h.

1.6 Search and replace text

To search for text in the buffer, use C-s to search forwards and C-r to search backwards. Repeatedly pressing C-s or C-r will move to the next/previous match.

You can replace text using M-%. For example, to replace "foo" with "bar", use M-x RET foo RET bar and then emacs will step through all the occurrences of "foo" asking if you want to replace them. You can hit y, n, to say yes or no to each, or ! to say yes to all.

Replacement runs from the current cursor position, so to run it everywhere in the buffer, you can jump to the start of the buffer first. Also, remember that when you have finished with your search and/or replace, you can jump back to where you started with C-u SPACE.

1.7 Deleting white space

Use M-\ to delete all white space space at a point, and M-SPACE to delete all but one white space at a point.

1.8 Cycle spacing

In the comments on my post on deleting whitespace, Vargonaut pointed out the useful function cycle-spacing. This function, when called multiple times, cycles through

  1. replacing all spaces with a single space
  2. removing all spaces
  3. restoring the original spacing

As Vargonaut recommends, it is convenient to bind this to M-SPACE in place of the just-one-space function. Do this with

;; cycle through amounts of spacing
(global-set-key (kbd "M-SPC") 'cycle-spacing)

Here is an animation of this in action

cycle-spacing.gif

1.9 Paste history

After you have pasted (yanked in emacs-speak) text with C-y, you can use M-y immediately afterward to cycle through the clipboard (kill-ring in emacs speak) of all previous text that was cut or copied.

1.10 Comment blocks of text

To comment or uncomment several lines of text, highlight the lines, and use M-; to comment or uncomment all of the lines. Emacs should automatically use the right comment character for the mode you are using.

1.11 Create boxes around comments

Sometimes it is useful to break up blocks of your writing visually with comment boxes. I use these to separate out major sections of e.g. a piece of code. To do this, highlight the lines of text that you want to enclose in a comment box, and then use M-x comment-box.

The example below illustrates this, with the first comment box showing the default behaviour. I prefer a wider comment box, as in the second box below.

emacs-box.gif

To get the boxes in the second example, add the flowing code to your emacs config file. This defines a function that you can run with M-x bjm-comment-box and sets up a keyboard short-cut C-c b b.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Full width comment box                                                 ;;
;; from http://irreal.org/blog/?p=374                                     ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun bjm-comment-box (b e)
"Draw a box comment around the region but arrange for the region to extend to at least the fill column. Place the point after the comment box."

(interactive "r")

(let ((e (copy-marker e t)))
  (goto-char b)
  (end-of-line)
  (insert-char ?  (- fill-column (current-column)))
  (comment-box b e 1)
  (goto-char e)
  (set-marker e nil)))

(global-set-key (kbd "C-c b b") 'bjm-comment-box)

1.12 Reverse order of selected lines

Select multiple lines and use M-x reverse-region

1.13 Count words in region

Highlight (mark) a region and use M-= to count the number of lines, words and characters in the region. Results are reported in the mini buffer at the bottom of the window.

As pointed out over at irreal, this default command has the undesirable behaviour that it counts words in a region even when there is no region highlighted (it basically uses the last region you selected). Really, if there is no region highlighted, we would like it to count the words in the whole buffer. To do this, we can set M-= to a slightly different built-in function by adding the following to your emacs config file:

;; use count-words instead of count-words-region as it works on buffer
;; if no region is selected
(global-set-key (kbd "M-=") 'count-words)

1.14 Check spelling

Use M-x ispell-buffer to run spell-check on the whole buffer, or M-$ to check the spelling of the word at the cursor position. The spell check will suggest corrections for the words, or let you save the word to your personal dictionary (by hitting i).

Emacs can use several back-ends to do the actual spell checking, and there is a good comparison of them here. For myself, I have found hunspell to give the best suggested corrections. I installed hunspell with macports

sudo port install hunspell

and then added the following to my emacs config file:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; spelling                                                               ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; use hunspell
(setq-default ispell-program-name "hunspell")
(setq ispell-really-hunspell t)
;; tell ispell that apostrophes are part of words to allow e.g. doesn't
(setq ispell-local-dictionary-alist
      `((nil "[[:alpha:]]" "[^[:alpha:]]" "[']" t ("-d" "en_GB") nil utf-8)))

1.15 Check spelling as you type

To check spelling and highlight errors as you type, enable flyspell with M-x flyspell-mode. It has the incredibly useful feature that typing C-; will cycle through corrections for the most recent spelling error. This lets you correct typos without needing to move the cursor back to them.

To enable flyspell automatically, add the following lines to your emacs config file

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; flyspell spell checking                                                ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;enable flyspell in text mode
(add-hook 'text-mode-hook 'flyspell-mode)
;;enable flyspell in org-mode
(add-hook 'org-mode-hook 'flyspell-mode)
;;enable for tex-mode
(add-hook 'latex-mode-hook 'flyspell-mode)
;;or if you use AUCTeX for latex
(add-hook 'LaTeX-mode-hook 'flyspell-mode)

1.16 Change case of text

By default, you can use M-c to change the case of a character at the cursor's position. This also jumps you to the end of the word. However it is far more useful to define a new function by adding the following code to your emacs config file. Once you have done this, M-c will cycle through "all lower case", "Initial Capitals", and "ALL CAPS" for the word at the cursor position, or the selected text if a region is highlighted.

This is taken from ergoemacs - a useful resource for all things emacs.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; change case of letters                                                 ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http://ergoemacs.org/emacs/modernization_upcase-word.html
(defun toggle-letter-case ()
  "Toggle the letter case of current word or text selection.
Toggles between: “all lower”, “Init Caps”, “ALL CAPS”."
  (interactive)
  (let (p1 p2 (deactivate-mark nil) (case-fold-search nil))
    (if (region-active-p)
        (setq p1 (region-beginning) p2 (region-end))
      (let ((bds (bounds-of-thing-at-point 'word) ) )
        (setq p1 (car bds) p2 (cdr bds)) ) )

    (when (not (eq last-command this-command))
      (save-excursion
        (goto-char p1)
        (cond
         ((looking-at "[[:lower:]][[:lower:]]") (put this-command 'state "all lower"))
         ((looking-at "[[:upper:]][[:upper:]]") (put this-command 'state "all caps") )
         ((looking-at "[[:upper:]][[:lower:]]") (put this-command 'state "init caps") )
         ((looking-at "[[:lower:]]") (put this-command 'state "all lower"))
         ((looking-at "[[:upper:]]") (put this-command 'state "all caps") )
         (t (put this-command 'state "all lower") ) ) )
      )

    (cond
     ((string= "all lower" (get this-command 'state))
      (upcase-initials-region p1 p2) (put this-command 'state "init caps"))
     ((string= "init caps" (get this-command 'state))
      (upcase-region p1 p2) (put this-command 'state "all caps"))
     ((string= "all caps" (get this-command 'state))
      (downcase-region p1 p2) (put this-command 'state "all lower")) )
    )
  )

;;set this to M-c
(global-set-key "\M-c" 'toggle-letter-case)

1.17 Convert tabs to spaces

To replace tabs with the appropriate number of spaces, use M-x untabify. If a region is selected it will operate on the region only.

1.18 Complete partially typed words

Start typing a word, and then press M-/ to cycle through possible completions of the word based on words you have previously typed.

For an improved completions, add the following to your emacs config file (note this is done already if you are using the prelude configuration as in my tutorial).

;; use hippie-expand instead of dabbrev
(global-set-key (kbd "M-/") 'hippie-expand)

1.19 Use abbreviations to expand text

Emacs has the ability to use abbreviations to save time typing. For example, if I type fn and then press space or almost any punctuation character, it is automatically expanded to the word function. This is also great for correcting common typos, like "teh" for "the".

To make this work the most seamlessly, paste the following lines into your emacs config file, changing the location of your abbreviation file if you want:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; abbreviations                                                          ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq-default abbrev-mode t)
;; save abbreviations upon exiting xemacs
(setq save-abbrevs t)
;; set the file storing the abbreviations
(setq abbrev-file-name "~/docs/my-abbreviations.el")
;; reads the abbreviations file on startup
(quietly-read-abbrev-file)

and then restart emacs.

Now you can type the abbreviation you want, followed by C-x a - and you will be prompted for the expanded text. e.g. to set up the abbrevation above, I used

fn C-x a - function

You can set as many of these as you want. You will be asked if you want to save your abbreviations when you exit emacs.

If you type something that you don't want to be expanded, then follow the abbreviation with C-q, so typing fn C-q SPACE will give you the string fn followed by a space. If you want an abbreviation to be expanded without following it with another character, use C-x '.

1.20 Using multiple cursors

Multiple cursors is a very nice package that let's you create several cursors that all do the same thing as you type (see the example below). You can add it to emacs using the steps described here. Once you have installed it, it is useful to set up a keybinding (a keyboard short-cut) for it. You can do this by adding the following to your emacs config file to set C-c m c as the binding for multiple cursors.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; multiple cursors                                                       ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(global-set-key (kbd "C-c m c") 'mc/edit-lines)

Once you have done this and restarted emacs, you can use multiple cursors.

To use it, highlight the lines on which you wish to have cursors and use C-c m c. Now you can edit away and press enter when you are done to exit multiple cursors. In the following example, I create cursors on 4 lines and then use them to edit the four lines simultaneously.

emacs-mc1.gif

For a more complex example, I use multiple cursors to reformat a latex style table into plain text. In this clip I do the following

  1. First make the column headings that I want
  2. highlight the lines of the table and start multiple-cursors
  3. edit the line, making use of M-f and M-b to move the cursors forward and back by word, which is useful when the text is not aligned
  4. exit multiple cursors and highlight the table again
  5. use C-u M-x align to align the columns of the table (more tips on aligning text to follow)

emacs-mc2.gif

Note that sometimes when you type a command with multiple cursors running it will ask you if you want to apply this command to all cursors - you can answer yes or no to this and it will remember your choice.

For more examples, see this video.

1.21 Advanced undo/redo with undo-tree

In emacs, by default C-/ runs the command undo, which does what you would expect and undoes your changes to the current buffer. However, there is a really great upgrade to this called undo-tree which records and visualises your undo history as a branching tree. Install this package, and then add the following to your emacs config file

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; undo tree mode                                                         ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;turn on everywhere
(global-undo-tree-mode 1)
;; make ctrl-z undo
(global-set-key (kbd "C-z") 'undo)
;; make ctrl-Z redo
(defalias 'redo 'undo-tree-redo)
(global-set-key (kbd "C-S-z") 'redo)

Now you can use C-z for undo and C-Z for redo. Even better though is using C-x u to run undo-tree-visualize which opens a second buffer displaying a tree view of your undo history in a buffer. You can navigate this with the arrow keys and watch the main buffer change through its previous states, and hit q to exit when you have the buffer the way you wanted it, or C-q to quit without making any changes.

In this simple illustration, I do the following:

  • type some text and then undo some of that typing
  • type some new text
  • use undo-tree to undo the new text and then switch branches to redo the old text

undo-tree.gif

Undo-tree can do other neat things too - see the web page for details.

1.22 Prettier text replacement with anzu

We recently introduced basic text replacement, but it is easy to make things a bit snazzier. You can preview the replacement by installing the anzu package, and then adding the following to your emacs config file:

(require 'anzu)
(global-anzu-mode)
(global-set-key (kbd "M-%") 'anzu-query-replace)
(global-set-key (kbd "C-M-%") 'anzu-query-replace-regexp)

This is illustrated in the example below from my post on renaming multiple files in dired - note how when I replace "foo" with "bar" you see the replacement text previewed next to the original text

dired-rename.gif

If you use my recommended setup, prelude, this behaviour is the default,so you shouldn't need to do anything.

1.23 Use LaTeX syntax to enter non-standard characters

Sometimes it is handy to be able to enter non-standard characters in emacs documents. For example I sometimes need to use a £ symbol but my US keyboard doesn't have one. Other times I need to add an accent or similar to a letter like é or ö. There is a nice overview of the ways to do this at Mastering Emacs, and here I'll pick out the method I find most useful.

Since I use LaTeX a lot and am familiar with its syntax for symbols, I use C-\ to run the command toggle-input-method and then enter TeX as the alternate input method. Now I am in TeX input mode I can enter a string like \pound and have it appear as £ or \"o to give me ö. Pressing C-\ again now toggles back and forth between normal and TeX input modes.

For symbols you use a lot, you can also set up abbreviations e.g. by entering gbp C-x a - C-\ \pound we set the text gbp to expand to £.

2 Moving around

2.1 Move to start or end of buffer

Use M-< and M-> to move to the start or end of a buffer, respectively.

2.2 Move forward and backward by word

To move forward by one word use M-f, to move back by one word, use M-b.

2.3 Move to start/end of line or sentence

To move to the start of a line use C-a and to move to the end of a line, use C-e.

To move to the start or end of a sentence, use M=a and M-e respectively. Note that by default, emacs assumes sentences are broken up by a full stop and then two spaces. If you want it to recognise full stop followed by a single space as the end of a sentence then add the following to your emacs config file

;; sentences end with single space
(setq sentence-end-double-space nil)

Note that this will lead emacs to get a bit confused about abbreviations e.g. that one just there.

2.4 Move and mark by paragraph

Use M-{ and M-} to move forward or backward by paragraph.

Use M-h to mark (highlight) the current paragraph.

2.5 Move to a specific line number

To jump to a particular line use M-g M-g and enter the line number.

The current line number of the cursor is displayed in the modeline (the bar near the bottom of the window with various information displayed).

2.6 Jump around previous locations in a file

When you mark text using C-SPACE as described above, emacs adds that location to the "mark ring". This is just a list of places you have marked previously in a buffer. You can jump to the last place in the mark ring using C-u SPACE, then use C-SPACE to keep going to previous places.

The neat thing is that emacs adds marks for you when you do different things (e.g. when you start a search) so C-u SPACE will often magically take you back to where you want to go.

If you know you will want to come back to a particular spot, just use C-SPACE twice to mark that point.

2.7 Repeat previous search

You can search for text using C-s to search forwards and C-r to search backward. However, if you start a search, and then press C-s (or C-r) again before you start typing any text, your last search will be repeated.

2.8 Scrolling and moving by line

There are (of course) lots of ways to scroll the window and move the cursor in emacs. To move the cursor up or down by a line you can use the arrow keys, or C-n and C-p.

To scroll the window, you can use C-v and M-v to scroll down or up respectively by nearly one full screen. This is equivalent to page up/down.

Normally when you scroll the window, the cursor stays with its current line until it hits the edge of the window and then it moves to the next line. In other words the cursor follows the text as the text scrolls. I prefer the cursor to stay at the same position in the window when I scroll it, so the text moves under the cursor. I also like to add the following simple commands which scroll the window up or down by one line. Putting these two tweaks together, the window moves by one line while the cursor stays still.

;;keep cursor at same position when scrolling
(setq scroll-preserve-screen-position 1)
;;scroll window up/down by one line
(global-set-key (kbd "M-n") (kbd "C-u 1 C-v"))
(global-set-key (kbd "M-p") (kbd "C-u 1 M-v"))

Note how these commands work by passing a prefix argument to the normal scroll commands - this is described in the help for those functions which you can see by using e.g. C-h k C-v.

I used the keybindings M-n and M=p by analogy with C-n and C-p.

Here is a little animation to illustrate how this works.

scrolling-moving-line.gif

3 Operating on files

3.1 Visual comparison of differences between files with ediff

To compare the contents of two text files, use M-x ediff-files and open the two files you want to compare. Emacs will then open one above the other in your main emacs window (N.B. a window is called a frame in emacs terminology), and also open a smaller window which says Type ? for help.

Press | to put the two files side by side in your main emacs frame, and then stretch your window nice and wide so you can see both files side by side clearly. Now click back on the small emacs window with the help text.

In your main window, you should see blocks of text that differ between the two buffers highlighted. Press n to move to the next difference and p to move to the previous difference. Press a to copy the text from the left-hand file to the right-hand file, or press b to copy text from the right-hand file to the left-hand file.

Press q to exit ediff and then save your files if you have modified them.

To make the experience a little smoother I add the following to my emacs config file:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ediff                                                                  ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'ediff)
;; don't start another frame
;; this is done by default in preluse
(setq ediff-window-setup-function 'ediff-setup-windows-plain)
;; put windows side by side
(setq ediff-split-window-function (quote split-window-horizontally))
;;revert windows on exit - needs winner mode
(winner-mode)
(add-hook 'ediff-after-quit-hook-internal 'winner-undo)

3.2 Dired: Emacs as a file browser

Emacs has a powerful file browser built in. I'll introduce some of the things it can do here, and come back to this topic in future tips.

Use C-x d to enter dired mode (emacs' file browser), and give the path of a directory to open.

To move the cursor around you can use the arrow keys. Of course you can use emacs' usual tricks for moving around the buffer - e.g. C-s to search for a file name, or to jump to a particular file in dired, use j and then enter the name of the file or directory, and the cursor will jump to that point. You can also use > and < to move to the next or previous sub directory. Hitting ^ moves you up a level in the directory tree.

To open a file, move the cursor to the line containing a file and hit enter.

To create a new subdirectory, hit +, and to create a new file in the directory, just use C-x C-f as normal.

Hitting s will change the sorting of the directory listing between name and date.

g refreshes the view.

3.3 Dired: marking, copying, moving and deleting files

Use C, R, or D when the cursor is on the line of a file to copy (cp), rename (mv) or delete (rm) the file. This can also be done for multiple files by marking them.

You can mark files in dired by pressing m on the line of a file, and unflag it by pressing u. You can mark several files individually using m or mark all files whose names match a search string by using % m string <RET>. Use U to unmark all files.

The strings used for matching are regular expressions, so are very powerful. For example:

  • % m test <RET> will mark all files with names containing the string "test" (equivalent to *test* on the command line.
  • % m ^test <RET> will mark all files with names starting with the string "test" (equivalent to test* on the command line).
  • % m txt$ <RET> will mark all files with names ending with the string "txt" (equivalent to *txt on the command line).
  • % m ^test.*org$ <RET> will mark all files with names starting with the string "test" and ending with "org" (equivalent to test*org on the command line).
  • % m [kxj] <RET> will mark all files with names containing the letters k, x, or j
  • % m [kxj] <RET> will mark all files with names containing the letters k, x, or j
  • % m [6-9] <RET> will mark all files with names containing the digits 6,7,8,9

Read more about emacs' regular expressions here.

Once you have marked files, use C, R, or D as before to copy, move or delete them.

You can invert the marking of files using * t, and mark all files (or directories) using * s.

You can hide marked files from the current dired view using k. Note that these are not deleted, use g to see them again.

So, supposing you wanted to delete a bunch of files, you might do the following

  1. mark the files manually, or using a regular expression
  2. * t invert the selection
  3. k hide the selected files so now you see the ones you originally selected for deletion so you can check you got the right ones
  4. * s to select those visible files
  5. D to delete them

3.4 Dired: replace text in multiple files

Start dired and mark files as described above Then use Q to run query-replace (introduced previously) on all marked files.

3.5 Dired: rename multiple files

Following on from the previous dired tips, we can do much more in dired. A very powerful feature is that you can switch the dired buffer which lists the files into editable mode, and directly edit file names, links and so on. Here we will look at using dired to rename multiple files.

Now we will use dired to rename multiple files at the same time. Suppose in some directory we have a bunch of files called test_foo_01.dat, test_foo_02.dat, etc and we wanted to rename them to replace foo with bar, then we would do the following:

  • use C-x d to enter dired and choose the directory with the files in
  • use C-x C-q to turn dired into editing mode. You can then edit the file names by hand or
  • use M-% to replace foo with bar in the dired buffer. This will change the file names
  • use C-c C-c so apply the changes, or C-c C-k to cancel

The animation below shows this example. Of course you can also manually change the name of the file, as I do for the last file on the list.

dired-rename.gif

3.6 Dired: redirect symbolic links

We have previously looked at using dired for managing files and switching dired into writeable mode for renaming multiple files. Here is a related tip to redirect symbolic links in dired.

Suppose you moved some data from one location to another and ended up with a bunch of broken symbolic links, you can easily edit those links to point to the new path. In the example below, I have links pointing to files in /old/path and I want the to point to files in /new/dir instead, so I do the following

  • Use C-x d to enter dired and choose the directory with the files in
  • Use C-x C-q to turn dired into editing mode. You can then edit the file names by hand or
  • Use multiple cursors to edit the links in one go (you could also use e.g. M-% to do a query-replace). This changes the path of the links.
  • Use C-c C-c so apply the changes, or C-c C-k to cancel

This is illustrated in the following animation.

dired-links.gif

This is just great - it feels like magic every time!

3.7 Editing files remotely

Emacs supports editing files remotely, as a nice alternative to opening a new emacs session on your remote machine and sending the window over X11. This feature is called tramp.

It works seamlessly - just open a file as usual with C-x C-f and then give the name of the remote file, including the host address - e.g.

C-x C-f /aquila.star.bris.ac.uk:/homeb/bjm/myfile.org

Note the syntax, that the remote machine name is opened at the top level directory "/".

You can then edit and save as normal

3.8 Searching multiple files

Use M-x rgrep to search for a string in multiple files. You will be prompted for a string, the files to search and the directory to start the search. So, for example, to search for the word "emacs" in all .txt files in my documents directory, I might use M-x rgrep and then answer emacs, *.txt, and ~/docs/.

rgrep will open a new buffer containing the results. The nice thing is that clicking on one of the matches will open that file in emacs and take you right to the matching line.

Note that rgrep is recursive and so will also search all directories below the one specified. For more control, try M-x grep and M-x grep-find.

3.9 Show file in Finder

This is a tip for Mac users. Use M-x reveal-in-finder to show the current file in a new finder window. If you use this in dired, it will show the file at the cursor in a new finder window.

The reveal-in-finder package may be installed by default with your emacs, but if not, you can install it through the package manager using package-list-packages.

3.10 Compare buffer with file on disk

Sometimes you'll find yourself in the position where you want to see the differences between the unsaved buffer you are editing, and the saved version of the file on the disk. Ediff does this nicely with the command M-x ediff-current-file.

4 Appearance

4.1 Change text size

To change the size of the text in the current buffer, use C-x C-+ to increase the size, and C-x C-- (i.e. control x and control minus) to decrease the size. If you use my recommended setup, prelude, then these are set to the more convenient C-+ and C--.

5 Misc

5.1 Install packages

Installing packages in emacs is a bit like adding extensions to your browser - they add lots of extra functionality that can be very useful.

The easiest way to install packages is to use the command package-list-packages and them search for the package you want (using e.g. C-s) and then mark it for installation by pressing i and then install all marked packages by pressing x.

Packages are available from various sources, and to get the best selection you should add the following to you emacs config file to add the MELPA package repository, and then restart emacs:

;;Add MELPA repository
(add-to-list 'package-archives
             '("melpa" . "http://melpa.org/packages/") t)

You might also consider adding MELPA-stable and marmalade, but MELPA should be fine for most things.

5.2 Quick calculations

Emacs has a full featured calculator built in, but I only tend to use it for quick calculations. Use C-x * q to start the calculator in the minibuffer at the bottom of the screen, and then enter your calculation.

When you hit enter, the calculation is performed and the answer is shown. It is also saved to your clipboard so you can use C-y to paste it into your document if needed.

5.3 Using server and clients for instantaneous startup

If you use an advanced emacs configuration like my recommended set up prelude, then the startup time for emacs can be several seconds or longer. To avoid this, and to get other benefits I strongly suggest running emacs with a server and clients.

The way this works is that the first time you start emacs, you start a server, and then any other emacs sessions you start just connect to that server. This means they start instantly, and also have the same buffer list as every other emacs window (frame in emacs terminology) that you have open.

To do this we need to make a simple shell script

#! /bin/tcsh -f

# start emacs server - replace with path to your emacs
/Applications/Emacs.app/Contents/MacOS/Emacs --daemon

# start emacs client - replace with path to your emacsclient
# this is usually in the same place as your emacs executable
/Applications/Emacs.app/Contents/MacOS/bin-x86_64-10_9/emacsclient -c $argv

and save it somewhere sensible like ~/scripts/emacs_daemon.csh

Then set up an alias for your emacs command in your ~/.cshrc or similar:

# alias to start emacs in client mode
# starts server if one is not already started
# replace with path to your emacsclient
alias em '/Applications/Emacs.app/Contents/MacOS/bin-x86_64-10_9/emacsclient --alternate-editor "~/scripts/emacs_daemon.csh" -c'

Now you can use the command em to start emacs every time. The first time it will take as long as usual, but after that it will be instant. Running em file1 file2 or similar will open a new emacs window with the named files as you would expect.

One last point to note is that since your emacs windows are now clients of an emacs server that is running in the background, closing the window will not stop the server. If you want to close the entire emacs session and stop the server (e.g. so you can start a fresh emacs session after changing your config file), you can use M-x save-buffers-kill-emacs, which I have bound to C-x c for convenience. To do this, add the following to your emacs config file

;; set shortcut to kill whole emacs session
(global-set-key (kbd "C-x c") 'save-buffers-kill-emacs)

5.4 Make quick notes with deft

I tend to organise my notes into files related to a specific topic or project, so I find org-mode with org-capture very useful to add quick notes to a specific file, like adding a TODO item or an idea for a blog post (I will post lots more about org-mode in due course). However, if I want to make a more general note that doesn't fit into a category (say notes from a meeting), then deft is a nice alternative.

This post is a short introduction to deft, and I will describe some tweaks I have made in subsequent posts.

Deft is an emacs package (available through package-list-packages) that lets you quickly create, search and add to files containing notes. It is inspired by the Mac programme Notational Velocity.

My use case is that I launch deft, start typing a search string to very quickly find the file I want to add notes to, or create a new file on the fly, and then add my notes, quit deft and be back to where I was before.

Deft works simply by having all of your note files in a single directory, and the files themselves are simple text (org-mode if you like) files that can be viewed and edited anywhere else as well as via deft. Deft is really just a nice quick interface for finding/creating and opening the right file for editing.

To use deft, launch it with M-x deft and you will see a list of the files in your deft directory with short summaries. Start typing a search string and the list will dynamically filter down to files that match the string in their file name or body text. Use arrow keys to move up and down through the list of files and hit return to open that file for editing.

If no files match the search string then hitting enter creates a new file with a name taken from the search string. If you want to create a new file with a specific name, use C-c C-n.

You can also rename C-c C-r and delete C-c C-d files from the deft buffer.

Use C-c C-q to quit deft.

This is best illustrated with a couple of examples. In the first example I launch deft and type a search string to find an existing file and then open that file for editing. In this case I am looking for the file about an open day in 2014.

deft1.gif

In the second example I launch deft and type a search string that doesn't match any files and so create a new file with a name based on the search string. In this case, my search string "open day 2015" doesn't match anything so deft creates a new file for me.

deft2.gif

Once you have installed deft, add the following to your emacs config file to get the behaviour described above

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; deft                                                                   ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'deft)
(setq deft-directory "~/docs/deft")
(setq deft-extension "org")
(setq deft-text-mode 'org-mode)
(setq deft-use-filename-as-title t)
(setq deft-auto-save-interval 0)
;;key to launch deft
(global-set-key (kbd "C-c d") 'deft)

With this setup, my deft files are all stored in ~/docs/deft/ and have .org file extensions, and deft will open them for editing in org-mode.

The option (setq deft-use-filename-as-title t) tells deft to use the search string to generate the filename for a new file if the string does not match an existing file.

Those are the basics of deft, but stay tuned for some tweaks that (for me at least) make the experience even smoother.

5.5 Use emacs for thunderbird emails

Some people use emacs as their email client with e.g. gnus, wanderlust or mu4e. I am not quite hardcore enough for that, and do my emailing in Thunderbird. I don't have to give up on emacs completely when sending emails though. Using the external editor extension for Thunderbird, I can quickly compose your email in emacs and then send it in Thunderbird.

To use it, install the extension in Thunderbird, and then in its preferences, set the text editor path to your emacsclient with a -c option. For example, on my Mac, this is

/Applications/Emacs.app/Contents/MacOS/bin-x86_64-10_9/emacsclient -c

See this post about using emacsclient if you are not sure about that.

Now, when composing a mail in Thunderbird, I can click the emacs button that has appeared on the tool bar of the compose window (if it is not there, right click and add it from the list), or just hit Commad-E. This launches an emacs window with the email text ready to go. Type in your text and when you are done, hit C-x C-c to save and close the window. Your emacs text should now be in your Thunderbird compose window.

One last point is that I like to use org-mode style structures in my emails, so I add the following to my emacs config file to tell emacs to open .eml files in org-mode.

;;use org mode for eml files (useful for thunderbird plugin)
(add-to-list 'auto-mode-alist '("\\.eml\\'" . org-mode))

5.6 Run shell command on buffer or region

Emacs has tonnes of features built in, and is infinitely expandable with emacs lisp, but sometimes there is already a shell command that can do the job you want more easily. You can use M-! (wich runs shell-command) to run a shell command with the contents of the current buffer passed to stdin (standard input for the command), or M-| (which runs shell-command-on-region) to do the same for the currently selected text in the buffer.

The output of the shell command is then shown as a new buffer in emacs.

As a trivial example, suppose a buffer contained the following, and we wanted to sort the lines (N.B. this is easy to do in emacs)

bbb
aaa
ddd
ccc

Hitting M-! prompts for a shell command, and we then enter sort to call the standard unix/linux sort command. We now get a buffer called *Shell Command Output* containing

aaa
bbb
ccc
ddd

5.7 Make all prompts y or n

Emacs prompts you at various times to answer yes or no to something. If you add the following to your emacs config file, you will only have to hit y or n saving you countless seconds!

;; change all prompts to y or n
(fset 'yes-or-no-p 'y-or-n-p)

This basically aliases the built in "yes or no" prompt function to the built in "y or n" prompt function so that the latter is always used.

Date: [2015-04-30 Thu 22:29]

Author: Ben Maughan

Created: 2015-09-15 Tue 11:22

Validate