Source

slmenu / slmenu.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <stdbool.h>
#include <wchar.h>

wchar_t *wcsdup(const wchar_t *s);
int wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n);


#define XSEL          "xsel -h >/dev/null 2>&1 && test -n \"$DISPLAY\" && xsel -ob || cat /tmp/.sandy.clipboard.$USER"
#define CONTROL(ch)   (ch ^ 0x40)
#define MIN(a,b)      ((a) < (b) ? (a) : (b))
#define MAX(a,b)      ((a) > (b) ? (a) : (b))

enum Color {
	C_Normal,
	C_Reverse
};
typedef enum Color Color;

typedef struct Item Item;
struct Item {
	wchar_t *text;
	Item *left, *right;
};

static void   appenditem(Item*, Item**, Item**);
static void   calcoffsets(void);
static void   cleanup(void);
static void   die(const char*);
static void   drawtext(const wchar_t*, size_t, Color);
static void   drawmenu(void);
static wchar_t *fstrstr(const wchar_t*, const wchar_t*);
static void   insert(const wchar_t*, ssize_t);
static void   match(bool);
static size_t nextrune(int);
static void   readstdin(void);
static void   run(void);
static void   setup(int);
static size_t textw(const wchar_t*);

static wchar_t   text[BUFSIZ] = L"";
static int    mw;
static int    inputw, promptw;
static size_t cursor;
static wchar_t  *prompt = NULL;
static Item  *items = NULL;
static Item  *matches, *matchend;
static Item  *prev, *curr, *next, *sel;
static struct termios tio_old, tio_new;
static int  (*fstrncmp)(const wchar_t*, const wchar_t*, size_t) = wcsncmp;

void
appenditem(Item *item, Item **list, Item **last) {
	if(!*last)
		*list = item;
	else
		(*last)->right = item;
	item->left = *last;
	item->right = NULL;
	*last = item;
}

void
calcoffsets(void) {
        int i, n;

	n = mw - (promptw + inputw + textw(L"◀") + textw(L"▶"));

        for(i = 0, next = curr; next; next = next->right)
                if((i += MIN(textw(next->text), n)) > n)
                        break;
        for(i = 0, prev = curr; prev && prev->left; prev = prev->left)
                if((i += MIN(textw(prev->left->text), n)) > n)
                        break;
}

void
cleanup() {
	fprintf(stderr, "\033[K");
	tcsetattr(0, TCSANOW, &tio_old);
}

void
die(const char *s) {
	tcsetattr(0, TCSANOW, &tio_old);
	fprintf(stderr, "%s\n", s);
	exit(1);
}

void
drawtext(const wchar_t *t, size_t w, Color col) {
	const wchar_t *prestr, *poststr;
	int i;
	wchar_t *buf;

	if((buf=calloc(1, (w+1))) == NULL) die("Can't calloc.");
	switch(col) {
	case C_Reverse:
		prestr=L"\033[7m";
		poststr=L"\033[0m";
		break;
	case C_Normal:
	default:
		prestr=poststr=L"";
	}

	wmemset(buf, L' ', w);
	buf[w]=L'\0';
	wmemcpy(buf, t, w);
	if(textw(t)-4>w)
		for(i=MAX((w-4), 0); i<w; i++) buf[i]=L'.';

	fwprintf(stderr, L"%s  %s  %s", prestr, buf, poststr);
	free(buf);
}

void
drawmenu(void) {
	Item *item;
	int rw;

	/* use default colors */
	fprintf(stderr, "\033[0m");

	/* place cursor in first column, clear it */
	fprintf(stderr, "\033[0G");
	fprintf(stderr, "\033[K");

	if(prompt)
		drawtext(prompt, promptw, C_Reverse);

	drawtext(text, (matches?inputw:mw-promptw), C_Normal);

	if(matches) {
		rw=mw-(promptw+inputw);
		if(curr->left)
			drawtext(L"◀", 5, C_Normal);
		for(item = curr; item != next; item = item->right) {
			drawtext(item->text, MIN(textw(item->text), rw), (item == sel) ? C_Reverse : C_Normal);
			if((rw-= textw(item->text)) <= 0) break;
		}
		if(next) {
			fprintf(stderr, "\033[%iG", mw-5);
			drawtext(L"▶", 5, C_Normal);
		}

	}
	fprintf(stderr, "\033[%iG", (int)(promptw+cursor+3));
	/* fprintf(stderr, "\n"); */
}

wchar_t*
fstrstr(const wchar_t *s, const wchar_t *sub) {
	size_t len;

	for(len = wcslen(sub); *s; s++)
		if(!fstrncmp(s, sub, len))
			return (wchar_t *)s;
	return NULL;
}

void
insert(const wchar_t *str, ssize_t n) {
	if(wcslen(text) + n > sizeof text - 1)
		return;
	wmemmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
	if(n > 0)
		wmemcpy(&text[cursor], str, n);
	cursor += n;
	match(n > 0 && text[cursor] == L'\0');
}

