From: Michael D. Lowis Date: Mon, 24 Sep 2018 03:02:19 +0000 (-0400) Subject: added first pass at trimming of whatespace on save X-Git-Url: https://git.mdlowis.com/?a=commitdiff_plain;h=c8f96dc12ea97456b3a144d9ef28299f121a5064;p=projs%2Ftide.git added first pass at trimming of whatespace on save --- 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) {