Browse code

Use macros to represent control keys

Prefers "magic letters" to magic numbers. It's easier to think of all
control codes as their shifted versions of letters A-Z in the ascii
table.

John Hawthorn authored on 10/04/2016 05:10:09
Showing 1 changed files

  • fzy.c index 273e9c8..af45c3b 100644
... ...
@@ -119,6 +119,10 @@ static void emit(choices_t *choices) {
119 119
 	exit(EXIT_SUCCESS);
120 120
 }
121 121
 
122
+#define KEY_CTRL(key) ((key) - ('@'))
123
+#define KEY_DEL 127
124
+#define KEY_ESC 27
125
+
122 126
 static void run(tty_t *tty, choices_t *choices) {
123 127
 	choices_search(choices, search);
124 128
 	char ch;
... ...
@@ -131,40 +135,40 @@ static void run(tty_t *tty, choices_t *choices) {
131 135
 				search[search_size] = '\0';
132 136
 				choices_search(choices, search);
133 137
 			}
134
-		} else if (ch == 127 || ch == 8) { /* DEL || backspace */
138
+		} else if (ch == KEY_DEL || ch == KEY_CTRL('H')) { /* DEL || Backspace (C-H) */
135 139
 			if (search_size)
136 140
 				search[--search_size] = '\0';
137 141
 			choices_search(choices, search);
138
-		} else if (ch == 21) { /* C-U */
142
+		} else if (ch == KEY_CTRL('U')) { /* C-U */
139 143
 			search_size = 0;
140 144
 			search[0] = '\0';
141 145
 			choices_search(choices, search);
142
-		} else if (ch == 23) { /* C-W */
146
+		} else if (ch == KEY_CTRL('W')) { /* C-W */
143 147
 			if (search_size)
144 148
 				search[--search_size] = '\0';
145 149
 			while (search_size && !isspace(search[--search_size]))
146 150
 				search[search_size] = '\0';
147 151
 			choices_search(choices, search);
148
-		} else if (ch == 14) { /* C-N */
152
+		} else if (ch == KEY_CTRL('N')) { /* C-N */
149 153
 			choices_next(choices);
150
-		} else if (ch == 16) { /* C-P */
154
+		} else if (ch == KEY_CTRL('P')) { /* C-P */
151 155
 			choices_prev(choices);
152
-		} else if (ch == 9) { /* TAB */
156
+		} else if (ch == KEY_CTRL('I')) { /* TAB (C-I) */
153 157
 			strncpy(search, choices_get(choices, choices->selection), SEARCH_SIZE_MAX);
154 158
 			search_size = strlen(search);
155 159
 			choices_search(choices, search);
156
-		} else if (ch == 3 || ch == 4) { /* ^C || ^D */
160
+		} else if (ch == KEY_CTRL('C') || ch == KEY_CTRL('D')) { /* ^C || ^D */
157 161
 			clear(tty);
158 162
 			tty_close(tty);
159 163
 			exit(EXIT_FAILURE);
160
-		} else if (ch == 13) { /* CR */
164
+		} else if (ch == KEY_CTRL('M')) { /* CR */
161 165
 			clear(tty);
162 166
 
163 167
 			/* ttyout should be flushed before outputting on stdout */
164 168
 			tty_close(tty);
165 169
 
166 170
 			emit(choices);
167
-		} else if (ch == 27) { /* ESC */
171
+		} else if (ch == KEY_ESC) { /* ESC */
168 172
 			ch = tty_getchar(tty);
169 173
 			if (ch == '[' || ch == 'O') {
170 174
 				ch = tty_getchar(tty);