2009-02-27 48 views
12

我编辑我的StackOverflow答案和ViewSourceWith 和Emacs的问题。通常,我包含代码和StackOverflow formatting rules 说它必须缩进四个空格才能被识别为 等。用手或者用宏来做是很痛苦的。使用Emacs缩进(移位4)代码

我在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) 

这似乎工作,但我欢迎建议,方案,错误报告, 等

+0

这不是一个问题...... – 2009-02-27 09:59:34

+0

这是,我希望能够替代我的快速烹制的解决方案,或者接收有趣的补丁。 – bortzmeyer 2009-02-27 10:01:32

+0

此外,它似乎可以帮助一些人,所以我使用这种方式来查看是否有足够的兴趣去寻求文档。 – bortzmeyer 2009-02-27 10:03:11

回答

14

C-X TAB运行indent-rigidly。给出四个数字参数,它会做你想要的。或者,使用< pre> < code>来介绍您的代码(请参阅Markdown Editing Help的第一段)。

编辑:交互式声明将更好地被写成:

(interactive "r 
p") 
1

您的代码看起来好像没什么问题。我认为重新设置endtext-shift-region是没有必要的,但除此之外,它看起来很好。

11

另一个简单的方法是使用emacs强大的矩形编辑功能:从第一行的开头开始,结束于要缩进的最后一行的开头(注意:它的因为你不想替换你现有的文本!),那么做

C-x r t (string-rectangle) 

然后只需输入4空格作为提示。瞧!没有额外的lisp黑客需要。此外,还可以灵活地将其他内容插入到空格的开头或任意中间的一行中。

8

使用C-x TAB缩进(如另一个答案中提到的)是最简单的方法。只需标记要缩进的区域,然后按C-u C-x TAB。作为C-u的默认前缀是4,这应该完全按照你想要的做。

1

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