Archive for August, 2009

Emacs - Timing and Upgrades

Monday, August 31st, 2009

I have made a number of upgrades to functions and customizations I’ve previously blogged about, so this post is going to be an aggregation of these improvements. Think of it as a ‘corrections’ post.

In a previous post, I talked about updating imenu-generic-expression for java to work with functions with generic types or annotated arguments. The regular expression there is somewhat inadequate: if you used horrible spacing conventions, it could thing an if statement was a function. This new hook for java-mode to set imenu-generic-expression fixes this case by actually breaking out the annotations, types, and variable names, without just mixing them together as in the previous version.

(add-hook 'java-mode-hook
          '(lambda ()
             (setq imenu-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 htat 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,]*"
                                "\\)*"
                                ")"
                                "[ \t\n\r]*"
                                "{"
                                )) 1)))
             ))

The following are a few utilities I wrote in order to write functions such as my-grep. my-fn will take a function with one argument and a prompt, and execute that function with a default of the current word. Defun-my is a macro that defines both the original function and an interactive ‘my’ version of the function. The new my-grep has the same effect as the old my-grep, but uses my-fn.

(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))))
 
(defun my-grep nil
  "Grep the whole directory for something defaults to term at cursor position"
  (interactive)
  (my-fn (lambda (arg) (grep (concat "egrep -s -i -n -r " arg " * " ))) "grep for"))

I also used defun-my in order to upgrade java-describe. The new ‘my-java-descibe-class’ does the same thing, except it defaults to the word at point. I also renamed it to java-describe-class, since I’ve been working on some other Java utilities and wanted to make this name more specific.

(defun-my java-describe-class "Open Javadoc for Class"
  "Loads javadoc for specified class in your browser."
  (interactive "MClass Name: ")
  (let ((my-string (replace-regexp-in-string
                    "^.*class-use/.*\n"
                   ""
                   (shell-command-to-string
                    (concat "find ~/.emacs.d/documentation/java/ -name "
                            arg
                            ".html"))
                   )))
    (string-match "^\\(.*\\)$" my-string)
    (browse-url (match-string 0 my-string))))
 
