Table of Contents

Emacs Exercises
1.0 Emacs introduction
2.0 Exercises
3.0 Getting help
4.0 Advanced Exercises
5.0 Appendix - Emacs configuration examples

Emacs Exercises


1.0 Emacs introduction

1.1 Articles

An interesting article describing modern IDE's (Eclipse, Jbuilder etc.) in respect to Open Source arternatives VIM/Emacs from a developer's perspective: The Case for Emacs by Derek Slager. An exerpt:

I remember the first time I witnessed ... furious coding session ... Watching him operate his editor was truly an experience. He was working at a pace I'd never seen before, his cursor flying around the buffer like a pinball ... I rudely interrupted his session ... He walked me through the code he was working on, and the artistry continued – he seemed able to will his cursor around the buffer with the power of his stare, as if he was simply "thinking it" there. I'd never seen anything like it – he wasn't using his editor – he was his editor.

1.2 Emacs window layout

Emacs is multi platform (Windows/Linux/Unix etc.) "The Editor" which is quite a bit more than just a regular text editor. It is in fact a complete development environment, where you can edit several programming language files at one (C++ / Java / DOS *.bat / HTML / XML / PHP / Perl / Python ...). In addition you can list and manipulate directories, run shell commands, send mail, read network news, open SSH connections, compile files and use it as a terminal to several SQL databases. Emacs is more like a mini-operating system. The language to program Emacs itself is Emacs-Lisp, a variant of Common Lisp. There are several plug-in modules (*.el files) in the Internet that can be used to extend Emacs. The homepage of Windows version of Emacs is at http://www.gnu.org/software/emacs/windows/ntemacs.html

[Picture 1.  pic/emacs-layout.jpg]
Picture 1. Basic Emacs opening frame layout

1.3 Editing commands (keyboard)

There is also keyboard commands, where "M" means "Meta", which can be key ESC or Alt, depending on the environment or terminal capabilities. Note: The Windows keys C-c (copy) C-x (cut) and C-v (paste) DO NOT WORK inside Emacs,. because they have a different meaning.


2.0 Exercises

Note: In each exercise, explain the keyboard commands and possible typed text on prompts to solve the exercises.

2.1 The basic commands (E1)

1. Explain what are the basic parts in the Emacs program and what information is displayed (See picture at the beginning of this document).

2. How do you kill Emacs? Do not use the window's right hand corner to close Emacs, but report the key combination which exits Emacs.

3. Explain what are the following leftmost indicators in modeline. Refer to picture of the program at the beginning of this document.

      --         <User can affect this>
      **         <User can affect this>
      %%         <Emacs sets this indicator; Try C-h i>    

4. In modeline, what is the purpose of the middle indicator in parentheses. E.g. at program start the scratch buffer reads (Lisp interaction) while at opening a *.txt file (C-x C-f; Menu: [File > Open]), the buffer reads (Text).

5. Explain what do the following commands mean in Emacs. E.g. put cursor at the beginning of text in scratch buffer. Make sure there are some text; write few lines if necessary.

      C-n
      C-p
      M-b
      M-f    

6. You got Emacs in some weird situation and mistankenly pressed key sequence C-x C-f. You do not want to continue. How do you cancel the current action? Is there anything special that should be remembered with the use of cancel key?

7. Emacs is an Open Source program which supports plug-in module extension. There are thousands of additional packages available that provide additional features. Many of the commands do not fit in the menus. If the name of the command is known, it can be called. Below you find couple of examples. Explain how do you run these commands and what happened.

      M-x calendar
      M-x tetris
      M-x irc    

Note: you can close any active buffer (where cursor is), like the tetris, by using key C-x k.

2.2 Editing (E2)

Note: To select region, the starting point is marked with command C-SPC (Control + space-key) followed by cursor movement to the end point of region.

1. How do you kill the current line?

2. How do you kill a word?

3. How do you kill region of selected text?

4. How do you empty a buffer? That is, how to delete all text from buffer? (Hint: whole buffer can be treated to be a region).

2.3 Undo (E3)

