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

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

Re: Custom query-replace.


From: Yuri Khan
Subject: Re: Custom query-replace.
Date: Mon, 13 Jul 2015 13:19:31 +0600

On Mon, Jul 13, 2015 at 2:47 AM, R. Clayton <rvclayton@acm.org> wrote:
> I'm trying to write a query-replace command to deal with hyphens in text.  For
> each match, I want to perform one of three changes:
>
>   delete hyphen; go from "for- got" to "forgot"
>   unspace hyphen; go from "red- headed" to "red-headed"
>   space hyphen; go from "stop- it" to "stop - it"
>
> as well as the usual query-replace options (quit, skip, and so on).  For
> example, typing 'D' at the query-replace prompt would delete the hyphen.

So you want to search for a pattern and interactively optionally
replace each occurrence with one of several possible replacements. I
don’t know of a ready-made solution for that. Here’s what I would do
instead.


Record and save four macros that:

0. all assume the starting position where the point is immediately
after the hyphen and its following whitespace if any;

1a. one (“delete-hyphen-and-find-next”) deletes the preceding
whitespace and the hyphen;
1b. another (“unspace-hyphen-and-find-next”) deletes the preceding whitespace;
1c. yet another (“space-hyphen-and-find-next”) does a backwards
isearch for the hyphen, inserts a single space before it and pops the
mark saved by the isearch;
1d. the fourth (“find-next-hyphen”) does nothing at this point;

2. after which all four macros skip (using regexp isearch) to the next
occurrence of the search pattern, preparing for the next replacement.

Bind them to sufficiently easy keys.

Go to the start of buffer (M-<); if it is not an occurrence of the
search pattern, prime the loop by invoking “find-next-hyphen”.

Repeatedly invoke one of the four macros, until the buffer ends.

In case of mistake, undo. To return to the place of last occurrence in
case of doubt, pop the mark (C-u C-SPC).

Between the replacements, you can make any other edits, provided that
you leave the point at a position suitable for the next replacement.
(“find-next-hyphen” can be used at any position.)


Possible improvement: Rewrite the macros as elisp functions. Check
preconditions. Instead of isearch, use non-interactive elisp search
facilities. (This way, you protect against document corruption when
running macros at unsuitable positions, and stop clobbering the last
isearch pattern.)


Possible further improvement: If you encounter this task frequently
and the need for other edits is low, you might want to make it a minor
mode that (1) primes the loop on entry; (2) binds super-easy
(basically, single-character) keys; (3) binds another super-easy key
(such as “q”) to disable the mode.



reply via email to

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