my/pure-paragraph-refill

James Dyer : Feb 14, 2023 : 352 words
emacs linux elisp 2023

Simply a worded up elisp function (see below)

;; -----------------------------------------------------------------------------
;; Title: my/pure-paragraph-refill
;; -----------------------------------------------------------------------------
;; Description:
;; --------------------
;; To purely refill simple paragraph text in a multi facetted file (for example
;; org) to a desired fill-column by focussing on a very simple paragraph
;; redefinition thereby resulting in the refilling exemption of the following
;; types of textual elements:
;;
;; :stuffs
;; #+stuffs
;; * org headers stuffs
;; (lispy stuffs
;; and anything else - not a [[:word:]] or - or "
;;
;; --------------------
;; Use Example
;; --------------------
;; When switching to a new fill-column to enable a quick refactoring of existing
;; org files and to ignore everything that shouldn't be refilled.  This is
;; especially prevalent in an org file where the drawers / headers / source
;; blocks e.t.c should be exempt from a purely textual refill
;;
;; --------------------
;; Current emacs refilling
;; --------------------
;; fill-region causes corruption across most elements and a macro exits on an
;; error so I thought I would try and write something myself!
;;
;; options:
;; --------------------
;; <none>    - refill to fill-column (no justify)
;; C-u       - refill to fill-column (justify)
;; C-u C-u   - refill to very long lines (no justify)
;; C-u <num> - refill to <num> column (no justify)
;;
(defun my/pure-paragraph-refill (arg)
  (interactive "p") ;; allowing universal argument
  (save-excursion ;; save original cursor position so refill not too jarring
    (let ((paragraph-start "^[-\\\"[:word:]]") ;; setup character delimiter
          (paragraph-separate "^[-\\\"[:word: ]]")) ;; setup character delimiter
      (goto-char (point-min)) ;; goto start of file
      (while (not (eobp)) ;; loop through whole file
        (ignore-errors ;; don't stop if org-fill-paragraph raises error
          (forward-paragraph) ;; move to next paragraph
          (if (> arg 1) ;; if C-u has been activated
              (cond ((= arg 4)
                     (org-fill-paragraph arg)) ;; C-u
                    ((= arg 16)
                     (let ((fill-column 9999)) (org-fill-paragraph))) ;; C-u C-u
                    (t
                     (let ((fill-column arg)) (org-fill-paragraph)))) ;; C-u <num>
            (org-fill-paragraph) ;; refill the paragraph (works on non org files)
            ;; note: error raised when within a source code block but that is ok
            )
          )
        )
      )
    )
  )