From ce7d51f9be451bdfd7f836a2aa7e2e9c7d3e07da Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Sun, 26 Apr 2020 11:53:26 -0500 Subject: [PATCH] Add dedent to core. Makes longstrings easier to use - can be combined with comptime for overhead free long strings. --- src/boot/boot.janet | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/boot/boot.janet b/src/boot/boot.janet index 9f34f2e6..0fb2e1b0 100644 --- a/src/boot/boot.janet +++ b/src/boot/boot.janet @@ -1332,6 +1332,27 @@ (if (not= i len) (array/push ret (slicer ind i))) ret) +(defn dedent + "Remove indentation after concatenating the arguments. Works by removing + leading whitespace, and then removing that same pattern of whitepsace after + new lines." + [& xs] + (def x (string ;xs)) + (def first-letter (find-index (fn [c] (and (not= c (chr "\n")) + (not= c (chr " ")) + (not= c (chr "\t")) + (not= c (chr "\r")))) x)) + (if (not first-letter) (break "")) + (def leading-whitespace (string/slice x 0 first-letter)) + (def indent (last (string/split "\n" leading-whitespace))) + (if (and indent (not= indent "")) + (let [y (string/replace-all (string "\n" indent) "\n" (string/replace indent "" x))] + # Remove trailing newline to mimic long string newline omission. + (if (= (chr "\n") (last y)) + (slice y 0 -2) + y)) + x)) + ### ### ### IO Helpers