Showing posts with label background. Show all posts
Showing posts with label background. Show all posts

prefix arguments

You can jump to the next line in emacs with C-n ('next-line'). However, how can we specify that we want to jump to the nth next (or previous) line? Or, more in general, how can we specify a (numerical) argument to an interactive function that support them?

The answer is that you can provide prefix-arguments to such functions; this can be done in two ways:


  • positive numeric arguments can be specified with M-<number>; that is, to use 5 as the prefix argument, you'd type M-5;
  • any numeric argument can be specified using C-u; so to set -3 as the prefix argument, you'd type C-u -3. Some functions also take C-u as a kind of boolean parameter; you set the parameter by specifying C-u without any parameter.

Using this, we can jump to the fifth next line with M-5 C-n, and to the third previous line with C-u -3 C-n. For details, see the emacs manual, and the documentation for the specific function (use M-x describe-function or C-h f).

Note: after ten years of using emacs, I discovered the M-<number> notation only when writing this entry...

installing packages

One of the great things about emacs is the availability of external packages. Whatever you want to do with emacs, there is a good chance that someone already solved the problem, and made a package out of it. Emacs comes with many packages, but there are still many more that it does not include. In the entry about modes, we already looked at various file-type specific packages that are available for emacs. Howeve, we did not discuss how to install external packages/modes. So, how does one install an external package? Assuming, of course, that you know what package you would like to install. This blog tries to help with helping you to identify useful ones.

The first step is, not surprisingy, to get the external package. Linux distributions like Fedora and Debian/Ubuntu have many of them pre-packaged, that is, you can get them from their repositories. This is often the easiest way to get the packages, so it's good to first check if your distribution offers the package. For example, in Debian/Ubuntu, there's emacs-goodies-el which includes a lot of useful things.

If your distribution does not include the desired package, there are some different options:


  • First, your emacs might include some kind of automatic package retrieval system; XEmacs does, and for GNU/Emacs there is ELPA. I have not used it, so I won't go into that here.
  • Second, there are bigger packages that come with their own installation procedure, documentation etc., and which are usually shipped as .tar.gz-files. An example of this is the VM (ViewMail) package, which provides an email client for Emacs. It comes with documentation and installation instructions. Another one is magit, for using the git with emacs. Magit is (at this moment) only available by getting it from its repository, but the same rule applies: just follow the installation instructions.
  • Finally, there are many single .el-files that you can find, for example, in the Emacs Lisp List. You can download such a file, and put in some directory where emacs can find it. I made a directory ~/.elisp/ for this. And at the top of my .emacs, there is something like:
    ;; my elisp directories
    (defvar elisp-path '("~/.elisp/" "~/.another-path"))
    (mapcar '(lambda(p) (add-to-list 'load-path p)) elisp-path)

    This code creates a variable elisp-path with some directories, and uses mapcar to add each of them to load-path, which is the variable that emacs uses to determine where it can find packages. Emacs actually adds a lot of directories to load-path already before considering your .emacs; you can see the full load-path with describe-variable, or C-h v.

