Tag Archives: GNU/Linux

Powerful Regular Expressions Combined with Lisp in Emacs

Regular expressions are a powerful text transformation tool. Any UNIX geek will tell you that. It’s so deeply ingrained into our culture, that we even make jokes about it. Another thing that we also love is having a powerful extension language at hand, and Lisp is one of the most powerful extension languages around (and of course, we make jokes about that too).

Emacs, one of the most famous Lisp applications today, has for a while now the ability to combine both of these, to reach entirely new levels of usefulness. Combining regular expressions and Lisp can do really magical things.

An example that I recently used a few times is parsing & de-humanizing numbers in dstat output. The output of dstat includes numbers that are printed with a suffix, like ‘B’ for bytes, ‘k’ for kilobytes and ‘M’ for megabytes, e.g.:

----system---- ----total-cpu-usage---- --net/eth0- -dsk/total- sda-
     time     |usr sys idl wai hiq siq| recv  send| read  writ|util
16-05 08:36:15|  2   3  96   0   0   0|  66B  178B|   0     0 |   0
16-05 08:36:16| 42  14  37   0   0   7|  92M 1268k|   0     0 |   0
16-05 08:36:17| 45  11  36   0   0   7|  76M 1135k|   0     0 |   0
16-05 08:36:18| 27  55   8   0   0  11|  67M  754k|   0    99M|79.6
16-05 08:36:19| 29  41  16   5   0  10| 113M 2079k|4096B   63M|59.6
16-05 08:36:20| 28  48  12   4   0   8|  58M  397k|   0    95M|76.0
16-05 08:36:21| 38  37  14   1   0  10| 114M 2620k|4096B   52M|23.2
16-05 08:36:22| 37  54   0   1   0   8|  76M 1506k|8192B   76M|33.6

So if you want to graph one of the columns, it’s useful to convert all the numbers in the same unit. Bytes would be nice in this case.

Separating all columns with ‘|’ characters is a good start, so you can use e.g. a CSV-capable graphing tool, or even simple awk scripts to extract a specific column. ‘C-x r t’ can do that in Emacs, and you end up with something like this:

|     time     |cpu|cpu|cpu|cpu|cpu|cpu|eth0 |eth0 | disk| disk|sda-|
|     time     |usr|sys|idl|wai|hiq|siq| recv| send| read| writ|util|
|16-05 08:36:15|  2|  3| 96|  0|  0|  0|  66B| 178B|   0 |   0 |   0|
|16-05 08:36:16| 42| 14| 37|  0|  0|  7|  92M|1268k|   0 |   0 |   0|
|16-05 08:36:17| 45| 11| 36|  0|  0|  7|  76M|1135k|   0 |   0 |   0|
|16-05 08:36:18| 27| 55|  8|  0|  0| 11|  67M| 754k|   0 |  99M|79.6|
|16-05 08:36:19| 29| 41| 16|  5|  0| 10| 113M|2079k|4096B|  63M|59.6|
|16-05 08:36:20| 28| 48| 12|  4|  0|  8|  58M| 397k|   0 |  95M|76.0|
|16-05 08:36:21| 38| 37| 14|  1|  0| 10| 114M|2620k|4096B|  52M|23.2|
|16-05 08:36:22| 37| 54|  0|  1|  0|  8|  76M|1506k|8192B|  76M|33.6|

The leading and trailing ‘|’ characters are there so we can later use orgtbl-mode, an awesome table editing and realignment tool of Emacs. Now to the really magical step: regular expressions and lisp working together.

What we would like to do is convert text like “408B” to just “408”, text like “1268k” to the value of (1268 * 1024), and finally text like “67M” to the value of (67 * 1024 * 1024). The first part is easy:

M-x replace-regexp RET \([0-9]+\)B RET \1 RET

This should just strip the “B” suffix from byte values.

For the kilobyte and megabyte values what we would like is to be able to evaluate an arithmetic expression that involves \1. Something like “replace \1 with the value of (expression \1)“. This is possible in Emacs by prefixing the substitution pattern with \,. This instructs Emacs to evaluate the rest of the substitution pattern as a Lisp expression, and use its string representation as the “real” substitution text.

So if we match all numeric values that are suffixed by ‘k’, we can use (string-to-number \1) to convert the matching digits to an integer, multiply by 1024 and insert the resulting value by using the following substitution pattern:

\,(* 1024 (string-to-number \1))

The full Emacs command would then become:

M-x replace-regexp RET \([0-9]+\)k RET \,(* 1024 (string-to-number \1)) RET

This, and the byte suffix removal, yield now the following text in our Emacs buffer:

|     time     |cpu|cpu|cpu|cpu|cpu|cpu|eth0 |eth0 | disk| disk|sda-|
|     time     |usr|sys|idl|wai|hiq|siq| recv| send| read| writ|util|
|16-05 08:36:15|  2|  3| 96|  0|  0|  0|  66| 178|   0 |   0 |   0|
|16-05 08:36:16| 42| 14| 37|  0|  0|  7|  92M|1298432|   0 |   0 |   0|
|16-05 08:36:17| 45| 11| 36|  0|  0|  7|  76M|1162240|   0 |   0 |   0|
|16-05 08:36:18| 27| 55|  8|  0|  0| 11|  67M| 772096|   0 |  99M|79.6|
|16-05 08:36:19| 29| 41| 16|  5|  0| 10| 113M|2128896|4096|  63M|59.6|
|16-05 08:36:20| 28| 48| 12|  4|  0|  8|  58M| 406528|   0 |  95M|76.0|
|16-05 08:36:21| 38| 37| 14|  1|  0| 10| 114M|2682880|4096|  52M|23.2|
|16-05 08:36:22| 37| 54|  0|  1|  0|  8|  76M|1542144|8192|  76M|33.6|

Note: Some of the columns are indeed not aligned very well. We’ll fix that later. On to the megabyte conversion:

M-x replace-regexp RET \([0-9]+\)M RET \,(* 1024 1024 (string-to-number \1)) RET

Which produces a version that has no suffixes at all:

|     time     |cpu|cpu|cpu|cpu|cpu|cpu|eth0 |eth0 | disk| disk|sda-|
|     time     |usr|sys|idl|wai|hiq|siq| recv| send| read| writ|util|
|16-05 08:36:15|  2|  3| 96|  0|  0|  0|  66| 178|   0 |   0 |   0|
|16-05 08:36:16| 42| 14| 37|  0|  0|  7|  96468992|1298432|   0 |   0 |   0|
|16-05 08:36:17| 45| 11| 36|  0|  0|  7|  79691776|1162240|   0 |   0 |   0|
|16-05 08:36:18| 27| 55|  8|  0|  0| 11|  70254592| 772096|   0 |  103809024|79.6|
|16-05 08:36:19| 29| 41| 16|  5|  0| 10| 118489088|2128896|4096|  66060288|59.6|
|16-05 08:36:20| 28| 48| 12|  4|  0|  8|  60817408| 406528|   0 |  99614720|76.0|
|16-05 08:36:21| 38| 37| 14|  1|  0| 10| 119537664|2682880|4096|  54525952|23.2|
|16-05 08:36:22| 37| 54|  0|  1|  0|  8|  79691776|1542144|8192|  79691776|33.6|

