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.[2]
No matter how you start the editor, the result is the same.
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.
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.
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.[3] 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.
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.
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 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.
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.[4] 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)
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.
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.
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.
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.
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.
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.
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.
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).
Dired provides commands for selecting executable files, directories, and symbolic links. To select executable files, type * *. To select directories, type * /. Typing * @ marks symbolic links.
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.
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.
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).
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.
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.
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,[5] 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 File → Open Directory |
dired |
Start Dired. |
A Operate → Search Files |
dired-do-search |
Do a regular expression search on marked files; stops at first match; M-, finds next match. |
B Operate → Byte-compile |
dired-do-byte-compile |
Byte-compile file. |
C Operate → Copy to |
dired-do-copy |
Copy file. |
d Mark → Flag |
dired-flag-file-deletion |
Flag for deletion. |
D Operate → Delete |
dired-do-delete |
Query for immediate deletion. |
e Immediate → Find This File |
dired-find-file |
Edit file. |
f |
dired-advertised-find-file |
Find (so you can edit). |
g Immediate → Refresh |
revert-buffer |
Reread the directory from disk. |
G Operate → Change Group |
dired-do-chgrp |
Change group permissions. |
h |
describe-mode |
Display descriptive help text for Dired. |
H Operate → Hardlink 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 Subdir → Insert 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 Operate → Load |
dired-do-load |
Load file. |
m or * m Mark → Mark |
dired-mark |
Mark with *. |
M Operate → Change Mode |
dired-do-chmod |
Use chmod command on this file. |
n |
dired-next-line |
Move to next line. |
o Immediate → Find in Other Window |
dired-find-file-other-window |
Find file in another window; move there. |
C-o Immediate → Display in Other Window |
dired-display-file |
Find file in another window; don't move there. |
O Operate → Change Owner |
dired-do-chown |
Change ownership of file. |
p |
dired-previous-line |
Move up a line. |
P Operate → Print |
dired-do-print |
Print file. |
q |
quit-window |
Quit Dired. |
Q Operate → Query Replace in Files |
dired-do-query-replace |
Query replace string in marked files. |
R Operate → Rename to |
dired-do-rename |
Rename file. |
S Operate → Symlink 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 Mark → Toggle 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 Mark → Unmark |
dired-unmark |
Remove mark. |
v Immediate → View 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 Operate → Compress |
dired-do-compress |
Compress or uncompress file. |
~ Mark → Flag Backup Files |
dired-flag-backup-files |
Flag backup files for deletion; C-u ~ removes flags. |
# Mark → Flag Auto-save Files |
dired-flag-auto-save-files |
Flag auto-save files for deletion; C-u # removes flags. |
& Mark → Flag Garbage Files |
dired-flag-garbage-files |
Flag "garbage" files for deletion. |
.Mark → Mark Old Backups |
dired-clean-directory |
Flag numbered backups for deletion (if any). |
= Immediate → Diff |
dired-diff |
Compare this file to another file (the one at the mark). |
M-= Immediate → Compare With Backup |
dired-backup-diff |
Compare this file with its backup file. |
! or X Operate → Shell Command |
dired-do-shell-command |
Ask for shell command to execute on the current file or marked files. |
+ Immediate → Create Directory |
dired-create-directory |
Create a directory. |
> Subdir → Next Dirline |
dired-next-dirline |
Move to next directory. |
< Subdir → Prev Dirline |
dired-prev-dirline |
Move to previous directory. |
^ |
dired-up-directory |
Find the parent directory in a new Dired buffer. |
$ Subdir → Hide/Unhide Subdir |
dired-hide-subdir |
Hide or show the current directory or subdirectory. |
M-$ Subdir → Hide All |
dired-hide-all |
Hide all subdirectories, leaving only their names; repeat command to show. |
C-M-n Subdir → Next Subdir |
dired-next-subdir |
Move to next subdirectory (if you've inserted subdirectories using i). |
C-M-p Subdir → Prev Subdir |
dired-prev-subdir |
Move to previous subdirectory (if you've inserted subdirectories using i). |
C-M-u Subdir → Tree Up |
dired-tree-up |
If you've inserted subdirectories using i, move to the parent directory in this buffer. |
C-M-d Subdir → Tree Down |
dired-tree-down |
If you've inserted subdirectories using i, move to the first subdirectory for this directory in this buffer. |
* c Mark → Change Marks |
dired-change-marks |
Change marks on specified files, for example, from * (generic mark) to D (flagged for deletion). |
* ! or M-Del Mark → Unmark All |
dired-unmark-all-files |
Remove all marks from all files. |
* * Mark → Mark Executables |
dired-mark-executables |
Mark executables; C-u * unmarks. |
* / Mark → Mark Directories |
dired-mark-directories |
Mark directories; C-u / unmarks. |
* @ Mark → Mark Symlinks |
dired-mark-symlinks |
Mark symlinks; C-u * @ unmarks. |
M-} Mark → Next Marked |
dired-next-marked-file |
Move to the next file marked with * or D. |
M-{ Mark → Previous Marked |
dired-prev-marked-file |
Move to previous file marked with * or D. |
% d Regexp → Flag |
dired-flag-files-regexp |
Flag for deletion files that match regular expression. |
% g Regexp → Mark Containing |
dired-mark-files-containing-regexp |
Mark files whose contents match regular expression. |
% l Regexp → Downcase |
dired-downcase |
Lowercase marked files. |
% R Regexp → Mark |
dired-do-rename-regexp |
Rename files with filenames that match regular expression. |
% u Regexp → Upcase |
dired-upcase |
Uppercase marked files. |
[2] The one exception to this is running Emacs in the Mac OS X Terminal application, which has its own drag-and-drop behavior. In the terminal—and thus in Emacs running in the terminal window—dragging and dropping a folder inserts the complete pathname of that folder rather than opening the folder in Dired.
[3] What if it's a file that shouldn't be viewed in Emacs, like a JPG or a PDF? In this case, the variable dired-view-command-alist associates viewers with file extensions. The defaults for this command work on Linux, but require some tweaking on other platforms. See Chapter 10 for an example of using Custom to change this variable for Mac OS X and Windows.
[4] Emacs understands only compress and gzip formats, not ZIP or other proprietary file compression algorithms. When you uncompress files, Emacs recognizes and correctly uncompresses files with the following suffixes: .z, .Z, or .gz. When you compress files, Emacs uses gzip, resulting in files that end in .gz.
[5] And if all the Dired features aren't enough, there's Dired-x, an add-in module that includes other features such as omitting unimportant files from the listing, finding files mentioned in any buffer, and additional variables and means of marking files. For more details, see the Info text on this subject (type C-h i to get to the Info menu).