Emacs: HTML. Add Paragraph Tags šŸ“œ

By Xah Lee. Date: . Last updated: .

Here's a command to wrap a ā€œpā€ tag around current text block or selection.

(defun xah-html-blocks-to-paragraph (&optional z-begin z-end)
  "Add p tag to current block or selection.
If there is a selection, wrap p around each block.
After this command is called, press variable `xah-repeat-key' to repeat it.

URL `http://xahlee.info/emacs/emacs/emacs_html_wrap_tags.html'
Created: 2019-06-21
Version: 2026-08-13"
  (interactive)
  (let (xbeg xend)
    (progn
      (setq xbeg (if z-begin z-begin (if (region-active-p) (region-beginning) (save-excursion (if (re-search-backward "\n[ \t]*\n" nil 1) (match-end 0) (point))))))
      (setq xend (if z-end z-end (if (region-active-p) (region-end) (save-excursion (if (re-search-forward "\n[ \t]*\n" nil 1) (match-beginning 0) (point)))))))
    (cond
     ((eq xbeg xend) (insert "<p></p>") (backward-char 4))
     ((and (eq xbeg (pos-bol)) (eq xend (pos-eol)))
      (goto-char xbeg) (insert "<p>") (end-of-line) (insert "</p>")
      (skip-chars-forward "\n\n"))
     (t
      (save-restriction
        (narrow-to-region xbeg xend)
        (goto-char (point-min))
        (insert "<p>")
        (goto-char (point-max))
        (insert "</p>")
        (goto-char (point-min))
        (while (re-search-forward "\n\n+" nil t) (replace-match "</p>\n\n<p>" t t))
        (goto-char (point-min))
        (while (re-search-forward "<p></p>" nil t) (replace-match "" t t))))))
  (set-transient-map (let ((xkmap (make-sparse-keymap))) (define-key xkmap (kbd (if (boundp 'xah-repeat-key) xah-repeat-key ".")) this-command) xkmap)))

This is part of Emacs: Xah HTML Mode šŸ“¦