summaryrefslogtreecommitdiff
path: root/devdocs/elisp/saving-match-data.html
blob: 9aaa895b27194c571ce2c735e19dac31a8f6422a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 <h4 class="subsection">Saving and Restoring the Match Data</h4> <p>When you call a function that may search, you may need to save and restore the match data around that call, if you want to preserve the match data from an earlier search for later use. Here is an example that shows the problem that arises if you fail to save the match data: </p> <div class="example"> <pre class="example">(re-search-forward "The \\(cat \\)")
     ⇒ 48
(foo)                   ; <span class="roman"><code>foo</code> does more searching.</span>
(match-end 0)
     ⇒ 61              ; <span class="roman">Unexpected result—not 48!</span>
</pre>
</div> <p>You can save and restore the match data with <code>save-match-data</code>: </p> <dl> <dt id="save-match-data">Macro: <strong>save-match-data</strong> <em>body…</em>
</dt> <dd><p>This macro executes <var>body</var>, saving and restoring the match data around it. The return value is the value of the last form in <var>body</var>. </p></dd>
</dl> <p>You could use <code>set-match-data</code> together with <code>match-data</code> to imitate the effect of the special form <code>save-match-data</code>. Here is how: </p> <div class="example"> <pre class="example">(let ((data (match-data)))
  (unwind-protect
      …   ; <span class="roman">Ok to change the original match data.</span>
    (set-match-data data)))
</pre>
</div> <p>Emacs automatically saves and restores the match data when it runs process filter functions (see <a href="filter-functions">Filter Functions</a>) and process sentinels (see <a href="sentinels">Sentinels</a>). </p><div class="_attribution">
  <p class="_attribution-p">
    Copyright &copy; 1990-1996, 1998-2022 Free Software Foundation, Inc. <br>Licensed under the GNU GPL license.<br>
    <a href="https://www.gnu.org/software/emacs/manual/html_node/elisp/Saving-Match-Data.html" class="_attribution-link">https://www.gnu.org/software/emacs/manual/html_node/elisp/Saving-Match-Data.html</a>
  </p>
</div>