Chapter 5. Emacs as a Work Environment

Many of the everyday things you do from a command prompt can be done from within Emacs. You can execute commands, work with directories, and print files—all without leaving Emacs. Changing tasks is as simple as jumping between buffers.

What's important about this? Of course, it's nice to be able to move between tasks easily. What's even more important is that you have the same editing environment no matter what you're doing: you can use all of the Emacs editing commands to work on a file, give shell commands, then start up Dired, the directory editor, to do some file maintenance. It is simple to move text from one window to another. You can execute a command and then use Emacs commands to cut and paste the results into a file. If you're trying to compile a program and keep getting error messages, you can save the interactive session as a file and confer with someone about the problem. Despite the many advantages of modern window systems, Emacs often provides the best way to integrate the many kinds of work you do daily.

Much of the information in this chapter involves integration between Emacs and the operating system. Emacs is most commonly a Unix editor, so forgive us for a bias in that direction. But we are happy to report that for users of GNU Emacs on other platforms, integration with the operating system is still available; you can use shell mode to run commands and can edit directories with Dired. There's no reason to leave Emacs no matter what your platform is.

5.1 Executing Commands in Shell Buffers

One of the most important features of Emacs is its ability to run a command shell in a buffer. Once you have started a shell buffer, you can do all of your normal command-line work within Emacs. What does this buy you?

• You don't have to leave Emacs to get a command prompt. If you want to print or compile a file that you're editing, you can do it immediately.

• You can use Emacs editing features to write your commands.

• You can use Emacs editing features to "back up" through your command list, copy an old command, modify it, and execute it again.

• You can save your shell buffer, keeping a transcript of your editing session—which automatically includes the output from every command that you ran. For debugging or remembering commands you run infrequently, this can be invaluable.

• You can copy output from commands into a file or into another command.

• You can save complex commands in a file and insert the file at the prompt, rather than retyping the command.

As you get used to working within Emacs, you will undoubtedly discover more and more ways to put shell mode to use.

In this section, we discuss shell mode. Later in this chapter, we discuss directory editing, printing, and calendar and diary features for doing simple time management in Emacs. Right now, we'll start with a simple variation on shell mode, a feature that lets you execute commands one at a time.

5.1.1 Running One Command at a Time

To run a command while you're in an Emacs session, type M-!. Emacs asks for the command you want to run. Type the command and press Enter. Emacs then opens a window called

*Shell Command Output*
where it displays the results of your command.


Type: M-!

Emacs prompts you for a command to execute.


Type: diff joyce joyce2

Emacs executes the diff command and puts the output into a

*Shell Command Output*
buffer.


Because the output from the diff command is in a buffer, you can edit it, save it, or do anything else you would like with it. Of course, if the operating system has no diff command or cannot access it for some reason, this command fails.

An interesting twist to the shell command facility is that you can use a region of a buffer rather than a traditional file as input to the command. For example, let's say we want to sort a phone list. First, we put the cursor somewhere in the list (say, on the first character of

Liam
), then we give the mark-paragraph command (M-h). This command defines the phone list as a region, with the cursor at the beginning of the paragraph and the mark at the end.

In the following example, the shaded area shows the extent of the region we want to sort. After selecting a region, we press M-| (for shell-command-on-region); Emacs prompts for the shell command to run.


Type: M-h M-|

Emacs prompts you for a command to execute (Windows).


Now we give the command sort without specifying any input file. Emacs is taking care of the input for us.


Type: sort Enter

Emacs runs a sort on the region (Windows).


Emacs has sorted the phone list (i.e., everything within the region).

A useful variation for M-! puts the output directly into the current buffer, rather than into a

*Shell Command Output*
buffer. To do so, precede the command with C-u: for example, C-u M-! runs a shell command and puts the output in the current buffer.


Type: C-u M-! ls -la Enter

Emacs runs ls and inserts the result at your current location (Mac OS X).

5.1.2 Using Shell Mode

Now we're ready to discuss shell mode, the interactive facility for running commands. To start a shell buffer, type M-x shell Enter. This creates a buffer named

*shell*
. You see the prompt for your shell within this buffer. (This defaults to your usual shell; you can substitute another shell to use in Emacs. See "Which shell?" later in this chapter.)


Figure 5-1. Shell buffers for Linux, Mac OS X, and Windows


For the most part, shell mode is exactly like the normal command interface, except that you can use Emacs to edit the commands as you type them. You can copy commands from one place to another, copy the results into a file, save the whole shell buffer to a file, and so on. Note in Figure 5-1 that Emacs has added a few items to the menu bar (Complete, In/Out, and Signals).

A few tricks are worth knowing, though. For example, you normally interrupt a command by typing C-c. If you type C-c in shell mode, Emacs thinks that the C-c is part of a command meant for it, because many Emacs commands start with C-c. Therefore, you have to type C-c C-c to terminate the current job. Likewise, under Unix, you type C-c C-z to stop a job, instead of C-z, and C-c C-d instead of C-d, and so on. (C-c C-d is not strictly necessary because Emacs understands C-d in context. If you're at the end of the buffer, C-d means "end of file"; if you're anywhere else, it deletes a character.) Alternatively, you can select options from the Signals menu rather than using control characters, if desired (for example, selecting EOF instead of typing C-d).

Shell mode also provides a few convenient shortcuts. The command M-p retrieves the last shell command you typed, no matter how far back in the buffer it is. Typing successive M-p's brings back earlier commands.


Type: M-p

M-p retrieves the last command, even if it isn't on the screen (Mac OS X).


In this example, the previous command was more dickensxmas.tex. It's no longer on the screen; its output has pushed it off the top. M-p (for comint-previous-input) retrieves the command, but doesn't execute it; you can edit the command before pressing Enter. To find subsequent commands, type M-n.

If these commands sound familiar to you, they should. They are history commands, which are identical to the minibuffer history commands we discussed in Chapter 3. The In/Out menu is devoted to working with command history.