void
match(bool sub) {
	size_t len = wcslen(text);
	Item *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
	Item *item, *lnext;

	lexact = lprefix = lsubstr = exactend = prefixend = substrend = NULL;
	for(item = sub ? matches : items; item && item->text; item = lnext) {
		lnext = sub ? item->right : item + 1;
		if(!fstrncmp(text, item->text, len + 1))
			appenditem(item, &lexact, &exactend);
		else if(!fstrncmp(text, item->text, len))
			appenditem(item, &lprefix, &prefixend);
		else if(fstrstr(item->text, text))
			appenditem(item, &lsubstr, &substrend);
	}
	matches = lexact;
	matchend = exactend;

	if(lprefix) {
		if(matchend) {
			matchend->right = lprefix;
			lprefix->left = matchend;
		}
		else
			matches = lprefix;
		matchend = prefixend;
	}
	if(lsubstr) {
		if(matchend) {
			matchend->right = lsubstr;
			lsubstr->left = matchend;
		}
		else
			matches = lsubstr;
		matchend = substrend;
	}
	curr = sel = matches;
	calcoffsets();
}

size_t
nextrune(int inc) {
	ssize_t n;

	for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
	return n;
}

void
readstdin() {
	wchar_t buf[sizeof text], *p, *maxstr = NULL;
	size_t i, max = 0, size = 0;

	for(i = 0; fgetws(buf, sizeof buf, stdin); i++) {
		if(i+1 >= size / sizeof *items)
			if(!(items = realloc(items, (size += BUFSIZ))))
				die("Can't realloc.");
		if((p = wmemchr(buf, L'\n', sizeof buf)))
			*p = '\0';
		if(!(items[i].text = wcsdup(buf)))
			die("Can't wcsdup.");
		if(wcslen(items[i].text) > max)
			max = wcslen(maxstr = items[i].text);
	}
	if(items)
		items[i].text = NULL;
	inputw = textw(maxstr);
}

void
run(void) {
	wchar_t buf[32];
	wchar_t c;
	FILE *f;
	int n;

	while(1) {
		read(0, &c, 1);
		wmemset(buf, L'\0', sizeof buf);
		buf[0]=c;
		switch_top:
		switch(c) {
		case CONTROL('['):
			read(0, &c, 1);
			esc_switch_top:
			switch(c) {
				case CONTROL('['): /* ESC, need to press twice due to console limitations */
					c=CONTROL('C');
					goto switch_top;
				case '[':
					read(0, &c, 1);
					switch(c) {
						case '1': /* Home */
							read(0, &c, 1); /* Remove trailing '~' from stdin */
							c=CONTROL('A');
							goto switch_top;
						case '2': /* Insert */
							read(0, &c, 1); /* Remove trailing '~' from stdin */
							c=CONTROL('Y');
							goto switch_top;
						case '3': /* Delete */
							read(0, &c, 1); /* Remove trailing '~' from stdin */
							c=CONTROL('D');
							goto switch_top;
						case '4': /* End */
							read(0, &c, 1); /* Remove trailing '~' from stdin */
							c=CONTROL('E');
							goto switch_top;
						case '5': /* PageUp */
							read(0, &c, 1); /* Remove trailing '~' from stdin */
							c=CONTROL('V');
							goto switch_top;
						case '6': /* PageDown */
							read(0, &c, 1); /* Remove trailing '~' from stdin */
							c='v';
							goto esc_switch_top;
						case 'A': /* Up arrow */
							c=CONTROL('P');
							goto switch_top;
						case 'B': /* Down arrow */
							c=CONTROL('N');
							goto switch_top;
						case 'C': /* Right arrow */
							c=CONTROL('F');
							goto switch_top;
						case 'D': /* Left arrow */
							c=CONTROL('B');
							goto switch_top;
					}
					break;
				case 'b':
					while(cursor > 0 && text[nextrune(-1)] == ' ')
						cursor = nextrune(-1);
					while(cursor > 0 && text[nextrune(-1)] != ' ')
						cursor = nextrune(-1);
					break;
				case 'f':
					while(text[cursor] != '\0' && text[nextrune(+1)] == ' ')
						cursor = nextrune(+1);
					if(text[cursor] != '\0') do
						cursor = nextrune(+1);
					while(text[cursor] != '\0' && text[cursor] != ' ');
					break;
				case 'd':
					while(text[cursor] != '\0' && text[nextrune(+1)] == ' ') {
						cursor = nextrune(+1);
						insert(NULL, nextrune(-1) - cursor);
					}
					if(text[cursor] != '\0') do {
						cursor = nextrune(+1);
						insert(NULL, nextrune(-1) - cursor);
					} while(text[cursor] != '\0' && text[cursor] != ' ');
					break;
				case 'v':
					if(!next)
						break;
					sel=curr=next;
					calcoffsets();
					break;
				default:
					break;
			}
			break;
		case CONTROL('G'):
		case CONTROL('C'):
			puts("");
		case CONTROL('M'): /* Return */
		case CONTROL('J'):
			fputws(sel ? sel->text : text, stdout);
		case CONTROL(']'):
		case CONTROL('\\'): /* These are usually close enough to RET to replace Shift+RET, again due to console limitations */
			fputws(text, stdout);
		case CONTROL('A'):
			if(sel == matches) {
				cursor=0;
				break;
			}
			sel=curr=matches;
			calcoffsets();
			break;
		case CONTROL('E'):
			if(text[cursor] != '\0') {
				cursor = wcslen(text);
				break;
			}
			if(next) {
				curr = matchend;
				calcoffsets();
				curr = prev;
				calcoffsets();
				while(next && (curr = curr->right))
					calcoffsets();
			}
			sel = matchend;
			break;
		case CONTROL('B'):
			if(cursor > 0 && (!sel || !sel->left)) {
				cursor = nextrune(-1);
				break;
			}
			/* fallthrough */
		case CONTROL('P'):
			if(sel && sel->left && (sel = sel->left)->right == curr) {
				curr = prev;
				calcoffsets();
			}
			break;
		case CONTROL('F'):
			if(text[cursor] != '\0') {
				cursor = nextrune(+1);
				break;
			}
			/* fallthrough */
		case CONTROL('N'):
			if(sel && sel->right && (sel = sel->right) == next) {
				curr = next;
				calcoffsets();
			}
			break;
		case CONTROL('D'):
			if(text[cursor] == '\0')
				break;
			cursor = nextrune(+1);
			/* fallthrough */
		case CONTROL('H'):
		case CONTROL('?'): /* Backspace */
			if(cursor == 0)
				break;
			insert(NULL, nextrune(-1) - cursor);
			break;
		case CONTROL('I'): /* TAB */
			if(!sel)
				break;
			wcsncpy(text, sel->text, sizeof text);
			cursor = wcslen(text);
			match(true);
			break;
		case CONTROL('K'):
			text[cursor] = '\0';
			match(false);
			break;
		case CONTROL('U'):
			insert(NULL, 0 - cursor);
			break;
		case CONTROL('W'):
			while(cursor > 0 && text[nextrune(-1)] == ' ')
				insert(NULL, nextrune(-1) - cursor);
			while(cursor > 0 && text[nextrune(-1)] != ' ')
				insert(NULL, nextrune(-1) - cursor);
			break;
		case CONTROL('V'):
			if(!prev)
				break;
			sel = curr = prev;
			calcoffsets();
			break;
		case CONTROL('Y'):
			if((f=popen(XSEL, "r")) != NULL) {
				while((n= fread(&buf, 1, sizeof buf, f)) > 0) insert(buf, n);
				pclose(f);
			}
		default:
			if(!iscntrl(*buf))
				insert(buf, wcslen(buf));
			break;
		}
		drawmenu();
	}
}

