2009-02-27 71 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個空格。