Red Antigua Logo
Yet another piece of web.
Search this site (by Google)
Tools    (top)
Check a site for broken links
(W3C)

Perl modules    (top)
Tree::Numbered::Tools
(CPAN)
Perl tutorials    (top)
Perl modules
HTML::Template
CGI::Application
Cookies with CGI::Application
Upload files with CGI::Application
Download files with CGI::Application
Redirect with CGI::Application
CPAN shell
Install DBD::mysql from the CPAN shell
Perl trim function
Validate an IP with Perl
Run suid Perl scripts under Apache
Perl taint mode
Perl date functions with Date::Calc

In Spanish
Curso de Perl

C tutorials    (top)
C - Introduction
C - Absolute beginner's Emacs
C - Examples for beginners
C - Makefile examples
C - Autotools examples
Server configurations    (top)
DNS
Apache
Apache Authentication and Access Control
mod_perl on FreeBSD
MySQL
MySQL add account
phpMyAdmin
Squid
DHCP

UNIX on Windows    (top)
MSYS2 - UNIX environment for MS Windows 32/64 bits
Apache setup on Windows
MySQL setup on Windows
PHP setup on Windows
Perl setup on Windows
Emacs setup on Windows
PuTTY
WinSCP
GIMP on Windows
MinGW - gcc on Windows
MSYS - UNIX-styled shell on Windows
msysDTK - autotools on Windows
GDB for MinGW on Windows

Misc. FreeBSD/UNIX    (top)
'portupgrade' on FreeBSD
'ipf' on FreeBSD
'pf' on FreeBSD
'su' on FreeBSD
Mount an ISO image under FreeBSD
Load the correct sound driver under FreeBSD without knowing what sound card you are using
Simultaneous sound channels on FreeBSD
FreeBSD network stuff
DOS-to-UNIX file conversion
favicon.ico on UNIX
Emacs tips
Command Line Calculator
Save multimedia streams with 'mplayer'
xargs - solution to 'Argument list too long'
Process multiple images from the command line using 'ImageMagick'
Turn the system bell off under X Windows
Process each line in an input file from the command line (or in a shell script)
How to keep a program running in the background using 'nohup'
How to remove symbolic links in the current directory using 'find' and 'rm'
How to remove Emacs backup files in the current directory and all subdirectories using 'find' and 'rm'
How to execute .profile without logging in
Configure X to handle non-English characters
How to move /var to /usr/var

Redirect a web page    (top)
Redirect to another web page
Apache redirect
C redirect
Perl redirect
PHP redirect
HTML redirect
JavaScript redirect

Javascript    (top)
Trim function
Login form
Register form
Popup window

C - An absolute beginner's tutorial about editing C files with Emacs
C tutorials » An absolute beginner's tutorial about editing C files with Emacs

See also:
Emacs tips
Emacs setup on Windows

Install:  If you haven't installed Emacs yet:
FreeBSD:cd /usr/ports/editors/emacs && make install clean
Linux:Get a port/package corresponding to your Linux distribution, or compile and install Emacs from source.
Mac OSX:Get the Emacs binary from https://emacsformacosx.com/.
Windows:Read my tutorial about how to setup Emacs on Windows.
  1. Start Emacs
  2. Enable highlighting
  3. Open a file
  4. About cc-mode
  5. Copy, paste, edit, undo, select, indent, save
  6. C comments
  7. Moving around, more copy & paste, goto-line
  8. Search & replace
  9. Save As
  10. Exit Emacs
1. Start Emacs (up)
Start Emacs either by (double-)clicking its icon...
Emacs icon
...or from the command line:
$ emacs
Remember:
Wherever and whenever inside Emacs, if Emacs seems to hang, or if you got into the so-called "minibuffer" (see below) even if you didn't want to, you can always hold down CTRL and press g (that is C-g in Emacs terminology) as many times as you want.
CTRL-g is your panic button.
2. Enable highlighting (up)
Be sure the text will be color highlighted:
Go to the Options menu and check the three options Syntax Highlightning (if visible), Active Region Highlightning, and Paren Match Highlightning, if they aren't checked already.
Then click on Save Options.
Emacs - Save Options

3. Open a file (up)
Now, go to the File menu:
Emacs - File Menu
As you see, the keyboard shortcut for Open File is C-x C-f.
This is Emacs terminology for "holding down CTRL while pressing first x, then f".
For example, if you want to Exit Emacs, use the shortcut C-x C-c.
That is, "hold down CTRL while pressing first x, then c".

