13

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

我搜索了 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)

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

4

5 回答 5

14

Cx TAB 运行indent-rigidly。给定一个四的数字参数,它会做你想要的。或者使用 <pre><code> 来介绍你的代码(参见Markdown 编辑帮助的第一段)。

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

(interactive "r
p")
于 2009-02-27T10:07:40.490 回答
12

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

C-x r t (string-rectangle)

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

于 2009-02-27T15:10:02.260 回答
8

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

于 2009-02-27T16:58:20.720 回答
1

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

于 2009-02-27T12:54:51.523 回答
1

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

于 2011-12-08T08:48:51.373 回答