Enter and Tab have special functions in shell mode. Pressing Enter executes the command on the line where the cursor is, even if you move the cursor up to the line of an earlier command you want to execute again. When you press Enter, Emacs copies the command to the end of the buffer and executes it. Of course, you can modify the command before pressing Enter.

Pressing Tab puts the Emacs completion feature into action; use completion for operating system commands, filenames, and variables. Note that the completion of system commands works best on Unix implementations like Linux and Mac OS X; Emacs doesn't seem to find all the possible Windows commands, for example.

If you type a command that produces a lot of output, cluttering up your session, there's an easy way to get rid of it. Type C-c C-o (for comint-kill-output).


Type: C-c C-o

C-c C-o automatically deletes the output from the last command (Mac OS X).


The previous command (ls-la) remains on the screen, but its output, a long list of files, is deleted. C-c C-o can delete output from only the most recent command; it can't delete output from your previous commands.

Another useful command for shell mode is C-c C-r (for comint-show-output). This command is useful if a command produces a lot of output and causes the first few lines of output to scroll off the screen. C-c C-r repositions the window so the first line of output from your last command is at the top of the window. If you want to see the end of the output instead, type C-c C-e (for comint-show-maximum-output); this command moves the last line of the input to the bottom of the window.

When you're writing a book, moving by paragraphs makes sense, but when you're using a shell, moving by output group is more helpful. An output group consists of a command and its output. To move to the previous output group, type C-c C-p. To move to the next output group, type C-c C-n.

An advantage of shell mode is that you can start a command and then edit another buffer while the command runs. The shell buffer doesn't need to be onscreen; just type M-x shell to get the buffer back again.

You can have multiple shell buffers running at once; just use the command M-x rename-uniquely to rename your shell buffer. You can start another shell buffer, and another, and another—as many as you need to juggle all your tasks.

5.1.2.1 Which shell?

Normally, Emacs uses your default shell in shell mode. Under Windows that's cmd.exe (the familiar C:\> prompt or a close relative).[25] But Unix has a wide variety of available shells, including the GNU Project's bash and the zed shell, zsh. Whatever shell you normally use, that's what Emacs starts when you enter shell mode.

How does Emacs know which shell to start? First, it looks at the variable shell-file-name. Then it looks for a Unix environment variable named ESHELL. Finally it looks for an environment variable named SHELL. If you want to run another particular shell (for example, the zed shell) when you're in Emacs, you can add the following command to your .emacs file:

(setq shell-file-name "/bin/zsh")

When Emacs starts an interactive shell, it runs an additional initialization file after your shell's normal startup files. The name of this file is .emacs_shell-name, where shell-name is the name of the shell you want to use in Emacs. It must be located in your home directory. For example, if you use the C shell, you can add Emacs-only startup commands by placing them in the file .emacs_csh. Let's say that when you're in Emacs, you want to change the prompt to emacs:% and you want an environment variable called WITHIN_EDITOR to be set to T. Here's the contents of your .emacs_csh file:

set prompt="emacs:% "

setenv WITHIN_EDITOR T

Within a shell buffer, Emacs also sets the environment variable EMACS to t, and sets your terminal type (the TERM variable) to emacs.

5.1.2.2 Making passwords invisible in shell mode

By default, shell mode displays everything you type and that includes passwords—not a good situation if someone is peering over your shoulder. There is a way around this problem, however. Before you type the password, type M-x send-invisible. Emacs asks for the nonechoed text. When you type a character, Emacs puts an asterisk in the minibuffer. Press Enter and Emacs enters the password without displaying it. To have Emacs hide passwords as you type them, add the following two lines to your .emacs file:

(add-hook 'comint-output-filter-functions

  'comint-watch-for-password-prompt)

Emacs asks for nonechoed text in the minibuffer whenever a password prompt appears on the screen, making sure that the password is never displayed. Table 5-1 summarizes shell mode commands.


Table 5-1. Shell mode commands

Keystrokes Command name Action
(none) shell Enter shell mode.
C-c C-c SignalsBREAK comint-interrupt-subjob Interrupt current job; equivalent to C-c.
C-d comint-delchar-or-maybe-eof Send EOF character if at end of buffer; delete a character elsewhere.
C-c C-d SignalsEOF comint-send-eof Send EOF character.
C-c C-u comint-kill-input Erase current line; equivalent to C-u in Unix shells.
C-c C-z SignalsSTOP comint-stop-subjob Suspend or stop a job; C-z in Unix shells.
M-p In/OutPrevious Input comint-previous-input Retrieve previous commands (can be repeated to find earlier commands).
M-n In/OutNext Input comint-next-input Retrieve subsequent commands (can be repeated to find more recent commands).
Enter comint-send-input Send input on current line.
Tab comint-dynamic-complete Complete current command, filename, or variable name.
C-c C-o In/OutDelete Current Output Group comint-kill-output Delete output from last command.
C-c C-r comint-show-output Move first line of output to top of window.
C-c C-e In/OutShow Maximum Output comint-show-maximum-output Move last line of output to bottom of window.
C-c C-p In/OutBackward Output Group comint-previous-prompt Move to previous command.
C-c C-n In/OutForward Output Group comint-next-prompt Move to next command.

5.2 Using Dired, the Directory Editor

Dired is one of the most interesting features of Emacs. With Dired, you can look at a listing of all the files in a directory, delete them, rename them, copy them, and perform almost all basic file operations. More important, Dired can make you more productive. For example, you can work with groups of files, deleting, moving, compressing, or even query-replacing strings in them.

There are several ways to start directory editing. If you're not in Emacs, invoke Emacs with a directory name as an argument, for example:

% emacs literature

Emacs starts up editing the directory literature: you'll see a single window that contains a listing of the literature directory. You can also start the directory editor by using C-x C-f (or any other command for visiting a file) and naming a directory, rather than a file. For example, typing C-x C-f literature gets you ready to edit the literature directory. Typing C-x d (for dired) or selecting the folder icon on the toolbar also starts Dired; you then specify a directory name. Finally, dragging a folder onto the Emacs window also starts Dired.[26]

No matter how you start the editor, the result is the same.


Type: C-x C-f literature Enter

A basic directory editor display.


As you can see, Dired's display is similar to what you see if you type ls -l at a Unix shell prompt. The permissions associated with the file, the owner, the group name, the size of the file, and the date last modified all precede the filename. All files and directories are listed, including those whose names start with a dot. The cursor starts out on a filename, rather than in the first column.

Also, if your display supports colors (unfortunately this book doesn't), you'll see that directories are blue, backup and auto-save files are tan, and symbolic links are purple. Colors are a function of font-lock mode. If you don't see colors in your directory listing, type M-x font-lock-mode Enter or add the following line to your .emacs file:

(global-font-lock-mode t)

By default, the list is sorted by filename, but you can sort it by date instead. Look at the mode line. It says (

Dired by name
). To change the order of the display, type s (for dired-sort-toggle-or-edit). This command puts the newest files at the top of the list, solving the "Where's that file I worked on yesterday?" problem quite easily. The mode line says (
Dired by date
). Typing s again toggles the sort, putting it back in alphabetical order.

If you remember the commands used to edit the buffer list (from Chapter 4), you will find that they are almost identical to the directory editor commands. You can do many additional things, but the basic commands are the same.

Warning

Remember, in the directory editor you are working directly with files, not with buffers. When you delete a file using Dired, it's gone permanently.

There are several ways to move around in Dired. The commands Space, C-n, and n all move you to the next file in the list. Del, C-p, and p all move you to the previous file. Arrow keys and PgUp and PgDown work as well. You can also use any of the search commands (incremental search, word search, and so on) to find a particular file.

5.2.1 Viewing and Editing Files

When you look at a directory listing, you may want to get a quick look at the files. Dired's v command does just this: put the cursor on the file you want to view and press v (for dired-view-file). Emacs displays the file in view mode.[27] This is a read-only mode, so you can't modify the file. Press C-c or q to return to the directory listing. While you're viewing the file, you can use s to start an incremental search, or press Enter to scroll the display down one line. Typing

=
tells you what line the cursor is on. There are a number of shortcuts for other Emacs commands (like marking text), but frankly, the regular commands work correctly. There's no reason to remember a special set of commands when the ones you already know work.

If you want to edit a file from the Dired buffer, move to the line the file is on and press Enter (a variety of other keystrokes work as well, such as f for find or e for edit). Emacs finds the file and you can edit it. This is a completely normal editing buffer: you can make any changes you want, save them, visit other files, and so on. Typing C-x b followed by the name of the directory you were working in moves you back to the Dired buffer. Or you can use the buffer menu (C-x C-b) to find and display the Dired buffer.

Viewing and editing files is nice, but you already know how to do that—right? You're waiting for the interesting stuff: how to delete files.

5.2.2 Deleting, Copying, and Renaming Files

As we've said, file deletion is almost identical to buffer deletion with the buffer list. If you learned how to delete buffers, you know the basics of deleting files with Dired. First, you flag a file for deletion by moving to the file's name and typing d. Doing this places a D on the left margin and moves the cursor to the next file in the list. You can flag as many files as you want. You can change your mind at this point and type u to undelete the file. At some later time, you type x to delete the files (more on this in a minute). The following screen shows what the Dired buffer looks like when you flag a few files for deletion.


Type: d d d

Three files flagged for deletion (Windows).


As we mentioned, you can type u at any time to remove the deletion flags from the files. Typing u moves you to the next file in the list, and, if it is marked, unmarks it. You can also use Del to unmark. This command undeletes the previous file in the list and then moves up one line.

Because Emacs generates backup files and, at times, auto-save files, you may want to delete them from time to time. Emacs offers shortcut commands to flag such files. Typing

#
flags all the auto-save files (files whose names start and end with
#
) for deletion. Emacs flags them with D. Typing ~ flags all the backup files (whose names end with ~) for deletion. You can remove the flags from backup files you want to keep, for example, the backup copies of files you've recently worked on.

When you really want files to be deleted from disk, press x. Emacs displays the names of all the files flagged for deletion and asks you if you want to delete them.


Type: x

Emacs asks you to confirm the deletion by typing yes (Windows).


Type yes to delete them all or type no to return to the Dired buffer without deleting any of them.

This is the usual way of deleting files, but if you want a file deleted right away, type an uppercase D. Emacs asks if you want to delete the file (yes or no). Type yes to delete the file immediately or no to change your mind. In Dired, this is one of a number of cases in which the lowercase letter (like d to flag for deletion) and the uppercase letter (like D to delete immediately) have a different meaning.

To copy a file in Dired, type C next to it (it must be a capital C). Emacs asks for the name of the file you want to copy to. Type the name and press Enter. Emacs says,

Copied: 1 file
. To copy several files in the list, preface the C with a number. For example, typing 3C would copy this file and the next two files. (See "Working with Groups of Files" later in this chapter for fancier ways to select a group of files to operate on.)

To rename a file with Dired (similar to the Unix mv command), type R next to the filename. Emacs asks what the new name should be. Type it and press Enter. Emacs says,

Moved: 1 file
.

If you move files between platforms, you can wind up with some filenames in uppercase and some in lowercase. Files moving from older versions of Windows may be in all caps, for example. Simply mark the files in question by typing m, then press %l for lowercase or %u for uppercase. Voilà—painless case consistency.

5.2.3 Compressing and Uncompressing Files

Compressing files saves disk space, and Dired provides an easy way to do it. Put the cursor on the line of the file you want to compress and press Z (for dired-do-compress). Emacs asks the following:

Compress or uncompress filename? (y or n)

Emacs compresses the file if it's not compressed and uncompresses it if it is.[28] Press y to compress or uncompress the current file. Compression happens immediately, so you can watch both the extension and file size change as Emacs compresses the file.

What about editing compressed files? Although it's not on by default, Emacs has an automatic compression/decompression mode called auto-compress mode. To enter it for this session, type M-x auto-compress-mode Enter, which turns automatic compression on. To enable auto-compression automatically, add this line to your .emacs file:

(auto-compression-mode      1)

5.2.4 Comparing Files

In Chapter 4, we discussed comparing files in two windows. Emacs provides a way to do this using the diff command in Dired. Set the mark on the file you want diff to compare, put the cursor on the other file, then type =. Emacs compares the two files and opens a window with a

*diff*
buffer containing the output from the command.

Emacs has a separate option for comparing a file to its backup file. Put the cursor on the file you want to compare with its backup and type M-=. Emacs displays a

*diff*
buffer showing the differences between the two files.

If you are serious about version control, you may want to check out Chapter 12, which discusses version control as well as the GNU tool ediff.

5.2.5 Running Shell Commands on Files

While Dired's implementation of diff is useful (and there are implementations of chmod, grep, and find as well), in a more general sense, you can perform any command on a file by pressing an exclamation point (!). For example, let's alphabetize the phone list file using the sort command.


Move to the phone file and press !

Emacs asks what command you want to run (Mac OS X).


Type: sort

Emacs displays the output from the command in a separate window (Mac OS X).


Usually, asterisks (*) and question marks are used as wildcards in commands. In Dired, they have a special meaning. An asterisk means "use the file I'm on or the files I've marked"; that way you don't have to type filenames explicitly. When multiple files are marked, a question mark means to run this command separately on each file.

In a slightly more complex example, you might have a command with more than one file as an argument. For example, you might want to make a new file out of the sorted phone list.


Move the cursor to the phone file, then type: !

Emacs asks what command you want to run (Mac OS X).


Now tell Emacs you want to sort your phone file and put the output in a new file called phonesorted. The cursor is on the phone file, so you don't need to type its name in the command. Substitute an asterisk (*) for the name of the file:


Type: sort * > phonesorted

The operating system sorts the phone file and puts the output into the new file phonesorted (Mac OS X).


We created the file, but it doesn't appear on the display, which is not automatically updated in this case. To see the phonesorted file, type g.


Type: g

Emacs updates the Dired display, showing the file phonesorted (Mac OS X).


Dired is frankly inconsistent about whether you type g before the display is updated. Some commands, as we'll see shortly, update the display immediately. Others, such as running shell commands on files, do not (Emacs really doesn't know what shell commands it's running or their effect on the display). A good rule of thumb is to type g if you don't see what you expect to see.

5.2.6 Working with Groups of Files

So far we've talked about working with one file at a time; any commands you give apply to the file the cursor is on. Working with multiple files is a better illustration of the real power of Dired. You can organize your directories in a flash once you learn a few shortcuts. First let's talk about some ways to select files, and then we'll talk about what we can do with the selected files.

5.2.6.1 Selecting files

So far we've primarily talked about flagging files for deletion. When you want to do something else with a group of files, you first mark them with an asterisk. Pressing m marks the file the cursor is on; an asterisk appears where you normally see a D. Typing 3m marks this file and the next two files. Once you mark files with an asterisk, Emacs assumes that any command you issue is meant for these files. So if you have three files marked with an asterisk and press Z to compress, Emacs assumes you want to compress those three files. After the compression, the files remain marked with asterisks. So how do you get rid of the asterisks when you're done with these files?

To remove the asterisks, you press M-Del (for dired-unmark-all-files). Emacs asks which marks to remove. Press Enter, and Emacs removes all the marks.

Sometimes it's easier to mark the files you don't want to work with than those you do. Pressing t toggles the marks, marking all unmarked files and removing marks from those previously marked.

5.2.6.2 Selecting likely candidates for deletion

Marking files sequentially is simple but, in all honesty, it's not very powerful. Emacs provides commands for selecting types of files that you often want to get rid of when you're cleaning up a directory: backup files, auto-save files, and so-called garbage files.

Auto-save files are created when a session terminates abnormally; they have the format

#filename#
. Backup files which Emacs creates periodically, have the format
filename~
. To mark these files in Dired, type # or ~ respectively.

Emacs also has an option that automatically selects "garbage" files. By default, this includes files with the following extensions: .log, .toc, .dvi, .bak, .orig, and .rej. Garbage files are defined by a regular expression, which is contained in the variable dired-garbage-files-regexp; you can change the value of this variable to define garbage files as you see fit (after all, one man's junk is another man's treasure).

5.2.6.3 Selecting files by type

Dired provides commands for selecting executable files, directories, and symbolic links. To select executable files, type * *. To select directories, type * /. Typing * @ marks symbolic links.

5.2.6.4 Using regular expressions to choose files

Often you want to select related files and either archive them, move them, compress them, or just delete them. Typically, you use wildcards to select multiple files. In Dired, you use regular expressions. To mark a group of files whose filenames match a regular expression, press % followed by m to mark them with an asterisk.

For example, let's mark all the files that start with ch. Remembering the quick lesson on regular expressions from Chapter 3, ^ finds the beginning of a word, so the regular expression ^ch would mark all the files that start with ch.


Type: %m

Emacs asks for a regular expression so that it can mark the files (Windows).


Type: ^ch Enter

Emacs marks all the files starting with ch and tells you how many it marked.


Sometimes it's more useful to mark files whose contents match a given regular expression. To mark files that contain a certain regular expression, type % g, followed by the regular expression to match (think g for grep if you're familiar with grep).

Now that we've got the files marked, let's talk about what to do with them.

5.2.6.5 Operating on groups of files

In the course of daily work, a directory can get cluttered with many different kinds of files. Eventually, you need to make subdirectories to organize the files by project, then move the files to those subdirectories. You can do both these things from within Dired.

Let's say that the ch files are chapters from a novel you work on in your spare time. We need a subdirectory called novel to store the files in. You can create a directory by typing + (for dired-create-directory).


Type: +

Emacs asks for a directory name (Windows).


Type: novel Enter

Emacs creates the directory and displays it on the screen (Windows).


Now let's move the ch files we marked into the new directory. We'll use the rename command, R. This command, like the Unix mv command, is used for renaming files and for moving them. Because we have marked more than one file with an asterisk, when we type R, Emacs assumes we mean to move the marked files.


Type: R

Emacs asks where you want to move the marked files to (Windows).


Type: novel Enter

Emacs moves the files (Windows).


Now you can see that the files have moved. Marking files by regular expression allows you to work with a select group of files quickly.

One of the more interesting things you can do with a group of files is perform a query-replace on all of them with a single command. On large projects, a last-minute change often forces arduous searching and replacing of certain text in each file. First, select the files you want to include in the query-replace, then press Q (for dired-do-query-replace). Put in the search string, then the replacement string (the strings can be plain text or a regular expression) and Emacs starts a query-replace that moves you through each file sequentially. Here's the only hitch: if you interrupt the query-replace with a recursive edit, you can't restart it without going back to the Dired buffer.

Another interesting command is searching across files for a given regular expression. To do this, mark the files, then press A. Emacs stops at the first match; press M-, to move to the next match.

5.2.7 Navigating Directories

Often when you are cleaning up directories, you're moving files between them, organizing subdirectories, and the like. This naturally involves a lot of moving among directories.

To move to the parent directory of the one you're in, press ^. To move to the next directory in the buffer, press >; pressing <, not surprisingly, moves you to the previous directory in the buffer.

Sometimes it's more convenient to edit a directory and its subdirectories in the same buffer. To insert a subdirectory in the current Dired buffer, move to it and press i. Emacs inserts the subdirectory at the end of the buffer. If you insert more subdirectories in this fashion, they will appear in alphabetical order at the end of the buffer.

As you can see, much of your file maintenance and cleanup can be done easily from within Dired. Table 5-2 summarizes Dired commands, some of which we haven't fully discussed. There's more to learn about Dired,[29] but now that you know the basics, you can experiment on your own.


Table 5-2. Dired commands

Keystrokes Command name Action
C-x d FileOpen Directory dired Start Dired.
A OperateSearch Files dired-do-search Do a regular expression search on marked files; stops at first match; M-, finds next match.
B OperateByte-compile dired-do-byte-compile Byte-compile file.
C OperateCopy to dired-do-copy Copy file.
d MarkFlag dired-flag-file-deletion Flag for deletion.
D OperateDelete dired-do-delete Query for immediate deletion.
e ImmediateFind This File dired-find-file Edit file.
f dired-advertised-find-file Find (so you can edit).
g ImmediateRefresh revert-buffer Reread the directory from disk.
G OperateChange Group dired-do-chgrp Change group permissions.
h describe-mode Display descriptive help text for Dired.
H OperateHardlink to ... dired-do-hardlink Create a hard link to this file; Emacs asks you to name the hard link (not all OSes support hard links).
i SubdirInsert This Subdir ... dired-maybe-insert-subdir Add a listing of this subdirectory to the current dired buffer; if it's already there, just move to it.
k dired-do-kill-lines Remove line from display (don't delete file).
L OperateLoad dired-do-load Load file.
m or * m MarkMark dired-mark Mark with *.
M OperateChange Mode dired-do-chmod Use chmod command on this file.
n dired-next-line Move to next line.
o ImmediateFind in Other Window dired-find-file-other-window Find file in another window; move there.
C-o ImmediateDisplay in Other Window dired-display-file Find file in another window; don't move there.
O OperateChange Owner dired-do-chown Change ownership of file.
p dired-previous-line Move up a line.
P OperatePrint dired-do-print Print file.
q quit-window Quit Dired.
Q OperateQuery Replace in Files dired-do-query-replace Query replace string in marked files.
R OperateRename to dired-do-rename Rename file.
S OperateSymlink to dired-do-symlink Create a symbolic link to this file; Emacs asks you to name the symbolic link.
s dired-sort-toggle-or-edit Sort the Dired display by date or by filename (toggles between these).
t MarkToggle Marks dired-toggle-marks Toggle marks on files and directories; pressing t once marks all unmarked files and directories; pressing t again restores original marks.
u MarkUnmark dired-unmark Remove mark.
v ImmediateView This File dired-view-file View file (read-only).
w dired-copy-filename-as-kill Copy filename into the kill ring; if multiple files are marked, copy names of all marked files to kill ring.
x dired-do-flagged-delete Delete files flagged with D.
y dired-show-file-type Display information on the type of the file using the file command.
Z OperateCompress dired-do-compress Compress or uncompress file.
~ MarkFlag Backup Files dired-flag-backup-files Flag backup files for deletion; C-u ~ removes flags.
# MarkFlag Auto-save Files dired-flag-auto-save-files Flag auto-save files for deletion; C-u # removes flags.
& MarkFlag Garbage Files dired-flag-garbage-files Flag "garbage" files for deletion.
.MarkMark Old Backups dired-clean-directory Flag numbered backups for deletion (if any).
= ImmediateDiff dired-diff Compare this file to another file (the one at the mark).
M-= ImmediateCompare With Backup dired-backup-diff Compare this file with its backup file.
! or X OperateShell Command dired-do-shell-command Ask for shell command to execute on the current file or marked files.
+ ImmediateCreate Directory dired-create-directory Create a directory.
> SubdirNext Dirline dired-next-dirline Move to next directory.
< SubdirPrev Dirline dired-prev-dirline Move to previous directory.
^ dired-up-directory Find the parent directory in a new Dired buffer.
$ SubdirHide/Unhide Subdir dired-hide-subdir Hide or show the current directory or subdirectory.
M-$ SubdirHide All dired-hide-all Hide all subdirectories, leaving only their names; repeat command to show.
C-M-n SubdirNext Subdir dired-next-subdir Move to next subdirectory (if you've inserted subdirectories using i).
C-M-p SubdirPrev Subdir dired-prev-subdir Move to previous subdirectory (if you've inserted subdirectories using i).
C-M-u SubdirTree Up dired-tree-up If you've inserted subdirectories using i, move to the parent directory in this buffer.
C-M-d SubdirTree Down dired-tree-down If you've inserted subdirectories using i, move to the first subdirectory for this directory in this buffer.
* c MarkChange Marks dired-change-marks Change marks on specified files, for example, from * (generic mark) to D (flagged for deletion).
* ! or M-Del MarkUnmark All dired-unmark-all-files Remove all marks from all files.
* * MarkMark Executables dired-mark-executables Mark executables; C-u * unmarks.
* / MarkMark Directories dired-mark-directories Mark directories; C-u / unmarks.
* @ MarkMark Symlinks dired-mark-symlinks Mark symlinks; C-u * @ unmarks.
M-} MarkNext Marked dired-next-marked-file Move to the next file marked with * or D.
M-{ MarkPrevious Marked dired-prev-marked-file Move to previous file marked with * or D.
% d RegexpFlag dired-flag-files-regexp Flag for deletion files that match regular expression.
% g RegexpMark Containing dired-mark-files-containing-regexp Mark files whose contents match regular expression.
% l RegexpDowncase dired-downcase Lowercase marked files.
% R RegexpMark dired-do-rename-regexp Rename files with filenames that match regular expression.
% u RegexpUpcase dired-upcase Uppercase marked files.

5.3 Printing from Emacs

Emacs offers several commands for printing buffers and regions. To print a buffer with page numbers and headers for the filename, type M-x print-buffer Enter. This command sends the buffer to pr (a program that does simple formatting for listings), followed by lpr (which sends the listing to the printer). If you want to print the file directly, without the headers and page numbers that pr provides, give the command M-x lpr-buffer Enter. You can also use these commands to print a selected portion of a file. First define a region by setting a mark at one end and moving the cursor to the other end. Then give the command M-x print-region Enter (or M-x lpr-region Enter).

The lpr-buffer and lpr-region commands always check the variable lpr-switches to determine whether any options should be passed to the Unix lpr command. These options are used to request a particular printer and for many other purposes; see the manpage for lpr for more information. For example, if you want to use the printer named lpt1 whenever you print from Emacs, you would want to set lpr-switches to

-Plpt1
. To do so, add the following line to your .emacs file:

(setq lpr-switches '("-Plpt1"))

Note the single quote preceding, and the parentheses surrounding, the string "

-Plpt1
". This is just weird-but-necessary Lisp syntax; see Chapter 11 for more details.

You can also print from Dired. To print the file the cursor is on, type P. Emacs puts the default printing command in the minibuffer, and you can modify it.

Emacs also includes commands to print a buffer as a PostScript file. If you have formatted text in the file, you can print the buffer with those attributes by typing M-x ps-print-buffer-with-faces.

Table 5-3 provides a summary of commands for printing.


Table 5-3. Printing commands

Keystrokes Action
M-x print-buffer FilePrint Buffer Print the buffer (similar to Unix pr | lpr).
M-x print-region FilePrint Region Print the region (similar to Unix pr | lpr).
M-x lpr-buffer Print buffer with no page numbers (similar to Unix lpr).
M-x lpr-region Print region with no page numbers (similar to Unix lpr).
P OperatePrint From Dired, put the default print command in the minibuffer; you can change it or press Enter to execute it.
M-x ps-print-buffer-with-faces FilePostscript Print Buffer Print the buffer with text attributes.
M-x ps-print-region-with-faces FilePostscript Print Region Print the region with text attributes.

5.4 Reading Manpages in Emacs

You can read Unix online documentation (called manpages) from within Emacs by typing M-x man or by selecting Man from the Help menu.[30] This command creates a buffer with a formatted manpage in it, which you can scroll through (or copy from) using Emacs commands. Simply type: M-x man Enter Unix-command-name Enter.

For the Unix command name, you can use either a simple name, like ls, or a manpage section name like ttytab(5).

The advantage of using the man command is that you can scroll through the manpage easier than you can in some terminal applications or shell windows. Also, if you try to view manpages in shell mode, they may come out garbled if the settings aren't right, whereas man gives you clean text.

5.5 Using Time Management Tools

Emacs is a natural place to organize all your work. It won't replace your Palm or other handheld, but ongoing work in this area may help you sync your favorite device with your Emacs-based schedule. Here we cover the main features that Emacs itself offers—the calendar and the diary.

5.5.1 Displaying the Calendar

To display the calendar, type M-x calendar. Emacs displays a calendar window with three months: last month, this month, and next month.


Type: M-x calendar

Emacs puts the cursor on today's date and displays the date on the mode line. There's no room to write on the calendar; that's what the diary is for, which we'll discuss shortly.


By default, weeks start on Sunday. If you'd like them to start on Monday instead, type M-x set-variable calendar-week-start Enter 1 Enter. You enter the calendar again to have this take effect. If you'd like to have the calendar always start on Monday, add this line to your .emacs file:

(setq calendar-week-start-day 1)

If you'd like to see the calendar each time you start Emacs, you can add this line to your .emacs file:

(calendar)

5.5.1.1 Moving in the calendar

When you're in the calendar, Emacs sensibly moves by day rather than by character. C-f moves you to the next day; C-b moves you to the previous day. C-n moves you to the same day of the next week; C-p moves you back a week. The arrow keys work the same way. M-} and M-{ move forward and backward by month, and C-x [ and C-x ] move forward and backward by year. C-v scrolls forward by three months; M-v scrolls back three months.

The movement commands just discussed move you relative to the cursor position. If you're on Tuesday and you press C-n, you'll move to next Tuesday. If you're on January 25 and press M-} you'll move to February 25. If you're on August 15, 2004 and press C-x [, you'll move to August 15, 2003.

Other commands move to the beginning or the end of the week, month, or year. C-a and C-e move to the beginning and end of the week, M-a moves to the beginning of the month, and M-< moves to the beginning of the year. Table 5-4 summarizes these calendar movement commands.

To go to a particular date, press g d. Emacs asks for the year, then the month, and then the day. Emacs moves you to the day selected (this command is well-suited for answering that all-important question, "On what day of the week does my birthday fall in 2020?").


Table 5-4. Calendar movement commands

Keystrokes Command name Action
(none) ToolsDisplay Calendar calendar Display the calendar.
.GotoToday calendar-goto-today Move to today's date.
C-f calendar-forward-day Move forward a day.
C-b calendar-backward-day Move backward a day.
C-n calendar-forward-week Move forward a week.
C-p calendar-backward-week Move backward a week.
M-} calendar-forward-month Move forward one month.
M-{ calendar-backward-month Move backward a month.
C-x ] ScrollForward 1 Year calendar-forward-year Move forward a year.
C-x [ ScrollBackward 1 Year calendar-backward-year Move backward a year.
C-a GotoBeginning of Week calendar-beginning-of-week Move to the beginning of the week.
C-e GotoEnd of Week calendar-end-of-week Move to the end of the week.
M-a GotoBeginning of Month calendar-beginning-of-month Move to the beginning of the month.
M-e GotoEnd of Month calendar-end-of-month Move to the end of the month.
M-< GotoBeginning of Year calendar-beginning-of-year Move to the beginning of the year.
M-> GotoEnd of Year calendar-end-of-year Move to the end of the year.
g d GotoOther Date calendar-goto-date Go to the specified date.
o calendar-other-month Put the specified month in the middle of the display.
C-x < ScrollForward 1 Month scroll-calendar-left Scroll forward one month.
C-x > ScrollBackward 1 Month scroll-calendar-right Scroll backward one month.
C-v ScrollForward 3 Months scroll-calendar-left-three-months Scroll forward three months.
M-v ScrollForward 3 Months scroll-calendar-right-three-months Scroll backward three months.
Space scroll-other-window Scroll another window.

5.5.1.2 Displaying holidays

Let's move to a topic everyone is interested in: holidays. To display the holidays for the part of the calendar you are looking at, type a (for list-calendar-holidays) or select 3 Months from the Holidays menu.


Type: a

Emacs lists holidays for the time period shown.


As you can see, Emacs knows about a fairly wide variety of holidays or, as it calls them, "notable dates." If you are somewhere else on the calendar but want to see holidays surrounding the current month, type M-x holidays. Emacs lists them. To see whether today is a holiday, type h or select One Day from the Holidays menu.

Typing x marks holidays in a special way, typically highlighting them in pink. If the display doesn't support this, Emacs puts an asterisk to the right of the date. Typing u removes the marks.

We have taught you only the bare bones of the calendar commands. Emacs offers to tell you sunrise and sunset and phases of the moon. You can choose other calendars, like the Islamic calendar, the Hebrew calendar, the Mayan calendar, or even the French Revolutionary calendar. But we will leave these for you to explore.

More calendar commands are used in the context of the diary, discussed next.

5.5.2 Using the Diary

The diary, closely related to the calendar, allows you to make notes about certain dates. You can enter a full daily schedule or just mark major events. The level of detail is entirely up to you.

5.5.2.1 Creating a diary file

To use the diary, you must have a diary file that contains notations about important events or things to do. It can remind you to back up your system every Thursday, that you get paid every two weeks, that you're on vacation during the first two weeks in July, or that your mother's birthday is August 6.

The file must be called diary and must exist in your home directory. In this file, you insert lines—or have Emacs write lines for you—that note dates you want to remember. The diary file need not be all in one format and need not be sorted in any particular order. Date formats can be mixed: December 19, 2004 could be 12/19/04, Dec 19 04, or dec 19 2004. Here are a few lines from a diary file to illustrate what we mean.

11/14 My birthday

July 17 2004 Company picnic

March 18 2004 Annual report due

January 8 2004 Hair appointment

&Saturday Tea with Queen Elizabeth

Friday Payday

If you don't specify a year, Emacs assumes you want to mark that date every year, as in birthdays. If you don't specify a date but only the day of the week (as in tea with the queen on Saturday), Emacs displays the diary entry every Saturday. Putting an ampersand (&) before an entry tells Emacs not to mark it on the calendar (you don't want every Saturday marked, and you may not want everyone to know that you hang around with the royal family).

Date formats can be mixed, but the choice to use European date format (DD/MM/YYYY or 9 October 2004) versus the default American format (MM/DD/YYYY or October 9, 2004) must be made before you create the diary file. To specify European date format, add this line to your .emacs file:

(setq european-calendar-style 't)

5.5.2.2 Adding diary entries

You can write your own entries or have Emacs help you put them in. To have Emacs help you, go to the calendar by typing M-x calendar. Then press g d to specify the date you want to move to. Press i d (for insert-diary-entry). Emacs moves you to the diary window with the date written out. You can then make a diary entry next to the date. If your entry spans more than one line, begin the second and subsequent lines with a single space, so that Emacs understands it's a continuation. After you make the notation about the date, Emacs leaves you in the

diary
buffer so you can make more entries. Type C-x b to move to another buffer.

The insert-diary-entry command assumes you want to make a single, one-time entry. To create a recurring entry, you need a few more commands. To insert a weekly entry, type i w. Emacs moves you to the

diary
buffer with the day of the week written out. Type the weekly activity (such as a staff meeting), and save the diary file. To insert an annual entry, type i y. Emacs moves you to the
diary
buffer with the day and month written out; type the annual event. There is a more specific command for anniversaries. Type i a to add an anniversary; this entry includes the year (though we have not seen a function that uses this information for any particular purpose, such as counting which anniversary this is).

You can also put in cyclic diary entries, entries that occur at regular intervals, like reminders to change the oil in your car every three months. To do so, move to the date you changed your oil last and type i c. Emacs says,

Repeat every how many days:
and you type the number of days between oil changes. Emacs writes a Lisp function to handle this and puts it in the diary buffer. You can then make a notation next to the Lisp function, such as a note that tells you to change the oil. The entry that Emacs inserts looks like this (we put the part about changing the oil in ourselves):

%%(diary-cyclic 90 12 23 2004) Change the oil

The entry says that every 90 days, counting from the day we inserted the entry, December 23, 2004, we should change the oil in our car.

You can mark a block of dates, as in the case of a week-long conference or a vacation. Put the cursor on the first date and press C-Space to set the mark.[31] Move (using calendar movement commands like C-f, C-n, and so on) to the second date and press i b. Emacs moves you to the

diary
buffer and inserts an incantation that marks the week on your calendar. Make a notation following the Lisp function Emacs inserts. The entry will look something like this:

%%(diary-block 3 15 2004 3 20 2004) Trip to Alabama

This entry indicates that from March 15 to March 20, we'll go on a trip to Alabama.

What if you want to note that you have to file your expense report on the fifteenth of every month? Emacs accepts the asterisk wildcard (*) for the month, as you will see when you type i m (for insert-monthly-diary-entry). Emacs inserts an asterisk in place of the month, followed by the day, as in * 15 for something scheduled for the fifteenth of each month. As always, you make a note following the entry.

Now that you see how Emacs constructs diary entries, you can try writing some of your own based on what Emacs has done. After all, the diary file is like any other Emacs file; you can make changes, add lines, and delete lines at will. The only requirement is that you save the file when you're through. Now let's see how to display diary entries on the appropriate dates.

5.5.2.3 Displaying diary entries

If you want to review the diary entries for a given date, press d from the calendar. In order to see the whole diary file, press s from the calendar. If you want today's diary entries to display automatically when you start Emacs, add this line to your .emacs file:

(diary)

That way, when you start up Emacs on a day for which there is a diary entry, the diary entry displays automatically. For example, let's say you marked your best friend's birthday some time ago, and today is the day. When you start Emacs, the screen would look like this:


You start Emacs.

Emacs displays the diary entry for your friend's birthday.


If there are no diary entries for a given day, the diary is not displayed. If you start Emacs with two files so that you are editing in two windows, the diary is also not displayed.

If you have already put in a (calendar) entry in your .emacs file to have the calendar displayed automatically, the calendar supersedes the diary, and you'll have to remove the calendar if you prefer to see the diary instead.

To mark dates with diary entries in red, press m from the calendar. To remove the marks, press u. (This command removes highlighting for diary entries as well as for holidays.)

Table 5-5 summarizes the calendar and diary commands.


Table 5-5. Holiday and diary commands

Keystrokes Command name Action
p d calendar-print-day-of-year Display the day of the year this is (for example, Day 364 of 365).
p o calendar-print-other-dates Display information about this date for all calendars.
Space scroll-other-window Scroll the other window.
q exit-calendar Quit calendar.
a HolidaysFor Window list-calendar-holidays Display holidays for calendar period shown.
h HolidaysFor Cursor Date calendar-cursor-holidays In the minibuffer, display holiday information for the day the cursor is on.
x HolidaysMark mark-calendar-holidays Display holidays in a different typeface, color, or with an asterisk beside them.
u HolidaysUnmark Calendar calendar-unmark Remove marks for holidays and diary entries (opposite of x command).
i w DiaryInsert Weekly insert-weekly-diary-entry Add a weekly entry based on the day of the week.
i y DiaryInsert Yearly insert-yearly-diary-entry Add an annual entry.
i d DiaryInsert Daily insert-diary-entry Add an entry for a particular day.
i m DiaryInsert Monthly insert-monthly-diary-entry Add an entry for the day of the month.
i c DiaryInsert Cyclic insert-cyclic-diary-entry Add an entry to recur every n days.
i a DiaryInsert Anniversary insert-anniversary-diary-entry Add an annual entry (the year is included for reference).
i b DiaryInsert Block insert-block-diary-entry Add a block entry.
m mark-diary-entries Display diary entries in a different typeface, color, or with a plus sign beside them.
d view-diary-entries Display diary entries for the current date.
s DiaryShow All show-all-diary-entries Display diary file.
M-= calendar-count-days-region Count the number of days in a region.
M MoonLunar Phases calendar-phases-of-moon Display phases of the moon for a three-month period.
S calendar-sunrise-sunset Given longitude and latitude, display sunrise and sunset times for the current date.
C-Space or C-@ calendar-set-mark Mark regions by time rather than horizontally.

5.5.3 Problems You May Encounter

In shell mode on Mac OS X, Emacs says, "Warning: no access to tty (Bad file descriptor). Thus no job control in this shell." This happens with the graphical version of Emacs, not with the version run from the Mac OS X Terminal application. If you change to a different shell using the instructions under "Which shell?" earlier in this chapter, the error goes away.

Some commands don't work on Mac OS X. The graphical version of Mac OS X fails to find some operating system commands, especially when invoking them through M-! (for shell-command). Change to a different shell; see "Which shell?" earlier in this chapter for details. Another problem is that some Unix commands are not available by default on Mac OS X. Try them in the Mac Terminal application to see if they work at all before trying them in shell mode. To increase Mac OS X's Unix functionality, use Fink (http://fink.sourceforge.net) to download a wide variety of Unix commands and software for Mac OS X.

Some commands don't work on Windows. This chapter describes many commands that have no Windows equivalent. The Windows port of Emacs works well for most Dired functions, the calendar, and the diary. To get Unix command functionality under Windows, install Cygwin (http://cygwin.com).

Printing does not work from Windows on USB printers. Many USB printers do not support printing from the command line. This problem is not specific to Emacs.

Загрузка...