2010-12-30

color theming with emacs 24

The emacs development team is hard at work on emacs 24. As far as I know, there is no planned date for it yet. I'll write more about all the new cool things when we're a bit closer to the release date, but I'd like to highlight emacs 24 color-theming already, as it's an area people outside the core development theme should be able to contribute to as well.

Here at Emacs-fu, we already discussed color-theming and in particular the zenburn color theme; this was all based on the color-theme-package. While being popular, there were a few problems with that package, which is why emacs-24 comes with a new scheme for doing this.

The current development versions of emacs ship with a few themes (tango, tango-dark and wheatgrass), which you can activate with M-x load-theme. It would be great to include some more color themes, and to encourage this, emacs maintainer Chong Yidong has written the GNU Emacs Theme Generator (currently in bèta), which helps you in the process of making a simple theme. This tool currently only support changing colors, and not e.g. the boldness or slant, but it's a nice way to get started, and to immediately see the results.

For more complex theming, there is M-x customize-create-theme; however, that is built on the (in my opinion) cumbersome customize-interface, so I'll probably start by creating a basic theme with the web tool, and then edit it by hand. If you design some attractive color theme and would like to propose it for inclusion in emacs 24, you can send it to emacs-devel.

2010-12-01

conkeror: web browsing the emacs way

Web browsing is one of the few computer-based activities for which I usually do not use emacs. Of course, there are of emacs-based browsers like w3m, which is pretty good. But for the 21st-century web, a text-mode browser is a bit limited. There are some efforts underway to integrate a graphical web browser experience in emacs (e.g., using Xembed), but it will take a while before that is ready.
The next best thing to web browsing with emacs, is a browser that is inspired by emacs. Such a browser exists: it's called conkeror (not to be confused with KDE's Konqueror). conkeror is a Mozilla-based browser that brings an emacs-like experience to web browsing. I've been using it for more than a year now as my primary browser, and I am quite happy with it.
Conkeror is a user-interface for the normal Mozilla/Firefox engine (xulrunner); this means that all those websites that work with Firefox, work just as well in conkeror, including things like ad-blockers, Java, Flash etc. and many plug-ins. This is a very important point for me.
If you like emacs, you'll probably also like conkeror. For starters, it uses many of the same key bindings – C-x C-f will open a url in a new buffer (tab), C-x 5 2 will open a new window (frame), I can inspect a key-binding with C-h k… and so on. Some of the single-key shortcuts are the same as those in w3m, like g to go to a webpage, or B to go back. Conkeror is fully keyboard-driven; it allows you do almost anything on the web without using the mouse – it can overlay numbers on items in a webpage so you can interact with them by their number. Of course, you can still use a mouse if you want, too.
The conkeror wiki gives many more examples. It also discusses installation in quite some detail, which makes life a bit easier for me :) Instead, I will just list a couple of the customizations I have made and encourage you to try for yourself.

configuration

Like emacs, conkeror is very configurable. The big difference is that conkeror uses Javascript instead of Elisp for the configuration; however, the concepts and naming should be familiar for emacs-users. Conkeror's equivalent of ~/.emacs is ~/.conkerorrc. Below are some snippets from my setup, that can hopefully help you to create your Perfect Browser ™; all examples below are based on the latest development version of Conkeror, as per end of November 2010.
First, some basics:
//allow for 'contrib' stuff
load_paths.unshift("chrome://conkeror-contrib/content/");

// teach me something whenever I start my browser
homepage = "http://en.wikipedia.org/wiki/Special:Random";

// give me new tabs; open buffers (tabs) in the background
require("new-tabs.js");
require("clicks-in-new-buffer.js");
clicks_in_new_buffer_target = OPEN_NEW_BUFFER_BACKGROUND; 
clicks_in_new_buffer_button = 1; //  midclick links in new buffers with

// auto completion in the minibuffer
minibuffer_auto_complete_default = true;
url_completion_use_history = true; // should work since bf05c87405
url_completion_use_bookmarks = true;

modeline customization

As in emacs, you can customize the modeline. Also in good emacs tradition, this is far from intuitive…
require("mode-line.js");
// funky icons in the modeline
require("mode-line-buttons.js");
mode_line_add_buttons(standard_mode_line_buttons, true);

// we'd like to see the # of buffers being loaded 
add_hook("mode_line_hook", mode_line_adder(loading_count_widget), true);
// we don't need a clock
remove_hook("mode_line_hook", mode_line_adder(clock_widget));

bookmarks

Plain-old bookmarks are easy to add with define_webjump – and you can just bind them to a short string. You can then 'jump' to the corresponding website by pressing g and then this short string. For example, to go to Emacs-Fu, you could type g efu RET. No mousing around needed.
// some bookmarks
define_webjump("conk",  "http://conkeror.org");
define_webjump("efu",   "http://emacs-fu.blogspot.com");
define_webjump("lkml",  "http://lkml.org");
define_webjump("ew",    "http://emacswiki.org");
// ...

smart links

Smartlinks are just like normal bookmarks, which the one difference that they contain an %s-parameter which will be replaced by whatever you type after the name of the bookmark. Thus, g imdb grande bouffe RET would take you to the IMDB-page about the movie La Grande Bouffe.
Some examples:
define_webjump("so",    "http://stackoverflow.com/search?q=%s");
define_webjump("yts",   "http://www.youtube.com/results?search_query=%s&aq=f");
define_webjump("imbd",  "http://www.imdb.com/find?s=all&q=%s");
// ...

integration with emacs

Another useful feature in conkeror is the ability to interact with Emacs (or any other text editor), so you can use emacs for writing text in web pages; for example, when you're using emacs-daemon (you should), you could can add the below, and C-i will then take you to emacs whenever you are in a text field in a web page.
editor_shell_command = "emacsclient -c";

adding your own functions

It's fairly easy to add your own functions; admittedly, I'm still at the beginning stages with that, but it's not too hard to combine the internal function, and assign them to key bindings. Some examples:
// copy url with C-c u
interactive("copy-url",
        "Copy the current buffer's URL to the clipboard",
        function(I) {
            var text = I.window.buffers.current.document.location.href;
            writeToClipboard(text);
            I.window.minibuffer.message("copied: " + text);
        }
);
define_key(default_global_keymap, "C-c u", "copy-url");


// reload conkerorrc with C-c r
interactive("reload-config", "reload conkerorrc",
       function(I) {
          load_rc();
          I.window.minibuffer.message("config reloaded");
       }
);
define_key(default_global_keymap, "C-c r", "reload-config");
It's not necessarily so easy to find the exact functions / objects you need to accomplish what you want. There's a certain learning curve – just like when using emacs.

integration with org-mode

The integration with emacs can go further than merely editing text fields though; it's possible to integrate conkeror with org-mode in emacs; I have the following in my .conkerorrc (this requires emacs-daemon), based on the code in WOrg:
// org-protocol stuff
function org_capture (url, title, selection, window) {
    var cmd_str =
        'emacsclient \"org-protocol:/capture:/w/'+url+'/'+title+'/'+selection+'\"';
    if (window != null) {
      window.minibuffer.message('Issuing ' + cmd_str);
    }
    shell_command_blind(cmd_str);
}

