add key bindings for moving to the word start or end
[dmenu.git] / dmenu.c
blob5e9c36735152d883d00df4cc21eaad5b3172ce40
1 /* See LICENSE file for copyright and license details. */
2 #include <ctype.h>
3 #include <locale.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <strings.h>
8 #include <time.h>
10 #include <X11/Xlib.h>
11 #include <X11/Xatom.h>
12 #include <X11/Xutil.h>
13 #ifdef XINERAMA
14 #include <X11/extensions/Xinerama.h>
15 #endif
16 #include <X11/Xft/Xft.h>
18 #include "drw.h"
19 #include "util.h"
21 /* macros */
22 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
23 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
24 #define LENGTH(X) (sizeof X / sizeof X[0])
25 #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
27 /* enums */
28 enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
30 struct item {
31 char *text;
32 struct item *left, *right;
33 int out;
36 static char text[BUFSIZ] = "";
37 static char *embed;
38 static int bh, mw, mh;
39 static int inputw = 0, promptw;
40 static int lrpad; /* sum of left and right padding */
41 static size_t cursor;
42 static struct item *items = NULL;
43 static struct item *matches, *matchend;
44 static struct item *prev, *curr, *next, *sel;
45 static int mon = -1, screen;
47 static Atom clip, utf8;
48 static Display *dpy;
49 static Window root, parentwin, win;
50 static XIC xic;
52 static Drw *drw;
53 static Clr *scheme[SchemeLast];
55 #include "config.h"
57 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
58 static char *(*fstrstr)(const char *, const char *) = strstr;
60 static void
61 appenditem(struct item *item, struct item **list, struct item **last)
63 if (*last)
64 (*last)->right = item;
65 else
66 *list = item;
68 item->left = *last;
69 item->right = NULL;
70 *last = item;
73 static void
74 calcoffsets(void)
76 int i, n;
78 if (lines > 0)
79 n = lines * bh;
80 else
81 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
82 /* calculate which items will begin the next page and previous page */
83 for (i = 0, next = curr; next; next = next->right)
84 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
85 break;
86 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
87 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
88 break;
91 static void
92 cleanup(void)
94 size_t i;
96 XUngrabKey(dpy, AnyKey, AnyModifier, root);
97 for (i = 0; i < SchemeLast; i++)
98 free(scheme[i]);
99 drw_free(drw);
100 XSync(dpy, False);
101 XCloseDisplay(dpy);
104 static char *
105 cistrstr(const char *s, const char *sub)
107 size_t len;
109 for (len = strlen(sub); *s; s++)
110 if (!strncasecmp(s, sub, len))
111 return (char *)s;
112 return NULL;
115 static int
116 drawitem(struct item *item, int x, int y, int w)
118 if (item == sel)
119 drw_setscheme(drw, scheme[SchemeSel]);
120 else if (item->out)
121 drw_setscheme(drw, scheme[SchemeOut]);
122 else
123 drw_setscheme(drw, scheme[SchemeNorm]);
125 return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
128 static void
129 drawmenu(void)
131 unsigned int curpos;
132 struct item *item;
133 int x = 0, y = 0, w;
135 drw_setscheme(drw, scheme[SchemeNorm]);
136 drw_rect(drw, 0, 0, mw, mh, 1, 1);
138 if (prompt && *prompt) {
139 drw_setscheme(drw, scheme[SchemeSel]);
140 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
142 /* draw input field */
143 w = (lines > 0 || !matches) ? mw - x : inputw;
144 drw_setscheme(drw, scheme[SchemeNorm]);
145 drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
147 drw_font_getexts(drw->fonts, text, cursor, &curpos, NULL);
148 if ((curpos += lrpad / 2 - 1) < w) {
149 drw_setscheme(drw, scheme[SchemeNorm]);
150 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
153 if (lines > 0) {
154 /* draw vertical list */
155 for (item = curr; item != next; item = item->right)
156 drawitem(item, x, y += bh, mw - x);
157 } else if (matches) {
158 /* draw horizontal list */
159 x += inputw;
160 w = TEXTW("<");
161 if (curr->left) {
162 drw_setscheme(drw, scheme[SchemeNorm]);
163 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
165 x += w;
166 for (item = curr; item != next; item = item->right)
167 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
168 if (next) {
169 w = TEXTW(">");
170 drw_setscheme(drw, scheme[SchemeNorm]);
171 drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
174 drw_map(drw, win, 0, 0, mw, mh);
177 static void
178 grabfocus(void)
180 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
181 Window focuswin;
182 int i, revertwin;
184 for (i = 0; i < 100; ++i) {
185 XGetInputFocus(dpy, &focuswin, &revertwin);
186 if (focuswin == win)
187 return;
188 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
189 nanosleep(&ts, NULL);
191 die("cannot grab focus");
194 static void
195 grabkeyboard(void)
197 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
198 int i;
200 if (embed)
201 return;
202 /* try to grab keyboard, we may have to wait for another process to ungrab */
203 for (i = 0; i < 1000; i++) {
204 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
205 GrabModeAsync, CurrentTime) == GrabSuccess)
206 return;
207 nanosleep(&ts, NULL);
209 die("cannot grab keyboard");
212 static void
213 match(void)
215 static char **tokv = NULL;
216 static int tokn = 0;
218 char buf[sizeof text], *s;
219 int i, tokc = 0;
220 size_t len, textsize;
221 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
223 strcpy(buf, text);
224 /* separate input text into tokens to be matched individually */
225 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
226 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
227 die("cannot realloc %u bytes:", tokn * sizeof *tokv);
228 len = tokc ? strlen(tokv[0]) : 0;
230 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
231 textsize = strlen(text) + 1;
232 for (item = items; item && item->text; item++) {
233 for (i = 0; i < tokc; i++)
234 if (!fstrstr(item->text, tokv[i]))
235 break;
236 if (i != tokc) /* not all tokens match */
237 continue;
238 /* exact matches go first, then prefixes, then substrings */
239 if (!tokc || !fstrncmp(text, item->text, textsize))
240 appenditem(item, &matches, &matchend);
241 else if (!fstrncmp(tokv[0], item->text, len))
242 appenditem(item, &lprefix, &prefixend);
243 else
244 appenditem(item, &lsubstr, &substrend);
246 if (lprefix) {
247 if (matches) {
248 matchend->right = lprefix;
249 lprefix->left = matchend;
250 } else
251 matches = lprefix;
252 matchend = prefixend;
254 if (lsubstr) {
255 if (matches) {
256 matchend->right = lsubstr;
257 lsubstr->left = matchend;
258 } else
259 matches = lsubstr;
260 matchend = substrend;
262 curr = sel = matches;
263 calcoffsets();
266 static void
267 insert(const char *str, ssize_t n)
269 if (strlen(text) + n > sizeof text - 1)
270 return;
271 /* move existing text out of the way, insert new text, and update cursor */
272 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
273 if (n > 0)
274 memcpy(&text[cursor], str, n);
275 cursor += n;
276 match();
279 static size_t
280 nextrune(int inc)
282 ssize_t n;
284 /* return location of next utf8 rune in the given direction (+1 or -1) */
285 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
287 return n;
290 static void
291 movewordedge(int dir)
293 if (dir < 0) { /* move cursor to the start of the word*/
294 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
295 cursor = nextrune(-1);
296 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
297 cursor = nextrune(-1);
298 } else { /* move cursor to the end of the word */
299 while (text[cursor] && strchr(worddelimiters, text[cursor]))
300 cursor = nextrune(+1);
301 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
302 cursor = nextrune(+1);
306 static void
307 keypress(XKeyEvent *ev)
309 char buf[32];
310 int len;
311 KeySym ksym = NoSymbol;
312 Status status;
314 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
315 if (status == XBufferOverflow)
316 return;
317 if (ev->state & ControlMask)
318 switch(ksym) {
319 case XK_a: ksym = XK_Home; break;
320 case XK_b: ksym = XK_Left; break;
321 case XK_c: ksym = XK_Escape; break;
322 case XK_d: ksym = XK_Delete; break;
323 case XK_e: ksym = XK_End; break;
324 case XK_f: ksym = XK_Right; break;
325 case XK_g: ksym = XK_Escape; break;
326 case XK_h: ksym = XK_BackSpace; break;
327 case XK_i: ksym = XK_Tab; break;
328 case XK_j: /* fallthrough */
329 case XK_J: /* fallthrough */
330 case XK_m: /* fallthrough */
331 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
332 case XK_n: ksym = XK_Down; break;
333 case XK_p: ksym = XK_Up; break;
335 case XK_k: /* delete right */
336 text[cursor] = '\0';
337 match();
338 break;
339 case XK_u: /* delete left */
340 insert(NULL, 0 - cursor);
341 break;
342 case XK_w: /* delete word */
343 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
344 insert(NULL, nextrune(-1) - cursor);
345 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
346 insert(NULL, nextrune(-1) - cursor);
347 break;
348 case XK_y: /* paste selection */
349 case XK_Y:
350 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
351 utf8, utf8, win, CurrentTime);
352 return;
353 case XK_Left:
354 movewordedge(-1);
355 ksym = NoSymbol;
356 break;
357 case XK_Right:
358 movewordedge(+1);
359 ksym = NoSymbol;
360 break;
361 case XK_Return:
362 case XK_KP_Enter:
363 break;
364 case XK_bracketleft:
365 cleanup();
366 exit(1);
367 default:
368 return;
370 else if (ev->state & Mod1Mask)
371 switch(ksym) {
372 case XK_b:
373 movewordedge(-1);
374 ksym = NoSymbol;
375 break;
376 case XK_f:
377 movewordedge(+1);
378 ksym = NoSymbol;
379 break;
380 case XK_g: ksym = XK_Home; break;
381 case XK_G: ksym = XK_End; break;
382 case XK_h: ksym = XK_Up; break;
383 case XK_j: ksym = XK_Next; break;
384 case XK_k: ksym = XK_Prior; break;
385 case XK_l: ksym = XK_Down; break;
386 default:
387 return;
389 switch(ksym) {
390 default:
391 if (!iscntrl(*buf))
392 insert(buf, len);
393 break;
394 case NoSymbol:
395 break;
396 case XK_Delete:
397 if (text[cursor] == '\0')
398 return;
399 cursor = nextrune(+1);
400 /* fallthrough */
401 case XK_BackSpace:
402 if (cursor == 0)
403 return;
404 insert(NULL, nextrune(-1) - cursor);
405 break;
406 case XK_End:
407 if (text[cursor] != '\0') {
408 cursor = strlen(text);
409 break;
411 if (next) {
412 /* jump to end of list and position items in reverse */
413 curr = matchend;
414 calcoffsets();
415 curr = prev;
416 calcoffsets();
417 while (next && (curr = curr->right))
418 calcoffsets();
420 sel = matchend;
421 break;
422 case XK_Escape:
423 cleanup();
424 exit(1);
425 case XK_Home:
426 if (sel == matches) {
427 cursor = 0;
428 break;
430 sel = curr = matches;
431 calcoffsets();
432 break;
433 case XK_Left:
434 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
435 cursor = nextrune(-1);
436 break;
438 if (lines > 0)
439 return;
440 /* fallthrough */
441 case XK_Up:
442 if (sel && sel->left && (sel = sel->left)->right == curr) {
443 curr = prev;
444 calcoffsets();
446 break;
447 case XK_Next:
448 if (!next)
449 return;
450 sel = curr = next;
451 calcoffsets();
452 break;
453 case XK_Prior:
454 if (!prev)
455 return;
456 sel = curr = prev;
457 calcoffsets();
458 break;
459 case XK_Return:
460 case XK_KP_Enter:
461 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
462 if (!(ev->state & ControlMask)) {
463 cleanup();
464 exit(0);
466 if (sel)
467 sel->out = 1;
468 break;
469 case XK_Right:
470 if (text[cursor] != '\0') {
471 cursor = nextrune(+1);
472 break;
474 if (lines > 0)
475 return;
476 /* fallthrough */
477 case XK_Down:
478 if (sel && sel->right && (sel = sel->right) == next) {
479 curr = next;
480 calcoffsets();
482 break;
483 case XK_Tab:
484 if (!sel)
485 return;
486 strncpy(text, sel->text, sizeof text - 1);
487 text[sizeof text - 1] = '\0';
488 cursor = strlen(text);
489 match();
490 break;
492 drawmenu();
495 static void
496 paste(void)
498 char *p, *q;
499 int di;
500 unsigned long dl;
501 Atom da;
503 /* we have been given the current selection, now insert it into input */
504 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
505 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
506 == Success && p) {
507 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
508 XFree(p);
510 drawmenu();
513 static void
514 readstdin(void)
516 char buf[sizeof text], *p;
517 size_t i, imax = 0, size = 0;
518 unsigned int tmpmax = 0;
520 /* read each line from stdin and add it to the item list */
521 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
522 if (i + 1 >= size / sizeof *items)
523 if (!(items = realloc(items, (size += BUFSIZ))))
524 die("cannot realloc %u bytes:", size);
525 if ((p = strchr(buf, '\n')))
526 *p = '\0';
527 if (!(items[i].text = strdup(buf)))
528 die("cannot strdup %u bytes:", strlen(buf) + 1);
529 items[i].out = 0;
530 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
531 if (tmpmax > inputw) {
532 inputw = tmpmax;
533 imax = i;
536 if (items)
537 items[i].text = NULL;
538 inputw = items ? TEXTW(items[imax].text) : 0;
539 lines = MIN(lines, i);
542 static void
543 run(void)
545 XEvent ev;
547 while (!XNextEvent(dpy, &ev)) {
548 if (XFilterEvent(&ev, win))
549 continue;
550 switch(ev.type) {
551 case Expose:
552 if (ev.xexpose.count == 0)
553 drw_map(drw, win, 0, 0, mw, mh);
554 break;
555 case FocusIn:
556 /* regrab focus from parent window */
557 if (ev.xfocus.window != win)
558 grabfocus();
559 break;
560 case KeyPress:
561 keypress(&ev.xkey);
562 break;
563 case SelectionNotify:
564 if (ev.xselection.property == utf8)
565 paste();
566 break;
567 case VisibilityNotify:
568 if (ev.xvisibility.state != VisibilityUnobscured)
569 XRaiseWindow(dpy, win);
570 break;
575 static void
576 setup(void)
578 int x, y, i, j;
579 unsigned int du;
580 XSetWindowAttributes swa;
581 XIM xim;
582 Window w, dw, *dws;
583 XWindowAttributes wa;
584 XClassHint ch = {"dmenu", "dmenu"};
585 #ifdef XINERAMA
586 XineramaScreenInfo *info;
587 Window pw;
588 int a, di, n, area = 0;
589 #endif
590 /* init appearance */
591 for (j = 0; j < SchemeLast; j++)
592 scheme[j] = drw_scm_create(drw, colors[j], 2);
594 clip = XInternAtom(dpy, "CLIPBOARD", False);
595 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
597 /* calculate menu geometry */
598 bh = drw->fonts->h + 2;
599 lines = MAX(lines, 0);
600 mh = (lines + 1) * bh;
601 #ifdef XINERAMA
602 i = 0;
603 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
604 XGetInputFocus(dpy, &w, &di);
605 if (mon >= 0 && mon < n)
606 i = mon;
607 else if (w != root && w != PointerRoot && w != None) {
608 /* find top-level window containing current input focus */
609 do {
610 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
611 XFree(dws);
612 } while (w != root && w != pw);
613 /* find xinerama screen with which the window intersects most */
614 if (XGetWindowAttributes(dpy, pw, &wa))
615 for (j = 0; j < n; j++)
616 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
617 area = a;
618 i = j;
621 /* no focused window is on screen, so use pointer location instead */
622 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
623 for (i = 0; i < n; i++)
624 if (INTERSECT(x, y, 1, 1, info[i]))
625 break;
627 x = info[i].x_org;
628 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
629 mw = info[i].width;
630 XFree(info);
631 } else
632 #endif
634 if (!XGetWindowAttributes(dpy, parentwin, &wa))
635 die("could not get embedding window attributes: 0x%lx",
636 parentwin);
637 x = 0;
638 y = topbar ? 0 : wa.height - mh;
639 mw = wa.width;
641 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
642 inputw = MIN(inputw, mw/3);
643 match();
645 /* create menu window */
646 swa.override_redirect = True;
647 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
648 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
649 win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
650 CopyFromParent, CopyFromParent, CopyFromParent,
651 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
652 XSetClassHint(dpy, win, &ch);
654 /* open input methods */
655 xim = XOpenIM(dpy, NULL, NULL, NULL);
656 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
657 XNClientWindow, win, XNFocusWindow, win, NULL);
659 XMapRaised(dpy, win);
660 if (embed) {
661 XSelectInput(dpy, parentwin, FocusChangeMask);
662 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
663 for (i = 0; i < du && dws[i] != win; ++i)
664 XSelectInput(dpy, dws[i], FocusChangeMask);
665 XFree(dws);
667 grabfocus();
669 drw_resize(drw, mw, mh);
670 drawmenu();
673 static void
674 usage(void)
676 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
677 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
678 exit(1);
682 main(int argc, char *argv[])
684 XWindowAttributes wa;
685 int i, fast = 0;
687 for (i = 1; i < argc; i++)
688 /* these options take no arguments */
689 if (!strcmp(argv[i], "-v")) { /* prints version information */
690 puts("dmenu-"VERSION);
691 exit(0);
692 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
693 topbar = 0;
694 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
695 fast = 1;
696 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
697 fstrncmp = strncasecmp;
698 fstrstr = cistrstr;
699 } else if (i + 1 == argc)
700 usage();
701 /* these options take one argument */
702 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
703 lines = atoi(argv[++i]);
704 else if (!strcmp(argv[i], "-m"))
705 mon = atoi(argv[++i]);
706 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
707 prompt = argv[++i];
708 else if (!strcmp(argv[i], "-fn")) /* font or font set */
709 fonts[0] = argv[++i];
710 else if (!strcmp(argv[i], "-nb")) /* normal background color */
711 colors[SchemeNorm][ColBg] = argv[++i];
712 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
713 colors[SchemeNorm][ColFg] = argv[++i];
714 else if (!strcmp(argv[i], "-sb")) /* selected background color */
715 colors[SchemeSel][ColBg] = argv[++i];
716 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
717 colors[SchemeSel][ColFg] = argv[++i];
718 else if (!strcmp(argv[i], "-w")) /* embedding window id */
719 embed = argv[++i];
720 else
721 usage();
723 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
724 fputs("warning: no locale support\n", stderr);
725 if (!(dpy = XOpenDisplay(NULL)))
726 die("cannot open display");
727 screen = DefaultScreen(dpy);
728 root = RootWindow(dpy, screen);
729 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
730 parentwin = root;
731 if (!XGetWindowAttributes(dpy, parentwin, &wa))
732 die("could not get embedding window attributes: 0x%lx",
733 parentwin);
734 drw = drw_create(dpy, screen, root, wa.width, wa.height);
735 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
736 die("no fonts could be loaded.");
737 lrpad = drw->fonts->h;
739 if (fast) {
740 grabkeyboard();
741 readstdin();
742 } else {
743 readstdin();
744 grabkeyboard();
746 setup();
747 run();
749 return 1; /* unreachable */