help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Operate on each line in region


From: Pascal J. Bourguignon
Subject: Re: Operate on each line in region
Date: Wed, 23 Apr 2014 20:15:19 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

Jacob Gerlach <address@hidden> writes:

> I am writing a function that will indent each line in a region to justify 
> equals signs:
>
>  foo = 1
>  longerfoo = bar
>
> Would become 
>
>        foo = 1
>  longerfoo = bar
>
> I believe I understand how to iterate through the lines in a region using 
> either of two methods:
>
> condition on the buffer positions for the start and end of the region:
>
> (defun my-justify (start end)
> (interactive 'r')
> (while (< (point) end))
> ...body...
> (forward-line 1)))
>
> Narrow the buffer to region and use similar conditioning with (eobp).
>
> I'm wondering if there is a more straightforward way to accomplish this.

Good question.

If there's not, you should do it; it's trivial:

(defun call-with-region-narrowed-to-each-line-in-region (start end thunk)
  (save-excursion
   (save-restriction
    (narrow-to-region start end)
    (dolines (lstart lend)
             (save-restriction
              (narrow-to-region lstart lend)
              (funcall thunk))))))


(defmacro with-region-narrowed-to-each-line-in-region (start end &rest body)
  `(call-with-region-narrowed-to-each-line-in-region ,start ,end (lambda () 
,@body)))


(with-temp-buffer
    (let ((data '("deux" "trois" "quatre")))
      (insert "1 one
2 two
3 three
4 four
5 five
")
      (goto-char (point-min))
      (forward-line 1)
      (block nil
        (let ((start (point)))
          (goto-char (point-max))
          (forward-line -1)
          (let ((end (point)))
            (with-region-narrowed-to-each-line-in-region start end
              (let ((old (split-string (buffer-substring (point-min) 
(point-max))  " ")))
                (message "%S" (list  (point-min) (point-max) old))
                (delete-region (point-min) (point-max))
                (insert (format ":%s:%s" (first old) (pop data))))))))
      (buffer-substring (point-min) (point-max))))

"1 one
:2:deux
:3:trois
:4:quatre
5 five
"


You can find dolines in: 

https://gitorious.org/com-informatimago/emacs/source/b58a0a336b46f3523700931117b409307b13d9b0:pjb-emacs.el#L2262

Notice however, that the implementation of dolines doesn't allow you to
insert new lines in the processed lines, since this will lead to an
infinite loop.  It could be modified to skip to the marker to the end of
the old line.
 
-- 
__Pascal Bourguignon__
http://www.informatimago.com/
"Le mercure monte ?  C'est le moment d'acheter !"


reply via email to

[Prev in Thread] Current Thread [Next in Thread]