Finally, to align everything in neat, pipe-separated columns, we enable M-x orgtbl-mode, and type “C-c C-c” with the pointer somewhere inside the transformed dstat output. The buffer now becomes something usable for pretty-much any graphing tool out there:

| time           | cpu | cpu | cpu | cpu | cpu | cpu |      eth0 |    eth0 |  disk |      disk | sda- |
| time           | usr | sys | idl | wai | hiq | siq |      recv |    send |  read |      writ | util |
| 16-05 08:36:15 |   2 |   3 |  96 |   0 |   0 |   0 |        66 |     178 |     0 |         0 |    0 |
| 16-05 08:36:16 |  42 |  14 |  37 |   0 |   0 |   7 |  96468992 | 1298432 |     0 |         0 |    0 |
| 16-05 08:36:17 |  45 |  11 |  36 |   0 |   0 |   7 |  79691776 | 1162240 |     0 |         0 |    0 |
| 16-05 08:36:18 |  27 |  55 |   8 |   0 |   0 |  11 |  70254592 |  772096 |     0 | 103809024 | 79.6 |
| 16-05 08:36:19 |  29 |  41 |  16 |   5 |   0 |  10 | 118489088 | 2128896 |  4096 |  66060288 | 59.6 |
| 16-05 08:36:20 |  28 |  48 |  12 |   4 |   0 |   8 |  60817408 |  406528 |     0 |  99614720 | 76.0 |
| 16-05 08:36:21 |  38 |  37 |  14 |   1 |   0 |  10 | 119537664 | 2682880 |  4096 |  54525952 | 23.2 |
| 16-05 08:36:22 |  37 |  54 |   0 |   1 |   0 |   8 |  79691776 | 1542144 |  8192 |  79691776 | 33.6 |

The trick of combining arbitrary Lisp expressions with regexp substitution patterns like \1, \2\9 is something I have found immensely useful in Emacs. Now that you know how it works, I hope you can find even more amusing use-cases for it.

Update: The Emacs manual has a few more useful examples of \, in action, as pointed out by tunixman on Twitter.

Speeding Up Emacs and Parsing Emacs Lisp from Emacs Lisp

I recently spent a bit of time to clean up all the cruft that my ~/.emacs file and my ~/elisp directory had accumulated. I have been using a multi-file setup to configure my Emacs sessions, since at least 2008. This turned out to be a royal mess after 5+ years of patching stuff without a very clear plan or structure. The total line-count of both my ~/.emacs and all the *.el files I had imported into my ~/elisp directory was almost 20,000 lines of code:

$ wc -l BACKUP/.emacs $( find BACKUP/elisp -name '*.el')
   119 BACKUP/.emacs
    84 BACKUP/elisp/keramida-w3m.el
    90 BACKUP/elisp/keramida-keys.el
   156 BACKUP/elisp/keramida-irc.el
  5449 BACKUP/elisp/erlang.el
   892 BACKUP/elisp/fill-column-indicator.el
   344 BACKUP/elisp/keramida-erc.el
    87 BACKUP/elisp/keramida-chrome.el
    89 BACKUP/elisp/keramida-autoload.el
   141 BACKUP/elisp/keramida-ui.el
    42 BACKUP/elisp/keramida-slime.el
  1082 BACKUP/elisp/ace-jump-mode.el
     2 BACKUP/elisp/scala-mode2/scala-mode2-pkg.el
   907 BACKUP/elisp/scala-mode2/scala-mode2-indent.el
    26 BACKUP/elisp/scala-mode2/scala-mode2-lib.el
   502 BACKUP/elisp/scala-mode2/scala-mode2-fontlock.el
    37 BACKUP/elisp/scala-mode2/scala-mode2-map.el
   808 BACKUP/elisp/scala-mode2/scala-mode2-syntax.el
   111 BACKUP/elisp/scala-mode2/scala-mode2.el
   121 BACKUP/elisp/scala-mode2/scala-mode2-paragraph.el
  1103 BACKUP/elisp/php-mode.el
   142 BACKUP/elisp/themes/cobalt-theme.el
   665 BACKUP/elisp/themes/zenburn-theme.el
   142 BACKUP/elisp/themes/sublime-themes/cobalt-theme.el
    80 BACKUP/elisp/themes/tomorrow-night-blue-theme.el
    80 BACKUP/elisp/themes/tomorrow-night-eighties-theme.el
   115 BACKUP/elisp/themes/tomorrow-theme.el
    80 BACKUP/elisp/themes/tomorrow-night-bright-theme.el
   339 BACKUP/elisp/cmake-mode.el
    95 BACKUP/elisp/keramida-cc-extra.el
  1341 BACKUP/elisp/lua-mode.el
  2324 BACKUP/elisp/markdown-mode.el
   184 BACKUP/elisp/rcirc-notify.el
   167 BACKUP/elisp/keramida-defaults.el
   203 BACKUP/elisp/keramida-hooks.el
    43 BACKUP/elisp/keramida-lang.el
   435 BACKUP/elisp/edit-server.el
   709 BACKUP/elisp/slang-mode.el
    66 BACKUP/elisp/keramida-eshell.el
 19402 total

20,000 lines of code is far too much bloat. It’s obvious that this was getting out of hand, especially if you consider that I had full configuration files for at least two different IRC clients (rcirc and erc) in this ever growing blob of complexity.

What I did was make a backup copy of everything in ~/BACKUP and start over. This time I decided to go a different route from 2008 though. All my configuration lives in a single file, in ~/.emacs, and I threw away any library from my old ~/elisp tree which I haven’t actively used in the past few weeks. I imported the rest of them into the standard user-emacs-directory of modern Emacsen: at ~/.emacs.d/. I also started using eval-after-load pretty extensively, to speed up the startup of Emacs, and only configure extras after the related packages are loaded. This means I could trim down the list of preloaded packages even more.

The result, as I tweeted yesterday was an impressive speedup of the entire startup process of Emacs. Now it can start, load everything and print a message in approximately 0.028 seconds, which is more than 53 times faster than the ~1.5 seconds it required before the cleanup!

I suspected that the main contributor to this speedup was the increased use of eval-after-load forms, but what percentage of the entire file used them?

