CSC161 2011S Imperative Problem Solving

Laboratory: The Emacs Text Editor

Summary: This laboratory will introduce you to Emacs, one of the earliest and most popular text editors for UNIX and "UNIX-like" systems. You will also get a small bit of experience compiling C programs.

Prerequisites: Familiarity with the bash shell. Basic knowledge of the form of C programs.

Introduction

In a previous course you may have used an Integrated Development Environment (IDEs), such as DrScheme or MediaScheme, to develop your programs. Similar IDEs exist for C, but it is more traditional among C programmers to use separate programs for editing, compiling, and debugging C code. Since part of the focus of the course is to become familiar with Linux and the UNIX tradition, we will follow this approach.

There are several text editors available on Linux in the MathLAN. The two that are the most commonly used by C programmers are Emacs and ViM. This laboratory will introduce you to Emacs.

Preparation

Using the Linux utilities you have learned, create a file in your own account that contains the names and departments of all Grinnell faculty members. Recall that this data can be found in the following files:

Detour: Notation for Emacs Commands

While Emacs allows many editing operations to be performed via toolbar icons and menu selections, it also allows those operations to be performed via keystroke commands as well as via toolbar icons and menu selections. I highly recommend learning the keystrokes since they can be faster once you know them and because some operations are only available via keystrokes.

However, these keystroke operations are likely to seem a bit foreign at first since they conflict with keystroke combinations you may have learned in other environments. Ah well, consistency is the hobgoblin of small minds.

Emacs also uses an unconventional notation for naming the keystrokes. Here are some examples, and what they mean:

C-x C-f
Hold down the ctrl key and press x, then lift your finger (or other key pressing apendage) off the x key and press f. The ctrl key should be down when you press f. It does not matter whether you do or do not lift it in between.
C-x 2
Hold down the ctrl key and press x, then lift your fingers off both keys and press 2.
M-w
The documentation refers to pressing the "Meta" key here, but on modern keyboards, use the Alt key instead. Thus, this key combination means hold down Alt and press w. On some keyboards, you must use the Escape (ESC) key, which you click and lift before typing the corresponding letter.

We will use this notation in the remainder of the lab since it is used in the Emacs help system and the Emacs menus.

Exercises

Exercise 1: Launching Emacs

To launch Emacs, type its name (that is, emacs) and (optionally) add the name of a file that you want to open. Since you will probably find it convenient to launch Emacs as a background process, you should also append an ampersand to the end of the command.

emacs filename &

a. Try this with the file you created in the preparation step.

To exit Emacs, type C-x C-c (where the meaning of this is described above).

b. Verify that we've just told you the truth. That is, exit Emacs.

What if you want to open emacs, but the file you want to work with doesn't exist yet? We do that exactly the same way: think of a name for your file, then open emacs using that file name. Emacs will create an empty file with that name.

c. Go ahead and give this a try.

When Emacs opens the window will be split into two panes, one above the other. Your document is in the upper window, and an Emacs splash screen is in the lower one. To make your document fill the full window, type C-x 1 (where the meaning of this is described above).

Exercise 2: Opening, Closing, and Saving Files

To open a file from within Emacs, type C-x C-f. Then note the "command buffer" at the very bottom of the Emacs window. It should contain a prompt "Find file:" and a default directory (the directory from which you launched Emacs). Type the name of the file you want to open, and press the Enter key.

Note that to create a new file, you also open it as just described. Thus, from the outset, the file will be associated with a name.

a. Open the file which contains your copy of the Grinnell faculty listing.

b. Open a new file, naming it anything you like.

Note that there is no difficulty with having multiple files open at once. Each one is associated with an "input buffer." You can see a list of your open buffers or switch between buffers by selecting the Buffers menu, at the top of the Emacs window.

c. Try using the Buffers menu to switch between the two files you have open.

If you don't feel like using the mouse, you can also switch buffers by going through the motions of "opening" the file you want again. Emacs knows it is already open, and will simply switch buffers.

To save a file, type C-x C-s.

