Ehvince
Ehvince

Reputation: 18395

Format directive or one liner to truncate a long string ?

My use case is to print a list of lists as a table, with columns of equal length, so I want to truncate long inputs. Is there a directive to do that ? Maybe a one liner with ~[ conditionals ?

The argument of ~a allows to fill with blanks:

    (format t "~10a***" "aaa")
aaa       ***
    ;; aaa       ***

a long input is entirely printed:

(format t "~10a***" "aaaaaaaaaaaaaaaaa")
;; aaaaaaaaaaaaaaaaa***

So I'm doing like this, with the help of str:substring where start and end can be larger than the list without throwing an error (on the contrary of subseq):

(ql:quickload "str")
(defvar mylist '(("header a" "header b")
                 ("col a" "col b")
                 ("much longer col a" "much longer col b")))
(mapcar (lambda (it)
          (format t "~10a | ~10a ~&" (str:substring 0 10 (first it)) 
                  (str:substring 0 10 (second it))))
        mylist)
header a   | header b   
col a      | col b      
much longe | much longe 

I don't expect format to be able to add an ellipsis (...) to the truncated strings, but that would be nice.

I didn't find what I'm looking for in the quick reference or here.

Thanks !

Upvotes: 2

Views: 351

Answers (2)

Ehvince
Ehvince

Reputation: 18395

There is also str:prune length string now, which accepts an :ellipsis argument to tell how to cut the string:

(mapcar (lambda (tuple)
                       (format t "~10a | ~10a~&" 
                               (str:prune 10 (first tuple) :ellipsis "…")
                               (str:prune 10 (second tuple) :ellipsis "…")))
                     mylist)
header a   | header b  
col a      | col b     
much long… | much long…

we can use the v directive to not repeat the column length that much:

(defparameter *col-length* 10)

(mapcar (lambda (tuple)
           (format t "~va | ~va~&" 
                     *COL-LENGTH*
                     (str:prune *COL-LENGTH* (first tuple) :ellipsis "…")
                     *COL-LENGTH*
                     (str:prune *COL-LENGTH* (second tuple) :ellipsis "…")))
       mylist)
header a   | header b  
col a      | col b     
much long… | much long…

and we could use (let ((str:*ellipsis* "…") …).

Upvotes: 0

Svante
Svante

Reputation: 51511

Not that I am aware, but you can certainly write your own and use it with Tilde Slash.

Upvotes: 3

Related Questions