So I wrote a tiny bit of Emacs Lisp to count how many times each top-level forms appears in my new ~/.emacs file:

(defun file-forms-list (file-name)
  (let ((file-forms nil))
    ;; Keep reading Lisp expressions, until we hit EOF,
    ;; and just add one entry for each toplevel form
    ;; to `file-forms'.
    (condition-case err
        (with-temp-buffer
          (insert-file file-name)
          (goto-char (point-min))
          (while (< (point) (point-max))
            (let* ((expr (read (current-buffer)))
                   (form (first expr)))
              (setq file-forms (cons form file-forms)))))
      (end-of-file nil))
    (reverse file-forms)))

(defun file-forms-alist (file-name)
  (let ((forms-table (make-hash-table :test #'equal)))
    ;; Build a hash that maps form-name => count for all the
    ;; top-level forms of the `file-name' file.
    (dolist (form (file-forms-list file-name))
      (let ((form-name (format "%s" form)))
        (puthash form-name (1+ (gethash form-name forms-table 0))
                 forms-table)))
    ;; Convert the hash table to an alist of the form:
    ;;    ((form-name . count) (form-name-2 . count-2) ...)
    (let ((forms-alist nil))
      (maphash (lambda (form-name form-count)
                 (setq forms-alist (cons (cons form-name form-count)
                                         forms-alist)))
               forms-table)
      forms-alist)))

(progn
  (insert "\n")
  (insert (format "%7s %s\n" "COUNT" "FORM-NAME"))
  (let ((total-forms 0))
    (dolist (fc (sort (file-forms-alist "~/.emacs")
                      (lambda (left right)
                        (> (cdr left) (cdr right)))))
      (insert (format "%7d %s\n" (cdr fc) (car fc)))
      (setq total-forms (+ total-forms (cdr fc))))
    (insert (format "%7d %s\n" total-forms "TOTAL"))))

Evaluating this in a scratch buffer shows output like this:

COUNT FORM-NAME
   32 setq-default
   24 eval-after-load
   14 set-face-attribute
   14 global-set-key
    5 autoload
    4 require
    4 setq
    4 put
    3 defun
    2 when
    1 add-hook
    1 let
    1 set-display-table-slot
    1 fset
    1 tool-bar-mode
    1 scroll-bar-mode
    1 menu-bar-mode
    1 ido-mode
    1 global-hl-line-mode
    1 show-paren-mode
    1 iswitchb-mode
    1 global-font-lock-mode
    1 cua-mode
    1 column-number-mode
    1 add-to-list
    1 prefer-coding-system
  122 TOTAL

This showed that I’m still using a lot of setq-default forms: 26.23% of the top-level forms are of this type. Some of these may still be candidates for lazy initialization, since I can see that many of them are indeed mode-specific, like these two:

(setq-default diff-switches "-u")
(setq-default ps-font-size '(8 . 10))

But eval-after-load is a close second, with 19.67% of all the top-level forms. That seems to agree with the original idea of speeding up the startup of everything by delaying package-loading and configuration until it’s actually needed.

10 of the remaining forms are one-off mode setting calls, like (tool-bar-mode -1), so 8.2% of the total calls is probably going to stay this way for a long time. That’s probably ok though, since the list includes several features I find really useful, very very often.

Saving Space in Rsnapshot Archives with Hardlinks

The hardlink package is quite handy on Linux systems. It appears to do a nice job saving disk space in my local rsnapshot archives (25 GB reported as “saved” after today’s run on a week of daily snapshots). The stress put on my external USB backup disk wasn’t too extreme either, as reported by Munin’s IO/sec graphs for /dev/sdc:

IO/sec graph for a USB disk, while hardlink was running on a collection of rsnapshot daily archives.

IO/sec graph for a USB disk, while hardlink was running on a collection of rsnapshot daily archives.

That’s a lot of read operations, and then a percentage of them converted back to writes, when hardlink(1) discovers duplicate files and replaces them with hard links. Which is exactly the sort of behavior we’d expect from this sort of thing.

The hardlink invocation that triggered these I/O operation was quite mundane:

# time hardlink -f -m -v *home.*
[output stats ellided]
        1380.243 real   17.525 user     47.975 sys

Having run for a little over 23m it managed to hardlink enough files in my daily laptop backup snapshots to save 25 GB of disk space. I think it was worth the time vs. space trade-off :-)

Controlling the Keyboard Backlight from CLI

I found out today how to query and set the state of the keyboard backlight of my Asus Zenbook laptop through dbus-send calls, so I instantly thought “hey this would be nice to have in a shell script”.

So I wrote a small script called “backlight“, whose basic usage is a simple set of three commands:

backlight up
backlight down
backlight [ 0 | 1 | 2 | 3 ]

With this script installed as ‘~/bin/backlight’ in my home directory I can control the brightness of my keyboard’s backlight with simple shell commands, which is rather convenient, because all that usually runs on my desktop is a tiling window manager and a couple of terminals.

The script itself is rather small and it may be useful to someone else too, so here it is:

#!/bin/sh

# backlight_get
#       Print current keyboard brightness from UPower to stdout.
backlight_get()
{
    dbus-send --type=method_call --print-reply=literal --system         \
        --dest='org.freedesktop.UPower'                                 \
        '/org/freedesktop/UPower/KbdBacklight'                          \
        'org.freedesktop.UPower.KbdBacklight.GetBrightness'             \
        | awk '{print $2}'
}

# backlight_get_max
#       Print the maximum keyboard brightness from UPower to stdout.
backlight_get_max()
{
    dbus-send --type=method_call --print-reply=literal --system       \
        --dest='org.freedesktop.UPower'                               \
        '/org/freedesktop/UPower/KbdBacklight'                        \
        'org.freedesktop.UPower.KbdBacklight.GetMaxBrightness'        \
        | awk '{print $2}'
}

# backlight_set NUMBER
#       Set the current backlight brighness to NUMBER, through UPower
backlight_set()
{
    value="$1"
    if test -z "${value}" ; then
        echo "Invalid backlight value ${value}"
    fi

    dbus-send --type=method_call --print-reply=literal --system       \
        --dest='org.freedesktop.UPower'                               \
        '/org/freedesktop/UPower/KbdBacklight'                        \
        'org.freedesktop.UPower.KbdBacklight.SetBrightness'           \
        "int32:${value}}"
}

