Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: move point to last non-whitespace character

Tags:

emacs

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.

like image 886
SabreWolfy Avatar asked Mar 07 '12 07:03

SabreWolfy


4 Answers

(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:]]"))
like image 92
phils Avatar answered Oct 14 '22 14:10

phils


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.

like image 38
Derek Slager Avatar answered Oct 14 '22 12:10

Derek Slager


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.

like image 1
kindahero Avatar answered Oct 14 '22 12:10

kindahero


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)
like image 1
justinokamoto Avatar answered Oct 14 '22 14:10

justinokamoto