2

I want to do this replacement:

\includegraphics{file
      }

==>

\includegraphics{file}

I wrote this code:

(goto-char (point-min))
(while (re-search-forward "\\\\includegraphics{" nil t)
  (save-excursion
    (backward-char 1)
    (forward-sexp)
    (backward-char 1)
    (when (looking-back "[ \n]+")
      (replace-match "" t))))

It doesn't work as I expected because only one space is replaced instead of all the space between file and }. Why (looking-back "[ \n]+") behaves as it were (looking-back " ") and does not match [ \n]+?

(I already found a solution by combining (skip-chars-backward " \n") with (looking-at "[ \n]+").)

1 Answer 1

2

Why (looking-back "[ \n]+") behaves as it were (looking-back " ") and does not match [ \n]+?

It does match "[ \n]+" -- a single space is a match for that regexp. Remember that looking-back only has a fixed end point, not a fixed start point -- the start point is moved backwards iteratively until either a match is found, or the LIMIT is reached. (n.b. This is why it's comparatively slow.)

The docs cover extending the start point backwards as far as possible with the GREEDY argument (but your solution is preferable as it avoids using looking-back at all).

looking-back is a compiled Lisp function in `subr.el'.

(looking-back REGEXP LIMIT &optional GREEDY)

  Probably introduced at or before Emacs version 22.1.

Return non-nil if text before point matches regular expression REGEXP.
Like `looking-at' except matches before point, and is slower.
LIMIT if non-nil speeds up the search by specifying a minimum
starting position, to avoid checking matches that would start
before LIMIT.

If GREEDY is non-nil, extend the match backwards as far as
possible, stopping when a single additional previous character
cannot be part of a match for REGEXP.  When the match is
extended, its starting position is allowed to occur before
LIMIT.

As a general recommendation, try to avoid using `looking-back'
wherever possible, since it is slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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