2010-02-19

dealing with many buffers: ibuffer


If you are like me, you'll open a lot of buffers in emacs. There may be a couple of buffers with source code, a few for e-mail. org-mode will open buffers for all your agenda files. Then, maybe an info page, a few ERC-channels, a couple of special emacs buffers such as **Messages** and **scratch**. So, in a moderately busy emacs session there may 30-40 buffers open, and after a day or so there can be many more.

With so many buffers, it can be hard to quickly find the one you are looking for - and clearly a one-tab-per-buffer (like Firefox uses) would not work very well either.

So, what can we do instead? Here, on emacs-fu, we discussed this a couple of
times already:

  • using ido-mode, you can quickly switch to buffers by typing a subset of
    their name
  • using elscreen to step through buffer configurations (this comes close to a
    workable tab-like solution)

These are really useful tools. What's still missing though, is a way to get an overview of all buffers. For that, emacs provide buffer-menu, normally bound to C-x C-b. It lists all your buffers, and you can interact with them in a way similar to dired, e.g. you can switch to a buffer by moving the point (cursor) to the buffer and pressing Return. Or you mark buffers for deletion by pressing d when point is on the buffer, and then press x to kill them all.

Very useful. But if you really have a lot of buffers, just having a long list of them may still be a bit hard to deal with. For that, there is ibuffer, which allows you to put your buffers in different categories -- which can even overlap. Emacs ships ibuffer since version 22, so you'll probably already have it.

Using a setup like the following, you can put your buffers in categories; each buffer is shown only once (apparently, the first match), and you can match on mode (the Emacs-mode of the buffer), name (the buffer name), filename (the full path to the file being visited, if any), and a couple of others (see EmacsWiki).

