39

你可以在 Emacs 中为 home 键设置智能行为吗?智能我的意思是,它应该转到第一个非空白字符,然后在第二次按下时转到 0,然后在第三次按下时返回到第一个非空白字符,而不是转到第 0 个字符,以此类推。拥有聪明的结局也会很好。

4

7 回答 7

63
(defun smart-beginning-of-line ()
  "Move point to first non-whitespace character or beginning-of-line.

Move point to the first non-whitespace character on this line.
If point was already at that position, move point to beginning of line."
  (interactive "^") ; Use (interactive) in Emacs 22 or older
  (let ((oldpos (point)))
    (back-to-indentation)
    (and (= oldpos (point))
         (beginning-of-line))))

(global-set-key [home] 'smart-beginning-of-line)

我不太确定 smart end 会做什么。你通常有很多尾随空格吗?

注意:这个函数和 Robert Vuković 的主要区别在于他总是在第一次按键时移动到第一个非空白字符,即使光标已经在那里。在这种情况下,我的会移动到第 0 列。

另外,他(beginning-of-line-text)在我用过的地方用过(back-to-indentation)。它们非常相似,但它们之间存在一些差异。 (back-to-indentation)总是移动到一行的第一个非空白字符。 (beginning-of-line-text)有时会移过它认为无关紧要的非空白字符。例如,在仅注释行上,它移动到注释文本的第一个字符,而不是注释标记。但是这两个函数都可以在我们的任何一个答案中使用,具体取决于您喜欢哪种行为。

于 2008-09-28T06:36:27.700 回答
12

这适用于 GNU Emacs,我没有用 XEmacs 尝试过。


(defun My-smart-home () "Odd home to beginning of line, even home to beginning of text/code."
    (interactive)
    (if (and (eq last-command 'My-smart-home)
            (/= (line-beginning-position) (point)))
    (beginning-of-line)
    (beginning-of-line-text))
)

(global-set-key [home] 'My-smart-home)
于 2008-09-28T06:37:38.853 回答
6

感谢这个方便的功能。我现在一直在使用它并且喜欢它。我只做了一个小改动:(交互式)变为:(交互式“^”)

来自 emacs 帮助:如果以 shift-select-mode' 开头的字符串^' and为非 nil,则 Emacs 首先调用函数 `handle-shift-select'。

基本上,如果您使用 shift-select-mode,这会使 shift-home 从当前位置选择到行首。它在 minibuffer 中特别有用。

于 2010-09-27T10:26:40.620 回答
4

请注意,已经有一个返回缩进功能,它可以执行您希望第一个智能家居功能执行的操作,即转到行上的第一个非空白字符。它默认绑定到 Mm。

于 2008-09-29T01:57:39.750 回答
2

现在有一个包可以做到这一点,mwim(移动我的意思)

于 2015-12-27T04:19:31.833 回答
1

我的版本:移到视线的开头,第一个非空白或行首。

(defun smart-beginning-of-line ()
    "Move point to beginning-of-line or first non-whitespace character"
  (interactive "^")
  (let ((p (point)))
    (beginning-of-visual-line)
    (if (= p (point)) (back-to-indentation))
    (if (= p (point)) (beginning-of-line))))
(global-set-key [home] 'smart-beginning-of-line)
(global-set-key "\C-a" 'smart-beginning-of-line)

[home]( "\C-a"control+a) 键:

  • 将光标(点)移动到视线的起点。
  • 如果它已经在可视行的开头,则将其移动到该行的第一个非空白字符。
  • 如果它已经存在,则将其移至行首。
  • 移动时,保持区域 ( interactive "^")。

这取自@cjm 和@thomas;然后我添加了视觉线的东西。(对不起我的英语不好)。

于 2019-11-11T18:59:45.677 回答
0

我将@Vucovic 代码调整为beggining-of-line首先跳转到:

(defun my-smart-beginning-of-line ()
  "Move point to beginning-of-line. If repeat command it cycle
position between `back-to-indentation' and `beginning-of-line'."
  (interactive "^")
  (if (and (eq last-command 'my-smart-beginning-of-line)
           (= (line-beginning-position) (point)))
      (back-to-indentation)
    (beginning-of-line)))

(global-set-key [home] 'my-smart-beginning-of-line)
于 2014-09-06T10:13:49.430 回答