void
setup(int position) {
	int fd, result=-1;
	struct winsize ws;


	/* re-open stdin to read keyboard */
	if(freopen("/dev/tty", "r", stdin) == NULL) die("Can't reopen tty.");

	/* ioctl() the tty to get size */
	fd = open("/dev/tty", O_RDWR);
	if(fd == -1)
		mw=80;
	else {
		result = ioctl(fd, TIOCGWINSZ, &ws);
		close(fd);
		if(result<0) mw=80;
		mw=ws.ws_col;
	}

	/* change terminal attributes, save old */
	tcgetattr(0, &tio_old);
	wmemcpy ((wchar_t *)&tio_new, (wchar_t *)&tio_old, sizeof(struct termios));
	tio_new.c_iflag &= ~(BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
	tio_new.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
	tio_new.c_cflag &= ~(CSIZE|PARENB);
	tio_new.c_cflag |= CS8;
	tio_new.c_cc[VMIN]=1;
	tcsetattr(0, TCSANOW, &tio_new);

	promptw=(prompt?textw(prompt):0);
	inputw=MIN(inputw, mw/3);
	match(false);
	if(position!=0) fprintf(stderr, "\033[%iH", (position>0 || result<0)?0:ws.ws_row);
	drawmenu();
}

size_t
textw(const wchar_t *s) {
	return (s?wcslen(s):0)+4;
}

int
main(int argc, char **argv) {
	int i;
	int position=0;

	for(i=0; i<argc; i++)
		if(!strcmp(argv[i], "-v")) {
			puts("slmenu, © 2011 slmenu engineers, see LICENSE for details");
			exit(EXIT_SUCCESS);
		}
		else if(!strcmp(argv[i], "-p"))
			mbstowcs(prompt, argv[++i], sizeof argv[i]);
		else if(!strcmp(argv[i], "-i"))
			fstrncmp = wcsncasecmp;
		else if(!strcmp(argv[i], "-t"))
			position=1;
		else if(!strcmp(argv[i], "-b"))
			position=-1;

	readstdin();
	setup(position);
	run();
	cleanup();
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.