To close a file, select Close from the File menu. What is the keystroke for this command? Well, you can use keboard menu control (M-` f c). You can also use the explicit command M-x kill-buffer, which will prompt you for the buffer to close. Finally, you can use the shortcut C-x k. Do you feel overwhelmed with options?

Exercise 3: Cancelling Partial Commands (i.e., Getting Un-Stuck)

To cancel a partial command, type C-g (i.e., ctrl-g).

When might you need to do this? Suppose you intend to open a file, so you press C-x C-f. Now the command buffer is waiting for input, but suppose you change you mind. To clear the command buffer, make sure your cursor is in the command buffer, and then type C-g.

a. Go ahead and try this now, the better to help you remember it when you need it.

When you are first learning Emacs, it may happen every so often that you type a command key combination without intending to. Now the command buffer wants input from you, but you want it to go away. If you don't notice at first what the problem is, Emacs may start beeping at you, in an inarticulate attempt to get you to stop typing your whole program in the command buffer. You can use the mouse to put your cursor back in the edit butter, but you will find that the command buffer still lurks, and the next time you want to use it for something else, all you get is more beeping! A few rounds of this may render you inarticulate as well. But never fear, C-g to the rescue!

Exercise 4: Backup Files, Journal Files, and File Recovery

If you open an exiting file and begin to edit it, the first time you save the file, Emacs writes the new version with the file's normal name, but it also retains the previous version and adds a tilde to the end of the name. For example, after you edit and save faculty.txt, you will have two files: faculty.txt and faculty.txt~.

a. Check your directory: you may already have a backup file there.

As you continue to work, it does not matter how many times you save your changes, the backup version of the file will still be the version that existed when you opened it.

b. Make a few changes to your file and save it. Then compare the changed file and the backup file. (Hint: you can use diff to compare files.)

As you work, if you have unsaved changes, Emacs will periodically create and update an autosave file (more properly called a journal file). The name of the journal file will be #filename#. Yes, indeed, the # characters are part of the file name.

c. To see this in action, make some minor change to one of your open files, but don't save the change. Now wait a minute until the autosave feature kicks in. (This really should only take a minute or so, although that does feel like a long time while you are waiting.) Once you have seen the "autosave" message at the bottom of the Emacs window, look at a listing of the files in your current directory. You should see the journal file there.

d. Look at the contents of the journal file to see what it contains.

When you save your changes, Emacs will remove the journal file.

e. Try this, and confirm the behavior by getting another file listing.

Thus, if you save your changes before exiting Emacs, there will be no journal file left behind. However, if you exit without saving your changes, or if Emacs closes abnormally for some reason, the journal file will be retained, and it can be used to recover your changes.

Let's practise file recovery,

f. You first need to make some more changes and wait for another journal file to be created. Then you need to simulate closing the file abnormally. To do this, you want to exit Emacs without saving your changes; however, you will notice that this is hard to do by accident. You will need to answer "No" when asked if you want to save the file and then "Yes" when asked if Emacs should exit even though there are un-saved buffers.

g. Now let's recover your file that was closed abnormally. To do so, open the file as you normally would (i.e., open the file you want to recover, not the journal file). Then type M-x recover file<Enter>. (Yes, you have to type both the keystrokes and the words.) Emacs will give a prompt in the command buffer, and you respond with the name of the file to be recovered (not the journal file). Finally, Emacs asks if you really mean it, and you answer yes. Voila! At this point, your file should be back to the previously autosaved state.

Hopefully, you will never need this feature, but it is nice to have when you need it.

Exercise 5: Cursor Movement

Now let's practise editing files with Emacs. To get started, please open the file you made that lists the Grinnell College faculty.

a. First off, let's practise navigating around within the file. Of course, much of this will come naturally to you -- you can use the arrow keys, the Page Up and Page Down keys, or the mouse to move your cursor position in obvious ways.

What may not be obvious though is how Emacs behaves when you scroll down past the bottom of the current screen.

b. Predict what will happen when you navigate down when the cursor is at the bottom of the screen and what will happen when you navigate up when the cursor is at the top of a screen.

c. Check your answer experimentally. THat is, move the cursor to the bottom of the screen and then hit the down arrow, then more the cursor to the top of the screen and hit the up arrow.

This behavior may seem strange at first, but experience suggests you will get used to it quickly.

It is also nice to have keystrokes that move you around the file more quickly than simple scrolling.

d. Try the Home and End keys. If you prefer not to move your hands away from the normal typing position, you will find that Ctrl-a and Ctrl-e have the same effect.

e. Now try out what each of the four arrow keys does when combined with the Ctrl key.

f. Finally, try Ctrl-Home and Ctrl-End, as well as Ctrl-PageUp and Ctrl-PageDown. (Hereafter, I recommend avoiding Ctrl-PageDown, but if you ever see that result again, you will know how to recover: Ctrl-PageUp.)

Now please take a moment to notice the "mode line" near the bottom of the Emacs window. It should look something like the following:

--:--  faculty.txt         (TEXT)--L35--16%-------------------------------

g. Try moving around the file, while watching the mode line to determine what information is being displayed. Similarly, try making a change to the file, and then saving the file. How does this affect the mode line? Be prepared to describe the form of the mode line to the class.

Note that the entry "(TEXT)" indicates that Emacs recognizes the file to be a text file. Emacs recognizes many file types, including html and various programming languages. You will find the fact that Emacs knows when you are writing a C program to be very useful, but more on that a bit later on.

Exercise 6: Searching

To prepare for the next exercise, please move your cursor to the top of the file.

To search for a given word within a document, you begin with the keystroke C-s. Go ahead and try this. You should see the prompt I-search: appear in the command buffer. (I-search stands for incremental search, and you will see why in a moment.)

a. Suppose you want to search for the entry for Sam Rebelsky. For now, please type only the letter R to see what happens.

b. Then add an e and observe the result.

c. Finally add a b, and you should find the corrent entry.

d. Of course, Emacs does not yet know that you have found your target, so you need to tell it to leave search mode by pressing Enter.

e. Now suppose you want to search for Henry Walker, but you can't recall his last name. Please start a new search, and find the word "Henry." Uh-oh. I expect that you will find a "Henry," but not the one you want. To look for a second instance of "Henry," simply press C-s again. (Do not press Enter to re-start the search from scratch.)

f. Try pressing C-s a few more times. You should observe that after reaching the bottom of the file, the search wraps around to the top of the file and continues.

g. What happens if you search for an entry that is not in the file? Please think up an uncommon name to search for, or search for "Sigfried."

If you prefer to search upward through the file, it works the same way except that you begin with C-r (for "reverse").

h. Try at least one reverse search.

Exercise 7: Deleting Text

a. Check to ensure that that the Backspace and Delete keys work in the way that you expect.

b. It is also nice to be able to delete larger portions of text at a time, so try out Ctrl-Backspace and Ctrl-Delete to see what they do.

c. Next, experiment with C-k. What does it do? Does it matter where on the line you are positioned when you press it? One thing I frequently make use of is the following: position your cursor at the beginning of a line, and then press C-k twice.

You can also delete large portions of text by highlighting the text with the mouse, and then pressing the Delete key.

d. Give it a try?

One thing you may have noticed is that the Emacs keystrokes match the keystrokes used in the bash shell. This is because, by default, bash uses the Emacs keystrokes as its own.

Exercise 8: Undo-ing Changes

Luckily, we are also able to undo recent changes in Emacs. The keystroke for this is a bit awkward, but when you really want to undo, you'd probably be willing to do worse! To undo your last change, press C-_ (that is, ctrl-shift-hyphen or ctrl-underline). Nothing confusing about that... surely not.

a. Go ahead and make a few changes to the file, and then undo several of them.

What if you want to undo an undo command? To do this, you first need to leave undo mode by typing C-g. Then request an undo in the normal way, and what gets undone will be the previous undo command.

b. Give it a try.

Exercise 9: Cut/copy and paste

When you use any of the keystrokes you just learned for deleting text (except for the simple Backspace or Delete keys), the text that was cut is stored in a cut buffer. You can then paste the current contents of the cut buffer using the keystroke C-y, or by pressing the left and right mouse buttons simultaneously. Give it a try now.

When you repeatedly cut text using keystrokes, and without performing some intervening operation such as moving the cursor or typing, the repeated cuts are appended to the cut buffer.

a. Try cutting the names of several consecutive faculty members from the list, and then pasting them back, either in the same location or a different one.

So how do you copy text? One option is to cut the text, immediately paste it back, and then paste it again in the new location.

b. Try that method of copying.

Another option is to highlight the text with the mouse. This action replaces the contents of the cut buffer with the highlighted text (just as it usually does in Linux), and you can then proceed to paste the text where you want it with C-y.

c. Go ahead and try this approaches to get used to them.

But now a word of warning. It is wise, when you have a cut buffer that you want to paste somewhere else, to move to the desired location using keystrokes, rather than clicking in the new location. Why? Suppose you bobble just a little on the click, such that you accidentally highlight a letter or a line. What happens then? Your cut buffer gets overwritten by the bobble. That is mildly frustrating if the contents of the buffer was something you had copied into the buffer. It is worse if it is something you had cut into the buffer, but even then all is not lost. Just don't forget about undo!

d. At this point, it would probably be a good idea to try enacting the error described in the last paragraph to see it in action. Cut some large amount of text that you really wouldn't want to lose, and then "bobble" when you move to a new position in the file by highlighting a single character instead. Now paste. Ouch! Undo!

Exercise 10: Working with Multiple Windows

It is frequently nice when programming to have two source files open (and visible) at once. In Emacs, this can be done by splitting your window.

a. To try this, type C-x 2. Where you had one window before, you now have two.

At present both of the windows will be displaying the same file. This can actually be useful, since you can arrange to have the two windows display different portions of the file. If you choose to use it this way, you can edit text in either or both windows to update the file.

b. Alternatively, you can open a second file in one of the windows. To try this out, go ahead and open some other file, perhaps a source code file you wrote in a previous course.

The next thing you will want to know how to do is to move your cursor between the two windows. Certainly you can do this with the mouse. You can also do it with C-x o (where the last key is a lower-case letter o). What does that stand for? Other window. (You can also get the command with M-x other-window.)

c. Now let's resize the windows. Position your mouse over the gray bar (the mode line). When you see the mouse icon turn into a vertical double-headed arrow, you can click and drag the bar vertically.

When you want to revert to having only a single window open, type C-x 1 (i.e., I want one window open now).

d. Try it.

An important aside: Please do not increase the width of your Emacs window when you are writing programs. This is because, if you do so, you will start producing source code that has a non-standard width. Who cares? Anyone who wants to look at your code in an Emacs window that has not been widened exactly as you widened yours, and anyone who wants to look at a printout of your source code. (If you generate source code that is very wide and then print it, or look at it in a standard size Emacs window, your long lines will wrap around quite unpleasantly. The resulting code will look terrible. It really will. And your professors and future employers are likely to take serious offense at code that looks terrible.)

Exercise 11: Compiling Programs from within Emacs

Here is a little C program.

#include <stdio.h>

int 
main() 
{
  printf("Welcome to CSC161.\n");
  return 0;
}

a. Open a new file called welcome.c, and enter the program.

Next, let's compile the program from the terminal window. (After that I'll show you how to arrange things such that you can compile it within Emacs.)

b. To invoke the GNU C Compiler, type the following command at the bash prompt.

gcc -Wall welcome.c

The -Wall option asks gcc to report all warnings, and I highly recommend that you make a habit of using it. In C you are likely to get many warnings, rather than compilation errors, for true bugs. This happens when the syntax you have used is not strictly illegal, but it may mean something quite different than what you intended.

If you did not get any error messages, you should now have a compiled version of the program in a file named a.out in your current directory.

c. Run the program by typing the following command.

./a.out

Note that if you simply type a.out, it may or may not work, depending on how your account is configured. This is because your current directory may not be on the search path bash uses to find executable programs, so the program may not be found. Prepending ./ to the file name tells bash to look in the current directory.

d. Next, select Compile... from the Tools menu. You should see the following appear in the command buffer: make -k. That is the command we will use later in the course for compiling C programs that contain multiple files. If you type welcome, Make can figure out how to build it (although it won't include the helpful -Wall command). Give it a try.

Now let's modify your Emacs configuration file to make Emacs use a slightly more sophisticated compilation command, one that include the -Wall.

e. First of all, we need to make sure you have such a file -- you should, but I have noticed that occasionally someone doesn't. To check this, type the command below to list information about the file .emacs in your home directory. (Yes, the dot should be there. Many complex programs place configuration files in your home directory with names that begin with a "dot".)

ls -la ~/.emacs

If it appears that you don't have this file, talk to me or your class Mentor.

f. Now open the Emacs configuration file. (How? Go ahead and do it in Emacs!) And then add the following lines to the bottom of the file:

   ; Set a new default compile comand
   (setq compile-command '"make CFLAGS=-Wall ")

g. Save your work, close Emacs, and re-open it. Doing so will invoke the commands in the updated configuration file.

h. Now re-open welcome.c, and select Compile... from the Tools menu. This time you should see the (partial) command make CFLAGS=-Wall " appear in the command buffer. Complete the command by typing welcome, and press Enter.

You should find that the file ./welcome has been created.

Exercise 12: Auto-indent

Emacs is smart about tabs. To see what we mean, remove all indentation from your welcome.c program, such that every line of code begins at the left margin. (I know it hurts, and you wouldn't be caught dead writing programs without nice indentation, but do it just this once.)

Now move your cursor to the line with the printf() function call, and press the Tab key. Voila! Emacs knows from your braces how far the line should be indented.

Now move your cursor to the middle of the return line, perhaps placing it on the space. Press the Tab key again. Double-voila! There is no need to move your cursor to the beginning of the line to get automatic (correct) indentation.

Now add an if-statement to the program, but leave the indentation crummy for just a moment. Perhaps something like the following:

#include <stdio.h>

int 
main() 
{
int n = 3;

if (n == 3)
{
printf("Welcome to CSC201.\n");
}
else
{
printf("Welcome to the Twilight Zone.\n");
}
return 0;
}

Now, starting with the first line that is indented incorrectly, step through each line of your program, pressing the Tab key on each one, and Emacs will fix your indentation as you go.

It may not be obvious from this small example just how useful this feature is. But when you have a large program, and you make a structural change like adding an if-statement, it can be very nice to use a single keystroke per line to fix the indentation. Further, if you get in the habit of using this feature, you will find that Emacs can help you identify errors in the placement of your braces. (It will indent based on your braces, and if the indentation is not what you expect, your braces are not correct!)

Exercise 13: Parting Thoughts

Here are a few more tips that you may find helpful, under the right circumstances.

First, there are times when you may want to edit a file using Emacs, but you would rather not use the GUI interface. (Okay, I"ll admit that I never like the GUI interface.) One reason is that it's much faster not to use the GUI. Another is that you sometimes don't have access to the GUI, for example, when you are logged in remotely to a computer.

To open Emacs without the GUI interface, use the command option -nw, which stands for no window as follows:

emacs -nw filename

a. Give it a try. Almost all the keystrokes you have learned will still work, but the mouse won't. You can even use the menus with M-`.

Second, you can use the shell without ever leaving Emacs.

b. From the Tools menu, select Shell. You will be prompted for a shell command. Type one, such as ls.

c. Type M-x shell. You'll find that a new window opens up with a shell. But this is a special shell. You can type commands, but you can also treat it like an edit window. PLay around a bit.

Finally, Emacs can be very helpful. There's a help menu ith al sorts of options.

If your colleagues, professors, or coursework start to get you down, you may want to get some help from the Emacs psychiatrist. Select Emacs Psychiatrist under the Help menu.

 

History

January 2008 [Marge Coahran]

  • Created.

August 2008 [Marge Coahran]

  • Modified section on file recovery to have students actually try it.

January 2009 [Marge Coahran]

2 September 2010 [Samuel A. Rebelsky]

  • Reformatted
  • Renumbered problems.
  • Lots of changes to text.
  • Changed default compile command.

3 September 2010 [Samuel A. Rebelsky]

Tuesday, 1 February 2011 [Samuel A. Rebelsky]

 

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Tue Feb 1 10:30:21 2011.
The source to the document was last modified on Tue Feb 1 10:30:19 2011.
This document may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CSC161/2011S/Labs/emacs-lab.html.

Samuel A. Rebelsky, rebelsky@grinnell.edu