This patch facilitates writing wrappers to dmenu,because to understand what has been selected by comparing strings is slower than using the index of an array. Furthermore avoids ambiguity in the case that there were two elements with the same name in the input elements.
diff --git a/dmenu.1 b/dmenu.1
index 9eab758..8365e8b 100644
--- a/dmenu.1
+++ b/dmenu.1
@@ -3,7 +3,7 @@
 dmenu \- dynamic menu
 .SH SYNOPSIS
 .B dmenu
-.RB [ \-bfiv ]
+.RB [ \-bfivn ]
 .RB [ \-l
 .IR lines ]
 .RB [ \-m
@@ -47,6 +47,9 @@ X until stdin reaches end\-of\-file.
 .B \-i
 dmenu matches menu items case insensitively.
 .TP
+.B \-n
+output the element's position in the list instead of his name.
+.TP
 .BI \-l " lines"
 dmenu lists items vertically, with the given number of lines.
 .TP
diff --git a/dmenu.c b/dmenu.c
index d605ab4..b9e82de 100644
--- a/dmenu.c
+++ b/dmenu.c
@@ -43,6 +43,7 @@ static struct item *items = NULL;
 static struct item *matches, *matchend;
 static struct item *prev, *curr, *next, *sel;
 static int mon = -1, screen;
+static int numeric_output;
 
 static Atom clip, utf8;
 static Display *dpy;
@@ -57,6 +58,16 @@ static Clr *scheme[SchemeLast];
 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
 static char *(*fstrstr)(const char *, const char *) = strstr;
 
+
+static unsigned
+itemindex(struct item *it)
+{
+	unsigned i = 0;
+	for(; (it = it->left) != NULL; i++);
+	return i;
+}
+
+
 static void
 appenditem(struct item *item, struct item **list, struct item **last)
 {
@@ -424,7 +435,10 @@ keypress(XKeyEvent *ev)
 		break;
 	case XK_Return:
 	case XK_KP_Enter:
-		puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
+		if ((sel && !(ev->state & ShiftMask)))
+			if(numeric_output) printf("%u\n", itemindex(sel));
+			else puts(sel->text);
+		else puts(text);
 		if (!(ev->state & ControlMask)) {
 			cleanup();
 			exit(0);
@@ -636,7 +650,7 @@ setup(void)
 static void
 usage(void)
 {
-	fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
+	fputs("usage: dmenu [-bfivn] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
 	      "             [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
 	exit(1);
 }
@@ -659,7 +673,10 @@ main(int argc, char *argv[])
 		else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
 			fstrncmp = strncasecmp;
 			fstrstr = cistrstr;
-		} else if (i + 1 == argc)
+		} else if (!strcmp(argv[i], "-n")) /* output the element's position in
+			the list instead of his name */
+			numeric_output = 1;
+		else if (i + 1 == argc)
 			usage();
 		/* these options take one argument */
 		else if (!strcmp(argv[i], "-l"))   /* number of lines in vertical list */

Reply via email to