Note: In Emacs parlance the word "kill" is many times used as synonym for "delete".

1. Oops, you made a mistake and deleted text that was not intended to! Where is the Emacs undo command?

2. Kill lines 1 and 3 and 5. How do you get them back?

      1. First line
      2. Second line
      3. Third line
      4. Fourth line
      5. Fifth line    

3. Does undo work in all buffers? What if you run command C-x C-f , write filename, kill some text and hit undo?

2.4 Files (E4)

Note: The tilde(~) character refers to your HOME directory.

1. Open any file. How do you remove that file from Emacs, so that it does not show up Menu: Buffers => List all buffers. (Hint: a file is just like another buffer, which can be killed).

2. Open three files, say ~/test-name1.txt, ~/test-name2.txt and ~/test-name3.txt into Emacs. Do you have to clear the line in minibuffer prompt before typing the filenames? (Hint: see what happens if you write ~/test-name1.txt/~/ and press the TAB key).

Complete exercise by writing two lines of text to each of these files and save them to disk before moving to next exercises.

3. Activate file prompt with C-x C-f. What happens if you press TAB multiple times?

      Find file: ~/tes[keep pressing TAB]    

4. Make sure you have loaded or created at least three files with C-x C-f or Menu [File => Open File]. Next recall file prompt with C-x C-f. What happens when you press M-n and M-p at the minibuffer prompt?

5. Emacs includes a "directory browser" called dired. How do you run this dired and select files from it? Exit and start Emacs and launch dired at your HOME directory ~. How do you open files ~/test-name1.txt, ~/test-name2.txt and ~/test-name3.txt using the dired buffer? Are there multiple ways to select these files?

2.5 Searching (E5)

Note: to stop the search mode, press RET or move cursor.

1. How is the Emacs search command different from what you have gotten used to? Do you think this is harder or easier, limited or powerful way to search something?

2. What does key C-w do when you press it immediately after C-s? (Hint: place cursor at the beginning of word before you press C-s followed by C-w. You can repeat C-w.)

3. You can search immediately with C-s followed by letters to search, but what's the purpose of C-s RET key combination?

4. The search command in Emacs is a mode, which can be started forward with C-s and backward (reverse) with C-r. Call the key help listing by pressing C-h k C-s. Can you see any useful commands or key bindings?

2.6 Replacing (E6)

1. Suppose you want to "replace" something, but you have forgotten what was the keyboard key to access this commands. How do you find which key runs that command? How many steps you needed to find this information? (Hint: list all Emacs key bindings with C-h b and search with C-s for word "replace")

2. Explain what these keys do during replace: !, BACKSPACE and SPACE

3. How do you quit the replace mode?

2.7 Windows (E7)

1. Arrange your current workspace so that you have TWO windows open. Have one window show file test1.txt and the other one show file test2.txt What commands did you use?

      +-------------------------+ test1.txt
      |                         |
      |                         |
      +-------------------------+ test2.txt
      |                         |
      |                         |
      +-------------------------+    

2. Reverse the view. Have test2.txt first and below test1.txt. What commands did you use?

      +-------------------------+ test2.txt
      |                         | << Order is different >>
      |                         |
      +-------------------------+ test1.txt
      |                         |
      |                         |
      +-------------------------+    

3. What is the difference between these keystrokes? Can you find any use for very seldom used key binding C-x 3 ?

      C-x 0   <This is number "zero", not a character "o" >
      C-x 1
      C-x 2
      C-x 3    

3.0 Getting help

3.1 The help system and other commands (E10)

1. When starting the help system with a prefix key, the prompt keeps asking for more detailed selection. Pick 3 help key selections that you think would be the most used and useful ones (hint: see C-h ?) and explain what they do.

      C-h ...  (selection one)
      C-h ...  (selection two)
      C-h ...  (selection three)    

2. The help system can be used in two ways. Try following commands. What's the difference between these? What does the first do? And the second?

      C-h k C-k       WAY 1, started with C-h
      C-x 5 C-h       WAY 2, ended to C-h    

