DIFFERENCING TWO FILES

Often I need to compare two files. For example, I keep copies of an address list at work and at home, and make changes to both; every so often, I want to merge the changes.

To compare your two files, in emacs type "M-x ediff-files <RET> filename1 <RET> filename2 <RET>".

Emacs splits itself into three windows. Window "A" shows the first file, window "B" the second. Chunks of text in one file which are not in the other are shown highlighted. The third window has a list of possible keystrokes. For instance, press "n" to move to the next difference, and "a b" to copy the current difference from window "A" to window "B".

At the end of your session, type "w a" and "w b" to write the changed files to disk, then "q" to quit ediff mode.

OPERATING ON COLUMNS

The other day, someone emailed me a column of new data to add to my collection. The right place to put it was as column 6 of my data file.

I saved the email message as a file which I loaded into emacs. With the cursor at the top left corner of the column I hit "C-spc" to mark the spot. Then I moved the cursor to the lower right corner of the rectangle of text making up the column and typed "M-x kill-rectangle".

Finally I went to my data file, put the cursor at the top of the gap between present columns 5 and 6, and typed "M-x yank-rectangle".

Instead of "M-x kill-rectangle" and "M-x yank-rectangle", I could have used the shortcut keys "C-x r k" and "C-x r y". For a list of other commands which operate on rectangles of text, type "C-h a" (for apropos), then "rectangle RET".

CALENDAR, SUN & MOON

To bring up a three-month calendar, type "M-x calendar". Once you are in calendar mode, you can:

     (setq calendar-latitude 37)
     (setq calendar-longitude -122)
     (setq calendar-location-name "Santa Cruz, CA, USA")

Some more options let you convert to other standard calendars; count the number of days between two dates; and display your own schedule. For a description, type "C-h m" from within calendar mode.

FORTRAN MODE

FORTRAN is a wordy, format-sensitive language. You can reduce the number of keys you need to hit by using Emacs' Abbrev mode, and spot some kinds of bugs using Fortran mode's automatic formatting.

Load a file whose name ends in ".f", and Emacs enters Fortran mode. Now, typing a line number at the start of a new line automatically indents the cursor to the correct tab stop. So does pressing TAB anywhere on the line. You can

  M-C-e Move forward one subroutine
  M-C-a Move back    one subroutine
  M-C-q Correctly indent the entire current subroutine.  This only
    works if each "do" loop has a matching "continue" or "end do" --
    not a bad idea in any case.

To start the Abbrev minor mode within Fortran mode, enter "M-x abbrev-mode". Now you can type ";im" and hit SPC or RET, and those three characters expand to "implicit". Likewise with ";su" for subroutine, ";do" for double, ";c" for continue. For a list of others, type ";?".

You can have Abbrev mode started whenever you load a FORTRAN file by adding this line to your ~/.emacs file:

  (setq fortran-mode-hook (function (lambda () (abbrev-mode 1))))

RUNNING (LA)TEX

