M-m (back-to-indentation
) moves point to the first non-whitespace character on the line. I'd like to do the opposite: move point to the last non-whitespace character on the line. I have been unable to find a "built-in" command for this and I'm not familiar enough with ELisp to write something, so any help would be appreciated please.
(defun my-move-end-of-line-before-whitespace ()
"Move to the last non-whitespace character in the current line."
(interactive)
(move-end-of-line nil)
(re-search-backward "^\\|[^[:space:]]"))
Normally in this situation I want to get to the last non-whitespace character and also remove the trailing space, so I use this:
M-\ runs the command delete-horizontal-space, which is an interactive
compiled Lisp function in `simple.el'.
In the rare case that I would want to preserve the whitespace I just use M-b M-f (backward-word
, forward-word
) which is typically close enough.
I think already phils answered to your question. Just another POW.. trailing white spaces are very annoying, invisible and prone to bugs(?). So I have a hook for before-save-hook
to delete them.
;;; delete nasty hidden white spaces at the end of lines
(add-hook 'before-save-hook 'delete-trailing-whitespace)
So it your indented operation becomes simply C-e
for me.
I wrote this function to bind to C-e (usually move-end-of-line
). C-e works as usual, but if your pointer is already at the end of the line, it will remove trailing whitespace.
(defun my/smarter-move-end-of-line (arg)
"Move to the last non-whitespace character in the current line.
Move point to end of this line. If point is already there, delete
trailing whitespace from line, effectively moving pointer to last
non-whitespace character while also removing trailing whitespace.
If ARG is not nil or 1, move forward ARG - 1 lines first."
(interactive "^p")
(setq arg (or arg 1))
;; Move lines first
(when (/= arg 1)
(let ((line-move-visual nil))
(forward-line (1- arg))))
(let ((orig-point (point)))
(move-end-of-line 1)
(when (= orig-point (point))
(delete-horizontal-space))))
Remap C-e:
;; remap C-e to 'smarter-move-end-of-line'
(global-set-key [remap move-end-of-line]
'my/smarter-move-end-of-line)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With