=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * emacs in "N" Lessons * * Part 1 * * by Charles Lin * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Copyright 1999-2000. This document is copyright by Charles Lin. All rights reserved. [Other corrections are now listed in ~jm106001/Tutorials/emacs.tutorial.changes] [Please send email to: clin@umd5.umd.edu if there are errors, corrections, or any suggestions for improvement] [The location of the "states" file first mentioned in Lesson 4 is in ~jm106001/Tutorials/emacs.states] How to pronounce emacs ---------------------- It's pronounced EE-MAKS. Programming: It's Not All About Writing Programs ------------------------------------------------ Most people usually get a book on programming when they are learning how to program. Typically, the book will explain many aspects of the programming language, especially the syntax and semantics of the code. You will often find many examples of programs which you can study, trying to glean important lessons so you can learn how to write good programs. However, there's more to programming than programming. The actual process of writing a program and getting it to work is can be summed up in three steps. 1. Edit the program 2. Compile the program 3. Test the program and determine why the program has errors The first step is writing the program. To write a program, you use a "text editor". UNIX supports many different text editors: pico, vi, and emacs are among the most widely-used text editors. The goal of a text editor is to allow you to type and edit text. In many ways, a text editor is like a word processor. However, a word processor is primarily designed to produce nice looking papers. Thus, word processors allow you to italicize words, make them bold, underline, change the fonts, and any number of other nice features which gives you control over how the text appears when it's printed on paper. Text editors, on the other hand, have more modest goals. Text editors are used to edit "text". Generally, there's very little support for changing fonts or any features that you find on most word processors. Text editors generally allow you to search for text, do cut-and-paste, do search-and-replace. Admittedly, many word processors also do these tasks. Most commercial compilers give you an "environment". Thus, as part of getting a compiler like Visual C++, you will also get a built-in editor. However, in the UNIX environment, the editor and compiler are separate. While emacs is often used to edit programs, you can also use it to write letters, record phone numbers, store recipes. Admittedly, these will be saved in a rather crude format, but the point is that text editors edit any kind of text, not just C programs. Even though editing text isn't exactly programming, it is still important to learn how to use a text editor well. As an analogy, think of a writer who uses a word processor to write books. Being good at using the word processor is certainly not being good at writing, but if the writer is an expert at using a word processor, the writer can be much more productive. This tutorial ------------- The goal of this tutorial is to teach you the basics of using emacs, and even some of the more advanced features. It's recommended that you read parts of the tutorial, but also print the tutorial (or pull it up as a webpage) and practice using emacs. You won't get good at emacs unless you try out all the new features. Like learning anything new, it will be slow going at first, but if you are eager to learn all that's taught in this tutorial, then within a few weeks you will editing in emacs has become second nature. Tips for learning emacs 1. Read this tutorial 2. Print the tutorial and bring it with you to a computer 3. Practice using emacs with tutorial in hand 4. Write down anything that you found confusing while using emacs or any reminders that you might need when using emacs the next time you log on. Why emacs? ---------- When this course was originally taught, it was felt that students ought to use a simple editor, and then once they mastered the basics of programming, they could learn a more sophisticated editor. However, there was a problem. Humans hate to learn new things, especially when the new things are very similar to the old things. Case in point: students used pico as the text editor for programming. pico is a nice simple editor, which is also used in a UNIX mail reader called pine. However, it lacks many capabilities of more powerful editors, such as vi or emacs. Nevertheless, many students failed to switch from pico to, say, emacs. Why? Because they didn't know that much about emacs. In order to edit using emacs, they would have to spend time getting good at it. In the meanwhile, they would be less productive with emacs than with pico. Thus, there were senior computer science majors who still used pico, unwilling to spend the time it took (about a month) to learn a new, more powerful editor. Therefore, it seems to make sense to start of with a powerful text editor. You may struggle a little more learning how to use emacs, but within a month, most students can edit just fine in emacs. Even though emacs is more complicated to master than pico, it turns out that it's really not that much harder at all. Furthermore, because emacs is so powerful, there's always something new you can learn about emacs. In fact, you should always be looking out for better ways to edit. There are many books out on the market that teach you the basics of emacs. A reasonably good book is "Learn emacs in 24 hours". Some emacs enthusiasts are loathe to call emacs a "text editor". In their minds, emacs can do so much more than simply edit text. People use it to read mail, read news, as a shell, and so forth. Some open up an emacs window, and do everything they need to do on a computer within an emacs environment. Our goals are less lofty. We want you to learn to use emacs as a text editor. Those of you who have had some UNIX experience may wonder why we chose emacs. vi is primary rival for emacs. In fact, there are many reasons people like vi. vi is practically guaranteed to be part of any UNIX system. However, it's a rare UNIX system that doesn't have emacs as well. vi has somewhat fewer problems when used with telnet. emacs often requires a reasonably powerful terminal (vt100 is fine) to work. However, most people are able to run emacs successfully whether they are on campus or off campus. emacs was chosen over other editors, such as vi, because it has support for features in C programming. In particular, it does a very good job at indenting code, a normally tedious task. Also, more students find emacs "single-mode" editing easier to learn than vi's "dual-mode" editing. Also, don't let emacs (or other UNIX editors) fool you. Users of Windows or MacOS often find emacs "crude". It doesn't look fancy, and support for click and drag is minimal (although that has gotten better). As they say, don't judge a book by its cover. And don't judge a text editor by how "nice" it looks. You may discover, under emacs plain exterior, like a powerful engine. Do I Have To Learn emacs? ------------------------- Yes and no. We will quiz you on emacs, to make sure you are actually learning emacs. This is more to benefit students who are just learning how to use an editor. When starting out, students often learn just enough to get their work done. However, it's much better to learn the sophisticated features of emacs (mainly, searching, search-and-replace, cut-and-paste, and undo). By learning the more advanced aspects of emacs, you will save a great deal of time while editing. So, we highly encourage you to keep learning as much about emacs as time will permit. Try to spend sometime trying emacs. Sure, some of you have used Windows editors, and can't stand to learn anything new, or anything in the UNIX environment, but you should still learn emacs anyway. Why? For the simple reason that you will always be expected to learn something new. The computer industry moves so quickly that a person who isn't willing to try out new things is going to be replaced or outpaced by someone willing to learn. Furthermore, being proficient in UNIX and emacs is something that you could add to a resume. Sure, UNIX isn't nearly as widespread as Windows, but it's still got a decent niche. Final introductory thoughts --------------------------- As with anything new, emacs takes a while to learn, and you will make many mistakes before getting good at it. This may be especially frustrating to those who already know how to use a different UNIX editor. If you're such a person, give emacs a try. It never hurts to learn a new text editor, especially with one with as many features as emacs. This tutorial only covers the basic features of emacs. When you complete it, you may be interested in learning more about emacs by purchasing a book discussing more of emacs' features. Two good books on emacs are Learning GNU Emacs (by O'Reilly and Associates) and Emacs in 24 hours by SAMS publishing. You will discover that the more you learn about the tools that help you program (such as emacs), the more the tools save you time getting your work done. It requires a lot of time investment and diligence to keep learning, but pays off in the long run by making you more efficient. --------------------------------------- Lesson 1.1 Starting and exiting emacs --------------------------------------- emacs is a program, and like most programs in UNIX, you must type the name of the program to start it. So, once you see the C-shell prompt (which is the percent sign), type the following. % emacs test By typing this command, you have "opened" or started editing a file called "test". If the file did not exist before, then the following will occur. What should happen when you edit a new file ------------------------------------------- Assuming test is a new file (meaning it didn't exist in the directory before), you will either see a window pop up (typically on UNIX systems, such as Sun workstations or Linux), or you will see emacs in your current window (such as the telnet window on a PC). There are many versions of emacs (emacs is always being updated). The most recent ones have a menu at the top, which makes it easier to use. However, you will learn to use emacs without the menu options. Why? Because the menu doesn't always work. So it's better to learn without the pull-down menus. Originally, emacs had no pull down menus, and was run using the keyboard. You will learn this way of using emacs. Once you master it, it should be very easy to use the menu, since the menu options correspond to the keyboard commands that you will learn. Once you have typed "emacs test" at the prompt, you should see the following at the bottom of the screen. ---------------------------------------------------------- -----Emacs: test (Fundamental)--L1--All--------- ---------------------------------------------------------- (New file) Figure: The status line, which appears at the bottom few lines of an emacs window. The line that says "Emacs" is the "status line". It is usually in reverse video. If the background color of your text is white, and the text is black, then this status line will be reversed, with white text, on a black background. It should be easy to spot. The status line provides you several pieces of information. Other than "Emacs" (letting you know that, yes, indeed it is emacs), the status line also tells you the name of the file that you are currently editing. In this case, the name of the file is called "test". Then, you see something in parentheses that says "Fundamental". This is called the "mode". When you edit plain text files (such as this one), you will usually see Fundamental. A "mode" will be explained in detail later on, when we get to C files. For the time being, don't worry about it. Then you see L1. L1 means line 1. The line number refers to the current line of the cursor. Each time you open a file, the cursor is placed on line 1. As you move the cursor down, it will be on other lines. Thus, if you see L200, this means you are on line 200 (older versions of emacs didn't have this extremely useful feature). The "All" refers to what part of the file you are looking at. If the file can be fit on one page (and it can, since your new file contains nothing), then it will print All. If the cursor is at the top of the file, it will say "Top", and if the cursor is at the bottom of the file, it will say "Bottom". If the file is too big to fit one one emacs screen, and the cursor is in the middle of text file, then you will see a percentage, such as 19%. This tells you how far the cursor is down from the top of the file. Thus, 19% would indicate that you are 19% of the way down in the file. Thus, you should see the following information on the status line: (1) The name of the file that you are currently editing (2) The "mode" you are in, in this case, Fundamental (3) The line number you are currently on (4) Where the cursor is located (i.e., what percentage down the page) Just underneath the status line, you will see (New File). The line underneath the status line is called the "mini-buffer". We will talk about the mini-buffer later on. In the meanwhile, you should always be keeping an eye out on the status line and the mini-buffer since it provides you with useful information. Starting up with emacs ---------------------- Once you see the emacs window, you can begin to type. To begin, try typing in "hello", then hit the return key. Once you've hit the return key, type in "there". Notice the characters show up at the top of the screen and behave like most word processors. Your emacs window will look something like this: +----------------------------------------------------------+ |hello | |there# | | | | | | | | | | | |----------------------------------------------------------| |--**-Emacs: test (Fundamental)--L2--All----------| |----------------------------------------------------------| | | +----------------------------------------------------------+ Figure: The emacs window, after typing in hello, then hitting return, then typing there. It's hard to draw the cursor, so I put a # to indicate where the cursor is. Notice how the status line has changed. In particular, you should see a double asterisk (i.e., a **) to the left of Emacs. This double ** means that you have updated the "buffer", but not saved it. This is very similar to a word processor. Most word processors allow you to type and edit a paper, but to make the changes permanent, you need to save the file using a Save command. What is the buffer? When you open a file in emacs, it copies the file into an emacs "buffer". A buffer is a temporary location (in memory) where you can edit the file. When you save a file, it will copy the buffer (from memory) into the file, and the changes will be permanent. The other change to the status line is the line number. The line number is now L2, meaning line 2, since the cursor is on the second line. If you hit return once again, you will see L3, since the cursor will be on line 3. You're Editing a Buffer ----------------------- When you are editing a file, emacs copies the file into a temporary area in memory. This is called the "buffer". In reality, you don't edit a file, you edit a buffer. This is a more efficient way to edit files since it's quicker access and modify memory than it is to update a file all the time. The changes you made to the buffer only change the file once you save the buffer to the file. While this may sound a little unusual, it's rather common. In many computer applications (such as word processors), you are told to save the file often. The reason is because you are editing a buffer, and if the program fails then the changes to the buffer are not permanently saved to the file. How to Save a file ------------------ Even though you've barely edited a file, it's a good time to try saving the file. More accurately, you are really saving the buffer TO a file. If you emacs has a working menu, then you have two ways to save a file. 1. You can use the menu to save the file 2. You can use control keys. Saving The Buffer Using The Menu --------------------------------- 1. Move the mouse over the Files menu, and click with the left mouse button. This should produce a list. 2. Select "Save Buffer" (don't use "Save Buffer As"). 3. If the "Save Buffer" is not available, it means you have already saved the file, and do not need to do it again. You'll notice the menu system looks a lot like those on Macs, undoubtedly where emacs' menu system was inspired. Saving the Buffer Using Control keys ------------------------------------ Most people like to use the menu options. It's certainly handy if you can't remember how to save a buffer. However, for many of you, the menu options won't work. This is especially true if you are running on a PC or Mac (although there are versions of emacs that run directly on the machines, which should allow you to use the menu. However, since many of you will be running emacs from your class account, the menu won't be available). Using control keys are the heart of editing anything in emacs. Initially, you will be slow using control keys, and it will seem awkward. But once you get good, you will discover that it is MUCH faster than editing with a mouse, having to click and drag. As nice as mice are, they're geared more to beginners. It's slower to use them than it is to master control keys. Furthermore, many of you will simply have no choice. Control keys will be the only way to go. Thus, there are many reasons for mastering control keys, not the least of which is that you will be occasionally quizzed on your mastery of how to use control keys. To save the buffer, type the following: C-x C-s The "C" stands for the Control character, and thus, the saving of a buffer is a Control-x, followed by a Control-s. This allows you to save the buffer to a file, but doesn't exit you out of emacs. This means, once you save the buffer using this method, you can continue to edit the file (it's very similar to selecting a Save option in a word processor). You should save your file frequently, just in case emacs crashes. You're probably wondering how you will type these funny control key sequences. You're just about to find out. How to hit a Control character ----------------------------- Most of the characters that you type from the keyboard show up on the screen, just as you probably expect. When you type "hello", the word hello shows up on the emacs screen. However, you need the ability to do other tasks besides simply typing. For example, it would certainly be convenient to save the file. How can you do that, especially without the use of the menu? You use control keys. For example, in order to save the buffer to a file, you will need to type the control key sequence, C-x C-s (pronounced Control-X Control-S). The first step will be to type C-x (i.e., Control-X). Once that's done, you will type C-s. Emacs command: C-x C-s What it does: Saves the buffer to a file To hit a control character, find the control key on your keyboard. It is usually somewhere on the left side of the keyboard, either left of the "a" key, or below the "shift" key. This is how you should type C-x C-s (to save the buffer). 1. First, press the Control key (and no other key). 2. While keeping the control key pressed, press the letter x. 3. Release the letter x, while still keeping the control key pressed. 4. Release the Control key. Wait a second or two. Then, look at the very bottom line (i.e., the minibuffer), you will see the following: C-x- This means emacs has recognized that you've typed in C-x (pronounced Control-x), and it's waiting for you to type something else. Since you wish to save the buffer to a file, type Control-s, as follows: 5. Press the Control key first. 6. While keeping the control key pressed, press the letter s. 7. Release the letter s, while still keeping the control key pressed. 8. Release the Control key. When you do this, you will see something like the following in the minibuffer Wrote /fs/junkfood/clin/test The minibuffer indicates that the buffer has just been saved (or written) to the file, and then it gives the absolute UNIX path as to where it saved (i.e., /fs/junkfood/clin/test). When you save the file, you will see a different path for the file saved, and it will print the location of where you have saved your particular file. Notice that the ** goes away in the status line, because the buffer has been saved. If you modify the "buffer" (by typing or deleting characters) after saving, you will see the ** in the status line. Try typing a few characters to see this. What's The Minibuffer? ---------------------- The minibuffer is the last line of the emacs windows, and often tells you useful information about what's happening in emacs. It's called a minibuffer since it is only one line long. The rest of the screen (above the status line) is called the buffer. It's good to know that the buffer and minibuffer are two separate buffers. Saving some time ---------------- The instructions for typing C-x C-s is actually quite slow. Experts in emacs can type this much faster, and you might as well learn how to type control characters faster. In particular, whenever you have to type two control characters in a row (such as C-x C-s), you should use the following, faster alternative. Shortcut For Typing C-x C-s 1. Press the Control key 2. Press the letter, x, while keeping the control key pressed. 3. Press the letter, s, while keeping the control key pressed (but you should release x before typing s) 4. Release the Control key You can type the x, followed by the s as quickly as you want. There's no need to wait for the minibuffer to say that you pressed C-x. Again, once you have typed C-x C-s, you will see which file was "written" in the minibuffer. If you have already saved the file, and haven't made any changes (in other words, the ** doesn't appear in the status line), then you will see the following message in the minibuffer. (No changes need to be saved) emacs is "smart" enough to realize when you have saved the buffer, and therefore if you've saved the buffer AND have made no changes to the file, then it saves itself the effort of writing to a file (writing to a file is a somewhat slow process, though it's still extremely quick). Dreaded C-s ----------- In the "old" days before you could have multiple windows, programmers often worked on a dumb "terminal". The terminal was essentially one window, and often used green text. Sometimes, while running a program which was producing lots of output, the screen would fill up with text and scroll by so quickly that it was hard to read. Early computer designers thought it might be useful to allow the user to pause the screen (no one had thought about the scrollbar in those days). To allow the user to pause the screen, the user would press Control-s. Once the user had read what was on the screen, they would resume the scrolling by pressing Control-q. Depending on which terminal emulator program (or, possibly whichever telnet program) you are running, the C-s in C-x C-s might be "captured" by your emulator, and emacs may never see that command. You can tell if this happens in several ways. First, the minibuffer won't say that your program has been written. Second, you probably won't be able to edit within emacs since everything's "paused". Third, C-s won't show up in the minibuffer. If that happens, then, most likely, you have an emulator which is interpreting C-s as a command to pause the screen. To undo it, type C-q. This is NOT a problem with emacs. It's just that your terminal emulator program intercepts certain control characters. How can you solve this problem? There are two ways. First, many of these terminal emulator programs have some sort of menu option to turn off C-s/C-q from pausing and unpausing, so you may have to look around to see if you can turn the option off. If that doesn't work, then emacs is rather versatile. Practically anything you do in emacs has at least one, and often two or more ways of doing it. Since the problem occurs when you type C-s, there is an alternative to saving the buffer where you don't have to type in C-s. Instead of typing, C-x C-s, type in C-x s. Note the differences. To type, C-x s, you will need to type C-x as usual. But then release the Control key completely, and just press the letter 's' by itself. Unlike C-x C-s which automatically saves assuming the file has been modified, C-x s always asks if you want to save or not (in the minibuffer). Usually, you will type in 'y', for yes, and it will save it. This is generally more annoying that typing C-x C-s, which saves the buffer without Exiting emacs ------------- Whenever you finish using emacs, you should exit out of emacs, especially if you are planning to log out. You can try exiting emacs after having edited the file, "test". Emacs command: C-x C-c What it does: Exits emacs You can now exit emacs by typing: C-x C-c. (Control-X, followed by Control-C). You can use the same shortcut for typing these two control character sequences as you did for C-x C-s. That is, you can do: Shortcut For Typing C-x C-c 1. Press the Control key 2. Press the letter, x, while keeping the control key pressed. 3. Press the letter, c, while keeping the control key pressed (but you should release x before typing c). 4. Release the Control key If you haven't saved the file when you type C-x C-c (which means there will be a ** in the minibuffer), then there will be a message in the minibuffer asking whether you want to save the buffer. The message will look something like: Save file /fs/junkfood/clin/test? (y, n, !, ., q, C-r or C-h) but the absolute path of the file will be different. Generally, you only have to worry about the first two options. Type 'y' if you wish to save the buffer. If you type 'n' this means you do not wish to save the buffer to the file. The minibuffer will respond with the following message: Modified buffer exist; exit anyway? (yes or no) This basically says "Are you sure?". Most people usually want to save any changes made. Thus, the minibuffer will ask whether you to save the buffer or not a second time, and this time it wants you to type "yes" or "no" (instead of simply 'y' or 'n'---by the way, don't type the quotes or double quotes. It's only printed to make it easier for you to read). If you type the word "yes" and hit return, it will exit emacs without saving the buffer, and you will should see the shell prompt. Any changes made since the last time you saved will NOT be saved. If you type the word "no" and hit return, you will return back to editing the file. One thing to note. If the minibuffer asks "yes or no", then you must type the ENTIRE word--not just the first letter---and hit return. However, if it says "y or n", you can type either 'y' or 'n'. Do NOT hit the return key after typing 'y' or 'n' since emacs will respond right away once the character 'y' or 'n' has been pressed. Save, before exiting -------------------- Exiting emacs while the buffer has been unsaved will cause emacs to ask you whether you want to save changes. If you know that you want to save, and then exit, you can save yourself time by typing the following rather lengthy control sequence. C-x C-s C-x C-c If you look carefully, it is just C-x C-s (saving the buffer), followed by C-x C-x (exiting emacs). You can type this quickly by holding the control key down, then typing the letters x, s, x, c, then releasing the control key. Hitting Return at End of Lines ------------------------------ Unlike most word processors, which allow the user to keep typing without having to hit return, emacs requires that you hit return at the end of the line. It *may* appear that you are just going to the next line when you type a lot with emacs, but this isn't true. For example, look at this emacs window, +----------------------------------------------------------+ |The quick brown fox jumped over the lazy dog with total m\| |erriment and glee. | | | | | | | | | |----------------------------------------------------------| |-----Emacs: example (Fundamental)--L2--All----------| |----------------------------------------------------------| | | +----------------------------------------------------------+ Figure: Even though there appears to be TWO lines, the first line is wrapped. You can tell because of the backslash at the end of the first line. In the example above, the person has typed in a very long line and instead of hitting return after typing "total", the person kept on typing. Whenever you type a line that's too long, emacs still treats it as if it were a single line, even if it may appear as if were on two lines. Thus, if you could somehow stretch the window wider, you would see that words that appear on the second line would actually shift to the first line where they really belong. How can you tell if the line is too long? At the end of the first line, you can see a backslash (i.e., \). This means that emacs considers the line after to be a continutation of the current line. So, in this case, the second line is really to be considered the end of the first line (and the third line on the screen is really the second line). Remember to hit return at the end of the line, because emacs won't do it for you (although, one can configure emacs up to behave that way). What you have learned in lesson 1.1 ----------------------------------- 1. How to edit a file called test 2. How to read the status line 3. How to read the minibuffer 4. What a buffer is 5. How to determine when a file is saved or not by the status line. 6. How to save a file that you've edited 7. How to type control characters 8. How to type a sequence of two control characters quickly. 9. How to exit emacs These are the commands you should know from emacs in lesson 1.1. C-x C-s Save buffer to a file (save file) C-x C-c Exit emacs You should also know the alternative way of saving a file, in case C-s gives you problems. C-x s Save buffer to a file (but emacs asks you whether to save) Shortcuts: There are menu options for this on emacs that use menus. Look under Files. Other comments You can name the file whatever you want. You do not need to use the name, test. By and large, UNIX requires the names of the files use letters, digits, dots, dashes, underscores, but in general, no spaces, nor quotation marks. Even though there are tricky ways to put spaces in the name of a file, it's best to avoid it. ------------------------------------ Lesson 1.2 Maneuvering around emacs ------------------------------------ So far, you've edited a very tiny file. In this lesson, you will learn how to manipulate the cursor, so that you can put the cursor where you want. Presumably, you have seen a cursor from using a word processor before, so we'll skip any explanation of what a cursor is. Many modern emacs will let you use the mouse buttons to place the cursor onto the screen where you want. However, sometimes your computer setup won't allow the mouse to be used to place the cursor. Fortunately, emacs was originally designed to work without mice. You will learn how to move the cursor by using control keys. Let's reopen the same file that was used in Lesson 1.1, namely, test. % emacs test When you open the file, it should be as you last left it. Assuming you only typed "hello", then return, then "there", you will see: +----------------------------------------------------------+ |hello | |there | | | | | | | | | | | |----------------------------------------------------------| |-----Emacs: test (Fundamental)--L1--All----------| status line |----------------------------------------------------------| | | minibuffer +----------------------------------------------------------+ Figure: How emacs looks when you re-open the file test, as edited earlier on. The cursor initially sits in the upper lefthand corner on top of the 'h'. You will notice that the cursor is on the top row, leftmost column, right on top of the 'h'. (I can't do show you the cursor and the 'h' in the tutorial, because of obvious limitations with text files, but if you run it on a real emacs, you should be able to see the cursor sitting on top of the 'h'). In this lesson, you will learn how to move the cursor around. The two commands you'll learn now allow you to move the cursor forward one character, and to move it back one character. Command What it does ------- ------------ C-f Move cursor forward one character C-b Move cursor backward one character Unlike the commands to save a file or exit emacs, you only need to hit one control character, not two. Give it a try. 1. Hit C-f once (the cursor should move on top of 'e') 2. Hit C-b once (the cursor should move back on top of 'h') 3. Hit C-b again (emacs should beep, indicating that you can't go further to the left, since you are at the beginning of the file) You will notice that emacs beeps a lot, usually to indicated an error. Let's move the cursor forward until it's one past the letter 'o'. Do this by hitting C-f, five times. Again, to save time, press the control key, and press 'f' five times, then release the control key. +----------------------------------------------------------+ |hello# | |there | | | | | | | | | | | | | |----------------------------------------------------------| |-----Emacs: test (Fundamental)--L1--All----------| status line |----------------------------------------------------------| | | minibuffer +----------------------------------------------------------+ Figure: Cursor sits on the newline character after typing C-f five times. The cursor (which is represented above by the #) is now one character past the 'o'. The cursor is sitting on top of a "newline" character, which indicated the end of the current line. That newline character is there because you hit return at the end of typing hello, back in lesson 1.1. If you type C-f one more time, you will go to the beginning of the next line, and the cursor will lie on top of the 't' on line 2. Check the status bar and you will see L2, which indicates that the cursor is now on line 2. If you type C-b several times, you will back up to the previous line. Notice that C-f and C-b just move the cursor around, but do not change the text. Now move the character on top of the 'h' in the word "there", and type two o's. You should see +----------------------------------------------------------+ |hello | |toohere | | | | | | | | | | | | | | | | | |----------------------------------------------------------| |--**-Emacs: test (Fundamental)--L2--All----------| status line |----------------------------------------------------------| | | minibuffer +----------------------------------------------------------+ When you type, the characters are inserted underneath the cursor, and then the cursor moves one space to the right. Everything that was on the cursor and to the cursor's right, prior to typing, moves right one space. You will notice that before you typed, the cursor was on the 'h' of the word "there". As you type, it still remains on the 'h' but the 'h' moves right (along with all the text right of the 'h') as you keep typing. Thus, you can insert text wherever you want on the screen. Notice the status line now has the double asterisk (**), indicating that you have updated the buffer. Moving to the beginning and end of a line ----------------------------------------- While moving forward and backward a character at a time will allow you to get to anywhere in the file, you can move the cursor in bigger jumps. emacs provides additional commands which allow the cursor to jump to the beginning of the line and to the end of the line. Command What it does ------- ------------- C-a Move to the beginning of a line C-e Move to the end of a line To get some practice, try the following exercise. Keep an eye on the cursor after you type each command to see that it matches the results below. 1. Press C-a. This should move the cursor on top of the 't' on the second line. 2. Press C-e. This should move the cursor one space to the right of the 'e'. 3. Press C-a again. You are back at the beginning of the line. 4. Press C-a again. Since you are at the beginning of the line, the cursor stays where it is. 5. Press C-b. This moves you to the end of the previous line. 6. Try pressing C-a and C-e several times, to get the feel for what the cursor does. Moving up and down faster ------------------------- C-a and C-e can help you move around faster, but it confines you to one line. While C-f and C-b can move to different lines, there's an obvious need to move the cursor up and down a line at a time. Here are the two commands to move up and down a line. Command What it does ------- ------------- C-n Move to the next line C-p Move to the previous line Place the cursor on top of the 'h' from the first line, and type C-n. This will place you on top of the 't' in "toohere". emacs attempts to move down one line, in the same column. However, each line does not have the same number of characters. Hence, you may attempt to move up one line or down one line, and move to a different column. To see, this press C-e, which will move you to the end of the second line. Then, press C-p, which will move you up one line. Because the second line of text has more characters than the first, the cursor will not move directly up. Instead, it does the best it can, and moves it at the rightmost part of line 1. Recall that the end of a line (except possibly the very last line) is a newline character. To illustrate this, let's put column numbers on top of the a new file called "test2". To create "test2", type the word "good" on the first line, then hit return, then type "morning" on the second line, and also hit a return. 123456789 +----------------------------------------------------+ |good | |morning | | | +----------------------------------------------------+ Figure: This is a new file, test2, with "good" on the first line and "morning" on the second line. There are column numbers written on top for the first nine columns. In the first line, there are actually 5 characters. The first 4 are the word "good" and the fifth one is the newline character, which is there because you hit the return key at the end of the first line. Hitting return causes a newline character to be added to a buffer. In the second line, there are 8 characters. The first 7 characters are the word "morning" and the eighth one is the newline character, which is there because you hit the return key at the end of the' second line. Suppose the cursor is on the second line (the one with "morning") on the 8th column. This means the cursor is sitting on top of the newline character. If you press the control sequence, C-p, emacs will attempt to move the cursor up one line in the same column. It is successful moving the cursor up one line, however, since the first line only has 5 characters, it will be unable to place the cursor in the 8th column. The best that emacs will do is to save it in column 5, which is the rightmost column of the first row. Even though emacs was unable to place the cursor in the 8th column, it "remembers" that you were attempting to go to the 8th column. For example, if you press C-n (assume you had just done C-p and are now in row 1, column 5), you will move back down to the second row, but be back in the eighth column, the same column it was originally. emacs continues to remember the column it was in as long as you are doing C-n or C-p. If you do pretty much any other operation to move the cursor, it updates the column. For example, suppose the cursor is in row 2, column 8 (the end of the second line), and then you do C-p. As before, it moves the cursor up to row 1, but must place it in column 5 since there are only 5 characters in the first line. Now, if you do C-b, you will move one column to the left. This will place the cursor on row 1, column 4. At this point, you've moved it to a new column using a command that isn't C-n, not C-p. It now assumes the column is 4. If you try C-n again, you will now be in row 2, column 4 (not column 7 nor column 8), which will be on top of the letter 'n' in "morning". Did you find that explanation complicated? Don't worry. You will hardly notice it's happening as you learn to move the cursor around. But as you do move it around, see how emacs moves the cursor, and you will begin to understand the explanation given. If it stil puzzles you, well, that's OK. It's not such a big deal. All you really need to know is that most of the times C-n and C-p will move the cursor down or up one line, respectively. Using arrow keys ---------------- Even though you will be responsible for knowing the control characters, most versions of emacs will allow you to use arrow keys. The arrow keys do pretty much what you expect that they might do, and thus some people prefer to use them instead of the control character. Here's a table that shows what the arrow keys do. Control chars Arrow keys What it does ------------- ---------- ------------ C-n down arrow Moves cursor to next line C-p up arrow Moves cursor to previous line C-b left arrow Moves cursor back one character C-f right arrow Moves cursor forward one character There are, of course, no arrow keys for C-a and C-e (there are only 4 arrows, and they are used above). You will find that, on occasion, your machine (especially on a PC) may not always allow you to use arrow keys. It *may* be possible to fix it so it does work, but if not, you can always use the control keys, which almost always works. Summary of new commands ----------------------- In this lesson, you should have learned the following commands: C-b, C-f, C-n, C-p, C-a, C-e. At this point, you should know 9 commands. 3 from the first lesson, and 6 more here. You're already making good progress! Now to get onto some more interesting emacs commands. ------------------------------------------------------ Lesson 1.3 Deleting characters and the cancel button ------------------------------------------------------ The third lesson will be fairly short. It involves deleting characters. You will learn 3 commands, as well as how to get out of some problems. On most computer keyboards, you will find both a backspace key and a delete key. Unfortunately, the computer recognizes them as two DIFFERENT keys, and sometimes only one of the two keys deletes the character just left of the cursor, while the other one does something annoying and DOESN'T delete a character. I will assume the backspace key deletes. If you have your emacs window open and are editing a file, say, test (at this point, you should experiment trying to create new files with other names besides test). Using C-e, you can move the cursor to the end of a line on which you've typed something. Typing the backspace character ought to delete the character that's just left of the cursor. Command What it does --------- ------------ Backspace Deletes previous character (usually left of the cursor) Suppose you have typed in the line, +------------------------------------------------------+ |the bat in the hat | | | +------------------------------------------------------+ and you wish to erase the word "bat" and replace it with the word "cat". You would place the cursor just right of the 't' in bat, as in: +------------------------------------------------------+ |the bat#in the hat | | | +------------------------------------------------------+ (again assume that # represents the cursor) and hit backspace several times until the cursor is covering up the 'b' (in fact, when it is on top of the 'b', it has deleted it, so you won't really see the 'b'). DON'T use the arrow keys to backspace! They don't delete characters. Of course, if you've ever used a computer before, you should already know how to delete words or characters in this manner. Occasionally, depending on what kind of terminal you are using when running emacs, you may discover that the backspace key isn't working correctly. Usually, if backspace doesn't work, the following message in the mini-buffer (recall the mini-buffer is on the last line of emacs): C-h (Type ? for further options)- This usually means that you must use the delete key to delete characters instead of the backspace key. This can be annoying because the backspace key may be the key you are used to hitting to delete characters. Typically, if you see the above message in the minibuffer AND hit backspace again, the screen will split into 2, and you will see in the bottom half of the screen: You have typed C-h, the help character. Type a Help option: (Use SPC or DEL to scroll through this text. Type q to exit the Help command.) a command-apropos. Give a substring, and see a list of commands (functions interactively callable) that contain that substring. See also the apropos command. b describe-bindings. Display table of all key bindings. c describe-key-briefly. Type a command key sequence; it prints the function name that sequence runs. f describe-function. Type a function name and get documentation of it. C-f Info-goto-emacs-command-node. Type a function name; it takes you to the Info node for that command. F view-emacs-FAQ. Shows emacs frequently asked questions file. i info. The info documentation reader. k describe-key. Type a command key sequence; In the minibuffer, you will see: Type one of the options listed or Space to scroll How to fix the mess when backspace causes problems -------------------------------------------------- Either way, you have a mess. The way to fix the problem is to hit C-g Command What it does ------- ------------ C-g Cancels current operation (keyboard quit) Pressing C-g either after seeing the first message or the second will return emacs back to where it was. If you discover backspace does NOT delete a character, use the delete key. Sometimes you get lucky. Sometimes both backspace and delete will both work correctly. That is, both keys will delete the character just left of the cursor (it will delete the newline at the end of the previous line if the cursor happens to be in the first column, just in case you were wondering). In that case, you can just use the key you're most comfortable using when deleting characters. Alas, it's a complete nuisance when the character you want to use to delete (say, backspace) doesn't work, and you're forced to use the other one. It would be nice if enough computer companies abolish one or the other, and then this problem wouldn't occur. Using C-d --------- Suppose you've just typed in "supercalifragilisticexpialidocious" and the cursor is on top of the 's' (i.e., the first letter in the word). However, you realize this adjective is not professional enough for an English essay, so you want to delete the word. Usually, this would require that you move the cursor to the end of the word, then hit backspace. This can take a long time. There's a quicker way to begin deleting all those characters. Use C-d. C-d is similar to backspace, except instead of deleting the PREVIOUS character, it deletes the CURRENT one. Everything to the right of the cursor will move left by one space. However, even though characters are being deleted, the cursor doesn't move when you use the C-d operation. You may find this way of deleting to be unusual, to say the least, but you'll soon find that it's very convenient to delete to the right of the cursor (using C-d) as it is to delete left (using backspace). You will find it more efficient to know how and when to use both, as you learn how to become an emacs expert. To practice C-d, try creating a new file (this may require that you exit emacs). Use emacs to create a new file (give it whatever name you want), and then type in the long word written above ("super...). Use C-a to move you to the beginning of a line, then move the cursor on top of the first 'c' (which emacs command should you use to move the cursor forward?). Try hitting C-d several times. You will see the 'c' deleted, but the cursor doesn't move. However, all the characters that used to be right of 'c' have now moved left by one. The cursor will now sit on top of the letter 'a'. Try typing 'hello' on one line (you can type this on the second line), then 'there' on the following line. Put the cursor anywhere in the word 'hello' and pressing C-d several times (recall the short cut: press the control key, then hit 'd' several times without releasing the control character). Once you delete 'o', then the next letter after the 'o', the word "there", which was on the next line, has now popped up to the first line. That's because you deleted the newline character. Remember that each line (except possibly the very last line) ends in a newline character. Whenever you are at the end of the line (C-e can quickly move the cursor to the end of the line) and press C-d, you will cause the newline character to be deleted. This will cause the next line to be added to the end of the current line, and all lines after the next line to shift up by one. For example, suppose your file looked like this: +------------------------------------------------------+ |hello# | |there | |everyone | +------------------------------------------------------+ Let's say the cursor is at the end of the first line (as shown above). In other words, the cursor was on the first line, and you typed C-e to move it to the end of the first line. The cursor is now on top of the newline character (which was put there when you hit return). If you type C-d, this will delete the newline character, and you will see the following. +------------------------------------------------------+ |hellothere | |everyone | | | +------------------------------------------------------+ The cursor will be sitting on top the the letter 't' on the first line, which is where the newline used to be. The buffer, which used to have three lines, now has two lines. By using both the backspace and C-d, you will learn how to delete much quicker than using just backspace. Using C-k --------- C-d and backspace work well if you only want to delete a few characters at a time. If you want to get rid of entire lines at a time, you can "kill" a line with the C-k operation. The C-k command will delete all the characters starting from the cursor to the end of the line that the cursor is on. However, it won't delete the newline character at the end of the line. None of the characters left of the cursor will be deleted. When the operation is complete, the cursor is either on top of a newline character or if you happened to be on the last line of the buffer, it will be at the end of the buffer. If you then hit C-k while the cursor is on the newline character, it will delete the newline character. This will cause the next line to be added shifted up and placed at the end of the current line (the same thing that happens when C-d is used to delete a newline character). To get an idea of how this works, type 'computer' on one line and the 'science' on the next: +-----------------------------------------------------+ |computer | |science | +-----------------------------------------------------+ Place the cursor on top of the 'u' in computer. Then, press C-k. This will "kill" the rest of the line, meaning the letter 'u' and everything to the right will disappear, and the cursor will lie on top of a new line. comp# science Again, I use # to represent the cursor, which is currently on the newline. Press C-k again. Since the cursor was sitting on the newline, C-k will delete the newline. This causes everything on the next line to move up. compscience The cursor will be on top of the 's'. Notice that using C-k, like using C-d, does not move the cursor at all. Typing C-k fast --------------- Sometimes you would like to "kill" more than one line and want to do it in a hurry. Rather than typing C-k, then releasing the control key, then pressing the control key, etc., you can save time by keeping the control key pressed at all times. Shortcut for typing C-k several times quickly 1. Press the Control key. 2. Press 'k' several times, as many as needed to delete the lines you want 3. Release the Control key. Pretty soon, you will be able to hit 'k' several times quickly as much as needed. In fact, nearly any command you need to repeat several times can be done by pressing the Control key and the other key several times in a row (such as C-f). There are some exceptions. For example, to hit C-x s several times in a row (which would really not make sense, but there are other commands it does make sense to repeat it several times in a row), you would be stuck. You type C-x, but you must release the control key to press the s. Holding C-x down and pressing s several times will not work. Thus to run C-x s twice, you must type C-x, then release both keys, press s, then back to pressing C-x, then back to pressing s. Oops, got rid of too many lines! ------------------------------- The problem with typing several C-k quickly is that you can easily get rid of too many lines. Obviously, you would like to get those accidentally deleted lines back. Are they gone forever? Will you have to retype? Of course not! emacs can help! When you kill several lines in a row, those lines are saved into something called a "kill ring" which is a temporary buffer. You can retrieve the results of the most recent "killed" lines by using C-y which "yanks" back the killed lines (actually pastes in the lines from the kill ring back into the buffer at the cursor). If you most recently killed 4 lines in a row, then C-y will yank back all 4 lines. It's a crude version of cut and paste, but it often does the job. Command What it does ------- ------------ C-y Pastes back the last sequence of killed lines. (More accurately, it copies any "killed text" from the kill ring to the current location of the cursor) You must be careful. If you killed 3 lines, then type space, then killed 1 more line, then yanking will only get back the last killed line (the 1 line). The other 3 lines can't be retrieved (at least, not yet...there's a useful command called undo which will be mentioned in Part 2 of the tutorial). Typing that space broke up the sequence of killed lines. Only consecutive sequence of killed lines are saved. Now suppose you wanted to kill 3 lines, but accidentally killed 4 lines (and have not killed any more lines in the meanwhile). Then, C-y will cause the 4 lines to be pasted back to the cursor's current location. Assuming you haven't moved the cursor after doing the sequence of C-k, you will see the 4 lines appears where they were before. Then, use C-k to delete 3 lines instead of 4. Later on, we'll show you a better way to "undo" mistakes made like this. The better way to fix the problem once you realized that you have killed 4 lines is to run the "undo" command in emacs, which will undo the last command. If the last command was C-k and that caused a line to be deleted, then the line will be undeleted, as if the C-k hadn't occurred. The undo command will be explained later on, as it is somewhat difficult to learn (but not TOO difficult). Summary ------- What you should have learned in this lesson 1. The backspace deletes the character left of the cursor. 2. Sometimes, the backspace doesn't work, and produces funny message. Use C-g to get rid of those messages. 3. If the backspace key doesn't work, use the delete key. 4. C-d is used to delete the character underneath the cursor, and works the "opposite" of backspace (C-d deletes from the front of a word rather than from the back) 5. C-k kills the everything right of the cursor (and the character under the cursor, too), but not including the newline character at the end of the line. 6. If the cursor is on top of the newline character, then C-k will delete the newline character, causing the next line to be placed at the location of the cursor (which effectively adds the next line to the end of the current line). All lines below the next line are shifted up by one. 7. You can C-k several times in a row. The last sequence of "killed lines" is saved to the kill ring. 8. The last sequence of "killed lines" can be retrieved (or "yanked") back using C-y. ------------------------------------------ Lesson 1.4 Moving the cursor in big leaps ------------------------------------------ Most programs will require you to type many lines. Initially, you are probably going to type anywhere from 50 to 150 lines. Some programs may fill up hundreds of lines of text of more. Even C-n and C-p won't be quick enough to move around the buffer. In this case, there are two commands to move you up and down a pageful at a time. Furthermore, you can move to the beginning and the end of the buffer. These commands will help you navigate the buffer much more quickly. Therefore, make sure you learn to be proficient using these commands. These commands are fairly easy to learn, and just extend what you already know about emacs. Command What it does ------- ------------ C-v Move cursor down one page M-v Move cursor up one page The only surprise is M-v. What does this mean? Do you type an M, then a v? No. M-v means "meta"-v. On some computer keyboards, there is a Meta key. A Meta key is similar to a Control key. In fact, you can simply think of it as a second Control key. On Sun workstations, the Meta key appears as a small diamond just left of the space bar. However, while most keyboards have a Control key, many machines do not have a Meta key. Fortunately, most keyboards to have an Escape key (usually, just written as Esc). If your computer has a Meta key (which many computers do not have), use the Meta key as you would the Control key (this will be explained soon). If your machine does NOT have a Meta key (or even if it does), you can use the Escape key to achieve similar effects. However, the Escape key does NOT behave like a Control key. Instead of pressing the Escape key down, then pressing another key (like 'v'), you must press the Escape key and RELEASE it (therefore, it acts like a normal key), THEN press the following key. It's very important to remember to release the Escape key. In fact, you really want to press the Escape key just as you would any other key. Keeping Escape pressed too long often causes emacs to think you want to type Escape several times, and this often causes some problems. Typing M-v using the Escape key 1. Press the Escape key once and release. 2. Press the letter v once and release. Typing M-v using the Meta key 1. Press the Meta key, and hold it down 2. Press the v key, then release it 3. Release the Meta key It takes a while to use the Escape key, especially since it doesn't behave like the Control key. On occasion, pressing the Escape key twice causes problems and the emacs minibuffer may ask a question. Even if this doesn't happen you may see ESC ESC- in the minibuffer. To get rid of this, again, press C-g to cancel the last operation, and your buffer should go back to the way it was before. These commands move to the beginning of a file, and to the end of a file. Command What it does ------- ------------ M-< Move cursor to the beginning of the file M-> Move cursor to the end of the file. Typically, you press the Escape key once, then the < (less than) or the > (greater than) key once. As annoying as the Escape key is, these commands aren't ones you use a whole lot, so it's tolerable. In fact, this is one of the few commands where it's easier to use the Escape key rather than the Meta key. Using the meta key requires a bit of dexterity. If you had a Meta key, and wanted to type M-<, then you would need to press the Meta key, then the Shift key, then the < sign, thus requiring 3 keys to be pressed at once. Make sure you press the keys in the order just described. This will cause the fewest problems to occur. In particular, DON'T attempt to press all three characters (the Meta, shift, and < key) simultaneously, as you may cause the keys to be pressed out of order, and not get the correct command. To get practice with all four commands (C-v, M-v, M-<, M->), copy the "states" file from the posting account to your home directory, and start using these commands to move the cursor. 1. Move down one page 2. Move up one page 3. Go to the end of the file 4. Go to the beginning of the file Recentering the cursor ---------------------- As you move the cursor up and down a page, sometimes some text splits across the screen leaving, say half of it at the bottom of one page, and half of it on the next page. C-v and M-v usually moves the cursor one page at a time, but sometimes the page isn't where you want it to be. emacs has a command to allow the cursor to be placed in the middle of the screen. Command What it does ------- ------------ C-l Recenter the page, at the cursor. To see how this works, go into the middle of the file, and place the cursor near the bottom or the top of the page. Now hit C-l. You will see that the cursor has moved to the middle of the screen. However, it is still at the same position within the text buffer. For example, if the cursor was on top of Maryland, and you type C-l, then it will still be on top of Maryland, but Maryland will now appear in the middle of the screen. By using C-l you will be able to see the page the way you want it to. This command is important when you are editing a large piece of code which fills up most of a page, and want to see all the lines in one page. What you should have learned from Lesson 1.4. 1. The "M" in M-v refers to the Meta key. However, if you don't have a Meta key, use the ESC key, as described earlier. 2. C-v and M-v move the cursor down one page and up one page at a time, respectively. 3. M-< and M-> moves the cursor to the beginning and end of the file respectively. 4. C-l (the letter l, not the number 1) recenters the text so the cursor is in the middle of the screen. ------------------------------- Lesson 1.5 Searching for text ------------------------------- If you've written a long paper using emacs, or a long program, you may wish to find a specific part in a hurry. Suppose you know a particular word that is near the location you want to edit. emacs will let you move the cursor to that word by searching for it, with the following two search commands. There are two search commands. Command What it does ------- ------------ C-s Searching forward in the buffer for a word C-r Searching backward in the buffer for a word I use the term "word" loosely. You can search for numbers, punctuation---practically anything that can be typed in a keyboard. C-s does a funny kind of search called an "incremental search". You type C-s and release. This causes the minibuffer to print: I-search: which is emacs way of saying that it is ready to do a search. Then type in the word you want to look for. As you type each successive letter, emacs will pop the cursor to the first occurrence of that word. To see this, use the states file. Move the cursor to the beginning of the file (use M-<). Then search for "new york". It doesn't matter whether you type "new york" in lowercase or uppercase, since the search is case-insensitive, so it's easier to stick to lowercase. As you type the letter 'n', it looks for the first occurrence ON or AFTER the cursor of the letter 'n', which happens to be the n in Arizona. Then, type in 'e'. emacs searches after the cursor for an 'ne', and the first occurrence is in Connecticut. Then, type 'w', and you reach the "new" in "New Hampshire". Typing a space will leave the cursor at the same location (since "New Hampshire has a space after the "New" just like "New York"). Then, type 'y'. At this point, the cursor is at "new york". To stop the search, hit the return key. Now that you're at New York, suppose you wanted to look for Michigan. If you use C-s, it will allow you to search forwards. Michigan, however, appears before New York in the buffer. Therefore, you won't find that Michigan if you use C-s, since C-s only searches after the cursor. What you need to do is to search backwards. How can you search backwards? You use a different emacs command! Instead of using C-s, use C-r. Try this out (assuming the cursor is at New York) 1. Type C-r 2. Type 'm'...this will move the cursor to the M in New Mexico. 3. Type 'i'...this will move the cursor to the Mi in Missouri 4. Type 'c'...this will move the cursor to the Mic in Michigan 5. Hit the enter key to exit the search. Suppose you were looking for Michigan, but instead of typing Mic, you type "mid". You can correct your error by using the backspace key to erase the 'd' (which you will see in the minibuffer). Then type 'c' and it will find the right spot. Notice that when you erase part of a word, the cursor moves back down to the place where it matched "mi". If you want to abort the search, or if you want the cursor to be place back to where it was originally just before the search began, type C-g, to cancel the operation. Suppose you are looking for New York. Instead of trying to type "new york", you can simply search for "new". Of course, as you search for new, you will find other states that have the word "new" as well. However, you can then REPEAT the search for the NEXT occurrence of "new". Let's see how this works. Assume that the cursor is back at the beginning of the buffer (use M-< to get you back there). 1. Type C-s to start the search forward. 2. Type "new" (no quotes)...this will place the cursor at New Hampshire 3. Type C-s again...this will move the cursor to the NEXT occurrence of new, which is "New Jersey" 4. Type C-s again...this will move the cursor to the NEXT occurrence of new, which is "New Mexico" 5. Type C-s again...this will move the cursor to the NEXT occurrence of new, which is "New York" Notice that each time you press C-s, emacs attempts to find the next occurrence of "new", and will continue to do so until you reach the end of the buffer (assuming it exists). If you do C-s again at the end, it will cause the search to start again from the very top of the buffer. Assuming you have just completed the last "C-s" and the cursor is now at "New York", try typing C-r. When you are in search mode, emacs continues to search with the same word, in this case "new". Pressing C-r moves the cursor to the beginning of New York. Pressing it several more times will move the cursor back up the list of new. If emacs can't find the word, it will beep. Hence, if you are at New Hampshire, and hit C-r, it will beep since there are no states listed prior to New Hampshire with the word "new" in it. In addition to the beep, the minibuffer will also alert you to a problem by displaying the following message: Failing I-search backward: new Or if you were searching forwards and failed to find the word you were searching for, the minibuffer would print: Failing I-search: new As usual, you can quit out of search mode by typing return, or by typing C-g. --------------------------- Lesson 1.6 Replacing text --------------------------- Another useful task is to replace words. Why might you do this? Most of us aren't perfect spellers. A few words may give you trouble. For example, many people write "definate" (which is incorrectly spelled), when the correct spelling is "definite". Therefore, you might wish to replace all occurrences of "definate" with the correct "definite". Another reason to replace text is changing the names of variables. Sometimes the first variable name you think of is not nearly as descriptive as it should be. However, you may have already typed in the variable name several times. Looking for the text then fixing it up could be so tedious that you would prefer not to make changes. However, in both examples, you can take advantage of search-and-replace, or more accurately, query-and-replace. emacs has a command that allows you to replace one word with another. Command What it does ------- ------------ M-% Goes into query-replace mode When you type M-%, you will see the following in the minibuffer Query-replace: emacs is expecting you to type a word. For example, in the states file, you might change the word "new" to "old". So you would type in "New" (again, anytime you see the double quotes in this tutorial, you should NOT type in the double quotes. The double quotes have been added to make it easier for you to see the word. If I could have used bold, I would have. Instead, I use double quotes) Query-replace: New "New" does not have to be typed with an uppercase 'N', as it will replace any occurrence of new in your text (even in a word like Sinew where new appears in the middle, and the 'n' isn't even capitalized). After typing in "New", hit return. You will see the following in the minibuffer. Query-replace: New with: And then type in "OLD" (again, don't use double quotes). Type it in uppercase to see what happens. It will replace the word "New" with "OLD" (actually, it will even replace "new" with "OLD"). The word you replace it with is case-sensitive meaning that if you type it in uppercase, then it will show up in your file in uppercase. Once you've typed "OLD", hit return. emacs will search FORWARD for the first occurrence of new. It will then ask you whether you want to replace that occurrence of new with OLD. If so, you type 'y'. If not, you type 'n'. In either case, it will go to the next occurrence of new. It continues until there are no further occurrences of new or until you hit C-g and stop the query-replace operation. ----------------------------- Lesson 1.7 Editing a C file ----------------------------- When you edit a C "source code" file, the name of the file should end in a .c (pronounced dot-C). For example, suppose you want to edit your program in a file called prog.c. At the shell prompt, you would type: % emacs prog.c emacs assumes that prog.c is a C file because of the .c at the end of the name of the file. The .c is called the file's *extension*. If you look at the status line, you will see the following: ---------------------------------------------------------- -----Emacs: prog.c (C)--L1--All---------- ---------------------------------------------------------- When editing a .c file, you will see the status line looks a little different than a normal text file: the word "Fundamental" no longer appears in the parentheses. Instead the letter "C" appears. This means emacs is in "C" mode. When emacs is in "C" mode, it has certain features already set up for helping you edit a C program. While you're not forced to write a C program when editing prog.c (you could for example, edit a Fortran program), emacs is already set up to help you edit C programs. This is what "C" mode means. While in "C" mode, certain keys will behave in a special way, because it it a C program, and will help make the editing of a C program a much more pleasant experience. One reason you're learning emacs is because emacs has many features (within "C" mode) to help you edit "C" source files. In particular, when you hit the TAB key, emacs will attempt to "correctly" indent the current line of C code for you. Ordinarily, if you were editing a text file (in Fundamental mode), hitting the TAB key would cause the cursor to move one tab stop up (about 8 spaces). However, in C mode, pressing the TAB key indents, which is a much more useful feature for editing programs. Let's see how this works. Suppose you type in this simple C program #include int main() { int x; int y; return 0; } Move the cursor to each line, and hit tab. You will discover that three lines are indented. #include int main() { int x; int y; return 0; } int x, int y, and return 0 are indented in. As long as you write your code according to the style guide, emacs will assist you in indenting. Note: the cursor does not have to be at the beginning of the line for the TAB to indent properly. The cursor can appear anywhere within the line when you press TAB. Note: the current line may not indent properly if the previous lines are not indented properly. This means you should be indenting each line of code as you write (presumably the code is being written from the top to the bottom). Make sure you indent as you write code. Those who indent their code only after it works, typically write code that doesn't work, because they don't understand the logical structure of the code. Indent as you write code! Don't indent after the fact! Indenting will make your code much easier to read, plus it's not that hard to do, especially in emacs. Just press the TAB key to indent each line of code as you are typing it in. ------------------------- Lesson 1.8 Backup files ------------------------- Perhaps one of the features that most annoys novice emacs users and users of other text editors besides emacs is that emacs creates backup files. For example, suppose you have edited a file called prog.c. If you have quit out of emacs, and type "ls" at the shell prompt, you may see something like this: % ls prog.c prog.c~ prog.c~ was created by emacs as a backup. prog.c is the latest version of your program, while prog.c~ is the previously saved version. Suppose you were editing a program using emacs, then you typed C-x C-s to save it. Then you edited some more, and then typed C-x C-s to save it a second time, then C-x C-c to exit. Then, prog.c would be the version you saved the second time, while prog.c~ will be the version you saved the first time. This is handy if you accidentally delete prog.c. However, as you edit more files, you will discover many such files. For the time being, just live with the fact that you have extra files. In part 2 of "UNIX in N Lessons", you will learn how to use wildcards and get rid of those files. If you need to use the backup, simply use the cp command. % cp prog.c~ prog.c This will make a copy of prog.c~ (the backup) to prog.c. You can also use mv, instead of cp. Of course, BEFORE you copy the backup, you might actually want to look at the backup to see if it's the file you want to copy or move. Either use the more command, as in: % more prog.c~ or use emacs itself, as in: % emacs prog.c~ Notice in both cases, you are looking at the backup (the ~ appears immediately after the .c). Aborted backups --------------- As you are editing your file, emacs will actually create a "running" backup. This backup is created while emacs is currently running. Then, if you abort out of emacs abnormally (for example, if emacs crashes, or if the telnet connection is cut, before you can type C-x C-c), then you will still have a backup to go to. emacs saves these files with a # before and after the name of the original file. Thus, if you were editing prog.c and somehow emacs aborted, and then you typed "ls", you would see: % ls prog.c #prog.c# Again, sometimes #prog.c# will contain the most recent version of your file. If you want this "backup" to be the current version of your file, then use mv to rename the file to the current one. % mv #prog.c# prog.c You can also recover the file in emacs, but it requires a little more work. It's easier to do the recovery of this backup within UNIX by using the mv command. Again, before you make the copy, make sure this is really the file you want to use by using emacs or more to look at the file. Making your own backups ----------------------- Even though emacs makes a backup, it only makes one backup, and that may not even be the backup you want. As you write programs, you may want to keep several versions, as you test out several ideas. Or, more likely, you will may want to make backups whenever you have program that's not perfect, but still works partly correct. That way, if you edit the file and find out that the program is really messed up, you can go back to a slightly older version and start again. The rule of thumb is to make a backup whenever your program compiles, and works better than the previous backup. The backups are just done by using the cp command in UNIX. % cp prog.c prog.back.1.c For example, this creates the first backup for prog.c. You might prefer to use dates, instead. % cp prog.c prog.2.2.2000.c Although I think just writing the version number (i.e., the first method described) is probably the better than using dates (since you might make two backups in one day, and there's a little less typing). Or, if you think of a better way to name backups, then use any scheme that makes sense to you.