2010-08-20 67 views
7

我最近在某些編程模式中添加了Emacs (delete-trailing-whitespace)函數給我的'before-save-hook,但是我覺得它讓人很沮喪,它從我當前正在編輯的行中刪除了空格。有關如何解決這個問題的任何建議?emacs delete-trailing-whitespace except current line

+0

我必須說,我不明白爲什麼你想要保留當前行的尾隨空格。 – offby1 2010-08-20 21:15:47

+0

理由:當我在編輯文件的過程中,我強制保存文檔。如果我開始輸入「print」然後保存我的緩衝區,那麼這行會縮小到「打印」並且光標會退出,迫使我輸入另一個空格! – pariser 2010-08-21 00:12:11

回答

9

由於delete-trailing-whitespace方面縮小,一種解決方案是當前行之前縮小緩衝器向部當前行之後調用它,然後窄於部分並再次調用它:

(defun delete-trailing-whitespace-except-current-line() 
    (interactive) 
    (let ((begin (line-beginning-position)) 
     (end (line-end-position))) 
    (save-excursion 
     (when (< (point-min) begin) 
     (save-restriction 
      (narrow-to-region (point-min) (1- begin)) 
      (delete-trailing-whitespace))) 
     (when (> (point-max) end) 
     (save-restriction 
      (narrow-to-region (1+ end) (point-max)) 
      (delete-trailing-whitespace)))))) 

將此功能置於您的before-save-hook而不是delete-trailing-whitespace

+0

完美的作品,謝謝! – pariser 2010-08-21 00:09:45

3

此包裝爲delete-trailing-whitespace可以用來做你想要什麼:

(defun delete-trailing-whitespace-except-current-line() 
    "do delete-trailing-whitespace, except preserve whitespace of current line" 
    (interactive) 
    (let ((current-line (buffer-substring (line-beginning-position) (line-end-position))) 
     (backward (- (line-end-position) (point)))) 
    (delete-trailing-whitespace) 
    (when (not (string-equal (buffer-substring (line-beginning-position) (line-end-position)) 
          current-line)) 
     (delete-region (line-beginning-position) (line-end-position)) 
     (insert current-line) 
     (backward-char backward)))) 
1

我遇到了同樣的問題,並且發現了ws-butler完美地解決了它。 有一個簡單的示例配置代碼:

;; autoload ws-butler on file open 
(add-hook 'find-file-hook #'ws-butler-global-mode) 
(setq require-final-newline t) 
0

我只是有一個包裝,以使兩個調用`刪除尾隨空白「:

(defun modi/delete-trailing-whitespace-buffer() 
    "Delete trailing whitespace in the whole buffer, except on the current line. 
The current line exception is because we do want to remove any whitespace 
on the current line on saving the file (`before-save-hook') while we are 
in-between typing something. 

Do not do anything if `do-not-delete-trailing-whitespace' is non-nil." 
    (interactive) 
    (when (not (bound-and-true-p do-not-delete-trailing-whitespace)) 
    (delete-trailing-whitespace (point-min) (line-beginning-position)) 
    (delete-trailing-whitespace (line-end-position) (point-max)))) 
(add-hook 'before-save-hook #'modi/delete-trailing-whitespace-buffer)