在Emacs中恢复垂直缓冲区位置

时间:2013-11-27 16:34:29

标签: regex emacs elisp

我使用以下代码更新了我正在处理的一些遗留代码的编码风格。它现在可以正常工作但是令人讨厌的是,在区域上执行命令后,缓冲区会滚动,因此区域的顶部位于窗口的顶部。我该如何解决这个问题?

(defun mkm/cleanup ()
  (interactive)
  (let (start end doit)
    (if (region-active-p)
        (setq start (region-beginning) end (region-end) doit t)
      (progn (setq start (point-min) end (point-max))
             (setq doit (y-or-n-p "Really cleanup whole buffer? "))))
    (if doit
        (save-excursion
          (save-restriction
            (narrow-to-region start end)
            (replace-regexp "\([[:alpha:]]\)[ ]+" "\1 " nil (point-min) (point-max))
            (replace-regexp " *&" " &" nil (point-min) (point-max))
            (replace-regexp "[ ]*\\*" " *" nil (point-min) (point-max))
            (replace-regexp "( +" "(" nil (point-min) (point-max))
            (replace-regexp " +)" ")" nil (point-min) (point-max))
            (replace-regexp "{ +" "{" nil (point-min) (point-max))
            (replace-regexp "} +" "}" nil (point-min) (point-max))
            (replace-regexp " +]" "]" nil (point-min) (point-max))
            (replace-regexp "\s*,\s*" ", " nil (point-min) (point-max))
            (replace-regexp "\s*->\s*" "->" nil (point-min) (point-max))
            (replace-regexp "\\[ +" "\\[" nil (point-min) (point-max))
            (replace-regexp " += +" " = " nil (point-min) (point-max))
            (replace-regexp "\([[:alpha:]]\)[ ]+>" "\1>" nil (point-min) (point-max))
            (replace-regexp "<\s+" "<" nil (point-min) (point-max))
            (replace-regexp "<<\([^\s]\)" "<< \1" nil (point-min) (point-max))))
      (message "Cleanup aborted."))))

3 个答案:

答案 0 :(得分:2)

以下是代码,相关函数为save-window-excursion

(defun mkm/cleanup ()
  (interactive)
  (let (start end doit)
    (if (region-active-p)
        (setq start (region-beginning)
              end (region-end)
              doit t)
      (setq start (point-min)
            end (point-max)
            doit (y-or-n-p "Really cleanup whole buffer? ")))
    (if doit
        (save-window-excursion
          (save-excursion
            (save-restriction
              (narrow-to-region start end)
              (mapc
               (lambda(x)
                 (replace-regexp
                  (car x) (cdr x)
                  nil (point-min) (point-max)))
               '(("\([[:alpha:]]\)[ ]+" . "\1 ")
                 (" *&" . " &")("[ ]*\\*" . " *")
                 ("( +" . "(")(" +)" . ")")("{ +" . "{")
                 ("} +" . "}")(" +]" . "]")("\s*,\s*" . ", ")
                 ("\s*->\s*" . "->")("\\[ +" . "\\[")
                 (" += +" . " = ")
                 ("\([[:alpha:]]\)[ ]+>" . "\1>")
                 ("<\s+" . "<")("<<\([^\s]\)" . "<< \1"))))))
      (message "Cleanup aborted.")))) 

答案 1 :(得分:0)

不要使用save-excursionsave-excursion说:“做这些事情,然后再回到这里。”这听起来像你想要它“做这个东西,并留在你最终的地方。”

答案 2 :(得分:0)

您可能只需要:

(let ((windowstart (window-start)))
  ;; ...
  (set-window-start (selected-window) windowstart))