aboutsummaryrefslogtreecommitdiff
path: root/module/output/text.scm
diff options
context:
space:
mode:
authorHugo Hörnquist <hugo@hornquist.se>2019-04-23 21:28:40 +0200
committerHugo Hörnquist <hugo@hornquist.se>2019-04-23 22:48:15 +0200
commit11f83cf1e3a179d3442ce5610a69483fececffb2 (patch)
tree77f6341e65cfc36e71f9d715a1fa4fe919780ef9 /module/output/text.scm
parentAdd ability to set start-date of term mode. (diff)
downloadcalp-11f83cf1e3a179d3442ce5610a69483fececffb2.tar.gz
calp-11f83cf1e3a179d3442ce5610a69483fececffb2.tar.xz
Replace text-flow function.
Diffstat (limited to 'module/output/text.scm')
-rw-r--r--module/output/text.scm53
1 files changed, 53 insertions, 0 deletions
diff --git a/module/output/text.scm b/module/output/text.scm
new file mode 100644
index 00000000..e86f4664
--- /dev/null
+++ b/module/output/text.scm
@@ -0,0 +1,53 @@
+(define-module (output text)
+ #:use-module (util)
+ #:export (justify-line flow-text))
+
+(define-public (words str) (string-split str #\space))
+(define-public (unwords list) (string-join list " " 'infix))
+
+(define-public (lines str) (string-split str #\newline))
+(define-public (unlines list) (string-join list "\n" 'infix))
+
+(define* (add-some list amount item #:optional flipflop?)
+ (cond ((zero? amount) list)
+ ((null? list) '())
+ (else
+ (cons (if flipflop? item (car list))
+ (add-some (if flipflop? list (cdr list))
+ (if flipflop? (1- amount) amount)
+ item (not flipflop?))))))
+
+;; (str) -> str
+(define* (justify-line-helper words #:key (width 70))
+ (let* ((len (1- (apply + (map (compose 1+ string-length) words))))
+ (to-add (- width len))
+ (slots (1- (length words)))
+ (sp-per (ceiling-quotient to-add slots)))
+
+ (unwords (add-some words to-add (make-string (1- sp-per) #\space)))))
+
+
+;; Splits and justifies the given line to @var{#:width}.
+;; Returns a list of justified strings.
+;; str -> (str)
+(define* (justify-line line #:key (width 70))
+ (let recur ((lst (words line)))
+ (let* ((head tail (take-drop-while
+ (let ((w 0))
+ (lambda (word) ; Take words until we are above the limit.
+ (< (mod! w = (+ 1 (string-length word)))
+ width)))
+ lst)))
+ (if (null? tail)
+ (list (unwords head)) ; Don't justify last line.
+ (cons (justify-line-helper head #:width width)
+ (recur tail))))))
+
+;; str -> str
+(define* (flow-text str #:key (width 70) (height 10))
+ (unlines
+ (take-to
+ (flatten
+ (map (lambda (line) (justify-line line #:width width))
+ (lines str)))
+ height)))