0

I want to write an Elisp command that searches for a specific string in the backward direction, pauses the cursor there for a second, echoes a message about that occurrence, and then returns the cursor back to its original position. The purpose of the command is to examine the contents surrounding the search string. My text is structured like below:

\begin{myverse}
line one of verse
line two of verse ॥ 3.2 ॥ \\
\end{myverse}
\vspace{2mm}
Lots of text
below
over multiple
lines
cursor here

If my cursor is at the last line (cursor here), I would like the Elisp function to search backwards for the first occurrence of the text , pause for a bit so that I can read the number (3.2), and then return the cursor back to its previous position. I have the following command:

    (defun fn ()
      "Retrieve verse number"
      (interactive)
      (setq test-str "॥")
      (save-excursion
        (search-backward test-str)
        (sit-for 1)))

How can this command be enhanced so that it that prints the verse number in the echo area (i.e. where I type M-x fn)?

1
2

I guess you want this. This matches the text between the markers and makes it a message in the minibuffer when it is found.

(defun fn ()
  (interactive)
  (save-excursion
    (when (re-search-backward "॥\\(.*\\)॥" nil t)
      (message (match-string 1))
      (sit-for 1))))
1
  • Perfect - thanks @John – linuxfan Jan 22 at 19:20
1

You can get behavior similar to what you want by just using backward incremental search (C-r, or C-M-r for regexp-searching). That takes you to the first search hit (and you can repeat the key to move to subsequent hits). This lets you see the search hit in context, which I guess is what your aim is.

You can then just use C-g to cancel searching -- that returns the cursor to the starting point.

(If you instead want to leave the cursor at a search hit, just use RET when you get to that hit.)

0

Your Q is a bit mixed up as at the end of it you've asked for something not related to the title, but all good.

Looking at your text structure wouldn't it not be a better idea to search backwards for text enclosed by your special format char?

eg ॥ FINDME ॥

And this is where you can have some fun reading the man page for re-search-backward

Of course, there are edge cases to sort out at a later date eg starting the search while inside your special grouping. But that's a separate issue for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.