tkbe

March 8, 2009

emacs :: my first emacs-lisp function (!)

Filed under: emacs — tb @ 1:31 am

I've been finding myself in a tricky situation a lot lately: I'm programming along, and suddenly I realize that the thing I'm writing really should be factored out and named with a variable.

PYTHON:
  1. page.calendar.add(Employee.username(...

"whoops, I'm going to refer to this employee again... I should have written:"

PYTHON:
  1. emp = Employee.username(request.user.username)
  2.    page.calendar.add(emp, ...

What to do? Should I finish the line I'm on and then insert a line above (from experience I know my memory is so bad I'm likely to have forgotten by the time I get to the end of the line); or should I navigate up, insert the line and then try to find my way back to where I was.

What I really needed was to be able to press C-return and magically be transported to a fresh, new, blank and properly indented line above my point. Then I could use the standard C-u C-spc to get back to where I started... After a couple of hours of reading the fine manual, here's what I came up with:


(defun insert-and-indent-line-above ()
  (interactive)
  (push-mark)
  (let* ((ipt (progn (back-to-indentation) (point)))
   (bol (progn (move-beginning-of-line 1) (point)))
   (indent (buffer-substring bol ipt)))
    (newline)
    (previous-line)
    (insert indent)))
 
(global-set-key [ (control return) ] 'insert-and-indent-line-above)

it brought me great satisfaction (even though I realize there is probably a much simpler and more elegant way to do this).

June 14, 2007

emacs :: autocompletion and code-commenting

Filed under: python, emacs — tb @ 6:29 pm

I'm a believing member in the church of emacs, and in honor of the new release I went looking for solutions to a couple of outstanding issues I've had with my emacs installation.

Today's first emacs find is M-; which, although undocumented, works excellently to comment and uncomment code blocks in Python (it had puzzled me for a while that the comment-block command on the Python menu was C-c # and that there was no mapping for the uncomment command). The M-; command works in a plethora of other modes as well to comment and uncomment blocks.

The second emacs treasure I found today was how to turn on autocompletion. Not the mind-numbingly annoying kind that some editors have that pops up and obscures half your program whenever you type a key, but rather cycling through options when pressing M-RET. To enable it, simply put this in your .emacs file:

(define-key global-map (read-kbd-macro "M-RET") 'hippie-expand)

Searching for some info on hippie-expand, I ran into dabbrev-expand which is bound to M-/. I couldn't tell you what the difference is, but the ESC-Enter combination is easier to find blindfolded so that's what I'm going with.

Powered by WordPress