tags:

views:

98

answers:

2

There has got to be a better way to indent a block of code for stackoverflow posts using Emacs. My current strategy is to:

  1. Select a text region
  2. execute M-x indent-code-rigidly
  3. run C-x z three times to reindent the region

This seems brain-dead. Please enlighten me as to how to make this happen in a clever and elegant manner.

+5  A: 

I recently created this helpful command:

(defun stackoverflow-copy-code-snippet (begin end)
  (interactive "r")
  (let ((buffer (current-buffer)))
    (with-temp-buffer
      (insert-buffer-substring-no-properties buffer begin end)
      (indent-rigidly (point-min) (point-max) 4)
      (clipboard-kill-ring-save (point-min) (point-max)))))

I just used it to copy its own source into this post. How meta!

Sean
For some reason, when I execute stackoverflow-copy-code-snippet, it doesn't copy the indented string to the clipboard. Instead it copies "stackoverflow-copy-code-snippet" to my clipboard. This is on emacs 23.2.1
speciousfool
I was using 22.3, but I just downloaded and compiled 23.2 and stackoverflow-copy-code-snippet still works for me. I probably should have mentioned that that routine indents the contents of the region and copies it into the system clipboard, so you need to set the region before calling it. That might explain the behavior you aw.
Sean
+2  A: 

This isn't materially different from scottfrazer's answer, but it's a tad easier to type: C-u C-x C-i

offby1
Fewest keystrokes I've seen for a built-in solution and not hard to remember.
speciousfool