[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: auto-indenting C++ files upon saving
From: |
Andreas Politz |
Subject: |
Re: auto-indenting C++ files upon saving |
Date: |
Fri, 19 Feb 2010 19:11:15 +0100 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) |
Eric James Michael Ritz <Eric@cybersprocket.com> writes:
> Art Werschulz wrote:
>> [...]
>>
>> How can this be automated, so that a file gets auto-indented whenever
>> it's saved?
>>
>> I thinking of something along the lines of (setq auto-save-hook
>> (lambda (mark-whole-region) (indent-region)))
>> but this didn't seem to work.
>>
>> Actually, I'd only want this to work in some situations, e.g., a file
>> whose name matches a certain pattern. Said pattern would be stored
>> in some variable.
>>
>> My emacs-lisp is very weak. Suggestions? Thanks!
>
> You should be able to add a hook to ‘before-save-hook’ to be called on
> save that will indent the file for you. If you specifically want this
> for C++ files then it may be easier to check the current major mode to
> see if it is in c++-mode, compared to trying to match against file
> names for C++ files. Maybe something like this?
>
> (add-hook 'before-save-hook
> (lambda ()
> (when (eq 'c++-mode (buffer-local-value 'major-mode
> (current-buffer)))
> (mark-whole-buffer) (indent-region))))
>
> I’m not very confident about my Emacs Lisp either, so there may be a
> better way to have save-related hooks for specific modes :)
>
I think it's better style to use a buffer-local hook.
(defun c++-indent-buffer-maybe ()
(when (and (string-match
"\\(foo\\|bar\\)\\.cpp\\'"
(buffer-file-name))
(y-or-n-p "Indent buffer before saving ?"))
(indent-region (point-min)
(point-max))))
(defun my-c++-hook ()
(add-hook 'before-save-hook 'c++-indent-buffer-maybe nil t))
Here the last argument `t' makes the hook local to the buffer.
(add-hook 'c++-mode-hook 'my-c++-hook)
-ap