interactive("org-capture", "Clip url, title, and selection to capture via org-protocol",
          function (I) {
              org_capture(encodeURIComponent(I.buffer.display_uri_string),
                        encodeURIComponent(I.buffer.document.title),
                                encodeURIComponent(I.buffer.top_frame.getSelection()),
                        I.window);
          });
// capture with C-c c
define_key(content_buffer_normal_keymap, "C-c c", "org-capture");
Then, on the emacs-side (in your .emacs), you should have a capture template for this; for example:
;; ;; the 'w' corresponds with the 'w' used before as in:
;;   emacsclient \"org-protocol:/capture:/w/  [...]
(setq org-capture-templates
  '(
     ("w" "" entry ;; 'w' for 'org-protocol'
       (file+headline "www.org" "Notes")
       "* %^{Title}\n\n  Source: %u, %c\n\n  %i")
     ;; other templates
))
Now, when in conkeror, you can select some text, push C-c c ('capture'); emacs will offer you to save this text, including a link to the source, the date and so on, and saves it for later retrieval. I really love this feature!

so…

These were just a couple of the many things you can do with conkeror; there's so much potential here. I haven't discussed many of the other powerful features, such as the page-specific modes, that give special features to specific websites, be it GMail or Wikipedia.
I've been using this fine browser for a year or so now, and I really like it. There are a few rough edges here and there, but it's quite amazing what the small development team has accomplished. I heartily recommend it – for web-browsing the emacs-way, there's simple no better alternative.
Finally, if you're using conkeror already, and have some clever tricks you'd like to share, feel free to do so in the comments.

2010-11-15

undo

One of the advantages that text-editors have over daily life is the ease of undoing things. Emacs in particular has a powerful undo-system to return to the previous state of things.

Undo can be activated by pressing C-x u or C-_; if you are more comfortable with using C-z for undo (as is the standard in many non-Emacs environments), you can of course add that key binding as well, by putting in your .emacs:

