How to center a string in elisp?

I would like to center to justify the given input string to the given size so that the created string is a string with spaces filled on both sides (left and right) of the input string.

Code I have to do:

(defun center-string (string size)
  (let* ((padding (/ (- size (length string)) 2))
         (lpad (+ (length string) padding))
         (lformat (format "%%%ds" lpad))
         (rformat (format "%%%ds" (- size))))
    (format rformat (format lformat string))))

And some test cases:

(center-string "KJF" 10)
 => "   KJF    "
(center-string "KF" 10)
 => "    KF    "
(center-string "0123456789" 10)
 => "0123456789"
(center-string "0123456789" 5)
 => "0123456789"       ; Notice justifcation is ignored as input string too large.

Is there an existing elisp function for this or a better method?

+3
source share
2 answers

No, there is no existing emacs lisp routine that does what you want. (A standard search through emacs lisp info and emacs info supports this).

0
source

a center-line, ( fill-column ), , , , -

(defun insert-centered (x)
  (insert "\n" x)
  (center-line)
  (insert "\n"))
+1

Source: https://habr.com/ru/post/1717154/


All Articles