# backlight_change [ UP | DOWN | NUMBER ]
#       Change the current backlight value upwards or downwards, or
#       set it to a specific numeric value.
backlight_change()
{
    change="$1"
    if test -z "${change}" ; then
        echo "Invalid backlight change ${change}."                    \
            "Should be 'up' or 'down'." >&2
        return 1
    fi

    case ${change} in
    [1234567890]|[[1234567890][[1234567890])
        current=$( backlight_get )
        max=$( backlight_get_max )
        value=$( expr ${change} + 0 )
        if test ${value} -lt 0 || test ${value} -gt ${max} ; then
            echo "Invalid backlight value ${value}."                  \
                "Should be a number between 0 .. ${max}" >&2
            return 1
        else
            backlight_set "${value}"
            notify-send -t 800 "Keyboard brightness set to ${value}"
        fi
        ;;

    [uU][pP])
        current=$( backlight_get )
        max=$( backlight_get_max )
        if test "${current}" -lt "${max}" ; then
            value=$(( ${current} + 1 ))
            backlight_set "${value}"
            notify-send -t 800 "Keyboard brightness set to ${value}"
        fi
        ;;

    [dD][oO][wW][nN])
        current=$( backlight_get )
        if test "${current}" -gt 0 ; then
            value=$(( ${current}  - 1 ))
            backlight_set "${value}"
            notify-send -t 800 "Keyboard brightness set to ${value}"
        fi
        ;;

    *)
        echo "Invalid backlight change ${change}." >&2
        echo "Should be 'up' or 'down' or a number between"           \
            "1 .. $( backlight_get_max )" >&2
        return 1
        ;;
    esac
}

if test $# -eq 0 ; then
    current_brightness=$( backlight_get )
    notify-send -t 800 "Keyboard brightness is ${current_brightness}"
else
    # Handle multiple backlight changes, e.g.:
    #   backlight.sh up up down down up
    for change in "$@" ; do
        backlight_change "${change}"
    done
fi

Fixing Shifted-Arrow Keys in 256-Color Terminals on Linux

The terminfo entry for “xterm-256color” that ships by default as part of ncurses-base on Debian Linux and its derivatives is a bit annoying. In particular, shifted up-arrow key presses work fine in some programs, but fail in others. It’s a bit of a gamble if Shift-Up works in joe, pico, vim, emacs, mutt, slrn, or what have you.

THis afternoon I got bored enough of losing my selected region in Emacs, because I forgot that I was typing in a terminal launched by a Linux desktop. SO I thought “what the heck… let’s give the FreeBSD termcap entry for xterm-256color a try”:

keramida> scp bsd:/etc/termcap /tmp/termcap-bsd
keramida> captoinfo -e $(                                  \
  echo $( grep '^xterm' termcap | sed -e 's/[:|].*//' ) |  \
  sed -e 's/ /,/g'                                         \
  ) /tmp/termcap  > /tmp/terminfo.src
keramida> tic /tmp/terminfo.src

Restarted my terminal, and quite unsurprisingly, the problem of Shift-Up keys was gone.

The broken xterm-256color terminfo entry from /lib/terminfo/x/xterm-256color is now shadowed by ~/.terminfo/x/xterm-256color, and I can happily keep typing without having to worry about losing mental state because of this annoying little misfeature of Linux terminfo entries.

The official terminfo database sources[1], also work fine. So now I think some extra digging is required to see what ncurses-base ships with. There’s definitely something broken in the terminfo entry of ncurses-base, but it will be nice to know which terminal capabilities the Linux package botched.

Notes:
[1] http://invisible-island.net/ncurses/ncurses.faq.html#which_terminfo

Mate desktop support for xdg-open (tiny patch)

The Mate desktop really lives up to its promise of a “traditional desktop”, compatible in look and feel with Gnome 2.X versions.

After running it for a few hours now, I’m sold. I never really liked Unity very much, so Mate feels like ‘home’.

There are a few minor things that need tweaking though, mostly because the desktop is no longer called ‘Gnome’. One of them is the default xdg-open script that ships with the xdg-utils package. The current version of the script assumes that the desktop is called one of ‘KDE’, ‘LXDE’, ‘gnome’ or something else. The detectDE() function fails to recognize Mate, because it tries to look for GNOME_DESKTOP_SESSION_ID in its environment, and this is obviously no longer there for Mate.

The following patch fixes that, by checking for the string 'mate' in DESKTOP_SESSION instead, and adding a tiny bit of dispatch code based on DE='mate' further down, to call a new open_mate() function.

--- xdg-open.orig	2013-03-18 12:39:07.955516232 +0100
+++ xdg-open	2013-03-18 12:38:45.955515638 +0100
@@ -308,6 +308,7 @@
     elif `dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetNameOwner string:org.gnome.SessionManager > /dev/null 2>&1` ; then DE=gnome;
     elif xprop -root _DT_SAVE_MODE 2> /dev/null | grep ' = \"xfce4\"$' >/dev/null 2>&1; then DE=xfce;
     elif [ x"$DESKTOP_SESSION" = x"LXDE" ]; then DE=lxde;
+    elif [ x"$DESKTOP_SESSION" = x'mate' ]; then DE=mate;
     else DE=""
     fi
 }
@@ -371,6 +372,21 @@
     fi
 }
 
+open_mate()
+{
+    if gvfs-open --help 2>/dev/null 1>&2; then
+        gvfs-open "$1"
+    else
+        mate-open "$1"
+    fi
+
+    if [ $? -eq 0 ]; then
+        exit_success
+    else
+        exit_failure_operation_failed
+    fi
+}
+
 open_xfce()
 {
     exo-open "$1"
@@ -545,6 +561,10 @@
     open_gnome "$url"
     ;;
 
+    mate)
+    open_mate "$url"
+    ;;
+
     xfce)
     open_xfce "$url"
     ;;

Now this is a tiny problem, but it’s one that improves the usability of Mate for every-day stuff. One of the things that this fixes it the handling of magnet: links in Chrome. When Chrome tries to open magnet: links without this patch, it seems to “do nothing” but open a new tab and stop. With this patch applied, xdg-open works fine for magnet links (depending on your current MIME application settings too, of course), and Chrome happily opens torrent links in Mate desktops without a glitch.

Mutt-like Scrolling for Gnus

Mutt scrolls the index of email folders up or down, one line at a time, with the press of a single key: ‘<‘ or ‘>’. This is a very convenient way to skim through email folder listings, so I wrote a small bit of Emacs Lisp to do the same in Gnus tonight.

