Emacs:将光标移动到最后一个非空格字符

6

M-m (back-to-indentation) 将光标移动到行中第一个非空格字符。我想要的是相反的:将光标移动到行末的最后一个非空格字符。我找不到内置的命令来实现这个功能,而且我对 ELisp 不熟悉,所以希望有人能提供帮助。

5个回答

7
(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:]]"))

1
谢谢。我在末尾添加了(forward-char),这样我就可以只使用C-k来删除空格了。 - SabreWolfy

5
通常在这种情况下,我想要找到最后一个非空格字符并删除尾随的空格,所以我使用以下代码:
M-\ runs the command delete-horizontal-space, which is an interactive
compiled Lisp function in `simple.el'.

在极少数情况下,如果我想保留空格,我只需使用 M-b M-fbackward-wordforward-word),这通常已经足够接近了。


这很有用,但需要将点移动到正确的位置。 - SabreWolfy
好的建议。如果还没有到行尾,您需要先添加一个 C-e - Derek Slager
2
是的,所以 C-e M-\\ 是另一种解决方案,它将光标移动到行尾,然后删除多余的空格。谢谢。 - SabreWolfy

1

我觉得Phil已经回答了你的问题。还有一个POW(Power-of-Whitespace)是,尾随的空白非常让人恼火,不可见且容易出现错误。因此,我为before-save-hook创建了一个钩子来删除它们。

;;; delete nasty hidden white spaces at the end of lines
(add-hook 'before-save-hook 'delete-trailing-whitespace)

所以对我来说,你的缩进操作变成了简单的C-e


顺便说一下,你可以更简单地写成(add-hook 'before-save-hook 'delete-trailing-whitespace) - sanityinc
@sanityinc 是的,你说得对。删除了多余的 lambda。谢谢。 - kindahero
1
我推荐优秀的 ws-trim-mode(还包括 global- 变体)来修剪行末空格。它非常可定制,但默认配置仅修改您编辑的行,使其版本控制安全(即,如果您编辑具有大量行末空格的文件,则不会引入大量无关更改)。ftp://ftp.lysator.liu.se/pub/emacs/ws-trim.el - phils
@phils 很高兴知道这个。我认为在编辑他人的文件时会非常有用。感谢您的通知。 - kindahero

1
我编写了这个函数来绑定到C-e(通常是move-end-of-line)。C-e像往常一样工作,但如果您的指针已经在行末,则会删除尾随空格。
(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))))

重新映射 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)

0

我的版本:将光标移动到行尾或最后一个非空格字符处(通过删除末尾空格)

(defun smart-end-of-line ()
  "Move to end of line or last non-space (by deleting ending spaces)"
  (interactive "^")
  (let ((p (point)))
    (end-of-visual-line)
    (if (= p (point)) (end-of-line))
    (if (= p (point)) (let (deactivate-mark) (delete-horizontal-space)))))
(global-set-key [end] 'smart-end-of-line)
(global-set-key "\C-e" 'smart-end-of-line)

[end]"\C-e"(control+e)键:

  • 将光标移动到视觉行的末尾。
  • 如果已经在视觉行的末尾,则将其移动到行的末尾。
  • 如果已经在行的末尾,则通过删除所有这些结尾空格将其移动到该行的最后一个非空白字符。
  • 在移动时,保持区域(interactive "^")。
  • let (deactivate-mark)用于确保保留区域。

这是从@justinokamoto中获取的;然后我添加了视觉行末尾。(对我的破英语感到抱歉)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接