Function: markdown-ts--promote-or-demote

markdown-ts--promote-or-demote is a byte-compiled function defined in markdown-ts-mode.el.gz.

Signature

(markdown-ts--promote-or-demote DELTA)

Documentation

Change the heading at point by DELTA levels.

Negative DELTA promotes (fewer #), positive demotes (more #). If the heading has an optional trailing closing-# sequence, that sequence is resized to match the new level.

Source Code

;; Defined in /usr/src/emacs/lisp/textmodes/markdown-ts-mode.el.gz
(defun markdown-ts--promote-or-demote (delta)
  "Change the heading at point by DELTA levels.
Negative DELTA promotes (fewer #), positive demotes (more #).
If the heading has an optional trailing closing-`#' sequence, that
sequence is resized to match the new level."
  (when-let* ((heading (markdown-ts--heading-at-point))
              (marker (treesit-node-child heading 0))
              (level (length (treesit-node-text marker t)))
              (new-level (+ level delta)))
    (when (and (>= new-level 1)
               (<= new-level markdown-ts--parser-heading-max-level))
      (let* ((opener-beg (treesit-node-start marker))
             (opener-end (treesit-node-end marker))
             (line-end (save-excursion
                         (goto-char opener-end)
                         (line-end-position)))
             ;; Detect a CommonMark closing-`#' sequence: optional
             ;; trailing whitespace, a run of `#', and at least one
             ;; space/tab between it and the heading text.
             (closer (save-excursion
                       (goto-char line-end)
                       (skip-chars-backward " \t" opener-end)
                       (let ((end (point)))
                         (skip-chars-backward "#" opener-end)
                         (let ((beg (point)))
                           (when (and (< beg end)
                                      (> beg opener-end)
                                      (memq (char-before beg)
                                            '(?\s ?\t)))
                             (cons beg end)))))))
        (save-excursion
          ;; Resize the closer first so it doesn't shift the opener.
          (when closer
            (delete-region (car closer) (cdr closer))
            (goto-char (car closer))
            (insert (make-string new-level ?#)))
          (delete-region opener-beg opener-end)
          (goto-char opener-beg)
          (insert (make-string new-level ?#)))))))