2012-10-27 43 views
0

我用這個作爲參考: Emacs comment/uncomment current line切換評論,如果區域不活躍

我的問題是我是否可以使用defadvice(這似乎更適合我)執行相同的任務? 沿線的東西

(defadvice comment-or-uncomment-region (before mark-whole-line (arg beg end) activate) 
    (unless (region-active-p) 
    (setq beg (line-beginning-position) end (line-end-position)))) 
(ad-activate 'comment-or-uncomment-region) 
+0

'defadvice'是不是更合適。這是最後的解決方案。請記住,無論何時使用defadvice,您都會從根本上修改開發人員依賴的Emacs API。 –

+0

我第二個event_jr的判斷。爲什麼一個明確命名爲「comment-or-uncomment-region」的函數在當前行上工作?我會認爲這是相當不可預測的行爲。最好的方法是編寫一個小的實用程序函數,它可以完成代碼示例中指示的任務,並將其綁定到「M-」或您所選擇的鍵盤快捷鍵。 – Thomas

+0

我(意外地?)認爲這意味着moneky-patching可以根據我的個人需求在本地修改已有的函數,而不是重新定義它們。如果沒有地區是活躍的,這只是我希望在整個行中行動的許多職能的一個例子 - 抽籤,殺人和評論只是一些例子。 – CrimsonKing

回答

1

此答案是基於我上面的評論。

defadvice不比另一種解決方案更合適。它不會比其他解決方案更適合。


defadvice不得已時,你可以不解決您的問題任何其他 方式

PERIOD。


銘記,每當你使用defadvice您正在從根本上改變 Emacs的API,它封裝開發商依靠。

當你巧妙地改變這些行爲,就導致很多問題你 並最終爲包開發者,當你因爲 您的Emacs API與defadvice打破報告「錯誤」。

因此,當您想要在本地更改功能時,執行此操作的方法是使用現有功能定義新命令並將它重新映射到 。

機智(從answer您簡稱):

(defun comment-or-uncomment-region-or-line() 
    "Comments or uncomments the region or the current line if there's no active region." 
    (interactive) 
    (let (beg end) 
     (if (region-active-p) 
      (setq beg (region-beginning) end (region-end)) 
      (setq beg (line-beginning-position) end (line-end-position))) 
     (comment-or-uncomment-region beg end) 
     (next-line))) 

(global-set-key [remap comment-dwim] 'comment-or-uncomment-region-or-line)