(global-set-key (kbd "C-x j c") 'my-java-describe-class)

I also upgraded my-help, a function that gives documentation on whatever the point is on. It now checks to see if the buffer is a java buffer; if so, we open the javadoc for the current word instead of calling man on it. I was going to switch the order of checking whether a function or symbol was described first, in the case where a function and variable have the same name, but the issue then is that since function-called-at-point will return the calling function if you are anywhere in a function call, it would frequently mask variable lookup.

(defun my-help ()
  "If function given tries to `describe-function' if variable
uses 'describe-variable', otherwise uses `manual-entry' to display
manpage of a `current-word'."
  (interactive)
  (let ((var (variable-at-point))
        (fn (function-called-at-point)))
    (if (symbolp var)
        (describe-variable var)
      (if fn
          (describe-function fn)
        (if (eq major-mode 'java-mode)
            (java-describe (current-word))
          (man (current-word)))))))

I previously just added visual-line-mode to text-mode-hook, which actually toggled visual-line-mode in the buffer and could lead to strange behaviour. This correction turns visual-line-mode on when entering text modes.

(add-hook 'text-mode-hook '(lambda nil (visual-line-mode 1)))

A reader suggested this improvement in the comments of this post. This will open the current file as sudo at the current position; the old function would lose the position you were at.

(defun sudo-edit-current-file ()
  (interactive)
  (let ((pos (point)))
    (find-alternate-file (concat "/sudo:root@localhost:" (buffer-file-name (current-buffer))))
    (goto-char pos)))

Yank-pop is an advice I describe here to properly indent code fragments. I implemented a suggestion I received in the comments of the linked post in order to make it work better when transient-mark-mode is enabled.

(defadvice yank-pop (after indent-region activate)
  (if (member major-mode
              '(emacs-lisp-mode scheme-mode lisp-mode
                                c-mode c++-mode objc-mode
                                latex-mode plain-tex-mode))
      (let ((mark-even-if-inactive transient-mark-mode))
        (indent-region (region-beginning) (region-end) nil))))

I created a few new functions to keep track of how long each of my customization files take to load. While load time isn’t a problem for me right now, and I could easily fix it if it was by byte-compiling my customizations(right now, the only compiled elisp file I have that is not part of GNU Emacs core is js2.el), I do want to be able to account for what is taking the most time to load. While emacs-init-time tells me how long emacs took to initialize in total, I want a more fine-grained solution. I implemented this by defining time-load-file, a function that would load a file and return a pair consisting of the filename and the time taken to load it in seconds, and changing load-directory to use time-load-file instead of load-file. By saving the results of load-directory, I have a permanent record of the time taken to load each file.

(defun time-load-file (file)
  "Loads a file and returns a pair consisting of the filename and
the time in seconds it took to load."
  (let ((prev-time (float-time)))
    (load-file file)
    (cons file (- (float-time) prev-time))))
 
(defun load-directory (dir)
  "Loads every .el file in a directory."
  (mapcar 'time-load-file (directory-files dir t "\\.el\\'")))
 
(setq customizations-directory-load-times (load-directory "~/.emacs.d/customizations/"))
(setq util-directory-load-times (load-directory "~/.emacs.d/utilities/"))

That’s all I have for now, but I will no doubt improve my customizations further, so once I amass a suitable number I’ll do another one of these posts. If you see anything that should be corrected or could be improved in any of my posts, please leave a comment.

Easier Emacs

Friday, August 28th, 2009

I have enough random emacs customizations to put up another post, so here they are. Emacs is a great text editor, but a lot of the functionality that I have discovered is not enabled by default or not existing, but it is fortunately incredibly customizable so I can add it myself, or find someone else and use their customizations. A lot of these were taken from the Emacs Starter Kit - I browsed through their codebase and used the pieces that looked interesting.

(global-set-key (kbd "C-c r") 'revert-buffer)
(global-set-key (kbd "C-c a") 'apropos)
(global-set-key (kbd "C-c v") 'visual-line-mode)
(define-key isearch-mode-map (kbd "C-o")
  (lambda () (interactive)
    (let ((case-fold-search isearch-case-fold-search))
      (occur (if isearch-regexp isearch-string (regexp-quote isearch-string))))))

These are some keybindings for commands I use pretty frequently, as well as an additional command for isearch-mode. Revert-buffer does just as advertised; it re-loads the current buffer from what is saved on disk. Apropos, a very powerful help command, will search all defined symbols for the pattern you specify. Visual-line-mode is the Emacs23 version of longlines-mode, except much faster; it will make lines wrap and not extend past the window. I often change whether I want to be in this mode or not, so I made C-c v toggle this mode. The last keybinding makes C-o call occur with the string you are searching for when you are performing an interactive search.

(setq-default tab-width 4)
(setq comment-auto-fill-only-comments t)
(put 'downcase-region 'disabled nil)
(put 'upcase-region 'disabled nil)

These are just some standard Emacs customizations. I set the tab-width to be 4 in all buffers and have auto-fill only work with comments in programming modes. The next two lines just enable two disabled commands that I sometimes use; It gets annoying to specify that I want to do these each time.

(defun uwb ()
  "Untabifies the whole buffer"
  (interactive)
  (untabify (point-min) (point-max)))
 
(defun twb ()
  "Tabifies the whole buffer"
  (interactive)
  (tabify (point-min) (point-max)))
 
(defun eval-and-replace ()
  "Replace the preceding sexp with its value."
  (interactive)
  (backward-kill-sexp)
  (condition-case nil
      (prin1 (eval (read (current-kill 0)))
             (current-buffer))
    (error (message "Invalid expression")
           (insert (current-kill 0)))))
(global-set-key (kbd "C-c e") 'eval-and-replace)
 
(defun shell-current-directory ( )
  "Opens a shell in the current directory"
  (interactive)
  (shell (concat "shell-" default-directory "-shell" )))
(global-set-key (kbd "C-c s") 'shell-current-directory)

uwb stands for Untabify whole buffer, and is used when I have a programming file that I quickly need to standardize to keep from hooking messed up. Since it isn’t something I have to do often, I don’t need a keybinding for it. Similarly, twb tabifies the entire buffer. Eval-and-replace is similar to eval-last-sexp, a function I use quite frequently, except it replaces the evaluated expression with the result. This is something that will be useful to me; often I ended up doing this task manually, so it gets it’s own keybinding. The last command is one I now use pretty much constantly. shell-current-directory just creates a shell in the directory that the current buffer is in.This allows you to quickly pop into a shell without having to navigate to that directory, or do an eval-expression yourself. The one thing that I may end up modifying this to do is have the buffer name change based on the directory of the shell, since sometimes I wander off in the shell I opened and then the name is not that of the current directory.

(add-hook 'find-file-hook
         (lambda ()
           (if (string-match "log" (buffer-name (current-buffer)))
               (visual-line-mode -1))))

At work, I often deal with large logfiles with long lines, and I usually want to quickly scan through them. Not having visual-line-mode on in this case is very helpful, since I can just scan through the log type with one per column and see if there is an error. There’s a couple of other modifications I’ve been thinking of writing and packaging up as a log-file-mode, since I haven’t been able to find one of my own, but I have not gotten around to this yet.

The next set of modifications isn’t actually useful; they remove functionality from emacs instead of increasing it. I noticed I use the arrow keys more than I should, and want to train myself to use C-n and the like and not leave the home row as often. To this end, I disabled the arrow keys.

(global-unset-key (kbd "<left>") )
(global-unset-key (kbd "<right>") )
(global-unset-key (kbd "<up>") )
(global-unset-key (kbd "<down>") )
 
(global-unset-key (kbd "C-<left>") )
(global-unset-key (kbd "C-<right>") )
(global-unset-key (kbd "C-<up>") )
(global-unset-key (kbd "C-<down>") )
 
(global-unset-key (kbd "M-<left>") )
(global-unset-key (kbd "M-<right>") )
(global-unset-key (kbd "M-<up>") )
(global-unset-key (kbd "M-<down>") )

That’s it for now - let me know if there are any good packages for viewing log files, and if you have any suggestions for additional customizations please leave them in the comments.

CC and Java Customizations

Wednesday, August 26th, 2009

My job involves a lot of Java coding, so I have a few customizations for cc-mode and java-mode in order to make them easier to work with. While I don’t have too many at this time, they make working in Java a little more pleasant.

(require 'cc-mode)
(add-hook 'java-mode-hook 'c-subword-mode)
(add-hook 'c-mode-common-hook
          '(lambda ()
             (c-toggle-syntactic-indentation 1)
             (setq c-basic-offset 4)
	     (c-toggle-hungry-state 1)
             (c-toggle-electric-state 1)))

cc-mode, for those of you who don’t know, is emac’s base mode for c, c++, java, and a few other languages. It has a lot of keybindings in this mode for various movement commands, so you may want to look over the functions it gives. The manual is exhaustive and tells all the possible options you can do to modify it, but these are the ones I like the most. Java-mode is just a derived mode of cc-mode, so all hooks in c-mode-common-hook will be run for a java buffer.

C-subword-mode is a mode that treats changes of case to be word boundaries. This is often what I want, since Java uses camelcase by convention. If I want to change getBufferedReader() to getReader(), all I would have to do is place the point under ‘B’ and M-d to kill-word. Since Reader starts a new word, it will not be deleted. This can make it a bit less efficient to move past variables defined in camelcase, but if you’re traveling a long way you can probably get closer by searching for whatever it is.

The other hooks are all common to all cc-derived modes, since they are general utility functions. c-toggle-syntactic-indentatation will turn on indentation based on context; otherwise, all new lines will be aligned with the previous line. This also reindents the line on pressing of an ‘electric’ key, such as ‘;’, ‘(’, and many others. Without this command, creating a new line after opening a method would leave the point right below the first character in the function definition, instead of indenting it. the variable c-basic-offset just determines how large indentations should be; I like 4.

c-toggle-hungry-state and c-toggle-electric state turn on hungry deletion and eletric-mode, respectively. Hungry deletion is when backspacing or killing a character when on whitespace will delete not only one character, but to the next non-whitespace character. This is just very handy why you need to format code by deleting whitespace. Electric-mode will just turn on indentation when ‘electric’ keys are pressed.

Some people may be wondering why I don’t have CEDET or JDE in here. The problem with those packages is that they are incredibly slow and lag my emacs to the point of being unusable on most of my codebases - which is really annoying, since it makes programming in Java much better when it allows me to type. It provides some nice refactoring tools, automatic package importation, providing completion for the variable at point, and all sorts of nice stuff. I believe CEDET is being put into Emacs 23.2, so maybe when that comes out I’ll try it again and see if it’s gotten better.

The last thing you should know about if you are coding in emacs is M-x compile and M-x recompile. These commands give you nice buffers of the compile output with errors in red, linked to the location in the file in which they occur. You can cycle through the errors with next-error and previous-error (C-x ` and M-g p) without going into that buffer, making fixing your compile issues much easier.

Python-mode Customizations

Monday, August 24th, 2009

I do some Python coding on my own, and so I have a few python customizations. Python-mode now comes with GNU Emacs, and so these work pretty much out-of-the-box. However, this does not get autoloaded, so you have to put the following before modifying python-mode-map or python-mode-hook.

(require 'python)

Before you start modifying python-mode-hook or python-mode-map or you get void-variable errors. Python-mode-hook is a collection of functions that gets run whenever python is entered, and python-mode-map is the list of keybindings that python-mode provides. Anyway, on to the customizations:

(add-hook 'python-mode-hook
          '(lambda () (eldoc-mode 1)) t)

I’ve talked about eldoc-mode before here. It is still one of my favourite minor modes, and I am greatly saddened whenever I realize a programming mode doesn’t have it. Fortunately, Python does, so I always know the arguments to my functions.

(defun my-insert-self ()
  "Insert self. at the beginning of the current expression."
  (interactive)
  (save-excursion
    (search-backward-regexp "[ \n\t,(-]\\|^")
    (if (not (looking-at "^"))
        (forward-char))
    (insert "self.")))
(define-key	python-mode-map	(kbd "C-;")	'my-insert-self)

I forget to type ’self.’ in front of my variables a lot. If this happens, I can use this function to insert it at the beginning of the variable name I’m currently typing. This ends up saving me a ton of keypresses; I no longer have to navigate to the start of the name and back. This is even more efficient then typing ’self.’ in front of variable names; Two key presses instead of five, if you include the Control.

(defun python-self-insert-command ()
  "appends __ to the string if it should"
  (interactive)
  (save-excursion
    (let ((cur (point)))
      (search-backward-regexp "[\n\t .(-]\\|^" 0 t)
      (if (not (looking-at "^"))
          (forward-char 1))
      (if (looking-at "\\s\__")
          (setq my-temp-var t)
        (setq my-temp-var nil))))
  (save-excursion
    (when (> (point) 2 )
      (backward-char 2)
      (if (looking-at "__")
          (setq my-temp-var nil))))
  (if my-temp-var (insert "__"))
  (self-insert-command 1))
(define-key	python-mode-map (kbd ".")	'python-self-insert-command)
(define-key	python-mode-map " "	        'python-self-insert-command)
(define-key	python-mode-map (kbd "(")	'python-self-insert-command)

This function similarly helps when I forget to append ‘__’ to private variables. I usually remember to put them at the beginning of a variable or function name, but often forgot the end. This function will check to see if the current function/variable starts with __, and if so append __ to it. This only occurs, of course, if __ is not already appended to the variable. I bind this function to space, period, and paren, so that I don’t have to actively think about this for it to happen. This function is more complicated than it seems it should be, but I haven’t quite figured out how to simplify it.

I haven’t investigated python-mode very much, since I’ve recently been using Python only lightly. Looking over it’s documentation, it looks like there are a few commands that could be quite useful, and the next time I write a significant project in Python I’ll definitely look through the manual, but these functions should tide me over until then. If you know of any cool commands in python-mode, don’t hesitate to let me know.

One final thing I was playing with that sounded very useful was ropemacs, an emacs integration of a python refactoring library. This provides refactoring and intellisense, but I could never get it to work. Ropemacs requires pymacs in order to run. Pymacs is a package for Emacs that attempts to enable you to use Python to modify Emacs instead of elisp, which I’d certainly be on board with. However, loading it into my emacs ended up installing a lot of hooks that didn’t work, making it difficult to even quit. I tried getting it to work, but never managed to. I also had a few philosophical problems with it, in that it used python’s egg system and did not allow me to specify where I wanted everything installed; this makes it hard to keep under version control so all of my computers can easily obtain it. If you know an easy way of getting it configured and working, please let me know; I’d love to be able to play around with it.

Learning GNU Emacs

Friday, August 21st, 2009

I recently read a copy of O’Reilly’s Learning GNU Emacs. While fairly out-of-date(I read the 2nd edition, making it worse), it was still a valuable book for emacs beginners. Pretty much all of the items in the book are still around; the book may miss newer stuff than came in versions 20, but it covers the basics quite well. I didn’t learn a huge amount of useful things from it, since most of it I either already knew or didn’t care about, but it did tell me about some things I hadn’t known and was a great refresher. I think it would be great if you were just learning how to use emacs and wanted to get more proficient at it.

The book covers a wide range of topics, starting with basic editing tasks. It covers moving around the buffer, buffer and window management, and searching. These tasks are what Emacs novices need to know to start using Emacs, and the book does a very good job of introducing them. Even I learned about a few things, such as the various different kinds of searches and recursive edits. The book then quickly gets into more topics: file and directory management, as well as using a shell inside Emacs. Since I use Emacs almost exclusively for shell use, it’s nice to know other people thought this was rather important as well.

The next few chapters focused on a few things I don’t use Emacs for - email and browsing the Internet. It covers several different email setups, as well as GNUs. I, however, prefer gmail conversation threading to anything else I’ve used, so I’m going to stick with that. The section on browsing the Web and working remotely was out of date, mentioning ange-ftp and W3 instead of the newer Tramp and W3m. While Tramp is very useful, I actually haven’t liked web browsing with emadcs due to how slow it is. Until Emacs gets a faster browser, I’m going to have to stick with Firefox.

The section with more advanced text editing techniques unfortunately doesn’t cover some of the newer additions to Emacs, obviously. For example, the section on rectangle-editing does not cover the not-yet-developed(or at least included) cua-mode, which has the best rectangle implementation so far. There is also a chapter about various markup language modes, such as troff and noff. While these are probably not used much today(I hadn’t even heard of them before), the chapter also covers latex and html editing, which are still widely used. If you need to edit these types of documents, you should probably read the sections on them; otherwise, they aren’t going to contain any information you need.

The next few chapters got into the real meat of Emacs. Keyboard macros were covered extensively, including some tricks I didn’t know about. Since macros are essential to efficient use of Emacs, I’m very happy that they were covered so thoroughly. Customizing emacs is also covered, and some common customization options are discussed. For more advanced customizations, there is also a chapter on elisp that covers developing your own modes. The elisp chapter also covers elisp as a language, and while not complete is a good introduction to developing in elisp.

The next section covered programming modes, such as cc-mode and fortran. While Fortran isn’t used too much anymore, c and c++ definitely are, and the tutorial for cc-mode is pretty good. The chapter not only covers the modes, but how to integrate compiling into emacs, which is often quite useful. There is also a chapter on using Emacs in X, which is usually set up for you in modern emacs distributions

The chapter on version control showed the book’s age a bit, but was still very useful. I don’t use version control from emacs as much as I should, usually just opening up a shell buffer and executing commands from that, so this chapter was quite useful in explaining how to execute these commands using keyboard shortcuts. The three VC systems that emacs was said to support were SCCS, RCS, and CVS - not exactly in widespread use today. However, the commands that the book mentioned still work with the newer VCS’s that emacs comes with nowadays, so this section is still relevant with newer VCS’s like SVN and Git, the two I mainly use.

The book ends with a chapter on emac’s help commands, like describe-variable, describe-key, and apropos. I already knew about these options, but for a new user this section would be great - It gives them all the resources they need in order to get help on any new modes or problems they encounter. I’m not sure it should be at the end, as it is one of Emacs’ most important features, but at least it’s in the book.

All in all, this is a good book that is unfortunately rather dated. I wish it was updated to cover newer versions of emacs; as it is, it’s probably mostly useful only for newer users of emacs who need a introduction to the basic features that are in every release.

Top 10 Emacs Commands

Monday, August 17th, 2009

Last post, I talked about command-frequency-mode - both how to set it up and what it does. After I executed approximately 150000 commands, I found the most frequent ones, hoping to discover inefficiencies among my editing style that I could fix. This post has the top 10 different types of commands I tend to use, as long as subcommands and default keybindings. If you’re looking for a list of possible commands to use, you can just use these tables to increase your emacs knowledge. You can find more about these commands with C-h f, describe-function, and entering the command name.

Insertion

72045 46.17% self-insert-command Many
896 0.57% comint-send-input RET
629 0.40% newline-and-indent C-j
406 0.26% newline RET
323 0.21% slime-space SPACE
215 0.14% c-electric-paren (,)
176 0.11% c-indent-new-comment-line C-M-j
138 0.09% slime-repl-return RET
118 0.08% indent-new-comment-line C-M-j

The most frequent type of commands I use are, of course, related to inserting text. Self-insert-command is the basic command that insertion keys are bound to, which merely inserts the character pressed into the current location. The other input commands on the list are related either to inserting newlines, or special insert commands that do things such as indent the current line as well as insertion. Comint-send-input, for example, will execute the command you typed in as well as entering a blank line. Many of these commands will indent as well as adding a newline. indent-new-comment-line will also continue comments.

Movement

-

-

18034 11.56% next-line C-n
16036 10.28% previous-line C-p
1565 1.00% forward-char C-f
2099 1.35% backward-char C-b
1497 0.96% backward-paragraph M-{
1461 0.94% move-end-of-line C-e
1454 0.93% dired-previous-line p
1270 0.81% dired-next-line n
1162 0.74% back-to-indentation M-m
982 0.63% backward-word M-b
875 0.56% forward-paragraph M-}
525 0.34% end-of-buffer M->
497 0.32% forward-word M-f
370 0.24% end-of-visual-line C-e
308 0.20% beginning-of-buffer M-<

Movement commands are next frequent. These are mostly standard movement keys - either moving to the next of previous line, word, character, or paragraph are all standard commands that are some of the first you learn. Back-to-indentation I use probably more than most people, since I have it rebound to C-a instead of having that be the default key beginning-of-line. I tend to go to the end and beginning of buffer quite a bit, so these showed up.

Deletion

-

8218 5.27% delete-backward-char DEL
3498 2.24% backward-delete-char-untabify DEL
666 0.43% c-electric-backspace DEL
452 0.29% kill-and-join-forward C-k
333 0.21% kill-line C-k
329 0.21% backward-kill-word C-DEL
139 0.09% kill-word M-d
118 0.08% kill-visual-line C-k
176 0.11% delete-char DEL

Various ways of deleting text came in as the next most popular character. Most of these are more standard commands that everyone should know, and the various equivalents in other modes. Kill-line does sometimes act differently than most people expect, not killing newlines by default, but I prefer it’s default behaviour in most cases. It will kill from point to end of line, allowing you to replace whatever you just deleted.

Buffer Control

2069 1.33% other-window C-x o
1376 0.88% ido-exit-minibuffer C-g
769 0.49% ido-switch-buffer C-x b
613 0.39% ido-delete-backward-updir DEL
426 0.27% ido-kill-buffer C-x k
312 0.20% ido-find-file C-x C-f
212 0.14% ido-next-match RIGHT
111 0.07% dired-advertised-find-file v

These commands all relate to switching buffers and opening new windows. This allows you to have multiple buffers open and displayed at a time, to switch which buffers are displated, and create and kill existing buffers. These are not commands I’d expect beginning emacs users to learn, but I’d recommend anyone using emacs seriously to learn how to at least split the screen and use multiple buffers at a time. Most of these are Ido commands, which I talk about in my blog post here, but worse versions of the commands are available with the same keybindings if you haven’t enabled Ido.

Search

1155 0.74% isearch-printing-char Many
659 0.42% abort-recursive-edit C-]
273 0.17% isearch-other-control-char Many
196 0.13% isearch-repeat-forward C-s
174 0.11% isearch-repeat-backward C-r
164 0.11% isearch-forward C-s
121 0.08% isearch-backward C-r

Incremental search is just amazing. If you want to search for a word in your buffer, you can just press ‘C-s’ and start typing, and it will search as you type. C-s will go to the next match, and C-r will reverse direction and search backwards. You can also grab the word under point with C-w once you have entered isearch-mode by pressing C-s. The one thing that suprised me here was the large portion of abort-recursive-edits, since I almost never intentionally enter recursive edits.Recursive edits allow you to essentially suspend a search, edit the buffer some, and then resume the search. I should probably use these more than I do, but aborting recursive edit’s shouldn’t account for .42% of my commands.

History

554 0.36% undo C-/
291 0.19% comint-previous-input M-p
108 0.07% slime-repl-backward-input M-p

Now we’re getting to categories that are less than 1% of my total editing commands. These commands all involve using previously-entered data, either by undoing or using previous history. Undo works differently in emacs than most editors; in emacs, you can undo to any point in your editing of a buffer, one command at a time. However, there is no redo; if you want to redo, you need to perform a command and then undo twice after undoing. This will first perform the command, undo the command, and then undo the first undo. I really think there should be some type of redo command, but I’ve tried to implement it and it’s unfortunately rather difficult to get one that works well. The other two commands are all more standard terminal history commands, with shell-mode and slime specifically.

Completion

382 0.24% minibuffer-complete-word SPACE
573 0.37% pabbrev-expand-maybe TAB
197 0.13% comint-dynamic-complete TAB

Completion is another task I use a fair amount. One thing that immediately springs to mind is that yasnippet isn’t used at all here; I should make more extensive use of this. Pabbrev I’ve talked about here, and the other two commands in this category are fairly standard completion commands - comint-dynamic-complete is standard terminal tab-completion, whereas most people have probalby encountered minibuffer completion.

Miscellaneous

1063 0.68% save-buffer C-x C-s
568 0.36% cua-set-mark C-SPACE
418 0.27% execute-extended-command M-x
373 0.24% eval-last-sexp C-x C-e
312 0.20% keyboard-quit C-g
423 0.27% cua-paste C-y
165 0.11% slime-eval-last-expression C-x C-e
122 0.08% cua-copy-region M-w
107 0.07% dired-mark m

These are just miscellaneous commands that didn’t really fit into any category. Saving the buffer, setting the mark, M-x, C-y, and M-w are all command any basic emacs user should know. The cua-paste and cua-copy-region are just cua’s rebindings of kill-ring-save and yank, which function in pretty much the same way. Eval-last-sexp and slime-eval-last-expression are commands that are very useful for editing lisp; they will evaluate the expression right before point. Dired-mark is a dired command I’ve blogged about here.

Conclusions

Looking over these, there are several inefficiencies I noticed in the way I use emacs.
1) I use next-line and previous-line far too much. These should not be 10% of the commands I issue each. If I am moving around the buffer this much, I should learn more efficient ways to do so - either by using search more, or prefix keys, or just using forward-paragraph more.

2) My most frequent deletion command is by far deleting a single character. I find it hard to believe that this is the most common situation by that much, which means I should be using either kill-word more, or being more efficient at learning when i should mark a region and kill a region that way instead of just backspacing over it.

3) For someone who doesn’t consciously remember *ever* using a recursive edit in the time period I was recording this, I use way too many abort-recursive-edit calls. I need to find out how I’m entering recursive edits, and do that less. I’m not precisely sure how I’ll do this - maybe by defadvicing the recursive edit entry to notify me when it happens - but it really is something I should work on.

Even fixing just these three things seems likely to increase my editing proficiency with emacs by around 5%, so I think this was a valuable exercise. I highly recommend you doing the same - the process is described in my last blog entry, and it is quite simple to have runing for a few weeks while it gathers statistics. I’m probably going to do this again in a few months, hopefully once I’ve fixed or at least improved upon the three issues mentioned above.

Command-Frequency-Mode

Friday, August 14th, 2009

I’m going to do periodic analysis of my Emacs use, to better determine how I might more efficiently use it. I expect the frequency of command to change dramatically every few months, as what I use emacs for changes. For example, right now I mostly use emacs for writing blog posts, customizing emacs itself, and a small amount of programming that I do on my free time. This will no doubt change when I go back for my school term and will have many more programming projects.

To analyze my frequency, I need to keep track of what commands I am executing. Searching around found the comnmand-frequency package, originally used to develop an ergonomic keybinding set for emacs. This package can be found here. To enable command tracking, put the following in your initialization file:

(setq-default command-frequency-table-file "~/.emacs.d/frequencies")
(require 'command-frequency)
(command-frequency-table-load)
(command-frequency-mode 1)
(command-frequency-autosave-mode 1)

This will make the command frequency tracking persistent across your emacs sessions, as well. If you want this to happen, you need to set the command-frequency-table-file before loading the table and do that before enabling autosave-mode; otherwise, as I’ve found out, you’ll probably lose your old history. There are a few additional customizations you can make to specify where various files are saved and what format they are written in, but I find this sufficient.

Once you’re enabled command-frequency-mode, it’s very simple to use. M-x command-frequency will take you to a buffer showing the relative frequencies of all your commands. M-x command-frequency-insert will insert this table into the current document. M-x write-file will *theoretically* write this information to a file, but unless called non-interactively it fails for me. I haven’t fixed this, since I haven’t ever had a need for it, but it would probably be a relatively simple fix.

Tramp

Wednesday, August 12th, 2009

Tramp is a page that Emacs uses to access remote files. Tramp is very easy to use: chances are it’s turned on in your version of emacs without you knowing about it even if you do. It requires very minimal customization, although there are many options if you do M-x customize-group tramp: the only line in my init.el file that customizes tramp is the following, which tells tramp to use ssh for accessing remote files:

(setq tramp-default-method "ssh")

To use tramp to edit a file on a remote server, just use C-x C-f to find the file as normal, but then enter //ssh:username@hostname:path/to/file. This will open the file as if it were on your computer. Saving the file will save it to the remote computer. This is very useful if either the file is on a computer that doesn’t have emacs installed or has a very slow connection and so you’d rather that emacs be running on your computer.

Tramp can also be used to access files on your computer as another user. This is typically used to edit files as root when you are running as a regular user - this prevents having to run a sudo’d emacs and is a lot safer than the alternative. There are two functions I use to help with this: one gotten from the Emacs Starter Kit, and another one I wrote:

(defun sudo-edit (&optional arg)
  (interactive "p")
  (if arg
      (find-file (concat "/sudo:root@localhost:" (ido-read-file-name "File: ")))
    (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name))))
 
(defun sudo-edit-current-file ()
  (interactive)
  (find-alternate-file (concat "/sudo:root@localhost:" (buffer-file-name (current-buffer)))))
(global-set-key (kbd "C-c C-r") 'sudo-edit-current-file)

These two functions are just easy ways of opening files as root. The first function, sudo-edit, will prompt for a filename and then open that file as sudo. sudo-edit-current-file, will open the current file as sudo without prompting. sudo-edit-current-file will automatically close the non-sudo’d buffer; sudo-edit will only do this if given a prefix argument. This is useful fairly frequently, so I gave it a keybinding of C-c C-r to just open the current buffer as sudo.

Yet Another Emacs Post

Monday, August 10th, 2009

There’s been a lot of random emacs customizations I’ve added to my init file, so it’s time to document them all here. There are also a few additions to customizations I’ve talked about in previous blogs; when this occurs, I’ll link back to those.

The first category is just emacs options, that effect every buffer. I save often enough to find auto-saving, which can clutter my directories, annoying, so I disable it. While I personally don’t mind tabs, pretty much every place I work requires the use for spaces for indentation, so I just set indent-tabs-mode to nil so that they are happy. x-enable-clipboard determines whether you want emacs to be able to interact with the system clipboard under X, which of course you do. I like having the time displayed in the mode line, so I enable that. Blink-cursor-mode is responsible for determining whether the cursor blinks, as in many applications, or is just constant highlighting. I prefer the constant highlight, so I turn the mode off. The visible bell, which most people prefer, alerts you to errors by blinking the top and bottom lines instead of giving an annoying beep. I enabled one of the commands that I end up using, so that Emacs doesn’t complain when I do use it, and then gave query-replace-regexp a convenience alias since I use it a fair amount.

(setq auto-save-default nil)
(setq-default indent-tabs-mode nil)
(setq x-select-enable-clipboard t)
(display-time)
(blink-cursor-mode nil)
(setq visible-bell t)
(put 'erase-buffer 'disabled nil)
(defalias 'qrr 'query-replace-regexp)

There are a few modes that I’ve added back in but blogged about before restarting my .emacs file: pabbrev and cua. The links for those posts are here and here respectively. Pabbrev is a mode for predictive expansion, which is incredibly useful. Cua is a mode that does several things, the two main ones being adding windows-friendly keybindings when the region is visible and adding much better rectangle support. I only really like the rectangle support, as I’ve mentioned before.

(require 'pabbrev)
(global-pabbrev-mode t)
(setq pabbrev-read-only-error nil)
 
(setq cua-enable-cua-keys nil) ;
(cua-mode t)

The next category is for customizations for other modes that I’ve talked about but ended up changing. comint-process-echoes makes M-x shell behave more like a real terminal in some cases, stripping extraneous output. This isn’t necessary on my home computer, but it is on my work one so I missed it in my initial post here. I added a few more customizations for ido, which I wrote about here: one that moves the location of one of it’s files to centralize it in .emacs.d, and one that removes the prompt asking if you want to create a new buffer when you switch to one that doesn’t exist.

I also add a few additional keybindings to make my life easier:

(global-set-key (kbd "C-w") 'backward-kill-word)
(global-set-key (kbd "C-x C-k") 'kill-region)
(define-key visual-line-mode-map (kbd "C-a") 'beginning-of-visual-line)
(global-set-key (kbd"C-x \\") 'align-regexp)

The following function I had in my old setup, and it was much better than M-x rgrep in a lot of cases I wanted so I ended up pulling it back. It prompts you for an expression, defaulting to the symbol that your cursor is on, and greps for that in the current directory and all subdirectories. Very useful.

(defun my-grep ()
  "grep the whole directory for something defaults to term at cursor position"
  (interactive)
  (setq default (thing-at-point 'symbol))
  (setq needle (or (read-string (concat "grep for <" default "> ")) default))
  (setq needle (if (equal needle "") default needle))
  (grep (concat "egrep -s -i -n -r " needle " *")))
(global-set-key (kbd "C-x g") 'my-grep)

The last few things in this batch are just things that I have emacs do on startup. I almost always want to be able to look at my init file, so I load it up here. I also start a server, so I can connect to it with emacsclient and save on startup times when doing things from the command-line that need an editor.

(find-file "~/.emacs.d/init.el")
(server-start)

Autoindentation

Friday, August 7th, 2009

Indenting code is very important, even if you are not programming in Python. It makes the structure of the code much clearer if everything is properly indented. Most editors nowadays will properly indent your code for you, and emacs is no exception. Most of the following customizations were gotten from the emacs-wiki page on autoindentation.

The first set of utilities is advice for yank and yank-pop to indent whatever they just pasted. This is useful if, for example, you copy some code from another file at a different indentation level than you want to paste it at. With these advice, the code will be indented properly relative to wherever you paste it.

(defadvice yank (after indent-region activate)
  (if (member major-mode
              '(emacs-lisp-mode scheme-mode lisp-mode
                                c-mode c++-mode objc-mode
                                latex-mode plain-tex-mode))
      (let ((mark-even-if-inactive t))
        (indent-region (region-beginning) (region-end) nil))))
 
(defadvice yank-pop (after indent-region activate)
  (if (member major-mode
              '(emacs-lisp-mode scheme-mode lisp-mode
                                c-mode c++-mode objc-mode
                                latex-mode plain-tex-mode))
      (let ((mark-even-if-inactive t))
        (indent-region (region-beginning) (region-end) nil))))

The next function, also from the emacs-wiki, is a replacement for kill-line. Normally, if you kill a newline and the next line is indented, you will have to execute just-one-space or something similar to get rid of all the extra indentation. This will do that automatically for you, saving some time. I just rebind it to C-k, overriding kill-line, since this is almost always the behavior I want.

(defun kill-and-join-forward (&optional arg)
  "If at end of line, join with following; otherwise kill line.
    Deletes whitespace at join."
  (interactive "P")
  (if (and (eolp) (not (bolp)))
      (delete-indentation t)
    (kill-line arg)))
(global-set-key (kbd "C-k") 'kill-and-join-forward)

The last customization I have is a keybinding for a function that is already pretty accessible. C-j will perform a newline and indent, but I often just use the return key instead and then have to indent myself(admittedly, only a tab character, but it’s still annoying). Since the times I’ve needed to just insert a newline without indenting are very rare, I just set RET to newline-and-indent. The other option I considered was binding RET to indent-new-comment-line, but after trying that for a while I decided I preffered newline-and-indent.

(global-set-key (kbd "RET") 'newline-and-indent)