簡體   English   中英

如何有效地瀏覽emacs緩沖區修改行

[英]How do I navigate efficiently through emacs buffer modifying lines

我是一個elisp(但不是編程)的初學者,並且對實現函數的最佳實踐有一些疑問。 我編寫了一個elisp函數,根據某些規則重新格式化匯編程序源代碼; 此功能目前適用於單行。 它主要使用行內的導航,在子表達式上查看和替換匹配調用來實現目標。

現在我想將它應用於標記區域,逐行處理區域。 該行為將類似於縮進區域函數。

實現此目的的推薦(和有效)方法是什么? 我考慮使用(line-number-at-pos ...)應用於(region-beginning)(region-end)來計算行號,然后從上到下移動,逐行緩沖,修改這些。

此外,通過此操作我需要保留什么? 我雖然關於(保存匹配數據......)並且不確定如何處理標記和點。 我猜他們將無用,因為文本范圍發生了變化。

使用save-excursion保存和恢復點和標記以及save-restriction以縮小到該區域。

模板將是這樣的:

(defun my-process-region (beg end)
  "Apply `my-process-line` to every line in region."
  (interactive "r")
  (save-restriction
    (widen)
    (save-excursion
      (narrow-to-region beg end)
      (goto-char (point-min))
      (while (not (eobp))
        (my-process-line)))))

我接受了sds的答案。 最后,我使用了下面的代碼。 原因是我想要整行可用於重新格式化,而不僅僅是標記的區域。 所以(narrow-to-region)本身就不會完成這項工作。 我很高興了解更多,並欣賞有關利弊或缺失事物的評論:

(defun x-mode-reformat-region (beg end)
  "..."
  (interactive "r")
  (save-excursion
    (let ((nlines (+ 1 (apply '- (mapcar 'line-number-at-pos `(,end ,beg)))))
          bol
          ...)
      (goto-char beg)
      (dotimes (i nlines)
        (setq bol (line-beginning-position))
        (goto-char bol)
        ;; do reformatting for this line -- uses bol for calculations
        (forward-line)))))

接下來嘗試 - 根據評論進行修改。 我沒有找到一種更簡單的方法來擴展選擇以包括整行......任何想法是否可以進一步簡化setq / narrow-to-region組合(除了直接使用(progn ...)作為參數?

(defun x-mode-reformat-region (beg end)
  "..."
  (interactive "r")
  (save-restriction
    (widen)
    (save-excursion
      (setq beg (progn (goto-char beg) (line-beginning-position))
            end (progn (goto-char end) (line-end-position)))
      (narrow-to-region beg end)
      (goto-char (point-min))
      (while (not (eobp))
        (insert "*") ;; placeholder for fancy reformatting
        (forward-line)))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM