From c8f96dc12ea97456b3a144d9ef28299f121a5064 Mon Sep 17 00:00:00 2001 From: "Michael D. Lowis" Date: Sun, 23 Sep 2018 23:02:19 -0400 Subject: [PATCH] added first pass at trimming of whatespace on save --- lib/buf.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/buf.c b/lib/buf.c index 71bf15e..3827fb0 100644 --- a/lib/buf.c +++ b/lib/buf.c @@ -143,9 +143,36 @@ void buf_reload(Buf* buf) { buf_load(buf, path); } +static void trim_whitespace(Buf* buf) { + if (!TrimOnSave || !buf_end(buf)) return; + Sel sel = buf->selection; + unsigned prev = 1; + buf->selection.beg = buf->selection.end = 0; + while (buf->selection.end < buf_end(buf) && prev != buf->selection.end) { + int r = getb(buf, buf->selection.end); + /* If we reached a newline, then delete whatever we have selected */ + if (r == '\r' || r == '\n') { + buf->selection.beg = buf_byrune(buf, buf->selection.beg, +1); + buf_del(buf); + } + + /* if current char is not whitespace, then shrink the selection */ + if (r != ' ' && r != '\t') + buf->selection.beg = buf->selection.end; + + /* move to the next character */ + prev = buf->selection.end; + buf->selection.end = buf_byrune(buf, buf->selection.end, +1); + } + buf->selection = sel; +} + int buf_save(Buf* buf, char* path) { buf_setpath(buf, path); if (0 == buf_end(buf)) return buf->status; + + trim_whitespace(buf); + char* wptr; long fd, nwrite = 0, towrite = 0; if (buf->path && (fd = open(buf->path, O_WRONLY|O_CREAT|O_TRUNC, 0644)) >= 0) { -- 2.49.0