]> git.mdlowis.com Git - projs/tide.git/commitdiff
added first pass at trimming of whatespace on save
authorMichael D. Lowis <mike@mdlowis.com>
Mon, 24 Sep 2018 03:02:19 +0000 (23:02 -0400)
committerMichael D. Lowis <mike@mdlowis.com>
Mon, 24 Sep 2018 03:02:19 +0000 (23:02 -0400)
lib/buf.c

index 71bf15e702f98483b18225b79cd52b233d8b9fb9..3827fb0c098d1239eb10d5c11e7cc1a9654cdd32 100644 (file)
--- 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) {