Now try to open a new file with the shortcut for Open File, which also is used for creating new files.
Have a look at the lower left corner (called "minibuffer" in Emacs terminology):
Emacs - Open File
Hold down CTRL, then press x, and you should see a C-x (for CTRL x):
Emacs - Open File - 2
Keep on holding down CTRL and press f, and you should see Emacs' default path (which may vary):
Emacs - Open File - 3
Let's create a new file called helloworld.c in your home path, which may be:
C:\Documents and Settings\Administrator\My Documents\
or
/home/me/
Use backspace to delete anything but C:\ or /.
Emacs - Open File - 4
Then type the one or two letters of your home path (in this case "Doc" as in "Documents", or "ho" as in "home").
Then use TAB to autocomplete the path to "C:/Documents and Settings/" or "/home/", respectively, type one or two more letters of your home path (in this case "Ad" as in "Administrator", or "m" as in "me"), another TAB to autocomplete, and so on, until your home path is complete.
(Note that on Windows, all \ are converted to /.)
Then type helloworld.c and press ENTER.
Emacs - Open File - 5
This opens the file if it exists, or, as in our case, creates a new file.
(It is actually not created on disk until you save it for the first time.)

(You may just click the File menu and then Open File..., which may seem to be an easier way to open/create a file.
Anyhow, when you get used to the keyboard shortcuts, you will see that this method is both easier and faster.)

4. About cc-mode (up)
You will now see in the minibuffer that Emacs loaded cc-mode.
Emacs - CC Mode - 1
This is done automatically when you open a file with a .c extension.
cc-mode customizes Emacs for C programming by adding syntax highlighting and indenting.
Syntax highlighting = different colors for different words in the C language.
Indenting = number of tabs/spaces depending on the nested level for a text line.
Besides, cc-mode adds an extra C menu:
Emacs - CC Mode - 2
cc-mode is called a major mode in Emacs terminology.
Another major mode is perl-mode, used for editing Perl files.
A document can only use one major mode at a time (it doesn't make sense to try to use C style and Perl style simultaneously).
FYI: There are also minor modes, which can be used simultaneously, and coexist with a major mode.
They can be seen as "extras" or "plugins".

5. Copy, paste, edit, undo, select, indent, save (up)
Now copy the following text; a horribly indented and not syntax highlighted C program:
                              #include <stdio.h>
/* Compile: cc -o helloworld helloworld.c */
               /* Run: ./helloworld */
  int
                    main() 
    {
             printf("Hello, world!\n");
return 0;
 }
Paste it into Emacs using the Edit menu (further on we will see another way to copy and paste text inside Emacs):
Emacs - Paste

As you will se, Emacs tries to syntax highlight but not to indent the program:
Emacs - Higlight Indent - 1

To indent the program line by line, move the cursor to the first row using the Arrow Up key.
Use TAB to indent a line, move down a line with Arrow Down, use TAB, and so on.
When you come to the last line you will have a perfectly syntax highlighted and indented program:
Emacs - Higlight Indent - 2

Emacs remembers and can undo all modifications done to a document since it was opened.
You can use Edit->Undo, or you can use the shortcut C-_, that is CTRL + Underscore.
On my keyboard, I get Underscore by typing SHIFT + - (Minus sign).
So to Undo in Emacs, I have to hold down CTRL and SHIFT simultaneously, and then press -.

We will now learn how to indent the whole document without TABbingthrough all lines (which can be tedious if your program consists of several hundred lines of code).
Press Undo until you get the unindented version of your C program again.
Press C-x h, that is, hold down CTRL while pressing down x, release CTRL and press h, to select all text:
Emacs - Higlight Indent - 3
(A selection of text is called a Region in Emacs terminology.)
Then go to the C menu and click Indent Line or Region to indent the whole program:
Emacs - Higlight Indent - 4
Save your indented program: C-x C-s (hold CTRL while pressing first x, then s).

6. C comments (up)
Now use the Arrow keys to move the cursor to the letter w in world!.
Delete world, either letter by letter with C-d (hold CTRL, press d) or deleting the whole word with M-d (hold Alt, press d).
Then type in your name instead:
Emacs - C Comments - 1
Move the cursor to the position just after the opening bracket { and press ENTER to insert a line.
Type I changed the following line. and press C-SPC (hold CTRL while pressing SPACE).
This is called to "set mark". Any cursor movement will now create a Region (selection).
Move to the beginning of the line, either step by step with the Left Arrow key, or in one keystroke with C-a (hold CTRL, press a). The line is now selected.
Emacs - C Comments - 2
Press C-c C-c to convert the line to a C comment, and then TAB to indent it correctly.
You just created your first indented C comment!
Emacs - C Comments - 3
Use the arrow keys to place the cursor in the first position of line with the printf statement.
Cut the whole line with C-k (hold CTRL, press k) and paste it at the same place with C-y (hold CTRL, press y).
Why do this? Well, it is an alternative to copy one line, instead of select the line as a region, and then copy the region.
Now you can paste the line wherever you want repeating C-y. Press ENTER and then C-y to paste a copy of the previous line:
Emacs - C Comments - 4
Replace the second Hello, Johan! with DEBUG: This is a debug message.:
Emacs - C Comments - 5
Sometimes you want to comment out lines like debug messages, and uncomment them later.
Place the cursor on the debug line, on the p in printf.
"Set mark" (as we did before) with C-SPC and go to the end of the line with C-e:
Emacs - C Comments - 6
Comment the line (as we did before) with C-c C-c.
Emacs - C Comments - 7
Move to the beginning of the line with C-a, "set mark" with C-SPC and move the cursor down one line with Arrow Down. The commented line is now selected.
Emacs - C Comments - 8
Press C-u C-c C-c (yes, that is holding CTRL while pressing u, then c, then c again).
Try to remember the first u keystroke as"undo", then it makes more sense, like "undo" C-c C-c (comment).
Emacs - C Comments - 9
Just to practice, comment out the the debug line again, and save the document with C-x C-s.

7. Moving around, more copy & paste, goto-line (up)
To move the cursor to the beginning of the document in one keystroke, use M-< (hold ALT, press <).
To move the cursor to the end of the document in one keystroke, use M-> (hold ALT, press >).
(You may have to press SHIFT on your keyboard to get < and/or >.)
To move the cursor to the beginning of a line, use C-a.
To move the cursor to the end of a line, use C-e.
(We already tried that, remember?.)
There are two similar keystrokes, useful in C:
To move the cursor to the beginning of a C function, use C-M-a (hold CTRL and Alt simultaneously, press a).
To move the cursor to the end of a C function, use C-M-e (hold CTRL and Alt simultaneously, press e).

Let's try to move the cursor to the beginning of our only function main():
First go to the end of the document with M->.
We must do this, as moving to the beginning of a function/line always means moving backwards.
Then use C-M-a to go to the beginning of the function main.
Actually, the cursor is place on the function's first opening bracket {, so use the arrows keys to move the cursor to the i in int, "set mark" with C-SPC and go to the end of the function with C-M-e:
Emacs - Moving Around
Copy the Region (selected area) with M-w (hold Alt, press w).
Paste it 9 times, so you get 10 identical main() functions in your program.
To paste, use C-y 9 times (hold CTRL, press y 9 times).
Now, with several functions in one file, it is easier to see the usefulness of C-M-a and C-M-e.
Be sure you are at the document, and then hit C-M-a 10 times. You can see how you traverse the C functions one by one (even if they all are called main() at the moment).

Another very useful command for C programmers is M-x goto-line.
(Hold Alt, press x, release Alt, type "goto-line", press ENTER.)
The text Goto line: appears. Enter a line number, and the cursor will go there.
There is also a shortcut for this command, M-g g.
(Hold Alt, press g, release Alt, press g again, press ENTER.)
Warning and error messages from the C compiler often refers to a line number in the C source code.
Here is where the goto-line becomes powerful. No need to search for the error line manually...

8. Search & replace (up)
Search
To make a simple search, use C-s (hold CTRL, press s).
The cursor moves to the first match as you type, and other visible strings that match are highlighted.
Press C-s again to go to the next matching string.
Use C-r to search backwards.
Search & Replace
Now let's try some search & replace:
Be sure the cursor is somewhere between the first main() function and the second one.
Hit M-% (Hold Alt, press SHIFT+%) (I have to press SHIFT to get % on my keyboard, maybe you haven't to).
You should be asked for input in the minibuffer:
Emacs - Search & Replace - 1
Type main() and press ENTER:
Emacs - Search & Replace - 2
Type xxx() and press ENTER:
Emacs - Search & Replace - 3
The second main() is highlighted and you are now asked if you want to replace this match or not.
You can answer y (yes), n (no), or ! (all).
Or you can simply move the cursor in any direction to forget about it all.
The search & replace always starts from the cursor, so if you are at the end of a document, you will never replace anything.
Let's press !. All occurences (starting from the cursor) of main() will be replaces with xxx().
Go to the beginning of the document (M-<) and do another search & replace using M-%:
Query replace:
Type xxx() and press ENTER:
Query replace xxx() with:
Type yyy() and press ENTER:
Press n every second time, and y every second time, to replace every second occurence of xxx() with yyy():
Emacs - Search & Replace - 4
9. Save As (up)
Use C-x C-w (hold CTRL, press x, then w) to save a document with another name.
Type a filename, for example helloxxx.c, and press ENTER:
Emacs - Save As
10. Exit Emacs (up)
Use C-x C-c (hold CTRL, press x, then c) to exit Emacs.
If there are some unsaved documents, you will be asked if you want to save them before Emacs closes.

Links
This is definitely not a complete tutorial, just a way to make it a bit easier to start using Emacs for the very beginner.
Practicing by yourself is of course the best way to learn more.
To find out more, the are lots of manuals, references, guides and tutorials.
The links below are just a few:

Emacs Beginner's HOWTO
GNU Emacs Tutorial (from 1997, but still with valuable info)
A Emacs+Lisp Tutorial (basics, intermediate, and advanced tips, among other things)
Emacs tips (this site)
Emacs on Windows (this site)
Emacs refcard (PDF)
Emacs tour
Emacs manual (extensive reading)

Last modified: Thu Sep 8 06:15:35 EDT 2016