0

Aiming to convert first row of a html table from to tags.

So, I wrote the following code.

(defun tdtoth ()
  (if (search-forward "</tr>" nil t)
      (while (search-forward "td" nil t)
        (replace-match "th" 1))))

And executed it while I was on in the following text:

<tr>
  <td> Some text </td>
  <td> Another thing </td>
</tr>

The idea being search for </tr> only once and while that is not happening, replace every td with th

But that code does not work. What is wrong and how do I set it right?

2
  • 1
    Don't write that function if you don't need it in the context of some bigger program. Just narrow your buffer to the region <tr>...</tr>. Thereafter you can easily perform any replacements restricted to that region. Narrowing the buffer works as follows: Put point on <tr> and type C-_ (the underscore stands for a space). That sets mark and therefore starts the region. Search for </tr> via C-s and type C-x n n for narrow-to-region.
    – Tobias
    Commented Jun 12, 2018 at 13:26
  • @Tobias the function was doing several things together. This was one part of it. But I agree with your point. It would be quicker just to do it with narrowing, etc. in the buffer
    – deshmukh
    Commented Jun 12, 2018 at 16:52

1 Answer 1

2

After my comment about not needing the function in most cases I also want to give an answer to your actual question.

One of the many ways to replace all occurences of td-tags with th-tags starting at point and stopping at a closing tr-tag is shown below. The most important differences to your solution are:

  • You need to keep point's position when you search for the end tag </tr> (e.g., with save-excursion).
  • You need to restrict your search for <td> to the region between point and the found end position, e.g., with the BOUND-argument of search-forward.
(defun dttoth ()
  "Replace dt by th starting at point and stopping at </tr>."
  (interactive)
  (let ((bound (save-excursion (search-forward "</tr>" nil t))))
    (when bound
      (while (re-search-forward "<[/]?\\(td\\)>" bound t)
        (replace-match "th" t nil nil 1)))))

Your Answer

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

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