shithub: align

Download patch

ref: 4c0d4746f96e57e216b731662e1641da14c8137a
author: demyxology <spicycoldnoodles@gmail.com>
date: Thu Jan 2 16:36:07 EST 2025

initial commit, here we go!

--- /dev/null
+++ b/align.c
@@ -1,0 +1,111 @@
+#include <u.h>
+#include <libc.h> 
+#include <draw.h>
+#include <bio.h>
+
+enum {
+    Center,
+    Right,
+};
+
+static void usage(void);
+int getwidth(void);
+
+void
+main(int argc, char **argv)
+{
+    int termsize, linelen, align;
+    char *iline;
+    Biobuf in, out;
+    
+    int pos = 0; /* silence warnings */    
+    
+    align = Center;
+    ARGBEGIN{
+        case 'r': align = Right; break;
+        default: usage();
+    }ARGEND
+    
+    termsize = getwidth();
+    if(termsize == -1)
+        sysfatal("term length: %r");
+    
+    Binit(&in, 0, OREAD);
+    Binit(&out, 1, OWRITE);
+    
+    while((iline = Brdline(&in, '\n')) != 0){
+        linelen = Blinelen(&in);
+        if(linelen < termsize) {
+            switch(align){
+                case Center: pos = (termsize / 2) - (linelen / 2); break;
+                case Right:  pos = termsize - linelen; break;
+            }
+            for(int i = 0; i < pos; i++){
+                Bwrite(&out, " ", 1);
+            }
+        } /* give up and just echo the string if it's longer than the term size */
+        Bwrite(&out, iline, linelen);
+    }
+    
+    Bterm(&in);
+    Bterm(&out);
+}
+
+static void
+usage(void)
+{
+	fprint(2, "usage: %s [-r]\n", argv0);
+	exits("usage");
+}
+
+/* adapted from mc.c */ 
+int
+getwidth(void)
+{
+	int n, fd, linewidth;
+	char buf[128], *f[10], *p;
+
+	if(access("/dev/acme", OREAD) >= 0){
+		if((fd = open("/dev/acme/ctl", OREAD)) < 0)
+			return -1;
+		n = read(fd, buf, sizeof buf-1);
+		close(fd);
+		if(n <= 0)
+			return -1;
+		buf[n] = 0;
+		n = tokenize(buf, f, nelem(f));
+		if(n < 7)
+			return -1;
+		if((font = openfont(nil, f[6])) == nil)
+			return -1;
+		linewidth = atoi(f[5]) / stringwidth(font, "0");
+		return linewidth;
+	}
+
+	if((p = getenv("font")) == nil)
+		return -1;
+	if((font = openfont(nil, p)) == nil)
+		return -1;
+	if((fd = open("/dev/window", OREAD)) < 0){
+		font = nil;
+		return -1;
+	}
+	n = read(fd, buf, 5*12);
+	close(fd);
+	if(n < 5*12){
+		font = nil;
+		return -1;
+	}
+	buf[n] = 0;
+	
+	/* window stucture:
+		4 bit left edge
+		1 bit gap
+		12 bit scrollbar
+		4 bit gap
+		text
+		4 bit right edge
+	*/
+	linewidth = atoi(buf+3*12) - atoi(buf+1*12) - (4+1+12+4+4);
+	return linewidth / stringwidth(font, "0");
+}
--- /dev/null
+++ b/mkfile
@@ -1,0 +1,8 @@
+</$objtype/mkfile
+
+TARG=align
+HFILES=
+OFILES=align.$O
+BIN=$home/bin/$objtype/
+
+</sys/src/cmd/mkone
\ No newline at end of file