Posts Tagged ‘emacs’

Java Imenu

Monday, November 30th, 2009

My patch to CC-mode, which I talk about here, was finally accepted and submitted. The final regex turns out to be:

 
(defvar cc-imenu-java-generic-expression
  `((nil
     ,(concat
       "[" c-alpha "_][\]\[." c-alnum "_<> ]+[ \t\n\r]+" ; type spec
       "\\([" c-alpha "_][" c-alnum "_]*\\)" ; method name
       "[ \t\n\r]*"
       ;; An argument list that is either empty or contains any number
       ;; of arguments.  An argument is any number of annotations
 
       ;; followed by a type spec followed by a word.  A word is an
       ;; identifier.  A type spec is an identifier, possibly followed
       ;; by < typespec > possibly followed by [].
       (concat "("
               "\\("
                 "[ \t\n\r]*"
		 "\\("
		   "@"
		   "[" c-alpha "_]"
		   "[" c-alnum "._]*"
		   "[ \t\n\r]+"
		 "\\)*"
		 "\\("
		   "[" c-alpha "_]"
		   "[\]\[" c-alnum "_.]*"
		   "\\("
		     "<"
		     "[ \t\n\r]*"
		     "[\]\[.," c-alnum "_<> \t\n\r]*"
		     ">"
		   "\\)?"
                   "\\(\\[\\]\\)?"
                   "[ \t\n\r]+"
                 "\\)"
                 "[" c-alpha "_]"
                 "[" c-alnum "_]*"
                 "[ \t\n\r,]*"
               "\\)*"
               ")"
               "[.," c-alnum " \t\n\r]*"
               "{"
               )) 1))
  "Imenu generic expression for Java mode.  See `imenu-generic-expression'.")

You can install this in your emacs initializations for now; it will be in the 23.2 release. I’m glad it finally made it in - it will make my personal customizations slightly shorter.

As a result of this patch, I was also asked to join the cc-mode project in order to bring their Java support up to 1.6 - it’s unfortunately lagged behind, this patch being one example. If you’ve had any similar issue, please let me know!

Java and C++ Utilities

Wednesday, November 4th, 2009

I’ve been working on some utilities for coding in Java. JDE and CEDET ground my emacs to a halt the last time I tried them, so I wanted something lightweight. So far, I mostly have some functions for looking up documentation - including c++ documentation - that I store locally on my computer and keep in a repository, but I also have a few utilities for auto-importing Java classes.

The utilities to follow need these macros defined. I talked about them previously at:
http://nflath.com/2009/08/emacs-timing-and-upgrades/. They are utilities for generating functions that take arguments defaulting to word at point.

(defun my-fn (fn prompt)
  "When given a function taking one argument and applying a function to it, will use that function
   and default to the word at point, with a prompt including that word."
  (let ((default (current-word)))
    (let ((needle (read-string (concat prompt " <" default ">: "))))
      (if (equal needle "")
          (funcall fn default)
        (funcall fn needle)))))
 
(defmacro defun-my (name prompt &rest body)
  "Will define both a function and a my- version of the function,
which defaults to the word at point."
  `(progn
     (defun ,name (arg) ,@body)
     (defun ,(intern (concat "my-" (symbol-name name))) ()
       (interactive)
       (my-fn (quote ,name) ,prompt))))

These functions will be used in some of the later functions I wrote. These are used for caching large directory structures in a buffer to search for files instead of parsing the output of ‘find’ each time. Specifically, I use these to quickly look up which file I should be referencing to view documentation on Java and C++ classes. create-file-list will just create a list of files in the given buffer, and find-location-for-doc-from-buffer will return the full path of the matching html file you are searching for. Java-find-html-for-class is just a helper function that fills in the arguments for find-location-for-doc-from-buffer for Java buffers.

(defun create-file-list (directory buffer)
  "Creates the list of files in a directory"
  (save-window-excursion
    (let ((default-directory directory))
      (shell-command "find . " buffer)
      (switch-to-buffer buffer)
      (flush-lines "\.svn")
      (flush-lines "class-use"))))
 
(defun find-location-for-doc-from-buffer (arg buffer-name buffer-creation-fn begin)
  "Finds the file for a given documentation name in the buffer
that may be created with buffer-creation"
  (save-excursion
    (save-window-excursion
      (let ((doc-buffer (or (get-buffer buffer-name)
                            (funcall buffer-creation-fn))))
        (switch-to-buffer doc-buffer)
        (goto-char (point-min))
        (while (not (line-matches (concat "/" arg "\.html")))
          (search-forward arg))
        (concat begin
                (buffer-substring (1+ (line-beginning-position))
                                  (line-end-position)))))))

These next functions are used to look up documentation. my-java-describe-class will open up documentation for the input class file, whereas java-describe-variable will take a variable name and look backwards to it’s declaration and find documentation for that class. c-search-docs does something similar; it will prompt you for a keyword and see if anything in my c++ documentation matches it.

(defun-my java-describe-class "Open Javadoc for Class"
  "Loads javadoc for specified class in your browser."
  (interactive "MClass Name: ")
  (browse-url (java-find-html-for-class arg)))
 
(defun-my java-describe-variable "Open Javadoc for Variable"
  "Opens the javadoc for the variable at point, if possible."
  (interactive)
  (save-excursion
    (re-search-backward (concat "[ \t\n]"
                                "[A-Za-z]+"
                                "<[][A-Za-z0-9<>]*>"
                                "[ \t\n]"
                                arg))
    (forward-char)
    (java-describe-class (current-word))))
 
(defun-my c-search-docs "Documentation For"
  "Searches C++ Documentation for the requested term"
  (browse-url (find-location-for-doc-from-buffer
               arg
               "*C Documentation*"
               (lambda () (create-file-list "~/.emacs.d/documentation/c++/" "*C Documentation*"))
               "~/.emacs.d/documentation/c++/")))

Another task that I frequently have to do is fix imports in Java classes. Doing this manually is a huge pain, so I wrote a few functions to help. my-java-import-class will prompt for a class, look up it’s full package name, and add the import to the top of your file. Java-get-undefined-classes will run compile-command and parse the output to add all unimported classes. This needs java-undefined-symbol-regexp to be defined correctly, as well as compile-command to be set to something like ‘javac filename’.

(defun-my java-import-class "Import Class"
  "Adds an import statement for the class at point."
  (save-excursion
    (let ((my-retn-value nil))
      (let ((my-string (java-find-html-for-class arg)))
        (find-file my-string)
        (end-of-buffer)
        (re-search-backward "\"\\([A-Za-z0-9]+\\.\\)+[A-Za-z0-9]+ [ci][ln][at][se][sr]" )
        (let ((start (point)))
          (re-search-forward " " )
          (setq my-retn-value (substring (buffer-string) start (- (point) 2)))))
      (kill-buffer (current-buffer))
      (beginning-of-buffer)
      (re-search-forward "import " (point-max) t)
      (beginning-of-line)
      (when (looking-at "import")
        (end-of-line)
        (newline))
      (insert "import " my-retn-value ";\n" ))))
 
(defvar java-undefined-symbol-regexp "symbol  : class \\([A-Za-z0-9]*\\)")
(defun java-get-undefined-class-names ()
  (interactive)
  (save-window-excursion
    (remove-if
     #'not
     (remove-duplicates
      (mapcar (lambda (x)
                (if (string-match java-undefined-symbol-regexp x)
                    (match-string 1 x)))
              (split-string (shell-command-to-string compile-command) "\n *^\n")) :test #'string-equal))))
 
(defun java-import-undefined-classes ()
  (interactive)
  (save-window-excursion
    (mapc #'java-import-class (java-get-undefined-class-names))))

Org-mode

Wednesday, October 28th, 2009

I recently started to use org-mode, a emacs mode used for scheduling and organizing your tasks. I’ve really started to like it; I now do all my scheduling using it, instead of my previous Google Calendar.

Org-mode files are essentially trees, with * as the separator. An example is:

* Heading 1
** Subheading
some notes
more notes
** Subheading
* Heading 2

You can easily cycle the visibility using TAB. This is it’s basic note-taking mode; if you go far enough in, it’s quite complicated. For example, tasks can be scheduled, occur at a time, or have a deadline. You can insert deadlines for the current task with C-c C-d, schedule a task to begin with C-c C-s, or just add a timestamp to an item manually. Any of these can be recurring. These will show up on your agenda, which I’ll talk about shortly. An example with all of these types of timestamps is:

* Heading 1
** Subheading
<2009-10-19 Mon +1w>
some notes
more notes
** Subheading
TODO: <2009-10-21 Wed>
** Subheading 3
SCHEDULED: <2009-10-23 Fri>
* Heading 2

For a more detailed explanation of times with org-mode, read this.

Org-mode also has an ‘agenda’ view, which takes all the org files you’ve specified as agenda files and displays a timeline of them. This is one of my most used features; It allows you to easily see your schedule for a given day, see the list of items you have to do, and in general acts as a calendar. You can customize the various views; I haven’t done much of this, but you should read the org-mode manual in order to learn about this and other uses of org-mode.

To get started with org mode, you should require it:

(require 'org)

I set a few keybindings in order to make org easier to use. I remap left and right to raise the tree one level and indent the tree one level respectively. I map RETURN to add a new item; If i want a linebreak, I can still use C-j. I needed to use <, and it was bound to something I didn't care about, so I bound it to self-insert-command. Org-agenda switches to agenda mode, and I wanted it to be easily accessed.

(define-key org-mode-map (kbd "RET") 'org-meta-return)
(define-key org-mode-map (kbd "<left>") 'org-metaleft)
(define-key org-mode-map (kbd "<right>") 'org-metaright)
(define-key org-mode-map (kbd "<" ) 'self-insert-command)
(global-set-key "\C-ca" 'org-agenda)

There’s a few customizations I add to org to make it a smoother experience. The first thing is to turn off flyspell-mode. This is unfortunate; it could be useful, but as-is it just interferes with org-mode’s highlighting. I also set org-mode to log the time when I mark items as done. I set the list of my agenda files, and the amount of time in advance to start warning me of deadlines as 10 days. The last one is to set pabbrev to not activate; it interferes with org’s expanding and hiding of trees.

(add-hook 'org-mode-hook #'(lambda () (flyspell-mode -1)))
(setq org-log-done 'time)
(setq org-agenda-files '("~/org/technical.org" "~/org/designproject.org" "~/org/personal.org" "~/org/jobs.org" "~/org/martialarts.org" "~/org/emacs.org" "~/org/school.org" "~/org/financial.org"))
(setq org-deadline-warning-days 10)
 
(defadvice pabbrev-global-mode (around org-stop-pabbrev activate)
  (unless (eq major-mode 'org-mode)
    ad-do-it))

These functions are utilities used in publishing my agenda buffer. They work to generate a string describing the section number of the current bullet in an org buffer. These are required because exporting an org file to HTML will use these values as section numbers - to hyperlink to them in the agenda buffer, we will need to know this. There may already be functions to perform this, but I couldn’t find them.

    )))
 
(defun org-full-sections (&optional pos)
  "Returns a list coresponding to the full section number at pos"
  (interactive)
  (save-excursion
    (if pos (goto-char pos))
    (let* ((retn 1)
           (curnum (org-current-section-number))
           (retlist (list curnum)))
      (condition-case nil
          (while t
            (progn
              (outline-up-heading 1)
              (setq retlist (append (list (org-current-section-number)) retlist))))
        (error retlist))
      retlist)))
 
(defun org-full-sections-string (&optional pos)
  "Returns a string corresponding to the section at pos"
  (interactive)
  (substring (reduce (lambda (x y) (concat x "." (number-to-string y)))
                     (org-full-sections)
                     :initial-value "") 1))

Sometimes, I’m not on my primary computer, which has all of my agenda-files, and still want to be able to look at my schedule. To do this, the logical way would be to store my agenda as a HTML file that I can access from anywhere. Org has a few ways to publish to HTML, but I could not find how to export the agenda buffer and files, hyperlinked so that it emulates the actual agenda. I ended up writing a rather ugly method to do it myself; the results are below.

(defun org-publish-agenda ()
  (interactive)
  (save-window-excursion
    (mapcar (lambda (file)
              (find-file file)
              (org-export-as-html 3)
              (kill-buffer))
            org-agenda-files)
    (org-agenda 0 "a")
    (org-agenda-month-view)
    (let ((html-buffer (htmlize-buffer (get-buffer "*Org Agenda*")))
          (agenda-buffer (get-buffer "*Org Agenda*")))
      (switch-to-buffer html-buffer)
      (goto-char (point-min))
      (search-forward "<body>")
      (let ((line-start (line-number-at-pos)))
        (while (< (point) (point-max))
          (beginning-of-line)
          (cond
           ((line-matches "org-agenda-structure") (forward-line))
           ((line-matches "org-agenda-dat") (forward-line))
           ((line-matches "org-time-grid") (forward-line))
           ((line-matches " *\\([^:]+\\):")
            (let ((calendar (after-last " "(match-string 1))))
              (let ((agenda-line-no (1- (- (line-number-at-pos) line-start))))
                (switch-to-buffer agenda-buffer)
                (goto-line agenda-line-no)
                (let* ((marker (or (get-text-property (point) 'org-marker)
                                   (org-agenda-error)))
                       (buffer (marker-buffer marker))
                       (pos (marker-position marker)))
                  (switch-to-buffer buffer)
                  (goto-char pos)
                  (setq sec-string (concat "sec-" (org-full-sections-string)))
                  (switch-to-buffer html-buffer)
                  ))
              (insert (concat "<a href=\"" calendar ".html#" sec-string "\">"))
              (end-of-line)
              (insert "</a>")
              (forward-line)))
           (t (forward-line))
           )))
      (write-file "~/org/agenda.html")
      (let ((default-directory "~/org/"))
        (shell-command "mv *.html publish/")
        (kill-buffer "agenda.html")
        ))))
 
(defun org-publish-agenda-to-site ()
  (interactive)
  (save-window-excursion
    (org-publish-agenda)
    (shell-command "scp -r ~/org/publish nflath.com:/home/nflath/public_html/nflath.com/ &")))
 
(setq agenda-update-timer (run-with-timer 0 3600 'org-publish-agenda-to-site))

These functions require org-publish-location to be defined to the value you wish the HTML to be stored. This isn’t the best code; it assumes that your agenda files are in ~/org, and that the directory ~/org/publish exists, but this should be easy to fix if this is not where you store your agenda files.

org-publish-agenda works by modifying the results of calling htmlize-buffer on the org-agenda; htmlize.el is a package that can turn arbitrary buffers into HTML. It is sometimes useful when you want to export your view of a file, such as in this case. To use it, you have to put the following in your initialization file:

(require 'htmlize)

Save Visited Files, V1.1

Thursday, October 22nd, 2009

If you remember a post I wrote a while back, I had made a mode save-visited-files that was a lightweight replacement for desktop.el.  It saves the files you have opened, reloading these whenever you start emacs.  Ryan Thompson spent some time improving save-visited-files, so I thought I’d release his improvements.  save-visited-files.el can be downloaded from here.

Save-visited-files now uses auto-save-hook instead of a periodic timer.  This is probably the better decision, but it means you don’t want it to trigger too often.  In order to reduce the number of auto-saves, you can use the following, which will auto-save every 3000 input events:

(setq auto-save-interval 3000)

The functions and variables in save-visited-files are also named more consistently, with each one being prefixed with save-visited-files.  The mode can now also be customized with M-x customize-group save-visited files.  As a final improvement, the handling of the temporary buffer is handled much more nicely, so that the user is never presented with it.

To use the new save-visited-files, just put the following in your .emacs file:

(require 'save-visited-files)
(turn-on-save-visited-files-mode)

More Gmail with Emacs

Wednesday, October 21st, 2009

The last time I talked about using Gmail from Emacs, several people suggested using Wanderlust, an IMAP client written in ELisp. Details for setting it up can be found here; just following those set it up well for reading my email. This worked until I wanted to send a mail from emacs, and found that wanderlust had replaced emac’s send-mail function with it’s own, which didn’t work. I tried for a bit to figure out why it was failing, but eventually gave up on wanderlust and set GNUs up for gmail again.

After this, I decided to try using GNUs for accessing my Gmail again. This process is fairly easy:
put the following in your configuration file:

(setq gnus-select-method '(nnimap "gmail"
(nnimap-address "imap.gmail.com")
(nnimap-server-port 993)
(nnimap-stream ssl)))

Once you have evaluated this expression, do M-x gnus and then S s and enter INBOX. This will switch to your GMail inbox. There are a few problems with this, however. The first is that very few messages are actually presented to you; even though it asked how many to retrieve, and I used a value of ‘100′, only three were presented. I really want to be able to read older mail; If anyone knows how to fix this, please let me know. The other issue, which isn’t as bad, is that read mail does not update the Gmail web interface as read.

Getting back to sending emails, I wrote a function to allow me to easily insert emails. It works for both individual people and multiple addresses.

(defun insert-email ()
(interactive)
(insert (cadr (assoc (ido-completing-read
"Name: "
(mapcar #'car email-alist))
email-alist))))
(global-set-key (kbd "C-c m") 'insert-email)

This function uses the value of email-alist, which is an alist of names to emails. This doesn’t even have to be used to insert emails; that’s just what I’m using them for. To set email-alist to the proper value, use:

(setq email-alist
'(("Name1" "email1")
("Name2" "email2")))

This ends up letting you use Ido to select between name1 and name2 to insert email1 or email2. As I said, it’s more general than what I’m using it for currently - you can use it select any arbitrary text for insertion.

C++ Customizations for Emacs

Monday, October 19th, 2009

I’ve been doing more C++ than usual for courses, so I ended up revisiting my C++ configuration and loading up some old customizations that I had in order to be more productive. I didn’t pull in all of my old ones, such as all the CEDET stuff that had been slowing down my emacs significantly, but I did find some useful customizations that I had and wanted to put back in.

The first was to define a project type for C/C++ projects using eproject. This lets you easily switch between files in the same project, as well as perform other actions described in the linked post. I define the project base to just be the topmost directory with a Makefile.

(define-project-type cpp (generic)
  (look-for "Makefile")
  : relevant-files ("\\.cpp" "\\.c" "\\.hpp" "\\.h"))

Another re-addition is member-function.el, a mode that will automatically expand member functions in class definitions with stubs. This ends up saving me a lot of time, since I don’t have to write out the function definitions twice for every function - I just add it to the class definition and then it appears in the corresponding implementation file.

Normally expand-member-function must be run interactively and prompt you for the header and implementation file, but I just created a function that would find these values and run it with the correct values. I added it to c-mode-hook, which will cause it to be run whenever a C/C++ file is opened, without me having to do anything.

I also got tired of typing in #ifndef blocks for my header files, so I wrote a function that would insert this in newly-created .h and .hpp files. I also added this function to c-mode-hook, making it so I never have to type one again (I hope).

(defun h-file-create ()
  "Create a new h file.  Insert a infdef/define/endif block"
  (interactive)
  (if (or (equal (substring (buffer-name (current-buffer)) -2 ) ".h")
          (equal (substring (buffer-name (current-buffer)) -4 ) ".hpp"))
      (if (equal "" (buffer-string))
          (insert "#ifndef "(upcase (substring (buffer-name (current-buffer)) 0 -2)) "_H\n#define "
                  (upcase (substring (buffer-name (current-buffer)) 0 -2)) "_H\n\n#endif"))))
 
(defun c-file-enter ()
  "Expands all member functions in the corresponding .h file"
  (interactive)
  (let ((c-file (buffer-name))
        (h-file (concat (substring (buffer-name (current-buffer)) 0 -3 ) "h")))
    (if (equal (substring (buffer-name (current-buffer)) -4 ) ".cpp")
        (if (file-exists-p h-file)
              (expand-member-functions h-file c-file)))))

I also occasionally write small C++ programs for testing purposes. In these cases, it’s nice to be able to do a M-x compile and have it work without having to manually type in a compile-command. yourself. This will set the compile-command to one that will appropriately compile the current file if no Makefile exists whenever a c/c++ file is opened.

(add-hook 'c-mode-hook
          (lambda ()
            (unless (file-exists-p "Makefile")
              (set (make-local-variable 'compile-command)
                   (let ((file (file-name-nondirectory buffer-file-name)))
                     (format "%s -c -o %s.o %s %s %s"
                             (or (getenv "CC") "g++")
                             (file-name-sans-extension file)
                             (or (getenv "CPPFLAGS") "-DDEBUG=9")
                             (or (getenv "CFLAGS") "-ansi -pedantic -Wall -g")
                             file))))))

I also finally learned how to properly use tags. Tags allow you to quickly navigate to declarations of functions and symbols in your program. To use tags, you must first create a tags file using either etags or exuberant ctags - etags comes with emacs, so you will have at least one of these. You use one of these to generate a TAGS file just by using ‘etags’ in the directory you wish to create a TAGS file in. It will automatically scan all files and subdirectories to create this file.

Once your index is created, you can jump to the definition of a function with M-.. This will prompt for a TAGS file the first time you use it, and then use that index to jump to the function definition you supply (defaulting to the one at point). If there are several conflicting definitions, C-u M-. will go to the next possible definition. Once you are done with that location, M-* will take you back to where you originally jumped from. C-x 4 . will perform a find-tag, but will open the declaration in another window. There are a few other tags commands, but these are the most useful ones. To find out more, read the TAGS node in the Emacs manual.

One last utility I added was . Cscope is the reverse of etags; given a symbol, it will find all uses of that symbol. To use it, cscope must be installed; in Ubuntu you can do this with ’sudo apt-get install cscope’. To use it, just use M-x cscope-find-c-symbol to have it output a list of all references to the symbol; this list is linked to your source, so you can jump to files by pressing ‘enter’ on the line you have selected. cscope-find-functions-calling is also useful; it iwll return a list of all functions that call the function you specify. There are a few more commands, but these are the ones I use; look at the commands starting with cscope- to find a list of them. To enable cscope, you need to put cscope.el in your load path and add the following to your initialization:

(require 'cscope)

Bitlbee and Emacs

Friday, October 16th, 2009

As part of switching to bitlbee as my primary IM client, I ended up making a lot of customizations to my erc configuration, both for general use and for bitlbee-specific stuff. I didn’t really have any beforehand, since I don’t use IRC very much, but these make it a lot more usable with bitlbee. Bitlbee can be pretty annoying at the start; these help to make it much less so. Most of the general ERC customizations came from the emacs-Viki, but most of the bitlbee-related code is mine.

The first customization I made was to set the header-line of disconnected buffers to be a different face than normal. The header line is just the top line of the buffer; some modes, such as ERC, use it for displaying information about the current context. This just makes it easier to tell which ERC buffers are still connected to the server.

(defface erc-header-line-disconnected
  '((t (:foreground "black" :background "indianred")))
  "Face to use when ERC has been disconnected.")
 
(defun erc-update-header-line-show-disconnected ()
  "Use a different face in the header-line when disconnected."
  (erc-with-server-buffer
    (cond ((erc-server-process-alive) 'erc-header-line)
          (t 'erc-header-line-disconnected))))
          (setq erc-header-line-face-method 'erc-update-header-line-show-disconnected)
 
(setq erc-header-line-face-method 'erc-update-header-line-show-disconnected)

I like to log my IM messages. I often have useful discussions with people, or receive information from them, that I want to refer to later. The following sets my log directory and updates them whenever the ERC buffer is updated, ensuring I never lose information.

(setq erc-log-channels-directory "~/.emacs.d/logs/")
(setq erc-save-buffer-on-part nil)
(setq erc-save-queries-on-quit nil
      erc-log-write-after-send t
      erc-log-write-after-insert t)

IRC in general will give a lot of messages that you don’t care about, and there are some bitlbee-specific ones as well. erc-hide-list is a list of types of messages that ERC will hide, and erc-ignore-unimportant is a function I wrote to suppress other information I don’t want to see. This includes mode changes for people and reconnection attempts when an account is already online.

(setq erc-hide-list '("MODE"))
(defun erc-ignore-unimportant (msg)
  (if (or (string-match "*** localhost has changed mode for &bitlbee to" msg)
          (string-match "Account already online" msg)
          (string-match "Unknown error while loading configuration" msg))
      (setq erc-insert-this nil)))
(add-hook 'erc-insert-pre-hook 'erc-ignore-unimportant)

Speaking of reconnection attempts when an account is online, I have ERC automatically connect me to my accounts whenever I log on as well as every 60 seconds. This simulates the behaviour of other IM clients, which will auto-reconnect when disconnected.

(defvar bitlbee-password "<SECRET>")
(defun bitlbee-identify ()
  "If we're on the bitlbee server, send the identify command to the
 &bitlbee channel."
  (when (and (string= "localhost" erc-session-server)
             (string= "&bitlbee" (buffer-name)))
    (erc-message "PRIVMSG" (format "%s identify %s"
                                   (erc-default-target)
                                   bitlbee-password))))
(add-hook 'erc-join-hook 'bitlbee-identify)
 
(defun bitlbee-connect ()
  (interactive)
  (save-window-excursion
    (when (get-buffer "&bitlbee")
      (switch-to-buffer "&bitlbee")
      (erc-message "PRIVMSG" (concat (erc-default-target) " identify " bitlbee-password))
      (erc-message "PRIVMSG" (concat (erc-default-target) " account on 0")
      (erc-message "PRIVMSG" (concat (erc-default-target) " account on 1"))))))
(setq bitlbee-reconnect-timer (run-with-timer 0 60 'bitlbee-connect))

The ‘blist’ command for bitlbee will list your buddies and their statuses. However, by it doesn’t do any color-coding for your Friends who are online vs who are away, so I had to add this. It isn’t very difficult; erc-keywords is a list of keyword-face pairs that the keyword is matched with. All you need to do to perform any type of highlighting is be able to match the message you want highlighted with a regular expression.

(setq erc-keywords '((".*Online.*" (:foreground "green"))
                     (".*Busy" (:foreground "red"))
                     (".*Away" (:foreground "red"))
                     (".*Idle" (:foreground "orange"))
                     ))

One of the reasons I switched from Pidgin to Bitlbee was that Pidgin was no longer notifying me of new messages; I decided to try seeing if I could implement this for bitlbee. It actually turned out to be pretty easy, although there is one problem: it only occurs for messages sent to the public channel, not private messages, so it won’t inform me when someone starts a conversation with me. I’m still looking into how to fix this.

(defun erc-notify-on-msg (msg)
  (if (string-match "nflath:" msg)
      (shell-command (concat "notify-send \"" msg "\""))))
(add-hook 'erc-insert-pre-hook 'erc-notify-on-msg)

The last customization I have to bitlbee is so that I don’t have to type the user I’m addressing each time in the public channel. Usually, you have to prepend each message with user: in order for it to be sent to them; this code will auto-prepend messages with the last user you addressed. It’s a work in progress, as a lot of cases I don’t want this to happen - for example, when I’m listing my buddies - but it’s pretty good right now.

(setq bitlbee-target "")
(defun bitlbee-update-target (msg)
  (if (string-match "\\([^:]*: \\)" msg)
      (setq bitlbee-target (match-string 1 msg))
    (if (not (or
              (string-match "account" msg)
              (string-match "help" msg)
              (string-match "identify" msg)
              (string-match "blist" msg)))
        (setq str (concat bitlbee-target msg)))))
(add-hook 'erc-send-pre-hook 'bitlbee-update-target)

I generally want to be logged into IM, so I just start it up on emacs start.

(erc :server "localhost" :port "6667" :nick "nflath" :password bitlbee-password)

If you have any other customizations or improvements to suggest, please let me know in the comments.

Emacs Settings

Wednesday, October 14th, 2009

I recently upgraded to 23.1.5 from 23.0.6, and a few of my customizations broke - not many, but I also made a number of changes to my configuration, so I figured I’d cover them all here. Overall, it was a pretty easy process - the only customization that broke that I still haven’t figured out is Slime breaking. It works if I run everything up to and including the call to slime, but not if I then continue running my other customizations.

These first customizations modify general Emacs behavior. debug-on-error will give a backtrace when an error is encountered in any running elisp code; this makes it much easier to debug problems. If display-battery-mode is on, your battery level and heat is shown in the mode line. apropos-do-all will make apropos do everything; it is much more useful this way. Setting pop-up-windows to nil will stop emacs from changing your window configuration, and confirm-nonexistent-file-or-buffer will stop emacs from prompting you whenever you create a new file.

(setq debug-on-error t)
(display-battery-mode t)
(setq apropos-do-all t)
(setq pop-up-windows nil)
(setq temporary-file-directory "~/.emacs.d/tmp/")
(setq confirm-nonexistent-file-or-buffer nil)

I also noticed that hitting the spacebar now inserted a space character in my minibuffer. This is essentially never what I want, so I changed it to completion with:

(define-key minibuffer-local-map (kbd "SPC") 'minibuffer-complete)

The next set of customizations I added modified the behaviour of shell modes. The first one will cause cycling to skip unique values; if you run the same command twice, M-p twice will take you to a different commands. The other two are fairly self-explanatory, and are for showing as much as possible in the buffer.

(setq comint-input-ignoredups t)
(setq comint-scroll-show-maxiumum-output)
(setq comint-scroll-to-bottom-on-input t)

Finally, I added a few functions to help out. M-x google will now prompt me for a search string and then open a browser with a query for that string. Line-matches is used programatically in order to tell if the line point is on matches the given regular expression.

(defun google (query)
  "googles a query"
  (interactive "sQuery:")
  (browse-url (concat "http://www.google.com/search?q=" query)))
 
(defun line-matches (regexp)
  "Returns non-nil if the current line matches the given regexp, nil otherwise."
  (save-excursion
    (end-of-line)
    (let ((end (point)))
      (beginning-of-line)
      (re-search-forward regexp end t))))

Docview

Monday, October 12th, 2009

docview is a built-in document viewer for Emacs that can display dvi, ps, and pdf files. It isn’t as good as most PDF readers, but in a lot of cases it’s good enough without having to switch to a different application. It works by converting the files to a series of ‘png’ images, one per page, which Emacs can display. This means that you can’t edit them or copy text from PDF files, but if you only need to view them it works.

docview is enabled by default in emacs - opening a pdf file as a normal file will turn on docview-mode. The only customization I currently have for it is to turn on auto-revert for pdf files; I use this when creating a PDF file using latex and wish it to be auto-updated. There’s not much else I can think of that would improve this mode by the use of hooks - mostly to make it better Emacs would need native PDF support.

(add-hook 'doc-view-mode-hook 'turn-on-auto-revert-mode)

Using docview is fairly simple: n/p will move to the next or previous page and C-n/C-p moves up or down on the current page. You can zomm in and out with + and - respectively. Other normal movement keys are rebound to something appropriate - M-> will go to the last page, for example. You can also search for text with ‘C-s’ and ‘C-r’, but this will only take you to the correct page and message you the line the text is on - it won’t highlight the text for you, so it is rather subpar.

Gmail from Emacs

Friday, October 9th, 2009

I’ve meant to set up email from emacs for a while, but only recently got around to setting it up. I use GMail, so I’d wanted email sent from emacs to appear as being sent from my gmail account. To do this, you must install the ’starttls’ program. On Ubuntu, this can be done with ’sudo apt-get install starttls’. Once that is done, put the following in your .emacs file:

(setq send-mail-function 'smtpmail-send-it
      message-send-mail-function 'smtpmail-send-it
      smtpmail-starttls-credentials
      '(("smtp.gmail.com" 587 nil nil))
      smtpmail-auth-credentials
      (expand-file-name "~/.authinfo")
      smtpmail-default-smtp-server "smtp.gmail.com"
      smtpmail-smtp-server "smtp.gmail.com"
      smtpmail-smtp-service 587
      smtpmail-debug-info t)
(require 'smtpmail)

You will also need to create a ~/.authoinfo file with the following format:

machine smtp.gmail.com login username@gmail.com password secret

Once you add these customizations, you will be able to use ‘C-x m’ in order to create an email and send it to people. However, this does not allow you to read and reply to email from emacs. Unfortunately, I haven’t found a great solution for that yet; I tried using GNUs a while ago and didn’t like it, but if you want to try it the information on how to do so is located on the emacs-wiki. The other option that I sometimes use is to have a w3m buffer open and pointing to Gmail, but w3m isn’t as good as I would like and so this isn’t the best experience either. Let me Please let me now if you know of a better way to handle mail from emacs.