(require 'ibuffer) 
(setq ibuffer-saved-filter-groups
  (quote (("default"      
            ("Org" ;; all org-related buffers
              (mode . org-mode))  
            ("Mail"
              (or  ;; mail-related buffers
               (mode . message-mode)
               (mode . mail-mode)
               ;; etc.; all your mail related modes
               ))
            ("MyProject1"
              (filename . "src/myproject1/"))
            ("MyProject2"
              (filename . "src/myproject2/"))
            ("Programming" ;; prog stuff not already in MyProjectX
              (or
                (mode . c-mode)
                (mode . perl-mode)
                (mode . python-mode)
                (mode . emacs-lisp-mode)
                ;; etc
                )) 
            ("ERC"   (mode . erc-mode))))))

(add-hook 'ibuffer-mode-hook
  (lambda ()
    (ibuffer-switch-to-saved-filter-groups "default")))
If you like ibuffer, you can even override the buffer-menu key binding for
it:
(global-set-key (kbd "C-x C-b") 'ibuffer)
As with buffer-menu, you can do various funky things with those buffers, and also filter them further; see the documentation. I am mostly using it for its buffer-navigational qualities, and it's good at that.

2010-02-08

interactive replacement



I recently found an interesting little package called iedit.el, which allows
you to interactive replacements on multiple strings at the same time. That is,
as you do one replace, you can see how all the same matches being replaced as
you type. It's hard to explain in words, you just have to try it out.

So, how to install this package?

  • First, download the package (see the link above)
  • Put it in a directory where emacs can find it; for example,
    ~/.emacs.d/elisp. If you haven't done so already, you can tell emacs to look in that directory by adding to your .emacs:
    (setq load-path (cons "~/emacs.d/elisp/" load-path))
    
  • Then, tell emacs to load this specific module; you can add
    (require 'iedit)
    
    to your .emacs to load it (alternatively, you could use the autoload facility)
  • then, define a key binding for this:
    (define-key global-map (kbd "C-;") 'iedit-mode)
    
  • Now, search for some strings that appears multiple times in your buffer, select it,
    press C-; (Ctrl+;), and watch how all other matching strings are
    changing at the same time.

Very nice.

2010-01-21

duplicating lines and commenting them

Someone on the Emacs Help mailing list asked for an easy way to duplicate a line
and, optionally, comment-out the first one.

Let's first look at simple duplication of a line. This is a common operation,
and vi-users might use something like Yp for that. In emacs, one way to do
this is by typing C-a C-k C-k C-y C-y, which is actually not as bizarre as
it looks if you try it. When using slick copy, as explained in another post,
it's as easy as M-w C-n C-y; and of course it's easy to define a shorter key
binding.

repeat after me
repeat after me

However, neither of these methods works correctly when you're on the last line
of the buffer (by default at least). Also, it puts the point (cursor) below
the duplicated line, while I'd like to put it at the start of it. It seems we
need something a little smarter.

While we're at it, let's also consider the second question: commenting-out the
first line of the duplicates. This is a quite common thing to do when writing
programs or configuration files; you want to try the effect of a small
variation of a line, but want to keep the original so it can be restored when
the variation turns out not to be as good as expected.

/* for (;;) fork (); */
for (;;) fork ();

I hacked up something quickly to solve both questions, and it has evolved a
little bit since – to answer both of the questions. The bit of weirdness in
the end is because of the special case of the last line in a buffer. It
defines key bindings C-c y for duplicating a line, and C-c c for
duplicating + commenting – but of course you can change those.

(defun djcb-duplicate-line (&optional commentfirst)
  "comment line at point; if COMMENTFIRST is non-nil, comment the original" 
  (interactive)
  (beginning-of-line)
  (push-mark)
  (end-of-line)
  (let ((str (buffer-substring (region-beginning) (region-end))))
    (when commentfirst
    (comment-region (region-beginning) (region-end)))
    (insert-string
      (concat (if (= 0 (forward-line 1)) "" "\n") str "\n"))
    (forward-line -1)))

;; or choose some better bindings....

;; duplicate a line
(global-set-key (kbd "C-c y") 'djcb-duplicate-line)

;; duplicate a line and comment the first
(global-set-key (kbd "C-c c") (lambda()(interactive)(djcb-duplicate-line t)))

2010-01-16

rectangles and cua

CUA-mode is a minor-mode that enables the use of Ctrl-X/C/V for cut/copy/paste, as is customary in many computer programs. Of course, it's a bit different in emacs, as it predates CUA and all of those programs. With esp. Ctrl-X (C-x) being in heavy use as a prefix-key already, it's unlikely to change.

CUA-mode has a clever trick to solve that problem – C-x for cut only works when a selection is active, and when no other key is pressed shortly. Otherwise, C-x behaves as usual. This works quite nicely, but personally, I don't use it, as I already have the Emacs key bindings in my muscle memory. Still, it can be useful for people migrating from other CUA-based editors. See e.g. CuaMode for more information.

However, apart from the C-x-trick, CUA also has some nice functionality for rectangular selections. These are sometimes quite useful, and during emacs-fu's prehistory there was already an article about it. The method there works, but with CUA, it is much easier.

So, let's turn it on; put the following in your .emacs:

(setq cua-enable-cua-keys nil) ;; only for rectangles
(cua-mode t)

Now, just put your cursor anywhere, and press C-RET (Ctrl + Enter). You have now started a rectangular selection! There rest is pretty straightforward, you can cut, copy and paste with the normal Emacs key bindings..

I could go into more detail, but the best way is to see it in action in this wonderful screen cast by Mark Mansour. I especially like the way you can add numbered lists.

2009-12-30

automatically checking your spelling

When I'm typing fast, it's easy to make spelling mistakes (as you may have noticed reading Emacs-Fu). It's not so much that I don't know how to write things, but sometimes there seems to be a bit of a disconnect between brain and fingers.

One tool that helps me to make fewer mistakes is automatic spelling checking, and in particular on-the-fly spelling checking. Spell-checking in emacs is taken care of by the ispell-package. Traditionally, this was a way to interface emacs with the ispell-program on Unix, but nowadays it's often used with other programs, such as aspell.

aspell is GNU's intended replacement for ispell, and has been for a long time. In the meantime, other spelling checkers have come up; in the Free Software world, the most prominent one is probably hunspell, which is used by e.g. Mozilla and OpenOffice. As I said, Emacs supports all of those; I'm using aspell, which works well for me. To use aspell for spelling-checking, I have the following in my .emacs:

(setq ispell-program-name "aspell"
  ispell-extra-args '("--sug-mode=ultra"))

Please consult the aspell documentation for the details.

You can spell-check your text with ispell-buffer and friends, which are also available through the menu (Tools/Spell Checking/...). This works fine, but it makes spelling checking a separate step you have to go through and you may forget. So, I like to do the spelling-checking on-the-fly, that is, while I am typing. This can be done using flyspell-mode (you can also use flyspell-prog-mode, to do spell checking inside comments in computer programs, but I find that a bit over the top).

When flyspell-mode is enabled, it will mark misspelt eh misspelled words by painting them in a different color while you are typing -- the common way many word processing programs do it. A common way to enable flyspell-mode is to put it the the mode-hook for the modes where you want to use it. For example, to enable flyspell-mode for all your org-mode buffers, you can add something like the following to your .emacs:

(add-hook 'org-mode-hook
  (lambda()
    (flyspell-mode 1)))

Note, you can use the middle mouse button to get alternatives for a misspelled word.

By default, it uses the English dictionary, but it's easy to switch to another using M-x ispell-change-dictionary. To make it easier, I have defined the C-c N key binding to activate Dutch-language ("nederlands") spelling checking, and update the buffer.

(global-set-key (kbd "C-c N") 
  (lambda()(interactive)
    (ispell-change-dictionary "nederlands")
    (flyspell-buffer))) 

Now, there's another category of mistakes – their-they're-there, its-it's or to-too-two that require a spelling checker that's a bit smarter. There are some free implementations in OpenOffice and Abiword; it'd be interesting to see if those could be integrated with emacs as well.

Now, laugh about the sweet irony of the spelling errors that I failed to notice :)

2009-12-13

scrolling

Scrolling It's an integral part of just about any graphical user interface, including emacs. However, I always found that the default way scrolling works in emacs left something to be desired. It puts the scroll bar on the left (!), and when scrolling around, it does not scroll smoothly, but instead it seem to do so in bursts. But, this being emacs, we can change it!

First, the position of the scroll bar. Presumably for historical reasons, emacs puts the scroll bar on the left of the window, unlike most other programs. We can easily change that, by putting the following in .emacs (or ~/.emacs.d/init.el):

(set-scroll-bar-mode 'right)

Instead of right, you can also use left, or nil to hide the scroll bar completely. You can also do this through the menu (Options / Show/Hide / Scroll bar). Note that on X, when the cursor (point) reaches the end of the document, the slider on the scroll bar may not be at the bottom; I understand this is because of some disagreement between Emacs and the toolkit (GTK+ in this case).

Now, what about the other issue, the non-smoothness when scrolling with the cursor-keys or with C-n, C-p? Below are my settings for making scrolling a bit smoother, and the explanation. Of course, these are just my personal preferences.

(setq
  scroll-margin 0                  
  scroll-conservatively 100000
  scroll-preserve-screen-position 1)
  • The scroll-margin. This determines when scrolling should start; by setting it to 0, emacs will start to scroll whenever you are entering the top or bottom line of the window. You can also this to, say, 5 to let scrolling start whenever you're getting closer than 5 lines from top or bottom
  • Then, scroll-conservatively determines how far the cursor is allowed to be distanced from the center of the screen when scrolling start. The default sets this to 0, which means that whenever you start scrolling, the cursor jumps to the center of the screen. I find that quite annoying, so I set it to some big number (the 'effective maximum' for that is lines-in-window / 2, but you can put any bigger number there to avoid the jumpiness)
  • scroll-preserve-screen-position tries to maintain the current screen position when you scroll using Page-Up/Page-Down. I like that.

There are also the variables scroll-up-aggressively and scroll-down-aggressively. Normally, they determine how far emacs will scroll (up and down, respectively) when it does so. However, they don't make any difference with a big scroll-conservatively like I am using. Still, if you want to play with it, their values are fractions between 0.0 and 1.0 (inclusive); a value of 1 means that it will move a full screen when scrolling starts, a value of 0.0 causes a move of only one single line.

2009-12-06

changing the cursor color and shape dynamically

When typing some text, it's often useful to know what mode we're in – are we in overwrite-mode, in read-only-mode, or in normal insert-mode. The information is available in the mode-line – but wouldn't it be nicer to get some small visual cue, for example by changing the cursor color or style?

That indeed is possible. There are some existing ways to do this, described in EmacsWiki. However, I want to be able to control both the cursor color and cursor shape, and also distinguish between overwrite, read-only and 'normal' mode. Below is my attempt.

By putting the following snippet in your .emacs, the cursor becomes a yellow vertical bar during normal mode, it becomes a red block when you're in overwrite-mode and it becomes a gray vertical bar when you're in read-only mode.

;; Change cursor color according to mode; inspired by
;; http://www.emacswiki.org/emacs/ChangingCursorDynamically
(setq djcb-read-only-color       "gray")
;; valid values are t, nil, box, hollow, bar, (bar . WIDTH), hbar,
;; (hbar. HEIGHT); see the docs for set-cursor-type

(setq djcb-read-only-cursor-type 'hbar)
(setq djcb-overwrite-color       "red")
(setq djcb-overwrite-cursor-type 'box)
(setq djcb-normal-color          "yellow")
(setq djcb-normal-cursor-type    'bar)

(defun djcb-set-cursor-according-to-mode ()
  "change cursor color and type according to some minor modes."

  (cond
    (buffer-read-only
      (set-cursor-color djcb-read-only-color)
      (setq cursor-type djcb-read-only-cursor-type))
    (overwrite-mode
      (set-cursor-color djcb-overwrite-color)
      (setq cursor-type djcb-overwrite-cursor-type))
    (t 
      (set-cursor-color djcb-normal-color)
      (setq cursor-type djcb-normal-cursor-type))))

(add-hook 'post-command-hook 'djcb-set-cursor-according-to-mode)

You can change the colors and cursor types by modifying the various variables.

I should probably turn this into a proper minor mode, but for now this seems to work well.