views:

375

answers:

4

Building on http://stackoverflow.com/questions/318553/getting-emacs-to-untabify-when-saving-files , I'd like to run a hook to untabify my C++ files when I start modifying the buffer. I tried adding hooks to untabify the buffer on load, but then it untabifies all my writable files that are autoloaded when emacs starts.

(For those that wonder why I'm doing this, it's because where I work enforces the use of tabs in files, which I'm happy to comply with. The problem is that I mark up my files to tell me when lines are too long, but the regexp matches the number of characters in the line, not how much space the line takes up. 4 tabs in a line can push it far over my 132 character limit, but the line won't be marked appropriately. Thus, I need a way to tabify and untabify automatically.)

+1  A: 

Here is what I added to my emacs file to untabify on load:

(defun untabify-buffer ()
  "Untabify current buffer"
  (interactive)
  (untabify (point-min) (point-max)))

(defun untabify-hook ()
  (untabify-buffer))

; Add the untabify hook to any modes you want untabified on load
(add-hook 'nxml-mode-hook 'untabify-hook)
Alex B
Like I said in the question, I don't want something like this because I often have dozens of files being loaded when emacs starts, and it goes through and untabifies them even if I don't need them to be. When I close emacs down, all the buffers are dirty and I need to save them. Thanks, though.
+2  A: 

Take a look at the variable "before-change-functions".

Perhaps something along this line (warning: code not tested):

(add-hook 'before-change-functions 
          (lambda (&rest args) 
            (if (not (buffer-modified-p))
                (untabify (point-min) (point-max)))))
huaiyuan
A: 

This answer is tangential, but may be of use.

The package wide-column.el link text changes the cursor color when the cursor is past a given column - and actually the cursor colors can vary depending on the settings. This sounds like a less intrusive a solution than your regular expression code, but it may not suit your needs.

Trey Jackson
Thanks, that's an interesting solution. I think I'd prefer marking up the faces of the file so I can see when lines are long without having to position my cursor, though. Still, that's kind of neat. I may use it for other things. :)
A: 

And a different, tangential answer.

You mentioned that your regexp wasn't good enough to tell when the 132 character limit was met. Perhaps a better regexp...

This regexp will match a line when it has more than 132 characters, assuming a tabs width is 4. (I think I got the math right)

"^\\(?: \\|[^ \n]\\{4\\}\\)\\{33\\}\\(.+\\)$"

The last parenthesized expression is the set of characters that are over the limit. The first parenthesized expression is shy.

Trey Jackson