3. The current buffer is always in a certain mode that is mentioned in parentheses in the modeline. Take for example the buffer listing (Menu: Buffer => List all buffers): what 3 interesting commands you can see in that mode? Describe each command and what it does.

      C-x C-b    

4. There are many commands that are not listed in menus or bound to any keys, but they can be accessed via M-x key. Explain shortly what the following commands do:

      M-x tabify      1) have some *.txt file in you buffer
                      2) select region or whole buffer
                      3) try command

      M-x untabify    1) have some *.txt file in you buffer
                      2) select region or whole buffer
                      3) try command    

5. Open some text file and examine following command. What does it do and how do you exit it. Can you find use for it?

      M-x hexl-mode    

3.2 The INFO system (E11)

You can use tutorial to learn to use the info system by going through C-h t. Use mouse-2 or RET to navigate between links.

1. Emacs includes a text based help system, which is called info pages. The main entry is at key combination C-h i. When you access the page, the mode-line reads:

          Info: dir(top) (Info Narrow)    

The above says that the file displayed is the central "dir" and the MAJOR mode of the buffer is "Info" and one MINOR mode "Narrow" is also active.

How do find a section from Emacs manual (C-h i => Emacs) which talks about file backups?

2. Emacs manual pages are stored on *.info files. When the manuals are visited, a Info-mode is turned on. The mode contains special key binding that help to navigate between the info nodes. One such key is s. What does it do? Give an example how do you use it.

3. Emacs generates many files to the save directory. Can you find an explanation why these files are created? To demontrate: 1) Open any file 2) type some characters 3) save file 4) next type at least 300 new characters - several lines of text 5) and look at the directory listing which should show:

      test.txt
      test.txt~
      #test.txt#    

Hint: you can find the information from the emacs INFO pages C-h i => Emacs (press RET at the line) and by searching with s for words auto save files. You can go to the top of directory with d and start search again with s. Try also searching words backup files.


4.0 Advanced Exercises

4.1 Running Shell (E21)

1. How do you run shell buffer from inside Emacs?

2. Can you think of a reason why Emacs shell would be better than using a standard shell terminal (e.g. Putty)?

3. In shell buffer's command prompt, you can use M-n and M-p keys. What do they do?

4. You can run multiple shell sessions inside Emacs, by renaming the buffer. The M-x shell command always creates a buffer shell and jumps to existing shell, if there already is one. Do the following command sequences work as expected to create multiple shell buffers? Explain what happened.

      M-x shell       Creates *shell* buffer
      M-x shell       Already shell, so jumps to *shell* buffer

      M-x rename-buffer RET shell-1 RET     Give it a new name

      M-x shell       Now creates second *shell* buffer
      M-x rename-buffer RET shell-2 RET     Give it a new name    

5. Why would you need two or more shell buffers?

6. The shell buffer is also a mode in Emacs. List 5 key bindings that could be useful in shell-mode? (Hint: mode help command)

4.2 Running compile (E24)

Note: To "compile" something in Emacs, is actually a general method for launching any external process. This makes it possible to call Java, C++, Perl, run XML parser etc.

1. Emacs can launch separate processes via the M-x compile command. E.g. to run programming language compiler, try following command and report what it does.

      M-x compile RET
      Compile: java -version RET    

