views:

56

answers:

2

I would like to center justify a given input string to a given size so that what is produced is a string with padded spaces either side (left and right) of the input string.

The code I have to do this:

(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 to do this or a better method?

A: 

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

Trey Jackson
A: 

There's a center-line, which works in a buffer (and uses the buffer's value of fill-column as the line length), so if your goal is to produce a nicely formatted file, you could do something like

(defun insert-centered (x)
  (insert "\n" x)
  (center-line)
  (insert "\n"))
Jouni K. Seppänen