【问题标题】:difference between calling command directly and using keybinding直接调用命令和使用键绑定的区别
【发布时间】:2013-07-12 23:23:56
【问题描述】:

我是 elisp 新手,如果以下方法完全笨拙,请原谅我。

在我目前工作的团队中,通常的惯例是使用 pass 语句关闭 python 块(如果它们不是以关闭关键字结束,例如 elseexcept 等)。虽然不寻常,但这样做的好处是,如果程序被无意更改(使用 emacs indent-region),总是可以恢复程序的原始缩进。

为了让现有代码符合这个约定,我写了一个小的 elisp 函数:

(defun python-check-indent ()
 "Check if automatic indentation changes current indent, insert pass keyword if it does."
 (interactive)
 (move-beginning-of-line 1)
 (skip-chars-forward " ")
 (if
  (< 0
     (let (original)
      (setq original (point))
      (indent-for-tab-command)
      (- (point) original)
      )
     )
  (progn
   (insert "pass")
   (newline)
   (indent-for-tab-command)
   )
 )
 (next-line)
)


(global-set-key (kbd "C-`") 'python-check-indent)

这个想法只是测试按 TAB 是否会改变缩进,并在这种情况下插入 pass 语句。为了便于处理较长的代码块,它会前进到下一行。

当我使用M-x python-check-indent 运行它时,它会执行我想要的操作(除了它会稍微绕空行移动),在重复运行它以处理多行时也是如此。但是,当我使用 C-` 键绑定重复运行它时,它会从第二次调用开始弄乱代码。

所以这是我的问题:使用M-x ... 调用命令和使用它的键绑定有什么区别?我怎样才能改变功能不受这种差异的影响?

emacs-version: GNU Emacs 23.3.1 (x86_64-apple-darwin, NS apple-appkit-1038.35) of 2011-03-10 on black.porkrind.org

(编辑)当前的解决方法:我现在将它包装在键盘宏中,因此它“绑定”到 C-x e,并且行为正常。

【问题讨论】:

    标签: emacs elisp


    【解决方案1】:

    一般规则是最好避免复杂的交互 函数中的命令,因为它们可能会受到各种影响 的选项。

    (defun python-check-indent ()
      "Check if automatic indentation changes current indent, insert pass keyword if it does."
      (interactive)
      (goto-char (line-beginning-position))
      (skip-chars-forward " ")
      (when (< 0
               (let (original)
                 (setq original (point))
                 (python-indent-line)
                 (- (point) original)))
        (insert "pass\n")
        (python-indent-line))
      (forward-line))
    

    但是,即使这样也可能不好,因为python-indent-line 的行为取决于last-commandpython-indent-trigger-commands。我认为最好将python-indent-line 的第一次调用替换为计算目标缩进而不是实际缩进的代码,例如(nth python-indent-current-level python-indent-levels)

    PS。如果还是有问题,建议你使用edebug,单步执行函数。

    【讨论】:

    • 嗨,这条规则很有意义,但不幸的是,当我使用键绑定调用函数时,我仍然会得到不同的行为,而使用 M-x python-check-indent 时它可以正常工作。
    • 我明白了!我只需要用 python-indent-line 替换另一个 indent-for-tab-command。非常感谢!
    猜你喜欢
    • 2012-08-16
    • 2013-07-17
    • 1970-01-01
    • 2015-11-03
    • 2014-03-05
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多