Lately, I have seen some cases where I use re-search-forward to find a pattern, and then try to do something with the match, only to find that the match-data is apparently not correct.
For example, in a file I might have this text:
:RESULTS:
async-abcd-1234-output
:END:
I would expect this code to replace async-abcd-1234-output with "string"
(when (re-search-forward "async-abcd-1234-\\(output\\|value\\)" nil t)
(let ((result-type (match-string 1)))
(cond ((string= result-type "output")
(replace-match "string")))))
That works when I run it in a buffer, but when I run it from a callback function I find that (match-string 1) is nil, and even (match-string 0) is "". What could be causing this? I feel like sometimes it works, and then stops working. It is baffling. Any ideas on how to debug this? When I use edebug, I can see the search appears to work, but the match-data isn't correct.
re-search-forward
is returning non-nil, but not setting the match data, my only guess is perhapsinhibit-changing-match-data
somehow gets bound in that case?(match-string 1)
returns nil. Show the code for how you are using the code you showed. It sounds like you are searching in the wrong buffer, or with point at the wrong buffer position. You say that your code "works in a buffer, but not..." what do you mean by it not being in a buffer? Unless you provide a string argument,re-search-forward
always searches the text in a buffer. The question now seems unclear - underspecified. Originally it seemed that the "typo" you refer to was your problem...debug-on-entry
or inserting calls tomessage
to determine which buffer you are searching and where point is? If not, that would be a good first step.