(global-set-key (kbd "C-z") 'undo)

This overrides the default of C-z triggering suspend-frame, which is not a great loss for most people.

Emacs-undo has some nice features - for example, if you have selected some text ('marked a region'), the undo operation only applies to that area. At the same time, however, the undo-model can be confusing: in emacs, undo is treated like any other command, which means that undo can be applied even to… undo, which is different from what most other editors do. Let me give an example – if it's confusing or tedious then, well, that's what it is…

Suppose I type

hello
world

now I press C-_, and I get

hello

Now I type foo

hello
foo

And press C-_ C-_; and I get back:

hello
world

This is because we're 'undoing the undo' of adding the word 'world', and thus, it reappears! When you try this in most other editors, it would result in

hello

because those editors completely forget about 'world' after it is undone.

So, emacs' model is strictly more powerful - but some (many? )people find it a bit confusing, esp. when a series of 'undos' is interrupted by a 'do'.

If you prefer the model that many other editors use, you might be interested in redo-mode, in particular in RedoPlus. Using that package, undo (or rather, redo) follows a different model. In that model, redo is 'special': it's not registered as a buffer change, and as such it's conceptually different from the redo=undo-undo model that emacs uses by default. As seen above, you actually lose some information in the process.

Yet another way to tackle the undo-problem is implemented by UndoTree: the states of your buffer are seen as nodes in a tree, and you can freely move to specific nodes. UndoTree is as powerful as the emacs system, yet easier to understand. It can even visualize the tree of changes - and you can then by clicking on a node go back to the corresponding buffer state.

Now, when using UndoTree, let's look at our example again:

We started with:

hello
world

then did C-_ (which removed 'world') and typed 'foo' to get:

hello
foo

Now press C-u again, and 'foo' disappear. Now we press C-x u (undo-tree-visualize) and we get a buffer with:

  |
  o
  |
  |
  x
  | 
 / \
o   o

and we can now visually move to any of the nodes, and our buffer is instantly brought back. Cool! The two branches correspond to the states 'world' and 'foo'. I have been undo-tree-mode for the last few weeks, and it works very well: usually I don't even notice it, but when I need the extra power, it's there.

I am told that UndoTree is inspired by the way the vim-text editor does this. Anyway, there is another very powerful feature in the vim undo-system that would be nice to have in emacs to: time-based undo. In vim you can e.g. say something like:

:earlier 5m

to go to the state of your buffer 5 minutes ago. That would be a nice addition for undo-tree-mode!

Update Tavis Rudd notes that pressing t in undo-tree-visualizer-mode (i.e.. what you see when your press C-x u) will give you timestamps instead of o and x:

                  |
                  | 
             18:54:20
                  |
                  |
             18:54:20
          ________|___ 
         /            \
     18:54:15       18:53:37
        |              |
        |              |
     18:54:15       18:53:37
     ___|___           |
    /       \          |
18:54:10  18:53:43  18:53:36

2010-10-23

auto-complete-mode

Recently, we discussed CEDET in the interview with Eric Ludlam. CEDET has a deep understanding of the source code, and assists the development process by exploiting that knowledge. For example by drawing class diagrams (COGRE) or providing auto-completion for function names and parameters.

Currently, however, CEDET is also be a bit hard to set up effectively, and may also not support your programming language yet. Therefore, it's still useful to look at some other packages that can substitute (part of) the functionality.

For me, auto-complete-mode has been very useful for that. It's not as fancy as CEDET in the sense that it does not really understand the code – but in practice I found it to work quite well for both C/C++, Elisp and shell scripts. It can even display the docstrings of functions. And when editing shell-scripts, it can complete path names as you are editing the scripts; very nice.

To install, follow the instructions. Then, in your .emacs, have something like:

(when (require 'auto-complete-config nil 'noerror) ;; don't break if not installed 
(add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
  (setq ac-comphist-file  "~/.emacs.d/ac-comphist.dat")
  (ac-config-default))

After that, M-x auto-complete-mode to start using it. Alternatively, there's a YouTube-video explaining how to install and use auto-complete-mode; recommended. In any case, it is fully documented.

auto-complete-mode uses a configurable set of sources from which it takes it knowledge about what can be completed. For example, when writing in org-mode, it takes its input from

(ac-source-filename ac-source-abbrev ac-source-dictionary
 ac-source-words-in-same-mode-buffers)

while in a c-mode buffer it is (in my case):

(ac-source-filename ac-source-yasnippet ac-source-gtags ac-source-abbrev
ac-source-dictionary ac-source-words-in-same-mode-buffers)

You can customize this, and (for the more ambitious), it's possible to add your own sources as well.

2010-09-27

interview with Eric Ludlam (CEDET)

One of the notable new features of emacs 23.2 was the inclusion of CEDET. CEDET adds IDE-type functionality to emacs, and one only needs to read the responses to the 100th post to see the great interest in that.

The man behind CEDET is Eric Ludlam (EML), a long-time Emacs user and developer. He kindly answered the many questions we had for him. Thanks, Eric!

djcb: Eric, could you tell us a little bit about yourself? And about that fantastic hobby of yours, building siege engines?

EML: I manage a software engineering team at the MathWorks. The MathWorks are the creators of Matlab. In my spare time I maintain CEDET, the Matlab support for Emacs, and build replicas of ancient siege engines.

I've been building catapults of various types for use at the World Championship Punkin' Chunk since 1998. My team started with a traction trebuchet, then a HCW Trebuchet, then moved to Human Powered Centripetal, and finally to the torsion division with MistaBallista. As far as I know, Mista Ballista is the worlds largest farthest throwing currently functional ballista.

Most recently, I got to help demolish a building where I work by shooting stuff at it, which was a lot of fun.

djcb: How did you get involved with Emacs? Do you spend a lot of time with it?

EML: I've been hacking Emacs since version 18.54 on Ultrix because the alternative was vi. My first post (and thus contribution to Emacs) was to gnu.emacs.sources on June 6, 1992. I've used Emacs to work on C/C++ code for many years which inspired all the various parts of CEDET, but these days I don't get much coding time.

My work with Emacs and CEDET is seasonal currently. The summers are usually busy with family activities, and my falls are busy getting the catapult ready, so CEDET work usually happens in the winter.

djcb: Can you tell us a bit about the background of CEDET?

EML: I started with some really basic editors and eventually with LSE (Language Sensitive Editor) on VMS. LSE was pretty cool. When I switched OSes to Ultrix and was forced to use Emacs, and discovered you could script it, I was hooked. My first big Emacs hack was etalk, an implementation of Unix talk in Emacs.

In one of the Emacs related newsgroups, a spoof story floated around about how Emacs became sentient, and started writing code for Richard [Stallman] instead of the other way around. Since then I've always wanted to get Emacs to start writing my code for me. I wrote cparse.el, a regexp nightmare that could parse almost any C file into a sequence of highly detailed tags. The tags could be used to then generate code, and I had a cool comment writing utility, automatic prototype generation, and some navigation features. On the whole it failed for many reasons.

The concept, however, continued. CParse became the basic idea behind what is now the Semantic package in CEDET, though none of the old stuff remains beyond some echos in some SRecode utilities.

My end goal is to provide round-trip code management in Emacs. Emacs needs to be able to read your code, allow you to perform transformations in the code in an abstract way, and then write new code for you. Everything in CEDET is building toward that goal. It is taking a long time, and you can see it starting to take shape. Semantic can parse the code, COGRE can manipulate UML diagrams representing your code, and you can export diagrams into code through SRecode. Unfortunately this isn't a round-trip solution as the generated code currently should not replace existing hand-written code.

Can you tell us a bit about the CEDET-project?

EML: I maintain CEDET and field questions on the mailing list. There are several contributors who either own some tool in the "contrib" area, fix bugs, answer questions or apply patches for new features. There has always been someone to pick up the slack when I'm busy elsewhere, and I've greatly appreciated that.

The easiest (and most common) way to contribute code to CEDET is to provide support for some new language, or to create a language agnostic tool using the CEDET APIs. As with Emacs, you need to be able to assign copyright to the FSF to contribute to CEDET's core, but new language support or utilities can have a home in the contrib area as well.

djcb: CEDET is part of Emacs since 23.2. Can you tell us a bit about how that happened?

EML: I've been providing assignments for the parts of CEDET since 1996 or so. For Emacs 23.1, CEDET was at a stable and useful enough state that Chong Yidong was willing to do the work to integrate it into Emacs. My ability to get a legal release for CEDET in time for Emacs 23.1 failed, so it went into 23.2 instead. It is my understanding that CEDET's smart completion engine reached a performance and reliability point that made it desirable to have in Emacs.

Emacs currently includes the parts of CEDET needed to make EDE, the project management system, Semantic and it's user tools, and SRecode all work from a user perspective. Emacs lacks the Semantic development environment, needed for writing new language support, and COGRE, the UML diagram editing tool.

djcb: Are there plans to include those parts as well?

Yes. It is important for users with a stock Emacs to develop new languages using the missing Semantic development tools. I don't know if COGRE will ever go in, though I expect that this will be done via the new package management system [elpa].

djcb: Did you ever try IDEs such as Eclipse? How do you think CEDET stacks up against such programs?

EML: I have used Visual Studio more than Eclipse, and certainly watched demos on how these and other tools work.

These tools win over CEDET's features in that they usually integrate directly with the compiler, VM or whatever, and have very good completion engines and UIs that you can interact with.

CEDET wins in that you don't need a compiler, or even code that can compile for it to work and start providing useful completions. It can infer an awful lot from a project.

CEDET's language support structure is thus simple in comparison, and CEDET supports many more languages as a side effect. It also wins because it is in Emacs, and I've done my best to try and match the "Emacs Way". For an Emacs user, this is intuitive, but can appear quirky to outsiders.

djcb: What about other development tools for in emacs?

EML: There are a lot of language specific solutions like GCCSense, slime, JDEE, and others out there. These projects are great in that they take a language, and push it to the edge of what you can do, and the users generally love that stuff. When someone wants to do the same thing, like when CSDE started for C#, and it tried to copy JDEE, it was just that, a copy that didn't quite make it.

It is my hope that CEDET will become the target of choice for users who want to make their language support in Emacs the best. They will save a lot of time doing so as well. The same infrastructure for integrating in external tools can be used to get improved results out of CEDET, but CEDET will handle converting that into a representation that would then allow any tool built on CEDET to work. This is the same model that worked well for comint.el, and gud.el.

Yasnippet is a bit different in the way it "competes" with SRecode. My first implementation of SRecode tried recycling tempo templates, but I couldn't get it to work. In fact all the template systems I investigated fell short of what I was trying to do, so I had to roll my own, and ended up using a variant of the Google template format.

The key difference is that the goal was for SRecode to provide a series of base templates for code generation. A tool writer would then write some tool to generate code. A user would then use the tool, and say "This is great, how do I change where the { goes?"

The answer is to override the template with that detail in it without interfering with the system templates. That only works if the templates are sufficiently granular that the changed template can be simple. Template reuse needs to be high so that if your company formats your methods as:

int mymethod() { implementme() };

instead of

int mymethod() {
}

that one template change will allow this to happen for all code generated from every tool.

Thus, the audience for yasnippet and SRecode is quite different. Of course you could do yasnippet like things with SRecode if someone took the time to improve the field-editing feature in SRecode, but that has not been my focus.

djcb: Do you follow the overall Emacs development process? Are there things you would like to see changed/improved?

EML: I watch the emacs-devel mailing list, mainly to see if anything related to CEDET goes by that I can help with, or what the latest cool feature might be. My first contribution of Speedbar to Emacs in Emacs 20 helped drive some features related to overlines, boxes, and other face attributes that appeared in Emacs 21.

In the future, once CEDET and Emacs cross merge techniques are hashed out, I would expect some key parts that need performance improvements might move into C. Another part of CEDET that I'd love to see become bound closer to Emacs is mode-local.el. It tries to simulate mode-local variables and mode-local functions. This is critical in a complex system like CEDET that needs to provide a language support author with fine grained control. There are good reasons not to make what is currently implemented "the Emacs way", but it would be nice to resolve those and enable mode authors a with a more powerful way to customize the user experience.

djcb: Do you have specific plans for CEDET in the future?

EML: Here is the short list:

  • Improve Emacs/CEDET cross merging
  • Offload tag storage to an external process - needed for scalability
  • Design/define a "CEDET mode" as a way of simplifying the confusing array of distinct tools and modes that make up CEDET now.
  • Finish the smart-context menu project
  • Resolve the "code replacement" problem of parsing a block of code, transforming it, and re-creating that code in place reliably.
djcb: In addition to all these 'generic' improvements, are there specific areas where new contributors could make a difference?

EML: Supporting new "stuff" in CEDET is one big win. Stuff can be:

  • New project types under EDE to ease transition from something like Visual Studio to Emacs.
  • Language support, such as parsers, or mode overrides. Finding ways to take existing cool tools, like JDE's beanshell, or slime's inferior lisp process and allowing it to do work for CEDET is another big win.
  • Templates for code generation in new languages.

Tool writing would also be good. JDEE's author Paul Kinnucan converted many bits of JDEE to CEDET and co-designed many of CEDET's parts along the way, such as semanticdb, and that was a huge help. ECB's current maintainer Klaus has also had a big impact on the way concepts are abstracted to a tool that depends on CEDET.

Naturally, joining the mailing list and fixing reported bugs and improving the doc is also a huge help, but not as exciting as writing new code. :)

djcb: Finally, many people want to start using CEDET, but it seems they have a bit of trouble to get started. Do you have any recommendations for them?

EML: Start with the cedet.info file which has many of the common setup configurations in it. If you run into something not explained well or at all, be sure to join the mailing list and be specific about how that doc failed. Very few questions on the mailing list refer to the doc, so the doc is rarely improved in a way that can help others.

Another good starting point is Alex Ott's article A Gentle Introduction to CEDET, which is very helpful.

Thanks a lot for your time, Eric! Wishing you a lot of success with CEDET and all your other projects!

2010-08-22

narrowing buffer contents

'Narrowing' is yet another of those many useful emacs features that took me years to appreciate, mostly because I never really tried it. I may not be the only one, so here's a short introduction.

Narrowing is the concept of hiding the buffer contents except for what you are currently working on. This is useful when you don't want to be distracted, but also because it allows you to execute commands only on the narrowed part. You can narrow different things:

what's shownnamebinding
region (selection)narrow-to-regionC-x n n
current pagenarrow-to-pageC-x n p
functionnarrow-to-defunC-x n d
everythingwidenC-x n w

I never used narrowing for the current page, but apparently it's used by e.g. Info-Mode to show only one page.

That last one is pretty important to remember; it's not totally obvious how to get back to 'normal' mode where you can see everything. For this very reason ('where the #>*$@ did my text go'), always-helpful emacs by defaults disables narrow-to-region (but, for some reason, not the other ones). To enable it, put the following in your .emacs:

(put 'narrow-to-region 'disabled nil)

Also note that the mode-line will show 'Narrow' when you're in narrow mode, lest you forget.

When you're using org-mode there is an additional one you might want to memorize:

what's shownnamebinding
subtreeorg-narrow-to-subtreeC-x n s

I'm using that last one quite often; I have org-files where I keep meeting notes etc., and when in a certain meeting, I only want to see the notes for that specific meeting.

One bug? feature? of narrowing is that line-numbering is relative to the narrowed area rather than the full buffer. I'd prefer to have the real line numbers.

2010-07-30

some handy key bindings

Emacs offers many handy key bindings; every now and then I come across a new one, which has been hiding there somewhere for a decade or more… Here are some of my favorites – I'm listing those that are (a) often useful, (b) might not be known by everyone already (c) don't require any external packages or setup.

  • M-27 x gives you xxxxxxxxxxxxxxxxxxxxxxxxxxx; and, believe it or not, works also with different characters and numbers;
  • M-m jumps to the first non-whitespace character on the current line;
  • M-^ joins two lines into one – like vi(m)'s :join, except that point must be on the second line, not the first;
  • M-/ auto-completes based on words in all your buffers; there are more powerful alternatives, but this one does not require any setup;
  • C-h k followed by some key or key combination tells you what it does, C-h m describes the currently active modes, with their key bindings;
  • C-h f documents the current function, C-h v does the same for variables. C-h a gives you information about commands - for example to get date-related commands, press C-h a date. This will, however, also get you commands related to update; instead, you can use C-h a \bdate (because C-h a accepts regular expressions);
  • C-x C-o will delete all the empty lines around your current cursor position, except for one;
  • M-q re-aligns the current paragraph; I use it all the time when writing e-mails etc. (you might want to check out filladapt for a version that gives you a bit more smartness with indentations, lists etc.);
  • C-x 8 RET in a recent emacs version gives you an auto-completable list of special characters to insert. So if I need, say, the Yen-character, I type C-x 8 RET ye TAB and I get YEN SIGN, which RET will then insert: ¥. Note that the completion only works on the start of the character name, so if you'd want to include the α-character, you'd need to know that its UCS-name is GREEK SMALL LETTER ALPHA… (you can try *alpha or TAB the empty string, and search in the results buffer, but that's rather slow);
  • C-h l shows your last 300 key presses ('lossage'). Interesting to see, and it might be useful when defining keyboard macros.

What are your favorites? Please share them in the comments.

2010-07-21

navigating through files and buffers with the lusty explorer

I think quite a few people are using ido-mode to navigate through files an and buffers; we discussed it here already a long time ago. I am a happy ido-user myself – it took me some time to fully get full accustomed to the key bindings, but now it feels very natural. Definitely an improvement of my emacs user experience.

However, I am always looking for new things – and one of those is a sort-of ido-mode substitute. It's called the Lusty Explorer and it's the emacs implementation of an existing vim-plugin. It's quite similar to ido-mode; the difference is mainly that it shows all the files or buffers at the same time, in the way that shells (say, bash or zsh) do auto-completion.

The best way to show how it works is using an screencast (note, this is of a slightly older version). Lusty Explorer uses fuzzy matching; that means that I can type /etc/fo, and all items in /etc/ with names f.*o match.

To install lusty-explorer, simply copy lusty-explorer.el to your load-path, and put something like the following in your .emacs:0

(when (require 'lusty-explorer nil 'noerror)

  ;; overrride the normal file-opening, buffer switching
  (global-set-key (kbd "C-x C-f") 'lusty-file-explorer)
  (global-set-key (kbd "C-x b")   'lusty-buffer-explorer))

Side-note, the (when (require 'lusty-explorer nil 'noerror) ...) is there just make sure that no error is raised when lusty-explorer is not found, and the rest is ignored in that case. I use this construct for all packages that are not necessarily available everywhere I use my .emacs; thus, they will simply be ignored and not cause startup errors.

I've been using Lusty Explorer for about a week now, and I am quite happy with it. I still need some time (and maybe some more customization) to get used to the way it works - for example, I found the way ido-mode handles backspace a bit smarter. Also, ido-mode can be customized to a much greater extent. That might merely be a factor of the relative age of the packages – and I haven't really felt the need to customize Lusty Explorer too much. For now, I think I'm going to keep on using it. It's worth a try at least!

2010-07-16

keyboard macros

Keyboard macros are a truly classic emacs feature. Still, I only started to use them years after I got sucked into emacs – not so uncommon for emacs features… There may be more people like me, so let's raise the awareness a bit.

Keyboard macros allow you to record a number of keystrokes, and replay those at some later point. This can be a great time-saver when you need to do repetitive things. In many cases, they are an easy alternative to writing some elisp to get a job done. Note, keyboard macros are should not be confused with elisp-macros, which are something else altogether.

an example

So, when would we want to use a keyboard macro? Let's take some tedious task -- for example, we have a list of a few hundred names:

Newton, Isaac
Einstein, Albert
Maxwell, James
Turing, Alan
...

and we want to turn that into:

Isaac Newton
James Maxwell
Alan Turing
...

so, roughly, put the last name after the first name, and remove the comma.

We can solve this in different ways; we could simple change each line by hand. That's a fine solution if there are only a few lines, but it gets boring rather quickly.

Another way is to use regular expressions (see Building regular expressions); in this case, it's fairly easy to come up with one (assuming you know regular expressions). But let's see how we can solve it with a keyboard macro.

Schematically, we can solve this with the following:

actionkey
go to beginning of a lineC-a
kill (cut) the first wordM-d
delete the next two charactersDEL DEL
go to the end of the lineC-e
insert a spaceSPC
yank (paste)C-y
go to the next lineC-n

This may look like some magical incantation, but it comes quite natural when you are actually doing the editing.

An important thing to remember when working with keyboard macros is that you do your commands in such a way that they can be repeated for each line. Suppose you would select Newton with shift-select, i.e., C-SPC at the beginning of the line and pressing the right arrow key 6 times – that works for Newton, but not for Einstein. Instead, we need to use M-d ('kill-word') instead.

defining a macro

Now that we have solved the problem for a single line, let's make a keyboard macro.

We move the cursor to the first line, and start the definition by pressing C-x (, or alternatively, F3. Then, we press the commands C-a, M-d, DEL DEL, C-e, SPC, C-y, C-n (as in the list above). To finish the definition, press C-x ), (or F4).

Hurray, we have our macro. Now, let's use it.

using the macro

Now, to execute the last defined macro, you press C-x e. We could repeat that for our whole list, but fortunately there's an easier way to repeat a macro n times, using a prefix argument. For example, to repeat the macro 123 times, you first press C-u 123 and then C-x e.

There's a slightly shorter way to do this: instead of C-u 123 we can write M-123, and for C-x e we can use F4 (kmacro=end-or-call-macro).

You can even repeat the macro until the end of the buffer is reached with C-u 0 C-x e; this only makes sense if the macros ever reaches the end of the buffer of course. (Remember that you can always terminate with C-g, keyboard-quit)

You can also apply your keyboard macro to all lines in the selected area (region) with M-x apply-macro-to-region-lines (or C-x C-k r). Important to remember: this will actually move the cursor (point) to the start of each line, and then execute the macro. If you want your macro like that, the go-to-the-next-line should not be part of your macro, or you will be skipping lines.

saving macros for later use

If you want to use multiple macros, you can name them. You can do this with M-x name-last-kbd-macro. If you name your macro, say, foo (inventive as we are), you can then execute it after that as M-x foo, which will be available until you exit emacs.

If you want to have the macro for future emacs sessions as well, you can use insert-kbd-macro, which will give you an elisp version of your macro. For our example, this will look like:

(fset 'foo 
   [?\C-a ?\M-d delete delete ?\C-e ?  ?\C-y ?\C-n])

Not very readable, but we can put this in .emacs, and we can use it the next time we start emacs as well. We can also add a key binding for this, for example:

(global-set-key (kbd "C-c f") 'foo)

This will bind foo to C-c f.

final notes

Keyboard macros can be useful and easy, but they are fundamentally connected to key presses – so, if you remap your keys to something different, your macros may not work anymore. Also, the macros are pretty much write-only in the way we use them here. You can edit them in the macro editor though, with M-x edit-kbd-macro M-x foo; we'll then get something like:

;; Keyboard Macro Editor.  Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: C-a M-d 2*<delete> C-e SPC C-y C-n

Command: foo
Key: none

Macro:

C-a                     ;; move-beginning-of-line
M-d                     ;; kill-word
2*<delete>              ;; delete-char
C-e                     ;; move-end-of-line
SPC                     ;; self-insert-command
C-y                     ;; yank
C-n                     ;; next-line

Keyboard macros can be quite a useful trick in your arsenal. And I have not even gone into more advanced tricks like macros with variations or the macro ring. Please refer to the section Keyboard macros in the emacs manual (C-h r) for all the details.

And, finally, don't let the text-based example limit your imagination – you can turn just about any repetitive sequence of tasks into a macro.

2010-06-30

console apps in emacs with multi-term

multi-term

updated Whenever it makes sense, I try to use emacs for my computer-based activities; surely, programs like The Gimp or a graphical web browser cannot yet be replace by emacs, but I'm making progress. I like the ways emacs gives me to automate and speed-up my tasks; I get some return-on-time-investment.

2010 or not, I still spend quite a bit of time on the console. So why not do that from within emacs? There different ways to run shells within emacs.

The simplest one is shell (i.e,, M-x shell), which starts a simple shell, which does not support which does not support 'graphical' console applications, such as mutt, mc, htop.

Then there are term and ansi-term (M-x ansi-term) that do support such applications, which ansi-term supporting colors as well (it seems to have become the default for term in recent emacs versions).

Another one is the nifty EShell (included with emacs), which is not just a (simple) terminal, but also a full shell environment, and has integration with other things in emacs. It's nice, but has some of the limitations that shell has - you cannot run 'graphical' applications; also, I don't really need a shell, as I am quite happy with zsh (zed shell) already, which is more powerful, and I prefer a shell that works both inside and outside emacs.

For all these reasons, I am using MultiTerm, which has 'graphical' support that ansi-term has, but adds a nice extra, namely support for multiple terminals within emacs. I'm not fully up to date with the exact difference in the terminal support between the two, but I haven't had any problems so far.

You can install multi-term (put it in your load-path), and add the following to your .emacs:

(autoload 'multi-term "multi-term" nil t)
(autoload 'multi-term-next "multi-term" nil t)

(setq multi-term-program "/bin/bash")   ;; use bash
;; (setq multi-term-program "/bin/zsh") ;; or use zsh...

;; only needed if you use autopair
(add-hook 'term-mode-hook
  #'(lambda () (setq autopair-dont-activate t)))


(global-set-key (kbd "C-c t") 'multi-term-next)
(global-set-key (kbd "C-c T") 'multi-term) ;; create a new one

With this, C-c t will jump through your multi-term buffers (create a new one if it doesn not exist yet), while C-c T unconditionally creates a new terminal.

2010-06-17

automatic pairing of brackets and quotes

Some text-editors, notably TextMate for MacOS, have a nice feature where inserting a opening ( will automatically insert the closing ), and put the cursor in between them (and does same for [], {}, and various quote-marks).

Not surprisingly, there are some implementations for emacs as well; the best one I have found so far is called autopair, which was written by João Távora. It usually does things just right. Do things 'just right' is essential for such a tool; even small annoyances can disturb your flow. Autopair tries to do whatever makes the most sense for a given mode (programming language etc.), but it can be tuned as well.

After installation, you can automatically activate it for all modes with (in your .emacs):

(require 'autopair)
(autopair-global-mode 1)

Now, evaluate this or restart emacs, and enjoy the autopairing-magic!

Except for autopairing, autopair also takes care of autocleaning; that is, if I press ( it turns that into () (the pairing part), and if I press Backspace then, it removes the whole () (the cleaning part). This makes things much less annoying if you type a pair by accident. Autopairing is the kind of thing that can get annoying quickly if it does not things exactly right – and autopair succeeds!

Another nice trick it offers is autowrapping – that is, I select a word, press ", and automatically it's turned into "word". To enable that, you need to add the following:

(setq autopair-autowrap t)

Note: you might want to see the notes below about delete-selection-mode and cua-mode.

Anyway, autopair with autowrap makes for a really smooth editing experience, I love it! There are two small issues for me though. First, when the cursor in front of some non-whitespace, I'd like autopairing not to happen, and second, somehow I can't seem to get "-autopairing to work in org-mode; of course, that could be my own fault. These things might be tunable; I haven't tried very hard yet.

delete-selection-mode

Important to mention here is that autopair is (by default) not fully compatible with delete-selection-mode. As you may know, that is the mode that causes emacs to replace the current selection with a character typed, similar to what most other programs do. I think many people have it enabled in their .emacs with something like:

(delete-selection-mode 1)

If you want to keep on using that together with autopair, add the following to your .emacs:

(put 'autopair-insert-opening 'delete-selection t)
(put 'autopair-skip-close-maybe 'delete-selection t)
(put 'autopair-insert-or-skip-quote 'delete-selection t)
(put 'autopair-extra-insert-opening 'delete-selection t)
(put 'autopair-extra-skip-close-maybe 'delete-selection t)
(put 'autopair-backspace 'delete-selection 'supersede)
(put 'autopair-newline 'delete-selection t)

But, not that that still won't give you the autowrap behavior mentioned above. For that, we can use cua-mode.

cua-mode

We discussed CUA-mode before, focusing on its nice rectangle-editing features. But CUA-mode can also be an alternative for delete-selection-mode, and it goes together more nicely with autopair; so, instead of delete-selection-mode and the put's, add the following to your .emacs:

(setq cua-enable-cua-keys nil)           ;; don't add C-x,C-c,C-v
(cua-mode t)                             ;; for rectangles, CUA is nice

See the linked CUA-mode article for the 'why' of that first line. With this change, autopair should be working smoothly, including autowrap.

further customization

As I have hinted at, autopair can be tuned for different modes, and can differentiate between it's behaviour in literal strings, code, comments etc. The default are usually sane, but if you're interested, have a look at the documentation, in particular autopair-extra-pairs and the More tricks-section in the documentation.

2010-06-10

worldcup games in your org-mode agenda

A significant part of the world population will be watching the Football World Cup in South-Africa this month. For people who use org-mode to organize their lives, find the schedule of all the games in this message I sent to the org-mode mailing list.

In order to have the games show up in your agenda, make sure the file is in your org-agenda-files. If needed, you could add it with something like in your org-mode settings:

(add-to-list 'org-agenda-files "~/org/fifa-worldcup-2010.org")

One small issue with the schedule is that it use the South-African times, and there is no automatic way to adjust times for the local time zone. As a work-around, Juan Pechiar provided the following function which makes it easy to update all org-timestamps in a file:

(defun uphours (n)
  "update all timestamps n hours"
  (interactive "nAdd hours: ")
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "[[<]" nil t)
      (when (org-at-timestamp-p t)
        (org-timestamp-change n 'hour)
        ))))

Evaluate this function (in emacs, put your cursor after the last ")"), then press C-x C-e. After that, you can go to the file with the world cup schedule, and give an M-x uphours, provide the offset for your timezone, compare to South-African time (positive or negative).

2010-05-20

100th post

100

With that last post, emacs-fu reached the 100 posts milestone! Hurray! Thank you for all the support, it's been a great ride so far, and there's so much more to write about - if only there were 36 hours in a day.

Anyway, to celebrate, I'll be off for the coming weeks (Korea), and I'm not sure if I have much time to blog from there. So, let's take this opportunity for a small reader poll: what would you be interested to read about? More programming-related stuff, more org-mode, more about integration with other programs, more interviews, more …?

Please leave your ideas in the comments. I'd be interested to hear!

Update: I am back now; thanks for all the replies. It seems that many people are interested in CEDET. In fact, I am interested in it myself as well, but am not using it right now, so it will take a while. For the time being, Alex Ott's Gentle Introduction might be the best way to get started.

zenburn for org-mode-generated html

If you read this blog directly, instead of through some aggregator or feed-reader, you can now see the code blocks rendered in the nice zenburn color theme that I discussed before. I'm really enjoying it, so I added some style sheet definitions, so org-mode #+BEGIN_SRC / #+END_SRC blocks look as such in the web page (and just like they look on my screen), for instance:

(defun fibo (n) 
     "calculate the Nth (N>=0) fibonacci number in a simple yet
  inefficient way"
    (cond
      ((= n 0) 0)
      ((= n 1) 1)
      (t (+ (fibo (- n 1)) (fibo (- n 2))))))

;; now, gimme a list of fibo numbers 0..20
(mapcar 'fibo (number-sequence 0 20))

Note, I discussed the use of such code blocks earlier; it's one of many nice features of org-mode. Only quite recently I found that I can press C-c ' in such a code block to edit them in a mode-specific little buffer… something new and obvious to learn every day.

Anyhow, to get the nice zenburn-output in the generated HTML, you can use the following CSS (note, so far I have only done the code blocks):

/* zenburnesque code blocks in for html-exported org mode */

pre.src {
   background: #3f3f3f; color: #dcdccc; 
}

.org-preprocessor {
   color: #8cd0d3;
}

.org-preprocessor {
   color: #8cd0d3;
}

.org-variable-name {
   color: #f0dfaf;
}

.org-string {
   color: #cc9393;
}

.org-type {
   color: #dfdfbf;
   font-weight: bold;
}

.org-function-name {
   color: #8cd0d3;
   font-weight: bold;
}

.org-keyword {
   color: #f0dfaf;
   font-weight: bold;
}

.org-comment {
   color: #7f9f7f;
}

.org-doc {
   color: #afd8af;
}

.org-comment-delimiter {
   color: #708070;
}

.org-constant {
   color: #dca3ac;
   font-weight:bold;
}

.org-builtin {
   color: #7f9f7f;
}

You can save the above CSS-blob in a file (say, zenburn-code.css), and set the style sheet for the org-html export by putting a #+STYLE:-line in your org files:

#+STYLE: <link rel="stylesheet" type="text/css" href="zenburn-code.css" />

2010-05-14

emacs 23.2

Recently, emacs version 23.2 was released. It's a quick update after 23.1 came out (July 29 of 2009); it seems Chong Yidong / Stefan Monnier (interview) are doing releases more often than before they took over emacs maintainership. A welcome change, I would say.

The amount of changes is obviously also a bit smaller than in 23.1, but there are still some interesting updates. Let's go through a couple of those here; I am not striving for completeness, and I won't really go into the biggest change (inclusion of the CEDET IDE-framework), as I haven't been using that enough to say anything about it. Instead, let's look at some of the other highlights; for the full list of changes, please refer to the NEWS-file. If you have some other cool new feature that deserves mentioning, please add a comment.

Some highlights

  • Maximum file size increased to 512Mb (this used to be 256 on 32-bit machines). This may be useful for big log files etc. It does take a while to load such big files, but after that it's not too slow, at least if you have enough RAM. For 'normal' files, you're unlikely to ever hit the limit; e.g. Tolstoy's War and Peace is only 3 MB…

    Note, you can set large-file-warning-threshold to set the maximum file size after which emacs will starting asking you for confirmation when trying to open (eh, visit) files.

  • By default, the mouse cursor turns invisible when typing, so there is no more need for mouse-avoidance-mode and similar tricks. However, if you insist on seeing the mouse cursor, you can add to your .emacs:
(setq make-pointer-invisible nil)
  • On X-based systems, emacs now listens for font changes (Xft), and can automatically use the GNOME mono-spaced font (as set in the GNOME Appearance preferences dialog). Note that this may not work for all fonts/settings (at least in my tests, setting the font to italic does not seem to reflect in emacs). Anyway, to enable this, put the following in your .emacs (or the moral equivalent):
(setq font-use-system-font t)
  • On Unix, Emacs 23.2 now follows the freedesktop trash specification for file deletion; thus, the hacks we hacks we mentioned before are no longer needed.
  • Some cool additions for Tramp, allowing emacs to access files in rsync and even imap://-locations. On systems supporting GVFS, emacs can now directly use e.g. obex://-uris (Bluetooth). I need to play a bit with these things! Tramp support has also been built into eshell.
  • There are already quite some ways to do auto-completion in emacs using the TAB-key, and emacs 23.2 makes this a bit easier to set up. You can add basic auto-completion with:
(setq tab-always-indent 'complete)
  • After setting that, the TAB-key will (after trying if there's anything to indent first) provide possible completions. It works pretty well for Emacs-Lisp (I did not test other languages), although the way it shows the completions (separate *Completions*-buffer) is a bit clumsier that what for instance yasnippet or company-mode do.
  • You can also do partial completions now, by appending initials to the completion style, i.e.:
;; there must be a more elegant way...
(setq completion-styles (append completion-style '(initials)))
  • With this, you can complete on the initials of functions and variables in the minibuffer, say, typing C-h v tai and then pressing TAB will give you tab-always-indent.
  • As mentioned, the biggest change is the addition on the CEDET-framework, which contains things like smart completion, code browsing, UML diagram creation, project management – features somewhat similar to those in e.g. Eclipse. I don't know how well it works in practice, but I will give it a try. At least, inclusion in Emacs should make setting it up with all dependencies a bit easier, as there is now a guaranteed-to-work setup for Emacs 23.2 at least.

Summarizing, 23.2 provides us with some nice updates all around and brings CEDET to the masses. Chong Yidong / Stefan Monnier have done a very good job in making faster releases, while still keeping an eye on the quality. On the other hand, the previous version (23.1) is a very solid release, and if you don't need CEDET, there is no real need to hurry to 23.2.

Future releases

A lot is happening in the world of GNU/Emacs, with changes being proposed and implemented in many different places. There's Eli Zaretskii's way work on making emacs support bidirectional languages (for right-to-left writing systems such as Hebrew and Arabic; the /bi/directional part is that one should be able to mix left-to-right and right-to-left). There is Jan Djärv's work on adding UI-tabs to emacs (like e.g. Firefox has them). There is Ken Raeburn and Andy Wingo's work on adding Guile Scheme support to emacs - possibly replacing the current Emacs Lisp implementation in the future. These are just a few of the more prominent projects.

Nobody knows in which release these items will be available (if at all), but it's exciting to see all the directions people are taking emacs.

2010-05-12

cleaning up the mode-line

Emacs' version on a status-bar is called the mode-line, and contains all kind of information – the current buffer name, the cursor position and a lot of other things, depending on what major and minor modes are active.

Customizing the mode-line is, unfortunately, rather hard. One day, I'll write something about that… but for now at least we may be able to improve things a little bit, by reducing mode line pollution. Mode line pollution? Well, many parts of emacs like to announce their presence and state in the mode line. With the limited space available there, this can become a bit of an issue, the (Lisp Interaction company Yas abbrev) takes quite some space:


But there are some ways to limit the space taken by modes and minor-modes. Note, these snippets should go in your .emacs, and you need to restart emacs to make them active.

First, the minor modes (note, you can see the currently activated ones with C-h m); install the handy diminish.el (or get it using the emacs-goodies-el package when using Debian/Ubuntu) and add something like the following:
(when (require 'diminish nil 'noerror)
  (eval-after-load "company"
      '(diminish 'company-mode "Cmp"))
  (eval-after-load "abbrev"
    '(diminish 'abbrev-mode "Ab"))
  (eval-after-load "yasnippet"
    '(diminish 'yas/minor-mode "Y")))

And the major-modes, for example for Emacs Lisp mode:
(add-hook 'emacs-lisp-mode-hook 
  (lambda()
    (setq mode-name "el"))) 
This looks a bit shorter:

You can of course set these names to whatever is obvious to you.

2010-04-27

navigating the kill-ring

The kill-ring is emacs' implementation of a copy-paste-clipboard. As expected, it's more powerful than what most other editors offer - but at the same time, it may be a bit hard to use. We already discussed the kill-ring in the Emacs-Fu prehistory.

One of the more powerful features of the emacs kill-ring is that is allows for multiple entries to be saved there. You can then retrieve those older entries by using prefix arguments, that is: C-y will retrieve the last item from the kill-ring, while M- n C-y will retrieve the n th last stretch of 'killed' (cut/copied) text. For example, M-2 C-y will retrieve the second last one.

Unfortunately, for most people it's quite hard to remember what was 'killed' and when and in what order… Those people can of course use the menu (Edit/Paste from kill menu), but that is not always so convenient, requires mousing around etc.

Edit: As Anynomous mentions in the comments, one can of course use M-y to circle through the candidates. This is quite useful, esp. when you have only a few items in the ring. Note, this command only works just after a 'yank' (C-y).

browse-kill-ring

Instead, using the handy browse-kill-ring extension, you can open a buffer which lists the contents of the kill ring, and you can move your cursor to the desired item and insert it.

Installation in simple; first get the browse-kill-ring package from EmacsWiki, or, alternatively, Debian/Ubuntu users can install the emacs-goodies-el-package.

Then, add to your .emacs something like:

(when (require 'browse-kill-ring nil 'noerror)
  (browse-kill-ring-default-keybindings))

Now, the M-y key binding will activate browse-kill-ring iff the normal behavior (see above) is not available, i.e., when the last command was not a 'yank'. You can also edit the kill-ring (press C-h m when in the browse-kill-ring-buffer to see the available bindings).

a little pop-up menu

While browsing EmacsWiki, I found another trick:

(global-set-key "\C-cy" '(lambda ()
   (interactive)
   (popup-menu 'yank-menu)))

After which C-c y will show a little pop-up menu with the your kill-menu entries. It does not seem to fully synchronize with the (possibly edited) entries you get from browse-kill-ring, but it's a pretty neat way to navigate through your kill-ring-buffers – if you don't have too many of them (if so, you could customize the kill-ring-max variable).

2010-04-18

creating custom modes the easy way with generic-mode

Syntax highlighting is useful when editing configuration files, programs and so on, as it helps to prevent errors and makes it easier to quickly scan documents.

Emacs supports syntax highlighting (font locking in emacs lingo) for many different file types. For many common cases (e.g. editing for many programming languages, org-mode), emacs' support goes much further than merely colorizing keywords, and offers all kinds of 'magic' (auto-completion, 'electricity', special key bindings, …). For some other file types, at least keywords are given some different color.

Still, there are files that are not recognized by emacs as having some special format; these are displayed as plain text. This may be the case for less-common configuration files, or your own specific formats.

Defining a full 'mode' for such file types can be a lot of work. Fortunately, emacs offers a easier way: generic-mode. generic-mode defines a whole lot of mode of modes for common formats, but also defines the define-generic-mode macro to create your own modes.

Suppose we have a little language called foo; a typical foo-file might look something like:

!! this is a comment
account=foo; !! another comment
user=jimmy;
password=$3cre7;

Using define-generic-mode, we can easily define a mode for this:

(require 'generic-x) ;; we need this

(define-generic-mode 
  'foo-mode                         ;; name of the mode to create
  '("!!")                           ;; comments start with '!!'
  '("account" "user" 
    "password")                     ;; some keywords
  '(("=" . 'font-lock-operator)     ;; '=' is an operator
    (";" . 'font-lock-builtin))     ;; ';' is a a built-in 
  '("\\.foo$")                      ;; files for which to activate this mode 
   nil                              ;; other functions to call
  "A mode for foo files"            ;; doc string for this mode
)

Now, this will look something like this (if necessary, see the colorized version):

!! this is a comment
account = foo; !! another comment
user = jimmy;
password = $3cre7;

2010-04-04

the zenburn color theme

A popular way to customize emacs is changing its color scheme, as already discussed color theming. Until recently, I was using an evolved version of the color theme presented there, 'djcb-dark'. It works for me but, admittedly, it's a bit ugly.

But recently, in a post to the Wanderlust mailing list, someone mentioned a color theme called Zenburn. Zenburn started its life as a color scheme for vim, around 2002. The explicit goal was to have a pleasant theme that is light on the eyes, and allows you to stay 'in the zone' for long stretches of time. People liked it, and version for many other programs were made, including emacs.

I've been using Zenburn for the last few weeks, and I really like it. I used to think that 'low-contrast' would mean that things are not really clear; but the opposite seems true. Anyway, the screen shot says more than a thousand words I suppose…

Zenburn-for-emacs (written by Daniel Brockman) can be found at the link above. I've sent my updates to him of course, but as it may take a while for the 'official' version to be updated, I've put my version on Emacswiki: ZenburnColorTheme. The changes are the support for Wanderlust, hi-line (for highlighting the current line) , magit and elscreen; also, I made selected (eh, transiently marked regions) not loose their foreground color.

Note, the theme is not yet part of the color-theme package, but does require it.

2010-03-20

showing the buffer position in the mode-line

I do quite a bit of scrolling in emacs, but I hardly ever use the scroll bar for that. The main reason for still having the scroll bar is that it gives me some indication where I am in the buffer. Of course, there is some information in the mode-line, and you can get some more with size-indication-mode, but it's not as immediately obvious as the scroll bar.
But recently, I discovered Lennart Borgman's sml-modeline, which combines all of the scroll bar information into a nice visual indication on the modeline, and I have been happily using it, and got rid of my scroll bar.
Put you sml-modeline in your load-path, and the following fragment in your .emacs should do the trick:
(if (require 'sml-modeline nil 'noerror)    ;; use sml-modeline if available
  (progn 
    (sml-modeline-mode 1)                   ;; show buffer pos in the mode line
    (scroll-bar-mode -1))                   ;; turn off the scrollbar
  (scroll-bar-mode 1)                       ;; otherwise, show a scrollbar...
  (set-scroll-bar-mode 'right))             ;; ... on the right

Note, there is a older version available in Emacswiki which has some problems (such as conflicting with the Standard ML editing mode for emacs); thus, for now it's better to us the Launchpad version; the instructions above apply to that version.

2010-03-08

cleaning up buffers automatically

Recently, I discussed some ways to deal with large numbers of buffers. Maybe we can also take a step back and ask why we have so many buffers in the first place - do we really need all of them?

Well, the obvious answer is: probably not. After a few days of (emacs-uptime) there are all kinds of temporary output buffers, man pages and unchanged buffers you haven't touched in a long time. Let's get rid of those!

midnight

For this very purpose, emacs provides midnight-mode (as has done so for more than a decade). At midnight, it looks at all the buffers, and determines which of the buffers are no longer in use, and closes ('kills') them. Regardless of its name, this cleanup does not necessarily have to take place at midnight, but could be invoked at any time.

Setup is easy, just put the following in your .emacs:

(require 'midnight)

Clearly, the package was designed for emacs instances that are running for long times – for example, by default it clears buffers after having been inactive for 3 days. I'm not sure if that use case is very common today. Anyway, you can change it by setting clean-buffer-list-delay-general (which takes the number of days before a buffer becomes eligible for killing).

You can ask midnight-mode to clean-up unused buffers right now with M-x clean-buffer-list. Also, you can use some variables to control which buffers are to be killed, and which ones specifically not:

clean-buffer-list-kill-buffer-names
clean-buffer-list-kill-never-buffer-names
clean-buffer-list-kill-regexps
clean-buffer-list-kill-never-regexps

To run clean-buffer-list every n minutes or so, you could use run-at-time, left as an exercise to the reader.

tempbuf

Another way to accomplish roughly the same is TempbufMode.

It seems a bit better equipped for shorter cleanup interval, and you have some killed. However, that requires you to add it to the modes where you'd like to more influence on the algorithm it uses to decide whether a buffer may be use it, something like:

;; download tempbuf: http://www.emacswiki.org/emacs/tempbuf.el
(when (require 'tempbuf nil 'noerror) 
  (add-hook 'custom-mode-hook 'turn-on-tempbuf-mode)
  (add-hook 'w3-mode-hook 'turn-on-tempbuf-mode)
  (add-hook 'Man-mode-hook 'turn-on-tempbuf-mode)
  (add-hook 'view-mode-hook 'turn-on-tempbuf-mode))

Side-note: I'm using the (when (require 'tempbuf nil 'noerror) ... ) pattern here to make sure that my .emacs also works when tempbuf is not available.

Added: for cleaning-up your buffer list non-automatically, you can simply use M-x kill-some-buffers. (Thanks Susan!). Or you can use C-x C-b.