Friday, September 12, 2008

Making Emacs A Little more PHP Dev Friendly

Here are two emacs file handling functions that I've been meaning to work up up to make editing PHP less painful. Specifically, I wanted to be able to work with the require statements more efficiently.

insert-relative-path-at-point: This function asks you for a path, which you can tab complete against. When you hit enter, it inserts it at the current point as a relative path. It's useful for inserting paths into expressions like:

  require_once('<path goes here>');

Here's the code:

(defun insert-relative-path-at-point (path)
  "Prompt for a path, and insert the part relative to where we currently are."
  (interactive "GPath:\n")
  (let ((current-path (abbreviate-file-name default-directory)))
    (insert (substring path (length current-path)))))

find-filename-at-point: This function will open up the current file that your cursor is pointing to. It's like find-file, but context aware. This is useful for following require statements like:

  require_once('../../lib/foo.php');

Here's the code:

(defun find-filename-at-point ()
  "Open the file the curson is pointing to."
  (interactive)
  (find-file (thing-at-point 'filename)))

And I've bound these to keys like so:

 ;; Bind to: Control-c Control-f
 (global-set-key (kbd "C-c C-f") 'find-filename-at-point)

 ;; Bind to: Control-c i
 (global-set-key (kbd "C-c i") 'insert-relative-path-at-point)

No comments:

Post a Comment