Save yourself keystrokes in TeX or LaTeX mode:

  C-c C-f writes the buffer and runs (La)TeX on the file.

  C-c C-r runs (La)TeX on the current region (everything between the
  cursor and the last place you typed C-spc).  It's handy for seeing
  how the latest chapter of your thesis looks without waiting for the
  other chapters to be processed.  However, it doesn't correctly
  handle \ref{}s.  In LaTeX mode, the header of the document
  (\documentstyle and so on) also gets included in the region.

  C-c C-v previews the .dvi file output by either of the above.
  To make this command work, add these lines to your ~/.emacs file:
    (setq tex-dvi-view-command
      (if (eq window-system 'x) "xdvi" "echo 'Error: need X display!'"))

  C-c C-k kills the (La)TeX job before it finishes.

  C-c C-p prints the file.  To set this up for a Lick machine:
    (setq tex-dvi-print-command "dvips")

  C-c C-q shows the printer queue.

  C-M-v moves the other window forward a page.  If the cursor is in
  the (La)TeX window, C-M-v moves forward the window showing output
  from the commands above.

In LaTeX mode, instead of typing out \begin{} and \end{}, use C-c C-o.

Auto-fill minor mode saves you typing a carriage return at the end of each line. You can have auto-fill turned on by default in Tex and LaTex modes by adding this line to your ~/.emacs:

Thanks to George Blumenthal for suggesting the topic of this week's Emacs Trick.

ELECTRIC-BUFFER-LIST

By default, the key sequence "C-x C-b" is mapped to the list-buffers command, which just splits the window in half and puts the list of buffers in the other half.

A more useful behaviour lets you quickly choose another buffer from the list. Here's what the electric-buffer-menu command does: the new window automatically becomes the active window. Cursor keys move you up or down the list of buffers. Press "SPC", and the buffer you've chosen appears in the old window while the list of buffers drops out of sight.

Also, press "k" on a buffer's line, and the buffer is marked for deletion. When you select a buffer, the marked buffers are killed (with queries whether you want to save them first, if any have been modified).

Make electric-buffer-list the default action of "C-x C-b" by adding or uncommenting this line in your ~/.emacs file:

  (define-key ctl-x-map "\^b" 'electric-buffer-list)

COMPILING PROGRAMS

Reduce compilation to a few keystrokes by using Emacs:

Load a C or FORTRAN program you want to compile. Type "M-x compile", edit the compile command which appears on the line at the bottom of the screen, and press "RET". For instance, you could type "C-a" to move to the start of the entry, "C-k" to delete it, then "f77 foo.f".

If the compiler finds errors, you can click the middle mouse button on them, and Emacs will move to the corresponding place in the source code, ready for you to edit.

When you compile again, Emacs remembers the command you used last time, and offers it up for your approval. However, if you often compile different codes, you can save more keystrokes by creating a makefile for each code. Then every time you compile, the default command of "make -k" does the job and you only need to press "RET".

For instance, in the directory containing foo.f, you could create a file called makefile, containing the two lines

foo: foo.f
        f77 foo.f

For more information about makefiles, type "M-x man RET make RET".

To bind "M-x compile" to the key "M-C" (that's M-shift-c), add this line to your ~/.emacs:

  (define-key esc-map "C" 'compile)

EDITING DIRECTORIES

Compared with shell commands like "ls", "mv" and "chmod", Emacs' `dired' mode is a more visual way to maintain your directory tree so you can find things when you need them.

To list a directory, `find' it like you would any file: type "C-x C-f <directory name> RET". To list the directory that contains the file you're currently editing, type "." as the directory name.

In dired mode, you can sort the files either in reverse date order, or alphabetically by name. Toggle between the two by pressing "s".

Move the cursor to a file you want to work with. Then to

As with other emacs commands that require you to type a line at the bottom of the screen followed by "RET", dired's "!" command keeps a list of the lines you've typed in. Instead of retyping a line, recall it from the list using "M-p" (previous) and "M-n" (next).

You can create a subdirectory in dired mode by pressing "+".

You can have the directory listed in any format allowed by the "ls" command. For instance, to add a column with the number of kilobytes taken up by each file, along with a character after each filename showing the file type, add this line to your ~/.emacs:

  (setq dired-listing-switches "-Fsal")

The next Lick Emacs Trick will appear in three weeks' time, because I'll be offline 'til then.

MACROS: THEY DO THE DIRTY WORK

You want to make a lot of similar changes scattered through a huge file. The file isn't in columns, so you can't use the rectangle commands discussed in Lick Emacs Trick #3. The changes aren't simple replacements, so you can't use "M-x replace-string" or "M-x query-replace".

For example, in a manuscript you've written, pixel coordinates are listed in the format [x,y]. The referee now says you ought to list them in the order [y,x]. The coordinates have to be swapped in a hundred places through the text.

Swapping one pair takes a few keystrokes. If you save those keystrokes as a macro, you can then change all the other coordinate pairs with a couple more keys.

But the keystrokes for the macro have to be carefully chosen: at the end of the sequence, the cursor must be placed so the next call to the macro will operate on the next coordinate pair. Also, you must consider whether the macro will mistakenly operate on other places in the text where you have square braces.

To begin defining the macro, go to the start of the file and press "C-x (". Then type the keys which swap the first pair of coordinates. These are the steps needed to make the swap: move to the "]" after the y-coordinate. Cut out the text between here and the previous comma. Move back to the "[" before the x-coord. Paste the y-coord in here, and cut out the x-coord. Move forward past the comma and paste in the x-coordinate. Finally, move past the "]" ready for the next call to the macro.

Here's a key sequence which does this:

    C-s   ;; isearch-forward
    ]     
    C-b   ;; backward-char
    C-SPC ;; set-mark-command
    C-r   ;; isearch-backward
    ,     
    C-f   ;; forward-char
    C-w   ;; kill-region
    C-r   ;; isearch-backward
    [     
    C-f   ;; forward-char
    C-y   ;; yank
    C-SPC ;; set-mark-command
    C-s   ;; isearch-forward
    ,     
    C-b   ;; backward-char
    C-w   ;; kill-region
    C-f   ;; forward-char
    C-y   ;; yank
    C-f   ;; forward-char

Because this sequence uses C-s and C-r instead of explicit cursor movement keys, it works for cases where x and y are each made up of several words, as well as cases where they are each one character.

End the macro definition with "C-x )". You've swapped the first pair of coordinates as you defined the macro. To execute the macro once more, type "C-x e". If everything works OK, you can let the macro loose to run over and over: press "C-u 0 C-x e". The macro will repeat until the cursor passes the last "]" in the file and an error is returned when searching for the next "]". Should a problem in the macro leave it stuck in a loop, stop it by hitting "C-g".

If you need to add keystrokes to or delete them from the macro, start "Edit Macro" mode by typing "C-x C-k" then "C-x e".

The macro will be lost when you define a new macro or quit emacs. Saving macros for reuse is a topic for another Trick.

Thanks to Eric Sandquist for suggesting this week's Trick.

RECOVERING FROM DISASTER WITH AUTO-SAVE

The unlikely has happened: you've been adding text to your masterpiece for a week without typing "C-x C-s" to save to disk, and last night the system crashed. Short of despairing, what can you do?

Emacs automatically saves a copy of your document every so often. For instance if you are editing a copy of the file "foo.tex", emacs saves your changed version into a file called "#foo.tex#". This happens whenever you have typed at least a few characters since the last "C-x C-s" and you also have not hit a key for a few seconds (the last part means you don't have to wait in the middle of typing while the disk grinds).

To restore your peace of mind when you discover the crash: log back in, start up emacs in the directory where foo.tex lives, and tell it

     M-x recover-file RET foo.tex RET

You will see a directory listing showing foo.tex and the auto-save file #foo.tex#. Check that #foo.tex# is the newer, and (unless you recently deleted a big chunk of text) also the larger. When you are satisfied that you will gain back some of your hours of typing by overwriting foo.tex with #foo.tex#, type

     yes RET

And most importantly!

     C-x C-s

Whenever you save foo.tex using C-x C-s, emacs deletes the auto-save file since it is no longer needed. If you then make more changes to foo.tex, emacs will create a new auto-save file.

EDITING COMPRESSED FILES

You have more files than disk space, so you're forced to gzip or compress some of your files. But that's a hassle, because now you have to uncompress them to read or change them.

When you load a compressed file into emacs, you can have it automatically decompressed. When you make changes and save it, it's magically compressed again.

To bring this change to your life, add a line to your ~/.emacs file. On bigdog:

    (load-file "/usr/local/emacs/lib/emacs/19.28/lisp/jka-compr.elc")

On ra or helios:

    (load-file "/usr/local/lib/emacs/19.28/lisp/jka-compr.elc")

You'll need to use a different path, if your machine has its emacs version-19 .el and .elc files in some other directory.

SEARCH THE CARRIAGE!

Your MONGO data file has three columns: x, y, and point type. You want to change all of the open squares (MONGO ptype 40) to filled circles (MONGO ptype 203). If you use an ordinary M-x replace-string, the digits "40" in the x and y columns will also be messed up.

You can make use of the fact that all the 40s you want to change are immediately followed by a carriage return: move the cursor to the start of the buffer and type

        M-x replace-string 40 C-q C-j RET 203 C-q C-j RET

The key "C-q" means "instead of carrying out the next keystroke, accept it verbatim" (Q stands for quote). Because RET is used to end an entry, it cannot be part of an entry, so you have to input the carriage return as an explicit C-j.

SLOW CONNECTIONS

If you are running Emacs over a slow modem line, there are several ways you can reduce the delay between hitting a key and seeing its action.

If you have an X connection, you can consider turning off the menu-bar and scroll-bar. Toggle these between on and off using "M-x menu-bar-mode" and "M-x scroll-bar-mode", or turn them off in your ~/.emacs file with the lines

  (menu-bar-mode -1)
  (scroll-bar-mode -1)

When you're on a fast connection in an office where other people are working, you may prefer that Emacs flash the screen at you instead of beeping loudly on errors. Set this up in your ~/.emacs file with the line "(setq visible-bell t)". On the other hand, when you're at home on a slow line, the beep is faster. Turn off the flash using "M-x set-variable RET visible-bell RET 'nil RET".

Even if you have a text-only connection, you can save some bandwidth by turning off the items in your mode-line which are frequently updated. For instance, toggle display of the current line number to off using "M-x line-number-mode", or in your ~/.emacs, "(line-number-mode -1)".

You can retrieve past Lick Emacs Tricks from http://www.ucolick.org/~neal/emacsusers.html

TECHNICOLOR

Whether you're working in TeX, FORTRAN or C, you can see the structure of your code more easily if the keywords and text are displayed in different colors. One way to have this done for you in Emacs is to add a few lines to your ~/.emacs file:

(cond (window-system
       (setq hilit-mode-enable-list  '(not text-mode)
             hilit-background-mode   'dark
             hilit-inhibit-hooks     nil
             hilit-inhibit-rebinding nil)
       (require 'hilit19)
       ))

If your Emacs window has dark letters on a light background, you may prefer to replace "'dark" in the above with "'light".

Hilit mode is not documented in Emacs info. Its documentation is contained in its source code, emacs lisp file hilit19.el, on helios in directory /usr/local/lib/emacs/19.28/lisp.

Thanks to Scott Trager for introducing me to hilit-mode.

PLAY IT AGAIN, EMACS

A few keystrokes ago, you executed an elaborate replace-string command. Now you're editing another file and you realize you need to make the same replacement here. You could type the whole thing out again, but there is a better way.

Type "C-x ESC ESC" to call up the function "repeat-complex-command". Press "M-p" a few times to back up through recent commands, until the one you want appears in the line below the mode-line. Then press "RET" to play it again in the current buffer.

MAIL

I find myself using xterms less often as I learn more emacs nuggets. Xterms are still useful for reading email though, aren't they?

To read mail inside emacs, type "M-x rmail". Hit "n" to move to the next message, "p" to move to the previous one. To delete a message, hit "d". To quit reading mail and irrevocably delete the messages you've chosen for deletion, hit "q". The rest of the messages will be saved in a file called RMAIL in your home directory.

While reading mail, you can also hit "h" for a summary listing of the messages in your RMAIL file. You can sort the messages by date, author, subject, etc: type "M-x rmail-sort-by- TAB" for a list of the possibilities.

To reply to a message, hit "r". To forward the message you're reading, hit "f". To start a new mail message, hit "m". For a list of other commands, type "C-h m", or for more detail "C-h i m emacs RET m rmail RET".

To save a message from your RMAIL file into another RMAIL-format file, hit "o". To save it to an ordinary Unix mbox-format file, hit "C-o". To convert existing mbox files to RMAIL format, use the command "M-x rmail-input". To convert an entire RMAIL file back to mbox format, type "M-x unrmail".

When there is mail waiting for you, emacs puts "Mail" in the mode line, so if you want to, you can also dispense with xbiff.

MONGO

If you use a shell, like bash or tcsh, which completes filenames for you when you type the first few letters and press TAB, then you may find Mongo's lack of filename completion slows you down.

If you run Mongo within Emacs' shell-mode, Emacs will complete filenames and also keep a list of previous commands which you can recall.

To do this, type "M-x shell". In the window which appears, at your usual shell prompt start mongo. Now if you type "data myf" and press TAB, Emacs will complete the filename as much as possible. If the directory contains files "myfile" and "myfluxes", there are two possible choices at this point, and Emacs will list them in another window. To make your choice, type "i" or "l" and press TAB again to finish completing the filename.

To recall previous commands, at the Mongo " * " prompt use "M-p" (previous) and "M-n" (next). By default, Emacs stores the last thirty commands you have entered. For more help, type "C-h i m emacs RET m shell RET".

TURNING TONGS INTO TWEEZERS

Sometimes you want to manipulate not a whole file, but only one section of it.

For example, you are debugging a subroutine in a long FORTRAN code, and want to change all the WRITE(11) statements in that subroutine into WRITE(6), so you can see the output on the console.

Or you have a large table in your latest paper, and decide that all entries reading "T Tauri" should be abbreviated to "TT", while all references to T Tauri stars in the text should stay unabridged.

It's tedious to cut the section out, work on it in another buffer and re-insert it in the original file. Like me, you may also forget which version now contains the changes.

A simpler way is to use "narrowing", in which Emacs restricts its actions to some chunk of the file.

Load your FORTRAN program, place the cursor somewhere in the offending subroutine and type the fortran-mode command "C-M-a" to move to the start of the routine. Press "C-spc" to mark the spot, then move to the end of the routine with "C-M-e". The mark plus the current position of the cursor define a region enclosing the routine. Narrow Emacs' view of the buffer to just this region using "C-x n n". If this is the first time you have ever used this command, Emacs will ask for confirmation.

While you are in Narrow mode, only the affected part of the buffer is displayed: if you move to the start of the "buffer", you will find yourself in fact at the start of the subroutine. You can carry out your replace-string command and have it act only on this subroutine. However, if you save the buffer to disk, the whole buffer is saved, not just the part currently visible.

To return to viewing the whole buffer, type "C-x n w".

CHEKING YOR SPELING

Spell checking under emacs now works again on bigdog and other Alphas. By early next week it ought to be working on Suns.

The version of "ispell" installed is clever enough to recognise and ignore most of the formatting commands in a TeX or LaTeX document. Instead of skipping over \vspaces and \fleqns, you can focus on correcting your content.

To set up ispell on your Alpha account, edit your ~/.cshrc, ~/.local_cshrc or equivalent to add /opt/ispell/bin to the list of directories searched for executables. Place this new entry into the search path _before_ any entry reading /usr/local/emacs/bin, because that is where the carcase of the old version of ispell lies.

Next type "source ~/.cshrc" so your shell knows about the new path, and start emacs. To spell-check a document you are editing, type "M-x ispell-buffer". Emacs will move to the first spelling that it doubts and present you with a list of alternatives. Type the number or letter next to the alternative you want, or "SPC" to leave the word unchanged, "a" to accept your spelling of the word throughout the rest of the document, "r" to edit a replacement, "i" to insert your spelling into a private dictionary stored in ~/.ispell_english, or "x" to exit. After exiting, you can type "C-h d ispell-help" for some other options.

BINARY FILES

Sometimes you need to view and modify bits in a binary file. Maybe your FITS image is corrupted in one spot; or you've been sent the results of someone's simulation as a FORTRAN unformatted dump, and before you can read it you have to work out the byte order and locate any block markers.

Load the offending file into emacs and type "M-x hexl-mode". The buffer will be reformatted into ten columns: first, a hexadecimal number giving the offset from the start of the file in bytes. Next, eight columns each representing a pair of bytes of data in the file. Finally, the same sixteen bytes of data, rendered as ASCII characters. Non-printable characters are shown as ".".

You can insert data a byte at a time, either by typing ordinary keys to insert the ASCII codes into the file, by hitting "M-C-x" and supplying a hexadecimal number 00-ff, or by hitting "M-C-d" and supplying a decimal number 0-255.

Most of the usual cursor movement keys can be used in hexl-mode. For instance, "M-f" and "M-b" move you forward and back 8 bytes. "M-C-a" and "M-C-e" move you to the start and end of the current 512-byte block. To quit hexl-mode and re-format the buffer as text, type "C-c C-c".

ASCII AS ART

You want to make a strong impression via email, or you're writing up a FAQ, and you need to format ASCII text so it's transparent to the reader.

The most useful major mode for editing text is (surprise) text-mode. Type "M-x text-mode" to start it. In text-mode, you can rearrange a paragraph so line breaks are at or before column 70, by placing the cursor in the paragraph and typing "M-q". To change the column where lines end, and hence the width of your text, type "M-x set-variable RET fill-column RET", enter the new column number, and press "RET".

To center the text on the current line, between the start of the line and the fill-column, type "M-s" (this is useful for headings and trailers).

To make a section divider consisting of, say, 72 "=" signs in a row, use "C-u 72 =".

To enable automatic carriage returns, type "M-x auto-fill-mode". Auto-fill-mode is a minor mode which works within whatever main mode you are using, so whenever you have typed text past the fill-column and then hit "SPC" or "RET", a carriage return is automatically inserted.

You can have auto-fill-mode turned on whenever you enter text-mode by adding this line to your ~/.emacs file:

        (setq text-mode-hook (function (lambda () (auto-fill-mode 1))))

You can make text-mode your default major mode by adding this line:

        (setq default-major-mode 'text-mode)

TIP OF YOUR TONGUE

You can't quite remember the word you want, but you think you know the first syllable. Or you remember the word, but is it "ible" or "able"?

In text-mode, type as much of the beginning of the word as you have, then "M-TAB". Emacs will show you an ispell-style menu of possible completions.

ALAS I AM UNDONE!

Uh-oh, you pressed a key you didn't mean and hours of work have been drastically altered! How to recover your sanity?

Emacs remembers recent changes in the text of each buffer, and lets you undo them one-by-one. To undo a single batch of changes (usually one command worth), type "C-_" (yes, that's "ctrl-underscore") or else "C-x u".

(A few commands, like "query-replace", make many entries in the undo list; simple "commands" like ordinary letters and numbers are often grouped into words to make undoing less tedious.)

Typing "C-_" or "C-x u" over and over takes the buffer back to earlier and earlier stages of its existence. For example, you can use the command "C-u 100 C-_" to undo the last hundred changes. However if you break the sequence of "undo"s by typing any other command, then the previous undo commands become ordinary changes which you can now re-undo.

When emacs runs out of undo space for the current buffer, it frees up space by forgetting the oldest changes. The default maximum size of the undo list is 20000 bytes. If you regularly need a larger list, for example if you want to undo series of commands which cut a total of more than 20000 characters out of your buffers, then double the list size by adding these two lines to your ~/.emacs file:

(setq undo-limit 40000)
(setq undo-strong-limit 60000)

TAR FILES

With emacs you can extract files one-by-one from a .tar archive. You can also edit, delete and rename files without having to untar.

To start tar-mode, just load a file whose name ends with ".tar". If you have jka-compress installed as described in Lick Emacs Trick #12 (http://www.ucolick.org/~neal/emacsusers), you can also just load a gzipped tar file.

The files in the archive are listed in an "ls -l" or "dired" format (Lick Emacs Trick #9). Move the cursor to the one you want to copy into a file of its own and type "c NEWFILENAME RET". You can also edit a file by pressing "e" or clicking mouse button 2 on its name. Then type "C-x C-s" to save it back into the archive, or use "C-x C-w" to write it into a new separate file.

While viewing the list of files in the archive, press "h" for help, "d" to delete and "r" to rename.

GRAB THAT PARAGRAPH

Possibly the fastest way to select a paragraph you want to cut, copy or format is using "M-h".

This moves the cursor to the start of the current paragraph and puts a mark at the end. Straight away you can type "C-w" to cut the paragraph out, "M-w" to copy it, or "M-x ispell-region" to search it for wrong spellings.

A paragraph break in emacs text modes is any blank or indented line. In TeX mode, lines beginning with TeX commands also break paragraphs. In programming modes like fortran-mode, only blank lines do the job.

LIFE WAS MEANT TO BE EASY

In emacs, several neat tricks help you enter commands quickly. You rarely have to type out the whole name of a command or file.

To spell-check a buffer for instance, hit "M-x isp RET b RET" instead of "M-x ispell-buffer RET" and you've converted 16 keystrokes into 8. In cases like this when your answer is one of a list of possibilities, type the first couple of characters and press "RET". If you've uniquely identified the item, emacs will choose it for you. If not, press "RET" again and emacs will show the choices remaining. Then type another character or two and press "RET" to complete the command.

Save yourself even more keystrokes by re-using them. If you recently typed in "M-x what-cursor-position", no need to do it again: try "M-x" followed by "M-p" a few times to back up through the list of previous commands. Or follow "M-x" by "M-r cur RET" to search the list backwards for `cur'. Or edit previous commands before re-executing them, using "C-x ESC ESC" as described in Lick Emacs Trick #16.

Imagine you're working on one file and need to load another from a different directory. You type "C-x C-f" and emacs displays the current path "/scratch/ra/me/", ready for you to type a filename. No need to delete what's already displayed before you enter the new path: just type either "~" or "/" as the first new character and emacs ignores everything before. Say the new file is "~/constants.dat" and is the only file in your home directory whose name begins with `c'. If you type "~/c RET", emacs will create a new file called `~/c'. To call up the existing file, use "~/c TAB RET".

MILK FROM THE CREAM

To sort the lines in the current region into alphabetical order, use "M-x sort-lines". First mark the region you want to sort, either by dragging the cursor over it with the left mouse button held down, or by moving the cursor to one end, hitting "C-SPC", then moving the cursor to the other end.

For reverse alphabetical order, try "C-u M-x sort-lines".

To sort the lines according to a column of integers in them, say the second column, use "C-u 2 M-x sort-numeric-fields". Fields (columns) are separated by white space, with the first group of non-whitespace characters on the line being field 1.

Emacs provides several other ways as well to sort your lines, paragraphs or pages. For a description, type "C-h C-f sort-lines".

1000 FILES

How do you change the names of a large number of files all at once?

Imagine you have 1000 files called "frame.????.jpeg", where the ???? are digits. These have to be renamed to "fram????.jpg" so they can be transferred to a file system which accepts no more than 8+3 characters in a filename. You could write a shell script to do this, but is there a simpler way?

Enter "C-x C-f <pathname>" to start dired-mode in the directory containing the 1000 files (Lick Emacs Trick #9).

Mark the 1000 files using "% m frame\.[0-9]+\.jpeg RET". Rename the marked files with

          "% R frame\.\([0-9]+\)\.jpeg RET fram\1\.jpg RET".

How does it work? The "\1" asks emacs to take the part of the original filename that matches the first \(...\) in the "from" regular expression, and insert it into the "to" filename. The full stops have to be preceded by backslashes ("\.") because otherwise they have a special meaning in these regular expressions or regexps. The sequence "[0-9]+" means "one or more digits".

To find out about other ways to operate on many files at once, type "C-h C-k % R" while in dired-mode. For more info on using regexps in emacs, kill any existing *info* buffers and enter "C-h i m emacs RET m regexps RET".

PULLING TABS

To convert all of the TABs in a region, to SPCs: "M-x untabify" To convert as many as possible of the SPCs into TABs: "M-x tabify"

Remember, to set up a "region", put the cursor at one end and type "C-SPC", then move the cursor to the other end; or else drag the mouse over your text, with the right button held down.

The next Lick Emacs Trick will be January 2.

TOO WIDE FOR THE SCREEN

By default, Emacs displays too-long lines by folding them onto following lines on the screen, and shows "\" where the folds are made. When you're working on a table of data whose every line is longer than the window width, this is probably not what you want to see, because it makes the table hard to read.

Fix it by typing "M-x set-variable RET truncate-lines RET 1 RET" (To restore the default, repeat that with "'nil" instead of "1"). Now the ends of too-long lines disappear, but a "$" at the right-hand edge of the window shows there's more past the edge.

To see the columns of your table which are off the right-hand edge, move the whole table a screen left using "C-x <". Move the table back to the right with "C-x >". Move the table 24 characters to the left by typing "C-u 24 C-x <". If you change to another buffer and back again, your buffer with table will be reset to look at the usual left-hand edge of the text.

INDENTED TEXT

If you're typing an ASCII list, table, inset paragraph or something else with regular indenting, you can save yourself keystrokes by using Indented Text mode.

To enter it, type "M-x indente TAB RET". Now, each time you press "TAB", enough spaces and tabs are inserted to put you underneath the start of the next word in the previous non-blank line. With alignment taken care of automatically, you may be able to touch-type your whole list or table.

If you later make changes in an inset paragraph, you can automatically re-fill keeping the same indenting using "M-q", the same key as in ordinary text-mode. This lets you quickly change the indentation of a paragraph: adjust the first two lines and hit "M-q" to do the rest. In Indented Text mode, blank lines separate paragraphs but indented lines do not.

IS MY ABSTRACT TOO LONG?

To count the number of words in a region, type "M-| wc RET" (that's a `pipe' symbol). In the minibuffer at the bottom of the screen, three numbers are printed. The first is the number of lines in the region, the second the number of words, and the third the number of characters.

In the same vein, you can print part of a file using "M-| lpr -Pmyprinter RET", extract only lines which don't contain the word `jubjub' using "M-| grep -v jubjub", sum columns in a table using gawk, and so on with other shell commands.

TWIRL THAT KALEIDOSCOPE

Several people asked how to add to the list of words that are colored by hilit-mode (Trick #15, http://www.ucolick.org/~neal/emacsusers.html). One way is to plant your extra words inside your own copy of the hilit19.el lisp file. Here's how:

(setq load-path (append (list "~/mylisp") load-path))

SHOWING FILENAMES IN ICONS

If you use a single copy of emacs to edit files in multiple X-windows, you can have the name of each file displayed in its X-window's title bar and icon. To arrange this, add a line to your ~/.emacs file:

  (setq frame-title-format (list mode-line-buffer-identification))

With this set up, restart emacs and load a file using "C-x 5 f", and a new emacs X-window will appear with the file's name in the title bar. Iconify the X-window and the icon will include the name of the file. Load a new file in that X-window and the name in the title bar and icon will change too. So long as your emacs process has more than one X-window open, each X-window will show the name of its file.

To close an emacs X-window, use "C-x 5 0". To open a new X-window for sending mail, try "C-x 5 m". To open a new X-window displaying one of the existing buffers, press "C-x 5 b". To open a new X-window looking at a directory in dired-mode, enter "C-x 5 d".

Since Emacs already uses the word "window" for divisions within a single X-window, in emacs separate X-windows are called "frames".

WHAT DOMAIN?

Some of the Internet domain names are a little obscure. For instance, you receive email from someone at a .ch address. Where is that? China? Chile? Czechoslovakia?

Never fear, Emacs is here! Type "M-x what-domain RET ch RET" and you see the answer: "The Swiss Confederation".

BOOKMARKS

Place a "bookmark" in a long file, and next time you start emacs you can come straight back to the file at the place you were editing.

To put down a bookmark at the position of the cursor, type "C-x r m RET". Emacs stores the bookmark separately and makes no changes in the file itself.

To find a file if necessary, and then jump straight to the bookmark in it, use "C-x r b filename RET". You can type the start of the file name and use "TAB" to complete it. No pathname is needed because emacs stores the locations of the bookmarked files in ~/.emacs-bkmrks. Emacs also stores about a paragraph of context so "C-x r b" can find the proper position even if the file is changed some.

To delete a bookmark, either use "M-x bookmark-delete RET RET", or try "C-x r l" to bring up a list of your bookmarks which you can edit.

HELP HELP

How do you find out how to do the job in front of you?

If you remember a key sequence you might need, like say "M-q", use "C-h k M-q". You'll be told the command called up by the key sequence and briefly what it does.

If you know or guess a full command name like "fill-paragraph", see detailed help on that and related commands with "C-h C-f fill-paragraph".

If you don't know where to start, try the `apropos' help. For instance, "C-h a fill" shows a list of commands for filling paragraphs and regions, turning automatic fill-mode on and off, and a few others.

P.S. You can also work backwards: if you know a command's full name and want the shorter key sequence that calls it, use for instance "C-h w query-replace".

TAG TEAM PROGRAMMING

Writing a large code is easier if you break it up into small subroutines. If you put each subroutine in its own file, then recompiling is also fast, because only files you change are recompiled >from scratch.

But when your code is spread across dozens of files, how do you find the subroutine you want to modify? How do you search-and-replace through all of the files?

Build a "tags table", a list of subroutines and the files where they live, by typing at a shell prompt "etags <files>". For instance if you are writing a C program, you might use "etags *.[ch]". A file called "TAGS" will be created in the current directory.

To jump to a subroutine, press "M-.". You'll be asked for the name of the subroutine. Enter the first few characters and press "TAB" to complete it. You may be asked which tags table to use. Press "RET" to take the default, ./TAGS.

To search for a regular expression in all the files in the tags table, use "M-x tags-search RET REGEXP RET". To search and replace across all the files, try "M-x tags-query-replace RET REGEXP RET REPLACEMENT RET". Regular expressions also appear in Lick Emacs Trick #29, where they're used to operate on large numbers of files at once.

To continue to the next match for a tags-search or tags-query-replace, type "M-,".

If you add a new subroutine, give it an entry in the TAGS file by running "etags <files>" again. As well as functions and subroutines in FORTRAN and C code, the TAGS file remembers #defines and macros in C code, and \chapter, \section, \ref, etc in LaTeX.

MULTIPLE SHELL BUFFERS

Compared with ordinary xterms, emacs shell buffers allow virtually unlimited recall of past output, searching through past output, and filename completion in programs like mongo which don't provide it themselves. However, emacs shell buffers run more slowly than xterms.

If you open multiple shell buffers, you can use one for mongo and another for a code whose output mongo plots. Start a shell buffer using "M-x shell". It's called "*shell*". Rename it, for example using "M-x rename-buffer RET *mongo* RET". Now you can start a second shell buffer, which will again be called "*shell*".

PICK AND CHOOSE

Normally when you copy or kill a piece of text, it replaces the contents of the cut buffer. You can append it to the cut buffer instead, by typing "C-M-w" just before you kill or copy.

So to pick paragraphs from an article and stick them together in the cut buffer, click the left mouse button on each paragraph you want and type "M-h C-M-w M-w".

To then paste all the paragraphs into some other program which is running in an xterm window, click the middle mouse button there.

YOUR AVERAGE REGULAR EXPRESSION

With a regular expression or regexp you can rename 1000 files at once (trick #29). You can highlight extra language keywords in hilit mode (trick #34). Regexps are also very handy for search-and-replace operations. For instance:

To locate a phrase whether or not it's split up by multiple spaces or line breaks, type "M-C-s the mighty Keck".

To replace "image" with "frame" throughout a document while ignoring "saoimage", use "M-x query-replace-regexp RET \bimage RET frame RET". The sequence "\b" matches word boundaries.

To reverse the DO loops in your FORTRAN program, try "M-x replace-regexp RET do \(\w+\)=\(\w+\),\(\w+\)$ RET do \1=\3,\2,-1". The sequence "\w+" matches one or more characters which are part of words. For fortran-mode this includes a-z, A-Z and 0-9. The "$" matches the end of a line. You can read the "\2" as "whatever matched the sequence between the second \( and \)". In this example that's the original starting value for the DO loop.

If you want to call query-replace-regexp with fewer keystrokes you can bind it to the key M-C-%, by adding this line to your ~/.emacs file:

  (global-set-key [?\M-\C-%] 'query-replace-regexp)

This key is a good choice because M-% is already bound to the ordinary query-replace.

SENDING MAIL

To send someone mail from inside emacs, type either "C-x m" or, while reading mail in rmail-mode, just "m".

Yank into your letter an indented copy of the message you were reading using "C-c C-y". Rearrange the yanked copy so none of its lines spill over the edge of the page with "C-c C-q".

Add a CC: field with "C-c C-f C-c". Think ozone damage. Try "C-c C-f C-b" for blind carbon copies, "C-c C-f C-s" to jump to the Subject: line, or "C-c C-f C-t" for the To: line.

To have the contents of ~/.signature automatically appended before you edit each message, put this line in your ~/.emacs file:

  (setq mail-signature t)

Finally, send the message with "C-c C-c".

Thanks to George Blumenthal for encouraging this week's trick. For more on rmail-mode see Trick #17.

WINDOW WIPER

You may find you often split your emacs X-window in a certain way: half for notes during data reduction and the other half for dired operations on the images, for instance; or ten lines for the list of messages in your inbox, and the rest for the current message.

If you're about to do something else for a moment and return, you can save the current state of the windows by typing "C-x r w a". When your other task is done, restore your setup with "C-x r j a".

This saves the window configuration ("w") into the register ("r") labelled "a", then jumps back ("j") to the configuration stored in the register. To save more than one configuration, you can use the rest of the alphabet.

Following on last week's trick, if you prefer forwarded mail messages' lines to begin with say " %%", add to your ~/.emacs file the command (setq mail-yank-prefix " %%").

KEY STROKES

Some keyboards have neither an Alt key nor an Esc key, so there's no way to generate a Meta command in emacs! On other keyboards, only one Alt behaves as it ought. How can you fix these? A few minutes of setting-up can make your life a lot less frustrating.

Tell X-windows to translate your key into one emacs understands: find the translation needed using the xev command, test it using xmodmap, then make the change permanent by adding a line to your startup files.

For instance, you have no Meta key and want to make the f1 key do the job. To find out what key symbol f1 generates in X-windows, type "xev RET" at a shell prompt. A small window pops up, and whenever any X activity occurs in that window, descriptions appear back in the shell window. Move the mouse cursor into the xev window, press the f1 key, and from the paragraph of codes in the description, notice the part which looks like "(keysym 0xffbe, F1)". You now know the keysym for the f1 key is "F1". To kill the xev window, move the mouse cursor back into the shell window and press "C-c".

Next tell X to read f1 as a Meta or "first modifier" key, by typing at a shell prompt "xmodmap -e 'add mod1 = F1' RET". If the f1 key now does what you want, make this permanent for future X logins by adding a line at the end of your ~/.xmodmaprc file:

  add mod1 = F1

Another example remapping: your right Alt key does not work as Meta in emacs. Running xev, you find that the right Alt key generates X keysym "Meta_R". To your ~/.xmodmaprc file, append the line

  add mod1 = Meta_R

Yet another example: swap the Ctrl and Caps_Lock keys by adding to your ~/.xmodmaprc file the six lines

  remove Lock = Caps_Lock
  remove Control = Control_L
  keysym Control_L = Caps_Lock
  keysym Caps_Lock = Control_L
  add Lock = Caps_Lock
  add Control = Control_L

If you move from station to station and the keyboards are different, you might find it convenient to add "xmodmap -e ..." commands to a window manager menu, or create shell aliases for them.

TWO SPACES AFTER A FULL STOP

Normally emacs fill commands put two spaces after a full stop which ends a sentence. If you want just one, add these lines to your ~/.emacs file:

  (setq sentence-end "[.?!][]\"')]*\\($\\|\t\\| \\)[ \t\n]*")
  (setq sentence-end-double-space nil)

Now, when you start a new emacs, fill commands like M-q and sentence motion commands like M-e and M-a expect and leave only one space at the end of a sentence.

Beware that this leaves both emacs and the reader of your document with no way to tell periods ending sentences from those ending abbreviations.

JUMPING THE GUN

How can you quickly pull up a mail message about Gunn filters that you received months ago?

If you saved it in an RMAIL format mailbox (trick 17), load the mailbox file into emacs, press "j" to jump to the first message in the file and use "M-s Gunn RET" to find the next message containing the word.

SAVE THE MACROS

How can you automate an editing task you find yourself typing in again and again? If the task deals with one line of a file at a time, the "gawk" command may be the right tool; otherwise, an emacs macro can be easier to set up.

Trick 10 covered use of "C-x (" and "C-x )" to remember a sequence of keystrokes as a macro, and "C-x e" to execute it. To name the macro so it won't be lost if you define a new one, use "M-x name-last-kbd-macro RET NAME RET", where NAME might be "swap-xy" or "extract-transform-coeffs". Now you can execute the macro by typing "M-x NAME".

To save your macro so it'll be available each time you start emacs, load your ~/.emacs file and insert the macro's definition using "M-x insert-kbd-macro RET NAME RET".

To bind your macro to a key such as f9, add to your ~/.emacs file after the macro definition the line

        (global-set-key [f9] 'swap-xy)  

5TH COLUMN

To have the cursor's column and row position displayed in the modeline, add to your ~/.emacs file the 2 lines

        (autoload 'display-column-mode "column" nil t)
        (display-column-mode 1)

To have emacs automatically scroll long lines horizontally so your cursor stays visible, add to your ~/.emacs file the three lines

        (autoload 'hscroll-mode "hscroll" nil t)
        (setq hscroll-margin 5)
        (setq hscroll-step 50)

Now restart emacs and type "M-x hscroll-mode", then set your buffer to truncate long lines using "M-x hscroll-truncate-lines", and type a long line of text. When the cursor comes within 5 columns of the margin, the window moves across the text by 50% of the window's width, so you're always looking at the point where you're typing.

These will be the last regular emacs tricks, since I've described most of the stuff I actually use, and my thesis is pressing. If you have a question about how to do something, I'm happy to address it in an occasional trick.

Answers/Software/Emacs/Software/Emacs/NealsEmacsTricks (last edited 2007-09-12 22:06:59 by GregNovak)