Article View: gnu.emacs.help
Article #189114Re: Operating on lines containing a pattern
From: Barr3y Jaspan
Date: Sat, 04 May 1991 18:26
Date: Sat, 04 May 1991 18:26
47 lines
2438 bytes
2438 bytes
In article <1991May3.194541.12544@leland.Stanford.EDU>, alderson@Alderson.Stanford.EDU (Rich Alderson) writes:
|> >Is there some way to do this in Emacs, short of writing elisp code?
|> >(Or if not, has someone already written appropriate elisp code?)
|>
|> Hmm. Well, that would take a little elisp, using re-search-forward or
|> re-search-backward, and working like M-x replace-regexp or M-x
|> query-replace-regexp on the selected line.
I have written a function mapline that you might find useful. It takes a
region, a function, and arguments, and applies the function to the args for
each line in the region. (Note that a more robust implementation would use
unwind-protect or condition-case to trap errors in the function...)
(defun mapline (beg end f &rest args)
"With the point set to the beginning of each line between BEGIN and
END, apply FUNCTION to ARGS and return a list of the result."
(let* ((p (point-marker))
(mlist (list 'mlist))
(mtail (last mlist)))
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(beginning-of-line)
(while (< (point) (point-max))
(save-excursion
(setcdr mtail (list (apply f args)))
(setq mtail (cdr mtail)))
(forward-line 1))
)
(goto-char p)
(cdr mlist)))
I use this to call a certain function for each line that matches a regexp,
like this:
(mapline
(point-min) (point-max)
(function (lambda ()
(if (re-search-forward zwgc-znol-output-regexp nil t)
(zwgc-znol-login)
(error "zwgc-znol-output-regexp failed!"))))))
Generalized iterators like this are extremely powerful.
--
Barr3y Jaspan, bjaspan@mit.edu
Watchmaker Computing
Technical Details
Message-ID:
<1991May4.182621.2544@athena.mit.edu>Path:
arc1-ca.pugleaf.net!gmdzi!unido!mcsun!uunet!elroy.jpl.nasa.gov!usc!snorkelwacker.mit.edu!bloom-picayune.mit.edu!athena.mit.edu!bjaspanReferences:
<BAUMGART.91May3100021@esquire.esquire.dpw.com> <1991May3.194541.12544@leland.Stanford.EDU>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103b8b,80ffebd709a40a03 X-Google-Attributes: gid103b8b,public X-Google-ArrivalTime: 1991-05-04 11:59:13 PST Path: arc1-ca.pugleaf.net!gmdzi!unido!mcsun!uunet!elroy.jpl.nasa.gov!usc!snorkelwacker.mit.edu!bloom-picayune.mit.edu!athena.mit.edu!bjaspan From: bjaspan@athena.mit.edu (Barr3y Jaspan) Newsgroups: gnu.emacs.help Subject: Re: Operating on lines containing a pattern Message-ID: <1991May4.182621.2544@athena.mit.edu> Date: 4 May 91 18:26:21 GMT References: <BAUMGART.91May3100021@esquire.esquire.dpw.com> <1991May3.194541.12544@leland.Stanford.EDU> Sender: news@athena.mit.edu (News system) Organization: Massachusetts Institute of Technology Lines: 47