Now, in order to actually use a package, we have to ask for it in our .emacs. There are various ways:


  • Frequently, you need to require such a package, say:
    (require 'magit)

    This will load the package. Emacs will give an error if it cannot find the package (i.e., if it cannot find (provide 'magit) in the package), so if you are using your .emacs in different places, you might want to use the require-maybe function.
  • Another way is to use autoload. The idea is that we define a function, and the package is not loaded until we actually call that function. This can be helpful to speed up loading your emacs, and save some memory: we will only load packages that we actually use, and not before we need it. A useful pattern here is to use autoload together with auto-mode-alist:
    ;; post mode (used when editing mail / news)
    (autoload 'post-mode "post" "mode for e-mail" t)
    (add-to-list 'auto-mode-alist
    '("\\.*mutt-*\\|.article\\|\\.followup"
    . post-mode))

    This does two things: first, we use autoload to define a function post-mode; if this function is called, it will load "post", which contains the real definition of that function. Second, we use auto-mode-alist to tell emacs that whenever we open a file which name matches some pattern, call the function post-mode.

modes

Emacs has special modes for many different types of files; a mode might colorize the file in some useful way, or add some functions or keybindings to easily manipulate them. Each buffer has one specific mode called the major mode. In addition, each buffer can have multiple minor modes, which enhance the major mode in some way. You can get information about the major and minor modes for the current buffer with M-x describe-mode or C-h m.

As a practical example, let's look at text files. Text files are (by default) opened in text-mode; we can add some useful minor modes to that, by using a hook in your .emacs:

(add-hook 'text-mode-hook
(lambda()
(blink-cursor-mode -1) ; don't blink the cursor
(set-fill-column 78) ; buffer-local variable; wrap at col 78
(auto-fill-mode t))) ; wrap around automagically

This will activate two minor modes when we use text-mode. First, we turn off cursor blinking with (blink-cursor-mode -1) (because, obviously, we don't want a blinking cursor when editing text files...). Second, it activates auto-fill-mode, a minor mode that makes emacs automatically wrap long lines ('filling' is emacs terminology for wrapping). Neither of these two minor modes is specific for text-mode, and can be used with other modes as well.

Emacs recognizes many files already, but sometimes, you need to tell it to use some specific mode for a file. To do this, there is auto-mode-alist. Suppose, we want to use text-mode for all files with extension .foo or .bar; we add to our .emacs:

(add-to-list 'auto-mode-alist
'("\\.foo$\\|.bar$" . text-mode))

Now, whenever we open a file which matches that pattern (ends in .foo or .bar, text-mode will be activated. Please refer to the emacs documentation for details on the regular expression (the "\\.foo$\\|.bar$" pattern).

Some final notes:


  • For more information on installing modes (and other packages), see the installing packages-entry;
  • with some tricks you can actually have multiple major modes in a buffer at the same time; this can be useful for example when editing web documents that contain HTML and Javascript; see MultipleModes. It can be a bit tricky to set up though;
  • not all modes are buffer-specific; for example tool-bar-mode and menu-bar-mode (which determine whether your emacs window has a toolbar, menubar, respectively) are global for your emacs-session;
  • an interesting question is "where do I find interesting modes?"; well, you can search the Emacs documentation, or look through the Emacs Lisp List. And of course in this blog I am trying to show which ones I found particularly useful.

emacs terminology

The first emacs versions appeared in 1976, in a world quite different from the current, in particular when it comes to computing. For this reason, emacs uses a lot of terminology that is a bit foreign for people who learned computers in later years. This presents a challenge when trying emacs itself, or its extensive documentation. Here, I try to list the emacs terminology and the 'translation' in current computer terms. I expect to be continually updating this.

As with much of what is in this blog, for just about everything a footnote could be added with some exception/alternative explanation/..., but I will resist the urge to do so.

The following picture shows some of the important concepts to keep in mind... especially when reading emacs documentation. Of course, many of the visual details depend on your color settings, operating system, emacs-version and so on...

The following table is another way to help you understand the emacs jargon:


















emacs terminology common terminology
bufferdocument/workspace
evaluate expressionsinterpret/execute some code
font lockingsyntax highlighting
fillingline wrapping
framewindow
killcut
markbeginning of the selected area
mode linestatus bar
pointcursor position
regionselected area; the area between 'mark' and 'point'
visit a fileopen a file
windowwindow pane
yankpaste

hooks

When customizing emacs, often you might want to do something when some event occurs. For example, in the automatic timestamps entry, we used
(add-hook 'write-file-hooks 'time-stamp) ; update when saving
to automatically update the file timestamp whenever we save the file.

The mechanism (as the example suggests) is called a hook: you can add a 'hook-function' for some event, and it will be called if the event takes place. This turns out to be very useful. It is a very common way to customize emacs when some specific mode (there is also an entry about modes) is activated. For example, I like to have some specific settings when I am using text-mode, which is the mode for normal text files, and can add the following to .emacs:

(defun djcb-text-mode-hook ()
(set-fill-column 79) ; lines are 79 chars long ...
(auto-fill-mode t) ; ... and wrapped around automagically
(set-input-method "latin-1-prefix") ; make " + e => &euml; etc.
and
(add-hook 'text-mode-hook 'djcb-text-mode-hook)
Note, in the example we define a new function djcb-text-mode-hook; however, you can also define the function in-line in add-hook; such a nameless function is called a lambda-function. Using a lambda-function, we could also write the above example as:
(add-hook 'text-mode-hook
(lambda()
(set-fill-column 79) ; lines are 79 chars long ...
(auto-fill-mode t) ; ... and wrapped around automagically
(set-input-method "latin-1-prefix"))) ; make " + e => &euml; etc.
These things are equivalent; the only difference is that you could use djcb-text-mode-hook elsewhere as well, because we can refer to it by its name.

You can call add-hook multiple times for some event (hook); when the event occurs, the hook will be called in reverse order of adding them. It's best not to depend on that, as the emacs manual explains.

You should be able to find the hooks that some package provides from its documentation; just search for 'hook'...

.emacs

Many programs have start-up settings, which they read from a configuration file or from some database. Emacs is no exception: when it starts, it reads a file called ".emacs" from your home directory. However, the big difference is that .emacs does not consists of simple "key=value"-pairs. Instead, your .emacs is an Emacs-Lisp (elisp) program itself. At startup, Emacs interprets ('evaluates') your .emacs, and, hopefully, give you the desired results. One of the goals of this blog is to show you how.

Through .emacs, you have an almost unlimited power to make emacs do what you want. You can change the colors or the keybindings, but you can also make much deeper changes. And you can make it depend on the phase of the moon, if you want.

The flip side of all this power is that editing your .emacs is a bit harder than clicking through some 'Preferences'-dialog; this is a price that the typical emacs user gladly pays, but it does make learning emacs a bit harder. I should mention that actually, there is a way to configure emacs by clicking through some dialogs; go to Options/Customize Emacs. I find the system a bit clunky, and I don't use it; but you can give it a try. Any customizations you do that way will be written to the end of your .emacs-file.

Let's look at writing a simple .emacs by hand. It could look something like this:


;; a simple .emacs

;; don't show startup messages
(setq inhibit-startup-message t)
(setq inhibit-startup-echo-area-message t)

(column-number-mode t) ; show column numbers
This sets two variables (with 'setq') to true (t), and activates 'column-number-mode' (also, see modes), which gives you the column number in the mode-line (the information bar in the bottom of your emacs window). Everything on a line after a ';'-character is considered a comment.

NOTE: you are not required to have a .emacs-file at all; if you don't have one, emacs will start with its defaults. In fact, it's a good idea to start with an empty .emacs, and add things as you go -- if you don't like some default, or want to things in a different way.

If you made some error in your .emacs, emacs might complain. To find the exact problem, it can be useful to start emacs as:

  $ emacs --debug-init
Also, it might be useful to start without evaluating your .emacs:
  $ emacs -q
You could also try an alternative .emacs to test things out:
  $ emacs -q -l dot-emacs-2

(in this last example you would have an alternative .emacs in a file called dot-emacs-2).

Many of the tricks and tips discussed here in emacs-fu are about adding lisp-expressions to your .emacs-file, which will then influence the behaviour of emacs in some way - maybe some external package is loaded, some keybinding is set up, some color is changed, and so on. You can find many .emacs-files used by other people on-line (mine is here). However, as I've written elsewhere, I do not recommend you to copy large parts of people's .emacs without understanding what it does. It easily leads to a strange-behaving emacs, with no idea how to fix it.

binding keys

In quite some of the blog entries we define key bindings (or keyboard shortcuts, as they are called in other places). Key bindings are an essential part of what makes emacs such a productive editor.

Key bindings are discussed in a lot of detail in the Emacs documentation; but what about the very useful little subset we need here for defining keybindings? Let's see…

kbd

When defining key bindings, it's important to understand the emacs-notation for them. Emacs allows for different ways to specify key combinations, but the easiest way is to use the kbd-macro. We're using this macro in the examples below.

To figure out how to find the notation for some key we want to bind, we can use describe-key, or C-h k (Ctrl-h k), and type the key you want to use. Emacs will tell you if it's already bound, and the representation of the key. So, for example, pressing C-h k and then Ctrl-Shift-Return shows the representation for that as <C-S-return>.

binding a function

Once we have figured out the notation for the keybinding we'd like to use, the next step is mapping it to some function. If the function takes no arguments, it's easy (see the examples below). But how to call a function that requires an argument? Suppose,we want to insert the word "hello" whenever we presses C-c h. For that, we need a lambda-function:

(global-set-key (kbd "C-c h") '(lambda () (interactive)(insert "hello")))

Also note the (interactive), to tell emacs that this is an interactive function, because we want to have some output to the current buffer. Lambda-functions require some more explanation, which deserves its own entry…

keymap

So, we have seen how we can figure out a keybinding, and how we can bind it to some function. The final important concept ist that of a keymap, which is a set of keybindings. In emacs, you have multiple keymaps, because in different situations, we'd like to use different (combinations of) keymaps. You can define keybindings that apply throughout emacs (in the global keymap), in specific modes, or in the current buffer (in the local keymap). Let's see how this works in practice.

In this entry we define a global keybinding for toggling full-screen mode; in .emacs:

(global-set-key (kbd "<f11>") 'djcb-full-screen-toggle)

Because there are so many functions available in emacs, it is impossible to have global key bindings for everything that are still easy to remember (a keybinding you have to look up is rather useless). Also, many bindings only make sense in a particular mode.

Because of that, we can have mode-specific keybindings. For example, the command ff-find-other-file (to jump from .c-file to .h-file and vice-versa, as mentioned here), is only useful in c-mode (and derivatives), so:

(define-key c-mode-map  (kbd "C-c o")    'ff-find-other-file)

Finally, to set a key only for the current buffer, we could use:

(local-set-key (kbd "<f11>")  'djcb-full-screen-toggle)

But note that usually, all buffers in a certain mode share their keymap. This means that adding a keybinding to the keymap for the current buffer will likely add it to all buffers of that type.

Conclusion

This should be enough to get you started; the big challenge now is to come up with a set of intuitive key bindings for your most-used function. That is not so easy…

welcome to emacs-fu

Welcome to Emacs-Fu!



(If you want to read emacs-fu through your RSS feed reader, please read this)



This is my blog discussing little (and not so little) tweaks to make working
with the Emacs Text Editor even nicer. I have been an emacs-user for the last
decade or so. I spend a lot of time with it. Emacs allows near-infinite
customization, and I am always trying to improve things.




Over the years, I found many little tricks & tips. With this blog, I'm trying
to share these with others. I am not claiming I came up with all these things
myself. Quite the contrary - most things are inspired by things I found while
foraging through the web. Also, I am definitely not claiming that the way
shown here is the only way or the best way. I am not an emacs guru - I don't
even wear a beard. I do welcome comments with suggestions and improvements.



Now, regarding the content: I don't want to limit myself too much; but the
goal is to have something short you can read in a few minutes and pick up
something useful, maybe while reading it in a feed reader. While emacs'
documentation is very extensive, it can also be a bit intimidating. I'd like
to offer bite-size chunks that are directly useful (e.g. running emacs in
full-screen mode), or sometimes some background information (e.g., about
binding keys or .emacs itself). Also, an over overview of emacs terminology
may be quite useful. I'll be updating older posts whenever that makes sense.




Sometimes, I might write a bit longer, if the subject requires it.



About the target audience: the tips here probably make little sense for people
who have never used Emacs before; and they might be trivial for the true Emacs
wizards. So, the target audience is somewhere in between.



The kind of tips here are meant to be small additions to your .emacs (or
~/.emacs.d/init.el/. See the ever-useful EmacsWiki for some general
information about this. After you've added or changed a function in .emacs,
you can 'activate' it by either restarting emacs, or calling M-x
eval-buffer. Of course, you can find my full .emacs.




However, I would definitely not recommend copying my or other people's
.emacs without understanding what things mean. It's much better to start
from scratch, and organically developing your very personal .emacs so things
work exactly the way you like it. This blog is really about identifying small,
understandable and useful nuggets that you can re-use.



I am using the as-of-yet unreleased Emacs version 23; most things should work
just fine with the released versions. XEmacs-users might face some more
problems. But again, please leave a comment if something is not working for
you.



There are many other excellent resources with emacs information available; I
already mentioned EmacsWiki, and many other emacs blogs are aggregated in
Planet Emacsen. If you're just starting, you can try the built-in tutorial you
can start in emacs with C-h t (ie. press Ctrl-H and press 't'). I am not
sure if I can recommend it – many things seem a bit outdated (i.e., using

C-v instead of simply PgDown…). But I digress.



Some practical points: I try to prefix the functions/macros I define with
djcb-. That's not just because I am so pretentious, but also to clearly
separate them functions that come with emacs, or a part of other
packages. Another practical point is that all the code snippets here can be
used for any purpose, i.e. they are in the public domain. External scripts have
their own licenses, which you should check before using or distribution them.



Finally: I hope this blog provides some useful information to Emacs-users
everywhere. If you have an emacs tip you'd like to share with your fellow
emacs users, please let me know.




You can contact me through e-mail (GPG-key); I am djcb in IRC and
Twitter.

Followers

Popular Posts