Skip to content

Instantly share code, notes, and snippets.

@tatut
Created April 10, 2018 18:14
Show Gist options
  • Select an option

  • Save tatut/9557831becfd21a3f16cadd35dcc6edb to your computer and use it in GitHub Desktop.

Select an option

Save tatut/9557831becfd21a3f16cadd35dcc6edb to your computer and use it in GitHub Desktop.
String wrap (by splitting to words)
;; keeps original new-lines, so that there may be shorter lines
;; caveat: if a single word is longer than the split length, it will overflow
(defn split-line [n line]
(reduce
(fn [lines word]
(if (or (empty? lines)
(>= (+ (count (last lines)) (count word)) n))
(conj lines word)
(update lines (dec (count lines)) str " " word)))
[]
(str/split line #"\s+")))
(defn split-to-length [n text]
(str/join
"\n"
(mapcat (partial split-line n)
(str/split text #"\n"))))
;; (split-to-length 10 "this is something big\nkeep:\n- items\n- of great length here\nsupercalifragilisticexpialadicous")
;;this is
;;something
;;big
;;keep:
;;- items
;;- of great
;;length
;;here
;;supercalifragilisticexpialadicous
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment