July 5, 2011

Move line to end of file and comment

Posted in Emacs, Java at 15:40 by theBlackDragon

I had to work on a bunch of translation Java property files in an ancient J2EE project that had old translations in between the new ones resulting in a hardly readable mess that confused the hell out of Netbeans’ property file editor plugin, so I decided to just move all those old lines to the bottom of the file and comment them out.
For this I quickly hacked up two elisp functions

(defun move-line-to-end-of-file ()
  "Move the current line to the end of the file."
  (interactive)
  (save-excursion
    (beginning-of-line)
    (kill-whole-line)
    (end-of-buffer)
    (yank-as-comment)))

(defun yank-as-comment ()
  "Yank the last killed selection as a comment, but leave text 
  alone that is already a comment according to the current mode."
  (interactive)
  (save-excursion
    (yank)
    (if (not (comment-only-p (mark) (point)))
        (comment-region (mark) (point)))))

There probably is a much more idiomatic way to do this (which I’d love to hear about), but this seems to work just fine for my use. Note however that move-line-to-end-of-file will just append to the last line if the file doesn’t end with a newline (which isn’t an issue in my case).

Advertisements

2 Comments »

  1. Ian Eure said,

    The kmacro stuff can probably get you most of the way there, but I think it’s a tossup. You’d need to push the mark or set a register or something to jump back to your source line after running the macro, so it seems a bit more fragile.

    If you can add (when (not (looking-at “\\n”)) (insert “\\n”)) to yank-as-comment to work around the lack of newline.

    • Thanks, that works wonderfully!

      One thing I forgot to mention (and that bit me when I needed this function again) is that comment-only-p is defined in newcomment.el so it needs to be loaded.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s