2. One external command in Unix operating system (also available in Cygwin) is grep, which can search files. Suppose you have some some files in your home directory and you don't remember where particular information is. What could you do with function grep in Emacs? The name of the function happens to be the same as the running program in this case. Explain how do you search your *.txt files with following command (make sure you create those files first):

      M-x grep RET
      Run Grep: grep -n "a" ~/*.txt RET    

Note: Emacs also has dedicated command for this: M-x grep and recursive version M-x grep-find.

4.3 Configuring Emacs add-on packages (E26)

Additional Emacs add-on packages are available from Internet. There are active developer community which increase the spectrum of features and programming language support that may not be yet part of the standard Emacs. These features are sipped as Emacs Lisp files (*.el).

1. Where can user install his own personal Emacs packages? Explain what directory (or directories) must be created.

2. Explain how to tell Emacs where it can find new packages?

3. Install some add-on package. How do you download package X from http://www.emacswiki.org and activate it in Emacs startup file ~/.emacs ?


5.0 Appendix - Emacs configuration examples

[Picture 2.  pic/emacs-config.jpg]
Picture 2. The basic Emacs installation does not have many features active. User must activate each feature, like the colors by adding a line to startup file. Additional Emacs (*.el) packages can be easily installed to user's personal Emacs lisp (~/elisp) directory.

5.1 The HOME environment variable

Personal setting for Emacs are done in lisp language and stored in a configuration file named ~/.emacs. In Windows operating system the HOME environment variable does not exist and it must be created. In new Windows versions, you have open the control panel and add value there:

      Control Panel => System => Environment    

Wherever you point the HOME, remember to create the directory as well. An example:

      HOME   => c:\home    

Emacs substituted the value of tilde(~) with the content of the HOME:

      C-x C-f ~/txt/test.txt
              |
              |
              This tilde(~) is same as your HOME directory    

5.2 Changing Emacs configuration (dot-emacs)

The configuration file is directly located under your HOME in a file called dot-emacs (~/.emacs). The file is created by user. All Emacs customizations are stored to this file and written in dialect of lisp language.

      C-x C-f ~/.emacs    

Edit the configuration file and add any needed calls. Use pair of semicolons ;; as comment markers. Here are few configuration examples:

      ;; ~/.emacs -- personal Emacs configuration file

      (setq mouse-yank-at-point     t)  ;do not track mouse movement
      (setq query-replace-highlight t)  ;highlight during replace
      (setq search-highlight        t)  ;show colors
      (setq mark-even-if-inactive   t)  ;show regions
      (setq sentence-end-double-space nil) ;fix M-q to right fill
      (setq auto-save-interval     100) ;default is 300 characters

      ;; End of file    

Save settings and reload file with:

      M-x load-file RET ~/.emacs RET    

The syntax of setting a variable in lisp is explained below. In Emacs Lisp, everything must be put inside parenthesis, just the opposite of the other programming languages:

      (setq auto-save-interval 100)
       |    |                  |
       |    |                  The value for the variable: numeric
       |    The Emacs variable name
       |
       lisp way of saying "set variable's value"    

It is possible to define custom key bindings:

      ;;  Define f5 key to run command "kill-buffer"
      ;;  Notice lowercase "f5", not "F5".

      (global-set-key (kbd "<f5>") 'kill-buffer)    

Is is possible to define own commands and bind them to keys. User commands can be bound to C-c prefix.

      (global-set-key (kbd "C-c c") 'my-copy-all)

      (defun my-copy-all ()
        (interactive)    ;; Make function a user callable command
        (kill-ring-save (point-min) (point-max))
        (message "My: buffer copied."))    

5.3 Windows style line endings (DOS support)

By default Emacs uses line endings that are suitable for current environment. There are two characters (see ASCII table 1 and 2) at the end of line that differ from operating system to another

      \r\n        windows
      \n          Unix / Linux    

Due to this, if a file is saved in Unix and later read to a Windows program, like notepad, the file content looks like a one big line. In Windows, it's best to use wordpad which can read different end-of-file conventiosn. In Emacs, is possible to change the line ending type of the current working buffer with commands:

      C-x RET f  undecided-dos  RET       => \r\n
      C-x RET f  undecided-unix RET       => \n    

5.4 Finnish language support

To use Emacs with European characters and add these lines to the ~/.emacs startup file:

      (set-language-environment "UTF-8")    

5.5 Mail support

Emacs supports sending mail with C-x m. Normally nothing is needed to configure, but if you need to tell the NNTP (news) and SMTP (mail) servers, following settings are added to startup file:

      (setq user-full-name    "Foo Bar")
      (setq user-mail-address "foo@example.com")

      ;;  These two lines are specific to sites where you
      ;;  run Emacs. You must know the server names
      ;;
      ;;  !! CHANGE TO REFLECT YOUR HOST NAMES !!

      (setenv "NNTPSERVER" "news.example.com")
      (setenv "SMTPSERVER" "mail.example.com")

      (require 'smtpmail)
      (setq smtpmail-debug-info t)

      (setq message-send-mail-function     'smtpmail-send-it)
      (setq gnus-agent-send-mail-function  'smtpmail-send-it)
      (setq send-mail-function             'smtpmail-send-it)

      (setq  mail-user-agent               'mal-user-agent)    

5.6 Programming mode templates

To use automatic templates for programming modes, it is possible to use package autoinsert.el. You must naturally create the template files mentined below by yourself for each programming language; also indicated by the file extension. Here the template directory has been set to ~/template/ – trailing slash is required for this variable.

      (autoload 'auto-insert "autoinsert")
      (add-hook 'find-file-not-found-hooks 'auto-insert)
      (setq auto-insert-query nil)
      (setq auto-insert-directory "~/template/")

      (setq auto-insert-alist
        '(("\\.sh$"       . "template.sh")
          ("\\.pl$"       . "template.pl")
          ("\\.cc$"       . "template.cc")
          ("\\.php$"      . "template.php")
          ("\\.java$"     . "template.java")))    

5.7 Perl coding settings

There are two perl coding packages available for Emacs: the first version is called perl-mode.el and the improved version is in package cperl-mode.el, made by one of the Perl developers (Ilya Zakharevich). You should use M-x cperl-mode for coding the Perl files. The default settings are for "brace-at-the-end" style and here are settings for "brace-at-separate-line" style:

      (add-hook 'cperl-mode-hook 'my-cperl-mode-hook)

      (defun my-cperl-mode-hook ()
        "My Personal CPERL settings."
        ;;   See also `cperl-close-paren-offset'
        ;;   and `cperl-autoindent-on-semi'
        (setq cperl-brace-offset                0)
        (setq cperl-brace-imaginary-offset      0)
        (setq cperl-continued-brace-offset      0)
        (setq cperl-continued-statement-offset  0)
        (setq cperl-label-offset                0)
        (setq cperl-extra-newline-before-brace  t)
        (setq cperl-hairy                       t))    

5.8 Making backspace key work on terminal sessions

When connected through remote session to another host e.g. with ssh or putty, it must be remembered that the only thing that the connection accepts is ascii-code characters. One problematic key is BACKSPACE. If the key does not work as expected, run command:

      M-x normal-erase-is-backspace-mode    

5.9 Using additional features and packages

Emacs includes many additional packages and libraries which can provide features to programming languages like Java and Perl. The packages have some defaults, but usually you may want to change the settings in order to use their features.

An example: if you prefer the windows style "select region and replace it immediately when typing text" the feature is turned on using commands:

      ;;  load a package/library (included in core Emacs)
      (load "delsel" 'noerr)
                     |
                     Ignore errors, e.g. if package was not found

      ;;  Activate "feature"
      (if (fboundp 'delete-selection-mode)
          (delete-selection-mode 1))    

One useful key binding than can complete the filename in any buffer. This command is called comint-dynamic-complete-filename and it not bound to a key by default. If following code were added to Emacs startup file ~/.emacs, it would be possible to complete filenames everywhere by pressing M-SPACE (Alt-Space or Esc + Space).

      (autoload 'comint-dynamic-complete-filename "comint" t)
      (global-set-key (kbd "M-SPC") 'comint-dynamic-complete-filename)    

5.10 Installing add-on packages

There are several plug-in modules (*.el files) in the Internet that can be used to extend Emacs. The installation in a nutshell is same whether the package consists of one or multiple files:

An example. Let's install up to date Python programming language mode for Emacs:

      (autoload 'python-mode "python-mode" "Python Mode." t)
      (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
      (add-to-list 'interpreter-mode-alist '("python" . python-mode))    

The new settings become active after next Emacs reboot, or after forcing to reload the startup file with command:

      M-x load-file RET ~/.emacs RET