;;;
;; Scrolling like mutt for group, summary, and article buffers.
;;
;; Being able to scroll the current buffer view by one line with a
;; single key, rather than having to guess a random number and recenter
;; with `C-u NUM C-l' is _very_ convenient.  Mutt binds scrolling by one
;; line to '<' and '>', and it's something I often miss when working
;; with Gnus buffers.  Thanks to the practically infinite customizability
;; of Gnus, this doesn't have to be an annoyance anymore.

(defun keramida-mutt-like-scrolling ()
  "Set up '<' and '>' keys to scroll down/up one line, like mutt."
  ;; mutt-like scrolling of summary buffers with '<' and '>' keys.
  (local-set-key (kbd ">") 'scroll-up-line)
  (local-set-key (kbd "<") 'scroll-down-line))

(add-hook 'gnus-group-mode-hook 'keramida-mutt-like-scrolling)
(add-hook 'gnus-summary-mode-hook 'keramida-mutt-like-scrolling)
(add-hook 'gnus-article-prepare-hook 'keramida-mutt-like-scrolling)

This is now the latest addition to my ~/.gnus startup code, and we’re one step closer to making Gnus behave like my favorite old-time mailer.

Awesome WM in Ubuntu 12.04

I’ve been using awesome and other tiling window managers for a while now. I find it more comfortable when programs are using as much screen space as possible, and I like organizing my open windows in “workspaces” instead of having a huge pile of overlapping windows. Being able to extend the window manager’s default behavior with Lua is also rather appealing. So when a colleague recommended awesome a while ago, I started experimenting with it, and it stuck with me.

At first I was using the pre-packaged version of awesome, from the repository of Ubuntu Lucid. Then, as I started learning more about awesome, I installed a snapshot from the ‘master’ git branch of awesome’s development tree. For a while this worked fine, and when awesome started supporting fontconfig, pango and cairo, things were looking quite peachy!

My laptop was running Ubuntu Lucid though. This was not something I could change, for various reasons, security being one of the most important ones. So, when awesome’s git version switched from oocairo and oopango to lgi, various things broke. I could compile new git snapshots on Lucid just fine, but running awesome threw a traceback when it tried to load the very old “lgi” snapshot of Lucid. Compiling lgi and all its dependencies manually turned out to be a major undertaking, involving manual compiling of quite basic and central Gnome bits, like gobject-introspection. Replacing half of my Gnome desktop with manually compiled versions was a really bad idea, because it would require a major time and effort investment to keep up with all the fast-moving bits of Gnome. So I switched to another tiling window manager.

Why Awesome

The ‘container’ model of i3-wm is wonderful, but I was missing an easy way to extend the window manager, e.g. to tweak or extend its core features beyond what is supported by the relatively spartan roadmap of i3. Awesome’s scripting support fills that gap, using Lua for a large part of even the window-manager itself. A small core of awesome is written in C, and there’s a growing library of modules, extensions and plugins. In my not-so-humble opinion, having an extension language instantly makes a program a million times more useful. This is precisely why my favorite editor is GNU Emacs, for example.

So now that I had the opportunity to give awesome another try, I jumped right in. All I had to do was to make sure that lgi would work on my new Ubuntu installation. This post describes everything I tried, and how I eventually made my desktop look like this:

Tiled terminals and nautilus windows. A sample Gnome session with awesome as the window manager.

Sample awesome session, in Ubuntu Precise 12.04

I’m perfectly happy with this sort of setup. The rest of this article describes how I reached this installed and configured awesome, in the hope that other people who upgrade their machines to post-Gnome2 versions may find this useful too.

Installing Dependencies

The first thing I had to do was to make sure that all the dependencies of awesome are installed on my laptop.

Dependencies of Awesome Itself

Since awesome is already available in the package repositories of Ubuntu, the easiest way to do that is to use apt-get itself:

sudo apt-get install build-deps awesome

This will install all the dependencies of the pre-packaged awesome version. The latest development version of awesome uses the same libraries and one more: lgi, the Lua bindings to gnome libraries using gobject-introspection.

LGI: Lua bindings for gobject-introspection

Awesome depends on a fairly recent version of lgi. The one included in Precise repositories is, at the time of this writing, version 0.5-1, which is older than what awesome needs. So I had to compile lgi myself, from one of the newer releases. Release 0.6.2 is the latest version available at lgi’s Github repository, so I downloaded and unpacked this one:

wget -nd -np -c -r -O lgi-0.6.2.tar.gz \
    https://github.com/pavouk/lgi/tarball/0.6.2
tar xzvf lgi-0.6.2.tar.gz
mv pavouk-lgi-a4ad06c lgi-0.6.2

Before building lgi, it’s useful to have all its dependencies installed too. This is, again, rather easy to do with apt-get’s build-dep command:

sudo apt-get build-dep lua-lgi-dev

With the dependencies of lua-lgi out of the way, the next step is to compile and install lgi itself. The source of lgi uses a simple Makefile to compile everything, but you have to add the right directory to the C compiler’s include path, so that including “lua.h” works correctly. I did this by setting CPPFLAGS in the environment of make:

env CPPFLAGS='-I/usr/include/lua5.1' make

Then I installed the newly compiled lgi:

sudo env CPPFLAGS='-I/usr/include/lua5.1' make install

Gobject-introspection Repository

Lgi is not very useful without the necessary gobject-introspection data files. These are available as a package already, so the next things I installed are: libgirepository1.0-1 and libgirepository1.0-dev:

sudo apt-get install libgirepository1.0-1 libgirepository1.0-dev

That concludes the list of awesome and lgi dependencies, so it should be possible to build and run awesome just fine.

Getting the Sources

I normally run the git version of awesome. The master branch in the git repository is actively developed, and it’s always nice to be able to see recent developments in action, before they hit an official ‘stable’ release. I also happen to have git around “just in case”, since it’s now so popular that it threatens to dethrone Coca Cola or something similar from its popularity throne. So I branched awesome’s git repository and checked out the master branch:

cd ~/git
git clone git://git.naquadah.org/awesome.git
cd awesome
git checkout master

That’s all. A fairly recent, up to date, clean checkout of awesome’s development sources is now part of my permanent dumping ground of git clones, at ~gkeramidas/git/….

Compiling Awesome

The first thing you’ll notice when you look at a checkout of awesome’s sources is that it doesn’t use the ‘usual’ autoconf-based configure script to build. It uses CMake instead. If you don’t already have cmake around, now is a good time to install it:

sudo apt-get install cmake

Then you’re ready to build awesome from the sources. One of the interesting features of cmake is that it supports building in a “build directory”, separate from the source directory itself. This is very convenient, especially if you want to keep your git checkout ‘clean’. I often build stuff in “~/tmp/_build“, so I can quickly reclaim space by deleting old object files, without having to crawl my entire home directory. This is where cmake’s build-tree support came handy. To build awesome from its sources I typed:

cd ~/tmp/_build
mkdir awesome-git && cd awesome-git
cmake ~/git/awesome
make

If all goes well this should produce a full build of awesome and its associated files: an installable binary, Lua extensions of the core window-manager binary, manpages, etc. Installing this to the local system is then a piece of cake:

sudo make install

Note: By default this installs awesome in /usr/local. If you prefer to install awesome in /usr/bin instead, you should tell cmake to produce makefiles that use a different installation prefix directory:

cmake -DCMAKE_INSTALL_PREFIX:PATH='/usr' ~/git/awesome

Session Setup for Gnome

After awesome is installed to the system, some manual configuration is needed to launch awesome as part of the usual Gnome session. I created the following files, copying the xmonad instructions from another blog post.

The files I had to adapt are the following:

  • /usr/share/applications/awesome.desktop
  • /usr/share/gnome-session/sessions/awesome.session
  • /usr/share/xsessions/awesome-gnome-session.desktop

The first file, /usr/share/applications/awesome.desktop, registers awesome with the applications a Gnome user can run. It’s a simple text file, with the following contents:

[Desktop Entry]
Type=Application
Encoding=UTF-8
Name=Awesome
Exec=awesome
NoDisplay=true
X-GNOME-WMName=Awesome
X-GNOME-Autostart-Phase=WindowManager
X-GNOME-Provides=windowmanager
X-GNOME-Autostart-Notify=true

If you have installed awesome in /usr/local/bin/awesome and this directory is not in your default PATH for executables, you may have to replace “awesome” in the highlighted line 5 with the full path of the binary: /usr/local/bin/awesome.

The second file, /usr/share/gnome-session/sessions/awesome.session, defines what to start for a ‘Gnome session’ that uses awesome as the window manager. I use this file to launch awesome as the window-manager and a few useful applets: gnome-settings-daemon, gnome-sound-applet, bluetooth-applet and nm-applet.

[GNOME Session]
Name=Awesome Unity-2D Desktop
RequiredComponents=gnome-settings-daemon;gnome-sound-applet;nm-applet;bluetooth-applet;
RequiredProviders=windowmanager;
DefaultProvider-windowmanager=awesome

The third file, /usr/share/xsessions/awesome-gnome-session.desktop, configures the options that gnome-session will use when starting an ‘awesome style’ session. The most important bit is the –session option of line 5:

[Desktop Entry]
Name=Awesome GNOME
Comment=Tiling window manager
TryExec=/usr/bin/gnome-session
Exec=gnome-session --session=awesome
Type=XSession

Sample Awesome Desktops

Everything about awesome’s look and behavior is configured with Lua. This is very similar to what e.g. GNU Emacs does with Emacs Lisp, and it may seem a bit difficult to tweak at first. Fortunately there is a nice default startup file included in the sources of awesome itself. You will find it at awesomerc.lua in the source tree of awesome itself. This cna be immediately copied to ~/.config/awesome/rc.lua and you are ready to go. Incremental changes and small tweaks can then be added on top of the default configuration, to change the behavior of awesome or even to extend it with new features.

The two screenshots below show the default configuration of awesome, and how it looks with my own custom configuration file:

Screenshot of Default Awesome Configuration

Awesome running with its default configuration

Screenshot of Awesome with my custom configuration

Screenshot of Awesome with my custom configuration

You can find my own configuration attached below. Even more configuration examples are available at the wiki of awesome itself: http://awesome.naquadah.org/wiki/User_Configuration_Files

My Own Awesome Configuration

The rest of the post includes my current configuration file for awesome. This has diverged in several ways from the original configuration in the source tree of awesome, but I’m including it here for your reading pleasure.

-- -*- mode: lua; coding: utf-8; fill-column: 78; -*-
--
-- awesome/rc.lua -- startup code for the 'awesome' window manager
--
-- Copyright (C) 2010-2012, Giorgos Keramidas <gkeramidas@gmail.com>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
--    notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
--    notice, this list of conditions and the following disclaimer in the
--    documentation and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.

-- {{{ Important globals
-- Important global variables that have to be defined even before
-- loading modules or extensions, because they may affect where the
-- modules are loaded from.

-- Where most of the config files and loadable options live in my
-- current awesome setup.
home = os.getenv('HOME') or '/'
confdir = os.getenv("HOME") .. "/.config/awesome"

terminal = "term"
editor = os.getenv("EDITOR") or "utf-emacs"
filemgr = 'nautilus'
editor_cmd = editor

-- Standard awesome library
local gears = require("gears")
awful = require("awful")
awful.rules = require("awful.rules")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")

-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
    naughty.notify({ preset = naughty.config.presets.critical,
                     title = "Oops, there were errors during startup!",
                     text = awesome.startup_errors })
end

-- Handle runtime errors after startup
do
    local in_error = false
    awesome.connect_signal(
        "debug::error",
        function (err)
            -- Make sure we don't go into an endless error loop
            if in_error then
                return
            end
            in_error = true
            naughty.notify({ preset = naughty.config.presets.critical,
                             title = "Oops, an error happened!",
                             text = err })
            in_error = false
        end)
end
-- }}}

-- {{{ Variable definitions
-- Themes define colours, icons, and wallpapers
beautiful.init(confdir .. "/themes/keramida/theme.lua")

-- Default modkey.  Note that Mod1 is usually "Left Alt", so binding many
-- keys with this modifier may interfere with some of the shortcuts that
-- other programs want to use.  Use with caution.
modkey = "Mod1"

-- Table of layouts to cover with awful.layout.inc, order matters.
-- NOTE: These are not all the layouts supported by awesome; just the ones I
-- regularly find useful and want to have readily available.
local layouts = {
    awful.layout.suit.floating,
    awful.layout.suit.tile,
    awful.layout.suit.tile.left,
    awful.layout.suit.tile.bottom,
    awful.layout.suit.tile.top,
    awful.layout.suit.max,
}
-- }}}

-- {{{ Wallpaper
if beautiful.wallpaper then
    for s = 1, screen.count() do
        gears.wallpaper.maximized(beautiful.wallpaper, s, true)
    end
end
-- }}}

-- {{{ Tags
-- Define a tag table which hold all screen tags.
tags = {}
for s = 1, screen.count() do
    -- Each screen has its own tag table.
    tags[s] = awful.tag({ 1, 2, 3, 4 }, s, layouts[2])
end
-- }}}

-- {{{ Menu
-- Create a laucher widget and a main menu
myawesomemenu = {
    { "Terminal",    terminal },
    { "Preferences", "gnome-control-center" },
    { "Screenshot",  "gnome-screenshot -i" },
    { "Run",         "gmrun" },
    { "Restart",     awesome.restart },
    { "Lock",        "gnome-screensaver-command --lock" },
    { "Quit",        "pkill gnome-session" }
}
mymainmenu = awful.menu({ items = myawesomemenu })
mylauncher = awful.widget.launcher(
    { image = beautiful.awesome_icon, menu = mymainmenu })

-- Menubar plugin configuration
-- Just set the 'terminal' for those applications that require one.
menubar.utils.terminal = terminal
-- }}}

-- {{{ Wibox
-- Create a textclock widget
mytextclock = awful.widget.textclock(" %H:%M ")

-- Create a wibox for each screen and add it
mywibox = {}
mypromptbox = {}
mylayoutbox = {}
mytaglist = {}
mytaglist.buttons = awful.util.table.join(
    awful.button({        }, 1, awful.tag.viewonly),
    awful.button({ modkey }, 1, awful.client.movetotag),
    awful.button({        }, 3, awful.tag.viewtoggle),
    awful.button({ modkey }, 3, awful.client.toggletag),
    awful.button({        }, 4, function(t) awful.tag.viewprev(t.screen) end),
    awful.button({        }, 5, function(t) awful.tag.viewnext(t.screen) end)
)

mytasklist = {}
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1,
function (c)
    if c == client.focus then
        c.minimized = true
    else
        -- Without this, the following
        -- :isvisible() makes no sense
        c.minimized = false
        if not c:isvisible() then
            awful.tag.viewonly(c:tags()[1])
        end
        -- This will also un-minimize
        -- the client, if needed
        client.focus = c
        c:raise()
    end
end),
awful.button({ }, 3,
function ()
    if instance then
        instance:hide()
        instance = nil
    else
        instance = awful.menu.clients({ width=250 })
    end
end),
awful.button({ }, 4,
function ()
    awful.client.focus.byidx(1)
    if client.focus then client.focus:raise() end
end),
awful.button({ }, 5,
function ()
    awful.client.focus.byidx(-1)
    if client.focus then client.focus:raise() end
end))

for s = 1, screen.count() do
    -- Create a promptbox for each screen
    mypromptbox[s] = awful.widget.prompt()

    -- Create an imagebox widget which will contains an icon indicating which
    -- layout we're using. We need one layoutbox per screen.
    mylayoutbox[s] = awful.widget.layoutbox(s)
    mylayoutbox[s]:buttons(awful.util.table.join(
        awful.button({ }, 1, function () awful.layout.inc(layouts,  1) end),
        awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end),
        awful.button({ }, 4, function () awful.layout.inc(layouts,  1) end),
        awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end)))
    -- Create a taglist widget
    mytaglist[s] = awful.widget.taglist(
        s, awful.widget.taglist.filter.all, mytaglist.buttons)

    -- Create a tasklist widget
    mytasklist[s] = awful.widget.tasklist(
        s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons)

    -- Create the wibox
    mywibox[s] = awful.wibox({ height = "20", position = "top", screen = s })

    -- Widgets that are aligned to the left
    local left_layout = wibox.layout.fixed.horizontal()
    left_layout:add(mylauncher)
    left_layout:add(mytaglist[s])
    left_layout:add(mypromptbox[s])

    -- Widgets that are aligned to the right
    local right_layout = wibox.layout.fixed.horizontal()
    if s == 1 then
        right_layout:add(wibox.widget.systray())
    end
    right_layout:add(mytextclock)
    right_layout:add(mylayoutbox[s])

    -- Now bring it all together (with the tasklist in the middle)
    local layout = wibox.layout.align.horizontal()
    layout:set_left(left_layout)
    layout:set_middle(mytasklist[s])
    layout:set_right(right_layout)

    mywibox[s]:set_widget(layout)
end
-- }}}

-- {{{ Mouse bindings
root.buttons(awful.util.table.join(
    awful.button({ }, 3, function () mymainmenu:toggle() end),
    awful.button({ }, 4, awful.tag.viewnext),
    awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}

-- {{{ Key bindings
-- {{{
-- Experimental TAB focus cycling code for Awesome.
--
-- Copyright (C) 2011 Giorgos Keramidas <gkeramidas@gmail.com>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
--    notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
--    notice, this list of conditions and the following disclaimer in the
--    documentation and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.

-- The tabfocus function cycles through all the clients in the visible
-- screen, keeping the order of the clients unchanged.  Every time it is
-- called it returns the 'next' client in the list of clients of the
-- current screen.
function tabfocus()
    local focus = client.focus  -- the currently focused client
    local screen                -- the current screen

    -- If there's a currently focused client, cycle through the clients
    -- of the same screen.  Otherwise just use the one that the mouse is
    -- currently over.
    if focus then
        screen = focus.screen
    else
        screen = mouse.screen
    end

    -- Build a list of the clients listed in all the 'selected' tags of
    -- the current screen.
    local vc = {}
    local count = 1
    local stags = awful.tag.selectedlist(screen)

    for k, v in ipairs(stags) do
        local tag = v
        local tagclients = tag.clients(tag)
        for ck, cv in ipairs(tagclients) do
            if awful.client.focus.filter(cv) then
                vc[count] = cv
                count = count + 1
            end
        end
    end
    count = nil
    
    -- Cache the first client for later.  If the currently focused
    -- client is the last one, we will pick this one for focus.
    local first = vc[1]

    local found = nil           -- sentinel for focused client match
    local sel =  nil            -- the 'next' selected client for focus
    local first = vc[1]         -- cache first client for later

    for k, c in ipairs(vc) do
        if focus and c == focus then
            -- We just found the currently focused client.  Mark it as
            -- 'found' and let the next loop iteration pick up the next
            -- client in the list as the focus candidate.
            found = c
        end
        if sel == nil and found and c ~= focus then
            -- We don't have a focus candidate in 'sel' yet, but we
            -- found the currently focused client in a previous
            -- iteration and the current 'c' client is not the focused
            -- one.  Pick this one for the focus candidate.
            sel = c
        end
    end
    if sel == nil then
        -- We found the currently focused client as the last item in
        -- vc[], so loop back to the start of the client list and pick
        -- the first vc[] item for our focus candidate.
        sel = first
    end
    client.focus = sel
    if client.focus then
        client.focus:raise()
    end
end
-- }}}

-- A function that spawns 'gnome-screensaver-command' to lock the desktop.
-- Useful for binding to Alt-Ctrl-L to immitate Gnome's lock key behavior.
function lockdesktop ()
    command = "gnome-screensaver-command --lock"
    awful.util.spawn(command)
end

globalkeys = awful.util.table.join(
    awful.key({ modkey, "Control" }, "Left",   awful.tag.viewprev ),
    awful.key({ modkey, "Control" }, "Right",  awful.tag.viewnext ),
    awful.key({ modkey, "Control" }, "Escape", awful.tag.history.restore),

    -- Layout manipulation
    awful.key({ modkey, "Control" }, "j",
              function ()
                  awful.client.swap.byidx(1)
              end),
    awful.key({ modkey, "Control" }, "k",
              function ()
                  awful.client.swap.byidx(-1)
              end),
    awful.key({ modkey }, "Tab",
              function ()
                  tabfocus()
              end),
    awful.key({ modkey }, "space",
              function ()
                  awful.layout.inc(layouts,  1)
              end),

    -- Standard program
    awful.key({ modkey }, "Return",
              function ()
                  awful.util.spawn(terminal)
              end),
    awful.key({ modkey, "Control" }, "q",
              awesome.quit),
    awful.key({ modkey, "Control" }, "l",
              function()
                  lockdesktop()
              end),

    -- Menubar, and prompt.
    awful.key({ modkey, "Control" }, "p",
              function ()
                  menubar.show()
              end),
    awful.key({ modkey, "Control" }, "r",
              function ()
                  awful.util.spawn("gmrun")
              end)
)

clientkeys = awful.util.table.join(
    awful.key({ modkey,           }, "F11",
        function (c)
            -- TODO(gkeramidas): Save the state of the client window, to
            -- some place that allows restoring of all the 'important'
            -- attributes (c.maximized_horizontal, c,maximized_vertical
            -- and c.floating at least... maybe more).

            -- If the client-window is not already expanded to full-screen
            -- mode, maximize it at both directions first and float it before
            -- setting full-screen mode.  This avoids a small problem with
            -- compositing managers when a window is currently tiled.
            if not c.fullscreen then
                c.maximized_horizontal = true
                c.maximized_vertical = true
            end
            -- Now it should be safe to turn full-screen mode on or off.
            c.fullscreen = not c.fullscreen
        end),
    awful.key({ modkey,           }, "F4",
              function (c)
                  c:kill()
              end),
    awful.key({ modkey, "Control" }, "space",
              awful.client.floating.toggle),
    awful.key({ modkey, "Control" }, "Return",
              function (c)
                  c:swap(awful.client.getmaster())
              end),
    awful.key({ modkey,           }, "m",
              function (c)
                  c.minimized = not c.minimized
              end),
    awful.key({ modkey,           }, "F8",
        function (c)
          c.maximized_vertical = not c.maximized_vertical
        end),
    awful.key({ modkey, "Control" }, "m",
        function (c)
            c.maximized_horizontal = not c.maximized_horizontal
            c.maximized_vertical   = not c.maximized_vertical
        end)
)

-- Compute the maximum number of digit we need, limited to 9
keynumber = 0
for s = 1, screen.count() do
   keynumber = math.min(9, math.max(#tags[s], keynumber))
end

-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, keynumber do
    globalkeys = awful.util.table.join(globalkeys,
        awful.key({ modkey }, "#" .. i + 9,
                  function ()
                        local screen = mouse.screen
                        if tags[screen][i] then
                            awful.tag.viewonly(tags[screen][i])
                        end
                  end),
        awful.key({ modkey, "Control" }, "#" .. i + 9,
                  function ()
                      if client.focus and tags[client.focus.screen][i] then
                          awful.client.movetotag(tags[client.focus.screen][i])
                      end
                  end))
end

clientbuttons = awful.util.table.join(
    awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
    awful.button({ modkey }, 1, awful.mouse.client.move),
    awful.button({ modkey }, 3, awful.mouse.client.resize)
)

-- Enable the keys defined in the globalkeys table.
root.keys(globalkeys)
-- }}}

-- {{{ Rules
awful.rules.rules = {
    -- All clients will match this rule.
    {
        rule = { },
        properties = {
            border_width = beautiful.border_width,
            border_color = beautiful.border_normal,
            focus = true,
            size_hints_honor = false,
            keys = clientkeys,
            buttons = clientbuttons,
            maximized_vertical = false,
            maximized_horizontal = false
        }
    },

    -- Handle pidgin windows sensibly.  The buddy list is focused and
    -- set as the master window; conversations are slaves by default.
    { 
        rule = { class = "Pidgin", role = "buddy_list" },
        properties = {
        }
    },
    {
        rule = { class = "Pidgin", role = "conversation" },
        properties = {
            callback = awful.client.setslave
        }
    },

    -- Make the 'desktop' window of Nautilus sticky, so that it shows in
    -- all tags.  Other Nautilus windows, like 'file manager' views keep
    -- the normal, default window style.
    {
        rule = { class = "Nautilus", instance = "desktop_window" },
        properties = {
            border_width = 0,
            sticky = true
        }
    },

    -- Disable border for Chrome windows.  I usually run Chrome windows
    -- fully maximized, so a border doesn't appear useful.
    {
        rule = { class = "Google-chrome" },
        properties = {
            border_width = 0
        }
    },

    -- Some clients are floated by default.
    {
        rule = { class = "Gedit" },
        properties = {
            floating = true
        }
    },
}
-- }}}

-- {{{ Signals

--
-- Examples of what one can do in client signal callbacks:
--
--     c.opacity = 0.8        -- set transparency level
--     c.sticky = true        -- set the 'sticky window' property
--

-- Signal function to execute when a new client appears.
client.connect_signal("manage",
    function (c, startup)
        -- Enable sloppy focus
        c:connect_signal("mouse::enter", function(c)
            if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
                and awful.client.focus.filter(c) then
                client.focus = c
            end
        end)

        if not startup then
            -- Put windows in a smart way, only if they does not set an
            -- initial position.
            if ( not c.size_hints.user_position and
                 not c.size_hints.program_position ) then
                awful.placement.no_overlap(c)
                awful.placement.no_offscreen(c)
            end
        end
    end)

-- Signal that is triggered when a client window is focused.
client.connect_signal("focus",
    function(c)
        c.border_color = beautiful.border_focus
    end)

-- Signal that is triggered when a client window is unfocused.
client.connect_signal("unfocus",
    function(c)
        c.border_color = beautiful.border_normal
    end)
-- }}}

Unit Testing Uncovers Bugs

As part of the ‘utility’ library in one of the projects we are using at work, I wrote two small wrappers around strtol() and strtoul(). These two functions support a much more useful error reporting mechanism than the plain atoi() and atol() functions, but getting the error checking right in all the places they are called is a bit boring and cumbersome. This is probably part of the reason why there are still programs out there that use atoi() and atol(). Continue reading

FOSDEM 2010

Earlier tonight, on December 7 2009, a friend and me booked our flight tickets for FOSDEM 2010. I am really excited that I am going to attend another open source & free software conference. It has been a while since I had a chance to meet with other BSD people. The last time was in Milan, in EuroBSDCon 2006. It will certainly be tons of fun to meet in person with other free and open source fans, contributors and developers!

About FOSDEM

FOSDEM is an open conference, organized every year by volunteers to promote the widespread use of Free Software and Open Source Software. It takes place in the beautiful city of Brussels (Belgium). FOSDEM meetings are recognized as “The best Free Software and Open Source events in Europe”. Continue reading