Trying to find a way to better indent automatically with emacs
I find my self manually correcting indentation too often, so I am looking for a way to automatically indent a line according to mode when I enter or leave a line. At the moment I am just wrapping the next-line
and previous-line
commands with indent-according-to-mode
and rebinding my C-n and C-p to the new functions like so:
(defun next-line-and-indent (&optional arg try-vscroll)
"Move to the next line and indent according to mode."
(interactive)
(indent-according-to-mode)
(next-line arg try-vscroll)
(indent-according-to-mode))
(defun previous-line-and-indent (&optional arg try-vscroll)
"Move to the previous line and indent according to mode."
(interactive)
(indent-according-to-mode)
(previous-line arg try-vscroll)
(indent-according-to-mode))
开发者_如何学Python
This works, but is dirty feeling and whatnot, also it would not cover a line being entered or exitted by any means other than C-n and C-p. Is there some hook I can't find like enter-line
and leave-line
?
You could use pre- and post-command-hook to ascertain whether point is on the same line after the command as it was before it?
(defun my-auto-indent-remember ()
"Remember the current beginning and end of line."
(setq my-auto-indent-line-beginning-position (line-beginning-position))
(setq my-auto-indent-line-end-position (line-end-position)))
(defun my-auto-indent ()
"Indent if we have changed lines."
(and (boundp 'my-auto-indent-line-beginning-position)
(boundp 'my-auto-indent-line-end-position)
(or (< (point) my-auto-indent-line-beginning-position)
(> (point) my-auto-indent-line-end-position))
(indent-according-to-mode)))
(add-hook 'pre-command-hook 'my-auto-indent-remember)
(add-hook 'post-command-hook 'my-auto-indent)
I simply can't imagine this being a good idea, btw, but I had to try it out :)
With it enabled, I've already experienced undesired re-indentation just attempting to copy that code after indenting it four spaces for Stack Overflow.
Whenever the indentation is wrong, I find that a quick indent-region
will almost always fix everything.
This code doesn't handle the "leaving a line" bit, btw, and I'm not sure how that would work post-command to be honest. You might have to catch known movement commands pre-command, and indent there. You could easily test the idea with an unconditional (indent-according-to-mode) in my-auto-indent-remember, though.
You can try the following:
(define-key global-map (kbd "RET") 'newline-and-indent)
That should switch to the new line and automatically indent it according to the current indentation settings.
精彩评论