【问题标题】:Using Emacs to indent (shift 4) code使用 Emacs 缩进(移位 4)代码
【发布时间】:2009-02-27 09:55:16
【问题描述】:

我使用ViewSourceWith 编辑我的 StackOverflow 答案和问题 和 Emacs。通常,我包含代码和StackOverflow formatting rules 说它必须缩进四个空格才能被识别为 这样的。手动甚至使用宏都是很痛苦的。

我搜索了 SO 以前的帖子,但一无所获。

从Python模式开始,我写了:

(defun text-shift-region (start end count)
  "Indent lines from START to END by COUNT spaces."
  (save-excursion
(goto-char end)
(beginning-of-line)
(setq end (point))
(goto-char start)
(beginning-of-line)
(setq start (point))
(indent-rigidly start end count)))

(defun text-shift-region-right (start end &optional count)
  "Shift region of code to the right
   Stolen from python-mode.
   The lines from the line containing the start of the current region up
   to (but not including) the line containing the end of the region are
   shifted to the right, by `text-indent-offset' columns.

   If a prefix argument is given, the region is instead shifted by that
   many columns.  With no active region, indent only the current line."
  (interactive
   (let ((p (point))
     (m (mark))
     (arg current-prefix-arg))
 (if m
     (list (min p m) (max p m) arg)
   (list p (save-excursion (forward-line 1) (point)) arg))))
  (text-shift-region start end (prefix-numeric-value
              (or count text-indent-offset)))
  )

;; Code in StackOverflow must be marked by four spaces at the
;; beginning of the line
(setq text-indent-offset 4)
(global-set-key "\C-c>" 'text-shift-region-right)

它似乎有效,但我欢迎建议、替代方案、错误报告, 等等

【问题讨论】:

  • 是的,我希望能得到我速成解决方案的替代品,或者收到有趣的补丁。
  • 另外,它似乎可能对某些人有所帮助,所以我用它来看看是否有足够的兴趣在某处要求文档。
  • 冒着指出显而易见的风险,markdown 编辑器有一个工具栏按钮(也是 CTRL+K 键盘),它可以将文本缩进 4 个空格。
  • 谢谢,但重点是使用 Emacs,而不是内置编辑器(使用 Emacs 的所有其他功能)。
  • @hackinwords:因为,正如我多次说过的,我更喜欢 Emacs 而不是 SO 的内置编辑器。

标签: emacs elisp


【解决方案1】:

C-x TAB 运行 indent-rigidly。给定一个四的数字参数,它会做你想要的。或者使用

 来介绍您的代码(参见Markdown Editing Help 的第一段)。

编辑:您的交互式声明最好写成:

(interactive "r
p")

【讨论】:

  • C-x TAB 需要标记区域。我窃取的 Python 模式代码适用于该区域(如果有),否则适用于当前行。
  • 你的意思是活跃。通常将单行缩进 4 并不真正保证特定的绑定。 C-a 空间空间空间空间。
  • 好吧,我还是更喜欢我的方法,但这两个解决方案也不错。接受。
  • YMMV,但我一直发现C-x C-iC-x TAB 更容易输入。 (TABC-i (通常)是同一个东西。)
  • 令人惊讶的是,如果你想取消缩进,C-u -4 C-x TAB 是正确的。哇哦!
【解决方案2】:

另一个简单的方法是使用 emacs 强大的矩形编辑能力:设置你的区域从第一行的开头到你要缩进的最后一行的开头结束(注意:它 位于行首,因为您不想替换现有文本!),然后执行

C-x r t (string-rectangle)

然后按照提示输入4个空格即可。瞧!不需要额外的 lisp 黑客攻击。这还使您可以灵活地在一堆行的开头或中间的任何位置插入空格旁边的其他内容。

【讨论】:

  • 一个更简单的命令是 Cx ro,open-rectangle,假设区域的第一行或最后一行至少有四个字符长:将区域的任一端放置四个字符到行中另一个在行首,然后输入 Cx r o。
【解决方案3】:

使用 C-x TAB 严格缩进(如另一个答案中所述)是最简单的方法。只需标记要缩进的区域,然后按 C-u C-x TAB。由于 C-u 的默认前缀是 4,这应该完全符合您的要求。

【讨论】:

    【解决方案4】:

    您的代码对我来说看起来不错。我认为在text-shift-region 中重新设置end 是没有必要的,但除此之外,它看起来还不错。

    【讨论】:

      【解决方案5】:

      python-mode中,您可以标记一个区域(C-space,移动光标)并点击C-c >缩进4个空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多