winio.c 96.3 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
/* $Id$ */
Chris Allegretta's avatar
Chris Allegretta committed
2
3
4
/**************************************************************************
 *   winio.c                                                              *
 *                                                                        *
5
 *   Copyright (C) 1999-2004 Chris Allegretta                             *
6
 *   Copyright (C) 2005-2006 David Lawrence Ramsey                        *
Chris Allegretta's avatar
Chris Allegretta committed
7
8
 *   This program is free software; you can redistribute it and/or modify *
 *   it under the terms of the GNU General Public License as published by *
9
 *   the Free Software Foundation; either version 2, or (at your option)  *
Chris Allegretta's avatar
Chris Allegretta committed
10
11
 *   any later version.                                                   *
 *                                                                        *
12
13
14
15
 *   This program is distributed in the hope that it will be useful, but  *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    *
 *   General Public License for more details.                             *
Chris Allegretta's avatar
Chris Allegretta committed
16
17
18
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program; if not, write to the Free Software          *
19
20
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA            *
 *   02110-1301, USA.                                                     *
Chris Allegretta's avatar
Chris Allegretta committed
21
22
23
 *                                                                        *
 **************************************************************************/

24
#include "proto.h"
25

26
#include <stdio.h>
Chris Allegretta's avatar
Chris Allegretta committed
27
28
#include <stdarg.h>
#include <string.h>
29
#include <unistd.h>
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
30
#include <ctype.h>
Chris Allegretta's avatar
Chris Allegretta committed
31

32
static int *key_buffer = NULL;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
33
34
	/* The keystroke buffer, containing all the keystrokes we have
	 * at a given point. */
35
static size_t key_buffer_len = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
36
	/* The length of the keystroke buffer. */
37
static int statusblank = 0;
38
39
	/* The number of keystrokes left after we call statusbar(),
	 * before we actually blank the statusbar. */
40
static bool disable_cursorpos = FALSE;
41
42
	/* Should we temporarily disable constant cursor position
	 * display? */
43

44
45
46
47
48
49
50
51
52
53
54
55
/* Control character compatibility:
 *
 * - NANO_BACKSPACE_KEY is Ctrl-H, which is Backspace under ASCII, ANSI,
 *   VT100, and VT220.
 * - NANO_TAB_KEY is Ctrl-I, which is Tab under ASCII, ANSI, VT100,
 *   VT220, and VT320.
 * - NANO_ENTER_KEY is Ctrl-M, which is Enter under ASCII, ANSI, VT100,
 *   VT220, and VT320.
 * - NANO_XON_KEY is Ctrl-Q, which is XON under ASCII, ANSI, VT100,
 *   VT220, and VT320.
 * - NANO_XOFF_KEY is Ctrl-S, which is XOFF under ASCII, ANSI, VT100,
 *   VT220, and VT320.
56
 * - NANO_CONTROL_8 is Ctrl-8 (Ctrl-?), which is Delete under ASCII,
57
58
 *   ANSI, VT100, and VT220, and which is Backspace under VT320.
 *
59
 * Note: VT220 and VT320 also generate Esc [ 3 ~ for Delete.  By
60
61
 * default, xterm assumes it's running on a VT320 and generates Ctrl-8
 * (Ctrl-?) for Backspace and Esc [ 3 ~ for Delete.  This causes
62
 * problems for VT100-derived terminals such as the FreeBSD console,
63
 * which expect Ctrl-H for Backspace and Ctrl-8 (Ctrl-?) for Delete, and
64
65
66
67
68
69
70
71
72
 * on which the VT320 sequences are translated by the keypad to KEY_DC
 * and [nothing].  We work around this conflict via the REBIND_DELETE
 * flag: if it's not set, we assume VT320 compatibility, and if it is,
 * we assume VT100 compatibility.  Thanks to Lee Nelson and Wouter van
 * Hemel for helping work this conflict out.
 *
 * Escape sequence compatibility:
 *
 * We support escape sequences for ANSI, VT100, VT220, VT320, the Linux
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
73
74
75
 * console, the FreeBSD console, the Mach console, xterm, rxvt, and
 * Eterm.  Among these, there are several conflicts and omissions,
 * outlined as follows:
76
77
78
79
80
81
 *
 * - Tab on ANSI == PageUp on FreeBSD console; the former is omitted.
 *   (Ctrl-I is also Tab on ANSI, which we already support.)
 * - PageDown on FreeBSD console == Center (5) on numeric keypad with
 *   NumLock off on Linux console; the latter is omitted.  (The editing
 *   keypad key is more important to have working than the numeric
82
 *   keypad key, because the latter has no value when NumLock is off.)
83
84
85
86
 * - F1 on FreeBSD console == the mouse key on xterm/rxvt/Eterm; the
 *   latter is omitted.  (Mouse input will only work properly if the
 *   extended keypad value KEY_MOUSE is generated on mouse events
 *   instead of the escape sequence.)
87
 * - F9 on FreeBSD console == PageDown on Mach console; the former is
88
89
90
 *   omitted.  (The editing keypad is more important to have working
 *   than the function keys, because the functions of the former are not
 *   arbitrary and the functions of the latter are.)
91
 * - F10 on FreeBSD console == PageUp on Mach console; the former is
92
 *   omitted.  (Same as above.)
93
 * - F13 on FreeBSD console == End on Mach console; the former is
94
 *   omitted.  (Same as above.)
95
96
97
98
99
100
101
 * - F15 on FreeBSD console == Shift-Up on rxvt/Eterm; the former is
 *   omitted.  (The arrow keys, with or without modifiers, are more
 *   important to have working than the function keys, because the
 *   functions of the former are not arbitrary and the functions of the
 *   latter are.)
 * - F16 on FreeBSD console == Shift-Down on rxvt/Eterm; the former is
 *   omitted.  (Same as above.)
102
103
104
 *
 * Note that Center (5) on the numeric keypad with NumLock off can also
 * be the Begin key. */
105

106
/* Read in a sequence of keystrokes from win and save them in the
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
107
108
 * keystroke buffer.  This should only be called when the keystroke
 * buffer is empty. */
109
void get_key_buffer(WINDOW *win)
110
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
111
112
    int input;
    size_t errcount;
113
114
115
116
117
118

    /* If the keystroke buffer isn't empty, get out. */
    if (key_buffer != NULL)
	return;

    /* Read in the first character using blocking input. */
119
#ifndef NANO_TINY
120
121
    allow_pending_sigwinch(TRUE);
#endif
122

123
124
125
126
    /* Just before reading in the first character, display any pending
     * screen updates. */
    doupdate();

127
    errcount = 0;
128
    while ((input = wgetch(win)) == ERR) {
129
130
	errcount++;

131
132
	/* If we've failed to get a character MAX_BUF_SIZE times in a
	 * row, assume that the input source we were using is gone and
133
134
135
	 * die gracefully.  We could check if errno is set to EIO
	 * ("Input/output error") and die gracefully in that case, but
	 * it's not always set properly.  Argh. */
136
	if (errcount == MAX_BUF_SIZE)
137
138
	    handle_hupterm(0);
    }
139

140
#ifndef NANO_TINY
141
142
    allow_pending_sigwinch(FALSE);
#endif
143

144
145
    /* Increment the length of the keystroke buffer, save the value of
     * the keystroke in key, and set key_code to TRUE if the keystroke
146
     * is an extended keypad value or FALSE if it isn't. */
147
    key_buffer_len++;
148
149
    key_buffer = (int *)nmalloc(sizeof(int));
    key_buffer[0] = input;
150

151
152
153
154
    /* Read in the remaining characters using non-blocking input. */
    nodelay(win, TRUE);

    while (TRUE) {
155
#ifndef NANO_TINY
156
	allow_pending_sigwinch(TRUE);
157
#endif
158

159
	input = wgetch(win);
160

161
	/* If there aren't any more characters, stop reading. */
162
	if (input == ERR)
163
164
165
166
	    break;

	/* Otherwise, increment the length of the keystroke buffer, save
	 * the value of the keystroke in key, and set key_code to TRUE
167
168
	 * if the keystroke is an extended keypad value or FALSE if it
	 * isn't. */
169
	key_buffer_len++;
170
171
172
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
	key_buffer[key_buffer_len - 1] = input;
173

174
#ifndef NANO_TINY
175
176
	allow_pending_sigwinch(FALSE);
#endif
177
178
179
180
    }

    /* Switch back to non-blocking input. */
    nodelay(win, FALSE);
181
182

#ifdef DEBUG
183
    fprintf(stderr, "get_key_buffer(): key_buffer_len = %lu\n", (unsigned long)key_buffer_len);
184
#endif
185
}
186

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
187
/* Return the length of the keystroke buffer. */
188
size_t get_key_buffer_len(void)
189
190
191
192
{
    return key_buffer_len;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
193
/* Add the keystrokes in input to the keystroke buffer. */
194
void unget_input(int *input, size_t input_len)
195
{
196
#ifndef NANO_TINY
197
198
    allow_pending_sigwinch(TRUE);
    allow_pending_sigwinch(FALSE);
199
#endif
200

201
    /* If input is empty, get out. */
202
    if (input_len == 0)
203
204
	return;

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
205
206
    /* If adding input would put the keystroke buffer beyond maximum
     * capacity, only add enough of input to put it at maximum
207
     * capacity. */
208
209
    if (key_buffer_len + input_len < key_buffer_len)
	input_len = (size_t)-1 - key_buffer_len;
210

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
211
212
213
    /* Add the length of input to the length of the keystroke buffer,
     * and reallocate the keystroke buffer so that it has enough room
     * for input. */
214
215
216
    key_buffer_len += input_len;
    key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
	sizeof(int));
217

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
218
219
    /* If the keystroke buffer wasn't empty before, move its beginning
     * forward far enough so that we can add input to its beginning. */
220
221
222
    if (key_buffer_len > input_len)
	memmove(key_buffer + input_len, key_buffer,
		(key_buffer_len - input_len) * sizeof(int));
223

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
224
    /* Copy input to the beginning of the keystroke buffer. */
225
    memcpy(key_buffer, input, input_len * sizeof(int));
226
227
}

228
229
230
231
/* Put back the character stored in kbinput, putting it in byte range
 * beforehand.  If meta_key is TRUE, put back the Escape character after
 * putting back kbinput.  If func_key is TRUE, put back the function key
 * (a value outside byte range) without putting it in byte range. */
232
233
void unget_kbinput(int kbinput, bool meta_key, bool func_key)
{
234
235
    if (!func_key)
	kbinput = (char)kbinput;
236

237
    unget_input(&kbinput, 1);
238
239

    if (meta_key) {
240
241
	kbinput = NANO_CONTROL_3;
	unget_input(&kbinput, 1);
242
243
244
    }
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
245
246
247
248
249
/* Try to read input_len characters from the keystroke buffer.  If the
 * keystroke buffer is empty and win isn't NULL, try to read in more
 * characters from win and add them to the keystroke buffer before doing
 * anything else.  If the keystroke buffer is empty and win is NULL,
 * return NULL. */
250
int *get_input(WINDOW *win, size_t input_len)
251
{
252
    int *input;
253

254
#ifndef NANO_TINY
255
    allow_pending_sigwinch(TRUE);
256
257
258
    allow_pending_sigwinch(FALSE);
#endif

259
260
    if (key_buffer_len == 0) {
	if (win != NULL)
261
	    get_key_buffer(win);
262
263
264
265
266

	if (key_buffer_len == 0)
	    return NULL;
    }

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
267
268
    /* If input_len is greater than the length of the keystroke buffer,
     * only read the number of characters in the keystroke buffer. */
269
270
271
    if (input_len > key_buffer_len)
	input_len = key_buffer_len;

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
272
273
274
    /* Subtract input_len from the length of the keystroke buffer, and
     * allocate input so that it has enough room for input_len
     * keystrokes. */
275
    key_buffer_len -= input_len;
276
    input = (int *)nmalloc(input_len * sizeof(int));
277

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
278
279
    /* Copy input_len keystrokes from the beginning of the keystroke
     * buffer into input. */
280
    memcpy(input, key_buffer, input_len * sizeof(int));
281

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
282
    /* If the keystroke buffer is empty, mark it as such. */
283
284
285
    if (key_buffer_len == 0) {
	free(key_buffer);
	key_buffer = NULL;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
286
287
288
    /* If the keystroke buffer isn't empty, move its beginning forward
     * far enough so that the keystrokes in input are no longer at its
     * beginning. */
289
290
    } else {
	memmove(key_buffer, key_buffer + input_len, key_buffer_len *
291
292
293
		sizeof(int));
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
294
295
296
    }

    return input;
297
298
}

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/* Read in a single character.  If it's ignored, swallow it and go on.
 * Otherwise, try to translate it from ASCII, meta key sequences, escape
 * sequences, and/or extended keypad values.  Set meta_key to TRUE when
 * we get a meta key sequence, and set func_key to TRUE when we get an
 * extended keypad value.  Supported extended keypad values consist of
 * [arrow key], Ctrl-[arrow key], Shift-[arrow key], Enter, Backspace,
 * the editing keypad (Insert, Delete, Home, End, PageUp, and PageDown),
 * the function keypad (F1-F16), and the numeric keypad with NumLock
 * off.  Assume nodelay(win) is FALSE. */
int get_kbinput(WINDOW *win, bool *meta_key, bool *func_key)
{
    int kbinput;

    /* Read in a character and interpret it.  Continue doing this until
     * we get a recognized value or sequence. */
314
    while ((kbinput = parse_kbinput(win, meta_key, func_key)) == ERR);
315

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
316
317
318
    /* If we read from the edit window, blank the statusbar if we need
     * to. */
    if (win == edit)
319
320
	check_statusblank();

321
322
323
324
325
326
327
    return kbinput;
}

/* Translate ASCII characters, extended keypad values, and escape
 * sequences into their corresponding key values.  Set meta_key to TRUE
 * when we get a meta key sequence, and set func_key to TRUE when we get
 * a function key.  Assume nodelay(win) is FALSE. */
328
int parse_kbinput(WINDOW *win, bool *meta_key, bool *func_key)
329
{
330
    static int escapes = 0, byte_digits = 0;
331
    int *kbinput, retval = ERR;
332

333
334
    *meta_key = FALSE;
    *func_key = FALSE;
335

336
337
338
    /* Read in a character. */
    while ((kbinput = get_input(win, 1)) == NULL);

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
    switch (*kbinput) {
	case ERR:
	    break;
	case NANO_CONTROL_3:
	    /* Increment the escape counter. */
	    escapes++;
	    switch (escapes) {
		case 1:
		    /* One escape: wait for more input. */
		case 2:
		    /* Two escapes: wait for more input. */
		    break;
		default:
		    /* More than two escapes: reset the escape counter
		     * and wait for more input. */
		    escapes = 0;
	    }
	    break;
357
#if !defined(NANO_TINY) && defined(KEY_RESIZE)
358
	/* Since we don't change the default SIGWINCH handler when
359
	 * NANO_TINY is defined, KEY_RESIZE is never generated.  Also,
360
361
362
	 * Slang and SunOS 5.7-5.9 don't support KEY_RESIZE. */
	case KEY_RESIZE:
	    break;
363
364
#endif
#ifdef PDCURSES
365
366
367
368
369
370
371
	case KEY_SHIFT_L:
	case KEY_SHIFT_R:
	case KEY_CONTROL_L:
	case KEY_CONTROL_R:
	case KEY_ALT_L:
	case KEY_ALT_R:
	    break;
372
#endif
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
	default:
	    switch (escapes) {
		case 0:
		    switch (*kbinput) {
			case KEY_DOWN:
			    retval = NANO_NEXTLINE_KEY;
			    break;
			case KEY_UP:
			    retval = NANO_PREVLINE_KEY;
			    break;
			case KEY_LEFT:
			    retval = NANO_BACK_KEY;
			    break;
			case KEY_RIGHT:
			    retval = NANO_FORWARD_KEY;
			    break;
389
#ifdef KEY_HOME
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
390
			/* HP-UX 10-11 doesn't support KEY_HOME. */
391
392
393
			case KEY_HOME:
			    retval = NANO_HOME_KEY;
			    break;
394
#endif
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
			case KEY_BACKSPACE:
			    retval = NANO_BACKSPACE_KEY;
			    break;
			case KEY_DC:
			    retval = ISSET(REBIND_DELETE) ?
				NANO_BACKSPACE_KEY : NANO_DELETE_KEY;
			    break;
			case KEY_IC:
			    retval = NANO_INSERTFILE_KEY;
			    break;
			case KEY_NPAGE:
			    retval = NANO_NEXTPAGE_KEY;
			    break;
			case KEY_PPAGE:
			    retval = NANO_PREVPAGE_KEY;
			    break;
			case KEY_ENTER:
			    retval = NANO_ENTER_KEY;
			    break;
			case KEY_A1:	/* Home (7) on numeric keypad
					 * with NumLock off. */
			    retval = NANO_HOME_KEY;
			    break;
			case KEY_A3:	/* PageUp (9) on numeric keypad
					 * with NumLock off. */
			    retval = NANO_PREVPAGE_KEY;
			    break;
			case KEY_B2:	/* Center (5) on numeric keypad
					 * with NumLock off. */
			    break;
			case KEY_C1:	/* End (1) on numeric keypad
					 * with NumLock off. */
			    retval = NANO_END_KEY;
			    break;
			case KEY_C3:	/* PageDown (4) on numeric
					 * keypad with NumLock off. */
			    retval = NANO_NEXTPAGE_KEY;
			    break;
433
#ifdef KEY_BEG
434
435
436
437
			/* Slang doesn't support KEY_BEG. */
			case KEY_BEG:	/* Center (5) on numeric keypad
					 * with NumLock off. */
			    break;
438
#endif
439
#ifdef KEY_END
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
440
			/* HP-UX 10-11 doesn't support KEY_END. */
441
442
443
			case KEY_END:
			    retval = NANO_END_KEY;
			    break;
444
#endif
445
446
447
448
449
450
451
452
453
#ifdef KEY_SBEG
			/* Slang doesn't support KEY_SBEG. */
			case KEY_SBEG:	/* Center (5) on numeric keypad
					 * with NumLock off. */
			    break;
#endif
#ifdef KEY_SDC
			/* Slang doesn't support KEY_SDC. */
			case KEY_SDC:
454
455
			    retval = ISSET(REBIND_DELETE) ?
				NANO_BACKSPACE_KEY : NANO_DELETE_KEY;
456
457
458
			    break;
#endif
#ifdef KEY_SEND
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
459
460
			/* HP-UX 10-11 and Slang don't support
			 * KEY_SEND. */
461
462
463
464
465
			case KEY_SEND:
			    retval = NANO_END_KEY;
			    break;
#endif
#ifdef KEY_SHOME
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
466
			/* HP-UX 10-11 and Slang don't support
467
468
469
470
471
472
473
474
475
			 * KEY_SHOME. */
			case KEY_SHOME:
			    retval = NANO_HOME_KEY;
			    break;
#endif
#ifdef KEY_SIC
			/* Slang doesn't support KEY_SIC. */
			case KEY_SIC:
			    retval = NANO_INSERTFILE_KEY;
476
			    break;
477
478
#endif
#ifdef KEY_SLEFT
479
480
481
482
			/* Slang doesn't support KEY_SLEFT. */
			case KEY_SLEFT:
			    retval = NANO_BACK_KEY;
			    break;
483
484
#endif
#ifdef KEY_SRIGHT
485
486
487
488
			/* Slang doesn't support KEY_SRIGHT. */
			case KEY_SRIGHT:
			    retval = NANO_FORWARD_KEY;
			    break;
489
490
491
492
493
494
495
496
497
498
499
500
#endif
#ifdef KEY_SSUSPEND
			/* Slang doesn't support KEY_SSUSPEND. */
			case KEY_SSUSPEND:
			    retval = NANO_SUSPEND_KEY;
			    break;
#endif
#ifdef KEY_SUSPEND
			/* Slang doesn't support KEY_SUSPEND. */
			case KEY_SUSPEND:
			    retval = NANO_SUSPEND_KEY;
			    break;
501
#endif
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
			default:
			    retval = *kbinput;
			    break;
		    }
		    break;
		case 1:
		    /* One escape followed by a non-escape: escape
		     * sequence mode.  Reset the escape counter.  If
		     * there aren't any other keys waiting, we have a
		     * meta key sequence, so set meta_key to TRUE and
		     * save the lowercase version of the non-escape
		     * character as the result.  If there are other keys
		     * waiting, we have a true escape sequence, so
		     * interpret it. */
		    escapes = 0;
517
		    if (get_key_buffer_len() == 0) {
518
519
			*meta_key = TRUE;
			retval = tolower(*kbinput);
520
521
		    } else
			retval = parse_escape_seq_kbinput(*kbinput);
522
523
524
		    break;
		case 2:
		    /* Two escapes followed by one or more decimal
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
525
		     * digits: byte sequence mode.  If the byte
526
527
528
529
530
531
532
533
534
535
536
537
538
		     * sequence's range is limited to 2XX (the first
		     * digit is in the '0' to '2' range and it's the
		     * first digit, or it's in the '0' to '9' range and
		     * it's not the first digit), increment the byte
		     * sequence counter and interpret the digit.  If the
		     * byte sequence's range is not limited to 2XX, fall
		     * through. */
		    if (('0' <= *kbinput && *kbinput <= '6' &&
			byte_digits == 0) || ('0' <= *kbinput &&
			*kbinput <= '9' && byte_digits > 0)) {
			int byte;

			byte_digits++;
539
			byte = get_byte_kbinput(*kbinput);
540

541
			if (byte != ERR) {
542
543
544
			    char *byte_mb;
			    int byte_mb_len, *seq, i;

545
546
547
548
549
			    /* If we've read in a complete byte
			     * sequence, reset the byte sequence counter
			     * and the escape counter, and put back the
			     * corresponding byte value. */
			    byte_digits = 0;
550
			    escapes = 0;
551

552
553
			    /* Put back the multibyte equivalent of the
			     * byte value. */
554
555
			    byte_mb = make_mbchar((long)byte,
				&byte_mb_len);
556
557
558
559
560
561
562
563
564
565
566

			    seq = (int *)nmalloc(byte_mb_len *
				sizeof(int));

			    for (i = 0; i < byte_mb_len; i++)
				seq[i] = (unsigned char)byte_mb[i];

			    unget_input(seq, byte_mb_len);

			    free(byte_mb);
			    free(seq);
567
			}
568
569
570
571
572
573
574
575
576
577
		    /* Two escapes followed by one or more non-decimal
		     * digits: control character sequence mode,
		     * interrupted byte sequence mode, or escape
		     * sequence mode.  If there aren't any other keys
		     * waiting, we have either a control character
		     * sequence or an interrupted byte sequence.  If
		     * there are other keys waiting, we have a true
		     * escape sequence preceded by an extra escape, so
		     * interpret it. */
		    } else if (get_key_buffer_len() == 0) {
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
			/* Reset the escape counter. */
			escapes = 0;
			if (byte_digits == 0)
			    /* Two escapes followed by a non-decimal
			     * digit or a decimal digit that would
			     * create a byte sequence greater than 2XX,
			     * and we're not in the middle of a byte
			     * sequence: control character sequence
			     * mode.  Interpret the control sequence and
			     * save the corresponding control character
			     * as the result. */
			    retval = get_control_kbinput(*kbinput);
			else {
			    /* If we're in the middle of a byte
			     * sequence, reset the byte sequence counter
			     * and save the character we got as the
			     * result. */
			    byte_digits = 0;
			    retval = *kbinput;
			}
598
599
		    } else
			retval = parse_escape_seq_kbinput(*kbinput);
600
601
602
		    break;
	    }
    }
603

604
605
    if (retval != ERR) {
	/* If our result is NANO_CONTROL_8, translate it to either
606
	 * Delete or Backspace, depending on whether REBIND_DELETE is
607
608
	 * TRUE or FALSE. */
	if (retval == NANO_CONTROL_8)
609
610
	    retval = ISSET(REBIND_DELETE) ? NANO_DELETE_KEY :
		NANO_BACKSPACE_KEY;
611
612
613

	/* If our result is an extended keypad value (i.e, a value
	 * outside of byte range), set func_key to TRUE. */
614
	*func_key = !is_byte(retval);
615
    }
616
617

#ifdef DEBUG
618
    fprintf(stderr, "parse_kbinput(): kbinput = %d, meta_key = %d, func_key = %d, escapes = %d, byte_digits = %d, retval = %d\n", *kbinput, (int)*meta_key, (int)*func_key, escapes, byte_digits, retval);
619
620
#endif

621
    /* Return the result. */
622
623
624
    return retval;
}

625
/* Translate escape sequences, most of which correspond to extended
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
626
 * keypad values, into their corresponding key values.  These sequences
627
628
629
630
631
 * are generated when the keypad doesn't support the needed keys.  If
 * the escape sequence is recognized but we want to ignore it, return
 * ERR and set ignore_seq to TRUE; if it's unrecognized, return ERR and
 * set ignore_seq to FALSE.  Assume that Escape has already been read
 * in. */
632
int get_escape_seq_kbinput(const int *seq, size_t seq_len, bool
633
	*ignore_seq)
634
{
635
    int retval = ERR;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
636

637
638
    *ignore_seq = FALSE;

639
    if (seq_len > 1) {
640
	switch (seq[0]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
641
	    case 'O':
642
		switch (seq[1]) {
643
		    case '2':
644
			if (seq_len >= 3) {
645
			    switch (seq[2]) {
646
647
				case 'P': /* Esc O 2 P == F13 on
					   * xterm. */
648
				    retval = KEY_F(13);
649
650
651
				    break;
				case 'Q': /* Esc O 2 Q == F14 on
					   * xterm. */
652
				    retval = KEY_F(14);
653
				    break;
654
655
656
657
658
659
660
661
				case 'R': /* Esc O 2 R == F15 on
					   * xterm. */
				    retval = KEY_F(15);
				    break;
				case 'S': /* Esc O 2 S == F16 on
					   * xterm. */
				    retval = KEY_F(16);
				    break;
662
663
			    }
			}
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
664
			break;
665
666
667
668
669
670
671
		    case 'A': /* Esc O A == Up on VT100/VT320/xterm. */
		    case 'B': /* Esc O B == Down on
			       * VT100/VT320/xterm. */
		    case 'C': /* Esc O C == Right on
			       * VT100/VT320/xterm. */
		    case 'D': /* Esc O D == Left on
			       * VT100/VT320/xterm. */
672
			retval = get_escape_seq_abcd(seq[1]);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
673
			break;
674
675
		    case 'E': /* Esc O E == Center (5) on numeric keypad
			       * with NumLock off on xterm. */
676
			*ignore_seq = TRUE;
677
			break;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
678
		    case 'F': /* Esc O F == End on xterm. */
679
			retval = NANO_END_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
680
681
			break;
		    case 'H': /* Esc O H == Home on xterm. */
682
			retval = NANO_HOME_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
683
			break;
684
		    case 'M': /* Esc O M == Enter on numeric keypad with
685
686
			       * NumLock off on VT100/VT220/VT320/xterm/
			       * Eterm. */
687
			retval = NANO_ENTER_KEY;
688
			break;
689
		    case 'P': /* Esc O P == F1 on VT100/VT220/VT320/Mach
690
			       * console. */
691
			retval = KEY_F(1);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
692
			break;
693
		    case 'Q': /* Esc O Q == F2 on VT100/VT220/VT320/Mach
694
			       * console. */
695
			retval = KEY_F(2);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
696
			break;
697
		    case 'R': /* Esc O R == F3 on VT100/VT220/VT320/Mach
698
			       * console. */
699
			retval = KEY_F(3);
700
			break;
701
		    case 'S': /* Esc O S == F4 on VT100/VT220/VT320/Mach
702
			       * console. */
703
			retval = KEY_F(4);
704
			break;
705
		    case 'T': /* Esc O T == F5 on Mach console. */
706
			retval = KEY_F(5);
707
			break;
708
		    case 'U': /* Esc O U == F6 on Mach console. */
709
			retval = KEY_F(6);
710
			break;
711
		    case 'V': /* Esc O V == F7 on Mach console. */
712
			retval = KEY_F(7);
713
			break;
714
		    case 'W': /* Esc O W == F8 on Mach console. */
715
			retval = KEY_F(8);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
716
			break;
717
		    case 'X': /* Esc O X == F9 on Mach console. */
718
			retval = KEY_F(9);
719
			break;
720
		    case 'Y': /* Esc O Y == F10 on Mach console. */
721
			retval = KEY_F(10);
722
723
724
725
			break;
		    case 'a': /* Esc O a == Ctrl-Up on rxvt. */
		    case 'b': /* Esc O b == Ctrl-Down on rxvt. */
		    case 'c': /* Esc O c == Ctrl-Right on rxvt. */
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
726
		    case 'd': /* Esc O d == Ctrl-Left on rxvt. */
727
			retval = get_escape_seq_abcd(seq[1]);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
728
			break;
729
		    case 'j': /* Esc O j == '*' on numeric keypad with
730
731
			       * NumLock off on VT100/VT220/VT320/xterm/
			       * rxvt. */
732
			retval = '*';
733
734
			break;
		    case 'k': /* Esc O k == '+' on numeric keypad with
735
736
			       * NumLock off on VT100/VT220/VT320/xterm/
			       * rxvt. */
737
			retval = '+';
738
739
			break;
		    case 'l': /* Esc O l == ',' on numeric keypad with
740
741
			       * NumLock off on VT100/VT220/VT320/xterm/
			       * rxvt. */
742
			retval = ',';
743
744
			break;
		    case 'm': /* Esc O m == '-' on numeric keypad with
745
746
			       * NumLock off on VT100/VT220/VT320/xterm/
			       * rxvt. */
747
			retval = '-';
748
749
			break;
		    case 'n': /* Esc O n == Delete (.) on numeric keypad
750
751
			       * with NumLock off on VT100/VT220/VT320/
			       * xterm/rxvt. */
752
			retval = NANO_DELETE_KEY;
753
754
			break;
		    case 'o': /* Esc O o == '/' on numeric keypad with
755
756
			       * NumLock off on VT100/VT220/VT320/xterm/
			       * rxvt. */
757
			retval = '/';
758
759
			break;
		    case 'p': /* Esc O p == Insert (0) on numeric keypad
760
761
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
762
			retval = NANO_INSERTFILE_KEY;
763
764
			break;
		    case 'q': /* Esc O q == End (1) on numeric keypad
765
766
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
767
			retval = NANO_END_KEY;
768
769
			break;
		    case 'r': /* Esc O r == Down (2) on numeric keypad
770
771
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
772
			retval = NANO_NEXTLINE_KEY;
773
774
			break;
		    case 's': /* Esc O s == PageDown (3) on numeric
775
776
			       * keypad with NumLock off on VT100/VT220/
			       * VT320/rxvt. */
777
			retval = NANO_NEXTPAGE_KEY;
778
779
			break;
		    case 't': /* Esc O t == Left (4) on numeric keypad
780
781
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
782
			retval = NANO_BACK_KEY;
783
784
			break;
		    case 'u': /* Esc O u == Center (5) on numeric keypad
785
786
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt/Eterm. */
787
			*ignore_seq = TRUE;
788
789
			break;
		    case 'v': /* Esc O v == Right (6) on numeric keypad
790
791
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
792
			retval = NANO_FORWARD_KEY;
793
794
			break;
		    case 'w': /* Esc O w == Home (7) on numeric keypad
795
796
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
797
			retval = NANO_HOME_KEY;
798
799
			break;
		    case 'x': /* Esc O x == Up (8) on numeric keypad
800
801
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
802
			retval = NANO_PREVLINE_KEY;
803
804
			break;
		    case 'y': /* Esc O y == PageUp (9) on numeric keypad
805
806
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt. */
807
			retval = NANO_PREVPAGE_KEY;
808
			break;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
809
810
811
		}
		break;
	    case 'o':
812
		switch (seq[1]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
813
814
815
816
		    case 'a': /* Esc o a == Ctrl-Up on Eterm. */
		    case 'b': /* Esc o b == Ctrl-Down on Eterm. */
		    case 'c': /* Esc o c == Ctrl-Right on Eterm. */
		    case 'd': /* Esc o d == Ctrl-Left on Eterm. */
817
			retval = get_escape_seq_abcd(seq[1]);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
818
819
820
821
			break;
		}
		break;
	    case '[':
822
		switch (seq[1]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
823
		    case '1':
824
			if (seq_len >= 3) {
825
			    switch (seq[2]) {
826
827
				case '1': /* Esc [ 1 1 ~ == F1 on rxvt/
					   * Eterm. */
828
				    retval = KEY_F(1);
829
				    break;
830
831
				case '2': /* Esc [ 1 2 ~ == F2 on rxvt/
					   * Eterm. */
832
				    retval = KEY_F(2);
833
				    break;
834
835
				case '3': /* Esc [ 1 3 ~ == F3 on rxvt/
					   * Eterm. */
836
				    retval = KEY_F(3);
837
				    break;
838
839
				case '4': /* Esc [ 1 4 ~ == F4 on rxvt/
					   * Eterm. */
840
				    retval = KEY_F(4);
841
				    break;
842
843
				case '5': /* Esc [ 1 5 ~ == F5 on xterm/
					   * rxvt/Eterm. */
844
				    retval = KEY_F(5);
845
				    break;
846
				case '7': /* Esc [ 1 7 ~ == F6 on
847
848
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
849
				    retval = KEY_F(6);
850
				    break;
851
				case '8': /* Esc [ 1 8 ~ == F7 on
852
853
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
854
				    retval = KEY_F(7);
855
				    break;
856
				case '9': /* Esc [ 1 9 ~ == F8 on
857
858
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
859
				    retval = KEY_F(8);
860
				    break;
861
				case ';':
862
    if (seq_len >= 4) {
863
	switch (seq[3]) {
864
	    case '2':
865
		if (seq_len >= 5) {
866
		    switch (seq[4]) {
867
868
869
870
871
872
873
874
			case 'A': /* Esc [ 1 ; 2 A == Shift-Up on
				   * xterm. */
			case 'B': /* Esc [ 1 ; 2 B == Shift-Down on
				   * xterm. */
			case 'C': /* Esc [ 1 ; 2 C == Shift-Right on
				   * xterm. */
			case 'D': /* Esc [ 1 ; 2 D == Shift-Left on
				   * xterm. */
875
			    retval = get_escape_seq_abcd(seq[4]);
876
877
878
879
880
			    break;
		    }
		}
		break;
	    case '5':
881
		if (seq_len >= 5) {
882
		    switch (seq[4]) {
883
884
885
886
887
888
889
890
			case 'A': /* Esc [ 1 ; 5 A == Ctrl-Up on
				   * xterm. */
			case 'B': /* Esc [ 1 ; 5 B == Ctrl-Down on
				   * xterm. */
			case 'C': /* Esc [ 1 ; 5 C == Ctrl-Right on
				   * xterm. */
			case 'D': /* Esc [ 1 ; 5 D == Ctrl-Left on
				   * xterm. */
891
			    retval = get_escape_seq_abcd(seq[4]);
892
893
894
895
896
897
898
			    break;
		    }
		}
		break;
	}
    }
				    break;
899
900
				default: /* Esc [ 1 ~ == Home on
					  * VT320/Linux console. */
901
				    retval = NANO_HOME_KEY;
902
903
904
905
906
				    break;
			    }
			}
			break;
		    case '2':
907
			if (seq_len >= 3) {
908
			    switch (seq[2]) {
909
				case '0': /* Esc [ 2 0 ~ == F9 on
910
911
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
912
				    retval = KEY_F(9);
913
				    break;
914
				case '1': /* Esc [ 2 1 ~ == F10 on
915
916
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
917
				    retval = KEY_F(10);
918
				    break;
919
				case '3': /* Esc [ 2 3 ~ == F11 on
920
921
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
922
				    retval = KEY_F(11);
923
				    break;
924
				case '4': /* Esc [ 2 4 ~ == F12 on
925
926
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
927
				    retval = KEY_F(12);
928
				    break;
929
				case '5': /* Esc [ 2 5 ~ == F13 on
930
931
					   * VT220/VT320/Linux console/
					   * rxvt/Eterm. */
932
				    retval = KEY_F(13);
933
				    break;
934
				case '6': /* Esc [ 2 6 ~ == F14 on
935
936
					   * VT220/VT320/Linux console/
					   * rxvt/Eterm. */
937
				    retval = KEY_F(14);
938
				    break;
939
940
941
942
943
944
945
946
947
948
				case '8': /* Esc [ 2 8 ~ == F15 on
					   * VT220/VT320/Linux console/
					   * rxvt/Eterm. */
				    retval = KEY_F(15);
				    break;
				case '9': /* Esc [ 2 9 ~ == F16 on
					   * VT220/VT320/Linux console/
					   * rxvt/Eterm. */
				    retval = KEY_F(16);
				    break;
949
				default: /* Esc [ 2 ~ == Insert on
950
951
					  * VT220/VT320/Linux console/
					  * xterm. */
952
				    retval = NANO_INSERTFILE_KEY;
953
954
				    break;
			    }
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
955
956
			}
			break;
957
958
		    case '3': /* Esc [ 3 ~ == Delete on VT220/VT320/
			       * Linux console/xterm. */
959
			retval = NANO_DELETE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
960
			break;
961
		    case '4': /* Esc [ 4 ~ == End on VT220/VT320/Linux
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
962
			       * console/xterm. */
963
			retval = NANO_END_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
964
			break;
965
966
967
		    case '5': /* Esc [ 5 ~ == PageUp on VT220/VT320/
			       * Linux console/xterm; Esc [ 5 ^ ==
			       * PageUp on Eterm. */
968
			retval = NANO_PREVPAGE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
969
			break;
970
971
972
		    case '6': /* Esc [ 6 ~ == PageDown on VT220/VT320/
			       * Linux console/xterm; Esc [ 6 ^ ==
			       * PageDown on Eterm. */
973
			retval = NANO_NEXTPAGE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
974
975
			break;
		    case '7': /* Esc [ 7 ~ == Home on rxvt. */
976
			retval = NANO_HOME_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
977
978
			break;
		    case '8': /* Esc [ 8 ~ == End on rxvt. */
979
			retval = NANO_END_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
980
			break;
981
		    case '9': /* Esc [ 9 == Delete on Mach console. */
982
			retval = NANO_DELETE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
983
			break;
984
		    case '@': /* Esc [ @ == Insert on Mach console. */
985
			retval = NANO_INSERTFILE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
986
			break;
987
		    case 'A': /* Esc [ A == Up on ANSI/VT220/Linux
988
			       * console/FreeBSD console/Mach console/
989
			       * rxvt/Eterm. */
990
		    case 'B': /* Esc [ B == Down on ANSI/VT220/Linux
991
			       * console/FreeBSD console/Mach console/
992
			       * rxvt/Eterm. */
993
		    case 'C': /* Esc [ C == Right on ANSI/VT220/Linux
994
			       * console/FreeBSD console/Mach console/
995
			       * rxvt/Eterm. */
996
		    case 'D': /* Esc [ D == Left on ANSI/VT220/Linux
997
			       * console/FreeBSD console/Mach console/
998
			       * rxvt/Eterm. */
999
			retval = get_escape_seq_abcd(seq[1]);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1000
			break;
1001
1002
		    case 'E': /* Esc [ E == Center (5) on numeric keypad
			       * with NumLock off on FreeBSD console. */
1003
			*ignore_seq = TRUE;
1004
			break;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1005
1006
		    case 'F': /* Esc [ F == End on FreeBSD
			       * console/Eterm. */
1007
			retval = NANO_END_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1008
1009
			break;
		    case 'G': /* Esc [ G == PageDown on FreeBSD
1010
			       * console. */
1011
			retval = NANO_NEXTPAGE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1012
			break;
1013
		    case 'H': /* Esc [ H == Home on ANSI/VT220/FreeBSD
1014
			       * console/Mach console/Eterm. */
1015
			retval = NANO_HOME_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1016
1017
1018
			break;
		    case 'I': /* Esc [ I == PageUp on FreeBSD
			       * console. */
1019
			retval = NANO_PREVPAGE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1020
			break;
1021
		    case 'L': /* Esc [ L == Insert on ANSI/FreeBSD
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1022
			       * console. */
1023
			retval = NANO_INSERTFILE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1024
			break;
1025
		    case 'M': /* Esc [ M == F1 on FreeBSD console. */
1026
			retval = KEY_F(1);
1027
1028
			break;
		    case 'N': /* Esc [ N == F2 on FreeBSD console. */
1029
			retval = KEY_F(2);
1030
1031
			break;
		    case 'O':
1032
			if (seq_len >= 3) {
1033
			    switch (seq[2]) {
1034
1035
				case 'P': /* Esc [ O P == F1 on
					   * xterm. */
1036
				    retval = KEY_F(1);
1037
1038
1039
				    break;
				case 'Q': /* Esc [ O Q == F2 on
					   * xterm. */
1040
				    retval = KEY_F(2);
1041
1042
1043
				    break;
				case 'R': /* Esc [ O R == F3 on
					   * xterm. */
1044
				    retval = KEY_F(3);
1045
1046
1047
				    break;
				case 'S': /* Esc [ O S == F4 on
					   * xterm. */
1048
				    retval = KEY_F(4);
1049
1050
				    break;
			    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1051
			} else
1052
1053
			    /* Esc [ O == F3 on FreeBSD console. */
			    retval = KEY_F(3);
1054
1055
			break;
		    case 'P': /* Esc [ P == F4 on FreeBSD console. */
1056
			retval = KEY_F(4);
1057
1058
			break;
		    case 'Q': /* Esc [ Q == F5 on FreeBSD console. */
1059
			retval = KEY_F(5);
1060
1061
			break;
		    case 'R': /* Esc [ R == F6 on FreeBSD console. */
1062
			retval = KEY_F(6);
1063
1064
			break;
		    case 'S': /* Esc [ S == F7 on FreeBSD console. */
1065
			retval = KEY_F(7);
1066
1067
			break;
		    case 'T': /* Esc [ T == F8 on FreeBSD console. */
1068
			retval = KEY_F(8);
1069
			break;
1070
		    case 'U': /* Esc [ U == PageDown on Mach console. */
1071
			retval = NANO_NEXTPAGE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1072
			break;
1073
		    case 'V': /* Esc [ V == PageUp on Mach console. */
1074
			retval = NANO_PREVPAGE_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1075
			break;
1076
		    case 'W': /* Esc [ W == F11 on FreeBSD console. */
1077
			retval = KEY_F(11);
1078
1079
			break;
		    case 'X': /* Esc [ X == F12 on FreeBSD console. */
1080
			retval = KEY_F(12);
1081
			break;
1082
		    case 'Y': /* Esc [ Y == End on Mach console. */
1083
			retval = NANO_END_KEY;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1084
			break;
1085
		    case 'Z': /* Esc [ Z == F14 on FreeBSD console. */
1086
			retval = KEY_F(14);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1087
			break;
1088
		    case 'a': /* Esc [ a == Shift-Up on rxvt/Eterm. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1089
		    case 'b': /* Esc [ b == Shift-Down on rxvt/Eterm. */
1090
1091
		    case 'c': /* Esc [ c == Shift-Right on rxvt/
			       * Eterm. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1092
		    case 'd': /* Esc [ d == Shift-Left on rxvt/Eterm. */
1093
			retval = get_escape_seq_abcd(seq[1]);
1094
1095
			break;
		    case '[':
1096
			if (seq_len >= 3) {
1097
			    switch (seq[2]) {
1098
1099
				case 'A': /* Esc [ [ A == F1 on Linux
					   * console. */
1100
				    retval = KEY_F(1);
1101
1102
1103
				    break;
				case 'B': /* Esc [ [ B == F2 on Linux
					   * console. */
1104
				    retval = KEY_F(2);
1105
1106
1107
				    break;
				case 'C': /* Esc [ [ C == F3 on Linux
					   * console. */
1108
				    retval = KEY_F(3);
1109
1110
1111
				    break;
				case 'D': /* Esc [ [ D == F4 on Linux
					   * console. */
1112
				    retval = KEY_F(4);
1113
1114
1115
				    break;
				case 'E': /* Esc [ [ E == F5 on Linux
					   * console. */
1116
				    retval = KEY_F(5);
1117
1118
1119
				    break;
			    }
			}
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1120
1121
1122
1123
			break;
		}
		break;
	}
1124
1125
    }

1126
#ifdef DEBUG
1127
    fprintf(stderr, "get_escape_seq_kbinput(): retval = %d, ignore_seq = %d\n", retval, (int)*ignore_seq);
1128
#endif
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1129

1130
    return retval;
1131
1132
}

1133
/* Return the equivalent arrow key value for the case-insensitive
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1134
 * letters A (up), B (down), C (right), and D (left).  These are common
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
 * to many escape sequences. */
int get_escape_seq_abcd(int kbinput)
{
    switch (tolower(kbinput)) {
	case 'a':
	    return NANO_PREVLINE_KEY;
	case 'b':
	    return NANO_NEXTLINE_KEY;
	case 'c':
	    return NANO_FORWARD_KEY;
	case 'd':
	    return NANO_BACK_KEY;
	default:
	    return ERR;
    }
}

1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
/* Interpret the escape sequence in the keystroke buffer, the first
 * character of which is kbinput.  Assume that the keystroke buffer
 * isn't empty, and that the initial escape has already been read in. */
int parse_escape_seq_kbinput(int kbinput)
{
    int retval, *seq;
    size_t seq_len;
    bool ignore_seq;

    /* Put back the non-escape character, get the complete escape
     * sequence, translate the sequence into its corresponding key
     * value, and save that as the result. */
    unget_input(&kbinput, 1);
    seq_len = get_key_buffer_len();
    seq = get_input(NULL, seq_len);
    retval = get_escape_seq_kbinput(seq, seq_len, &ignore_seq);

    /* If the escape sequence is unrecognized and not ignored, throw it
     * out, and indicate this on the statusbar. */
    if (retval == ERR && !ignore_seq)
	statusbar(_("Unknown Command"));

    free(seq);

#ifdef DEBUG
    fprintf(stderr, "parse_escape_seq_kbinput(): kbinput = %d, seq_len = %lu, ignore_seq = %d, retval = %d\n", *kbinput, (unsigned long)seq_len, (int)ignore_seq, retval);
#endif

    return retval;
}

1183
1184
/* Translate a byte sequence: turn a three-digit decimal number from
 * 000 to 255 into its corresponding byte value. */
1185
int get_byte_kbinput(int kbinput)
1186
{
1187
    static int byte_digits = 0, byte = 0;
1188
    int retval = ERR;
1189

1190
1191
    /* Increment the byte digit counter. */
    byte_digits++;
1192

1193
    switch (byte_digits) {
1194
	case 1:
1195
1196
	    /* One digit: reset the byte sequence holder and add the
	     * digit we got to the 100's position of the byte sequence
1197
	     * holder. */
1198
	    byte = 0;
1199
	    if ('0' <= kbinput && kbinput <= '2')
1200
		byte += (kbinput - '0') * 100;
1201
1202
	    else
		/* If the character we got isn't a decimal digit, or if
1203
		 * it is and it would put the byte sequence out of byte
1204
1205
1206
1207
		 * range, save it as the result. */
		retval = kbinput;
	    break;
	case 2:
1208
1209
	    /* Two digits: add the digit we got to the 10's position of
	     * the byte sequence holder. */
1210
1211
1212
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 200 &&
		'6' <= kbinput && kbinput <= '9'))
		byte += (kbinput - '0') * 10;
1213
1214
	    else
		/* If the character we got isn't a decimal digit, or if
1215
		 * it is and it would put the byte sequence out of byte
1216
1217
1218
1219
		 * range, save it as the result. */
		retval = kbinput;
	    break;
	case 3:
1220
	    /* Three digits: add the digit we got to the 1's position of
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1221
	     * the byte sequence holder, and save the corresponding byte
1222
	     * value as the result. */
1223
1224
1225
1226
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 250 &&
		'6' <= kbinput && kbinput <= '9')) {
		byte += (kbinput - '0');
		retval = byte;
1227
	    } else
1228
		/* If the character we got isn't a decimal digit, or if
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1229
		 * it is and it would put the byte sequence out of byte
1230
1231
1232
		 * range, save it as the result. */
		retval = kbinput;
	    break;
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
	default:
	    /* More than three digits: save the character we got as the
	     * result. */
	    retval = kbinput;
	    break;
    }

    /* If we have a result, reset the byte digit counter and the byte
     * sequence holder. */
    if (retval != ERR) {
	byte_digits = 0;
1244
	byte = 0;
1245
1246
1247
    }

#ifdef DEBUG
1248
    fprintf(stderr, "get_byte_kbinput(): kbinput = %d, byte_digits = %d, byte = %d, retval = %d\n", kbinput, byte_digits, byte, retval);
1249
1250
1251
1252
1253
#endif

    return retval;
}

1254
1255
1256
/* Translate a Unicode sequence: turn a six-digit hexadecimal number
 * from 000000 to 10FFFF (case-insensitive) into its corresponding
 * multibyte value. */
1257
long get_unicode_kbinput(int kbinput)
1258
{
1259
1260
1261
    static int uni_digits = 0;
    static long uni = 0;
    long retval = ERR;
1262

1263
    /* Increment the Unicode digit counter. */
1264
    uni_digits++;
1265

1266
    switch (uni_digits) {
1267
	case 1:
1268
	    /* One digit: reset the Unicode sequence holder and add the
1269
	     * digit we got to the 0x100000's position of the Unicode
1270
1271
	     * sequence holder. */
	    uni = 0;
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
	    if ('0' <= kbinput && kbinput <= '1')
		uni += (kbinput - '0') * 0x100000;
	    else
		/* If the character we got isn't a hexadecimal digit, or
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
		retval = kbinput;
	    break;
	case 2:
	    /* Two digits: add the digit we got to the 0x10000's
	     * position of the Unicode sequence holder. */
	    if ('0' == kbinput || (uni < 0x100000 && '1' <= kbinput &&
		kbinput <= '9'))
		uni += (kbinput - '0') * 0x10000;
	    else if (uni < 0x100000 && 'a' <= tolower(kbinput) &&
		tolower(kbinput) <= 'f')
		uni += (tolower(kbinput) + 10 - 'a') * 0x10000;
	    else
		/* If the character we got isn't a hexadecimal digit, or
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
		retval = kbinput;
	    break;
	case 3:
	    /* Three digits: add the digit we got to the 0x1000's
	     * position of the Unicode sequence holder. */
1298
	    if ('0' <= kbinput && kbinput <= '9')
1299
		uni += (kbinput - '0') * 0x1000;
1300
	    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
1301
		uni += (tolower(kbinput) + 10 - 'a') * 0x1000;
1302
1303
	    else
		/* If the character we got isn't a hexadecimal digit, or
1304
1305
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1306
1307
		retval = kbinput;
	    break;
1308
1309
	case 4:
	    /* Four digits: add the digit we got to the 0x100's position
1310
	     * of the Unicode sequence holder. */
1311
	    if ('0' <= kbinput && kbinput <= '9')
1312
		uni += (kbinput - '0') * 0x100;
1313
	    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
1314
		uni += (tolower(kbinput) + 10 - 'a') * 0x100;
1315
	    else
1316
		/* If the character we got isn't a hexadecimal digit, or
1317
1318
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1319
1320
		retval = kbinput;
	    break;
1321
1322
	case 5:
	    /* Five digits: add the digit we got to the 0x10's position
1323
	     * of the Unicode sequence holder. */
1324
	    if ('0' <= kbinput && kbinput <= '9')
1325
		uni += (kbinput - '0') * 0x10;
1326
	    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
1327
		uni += (tolower(kbinput) + 10 - 'a') * 0x10;
1328
1329
	    else
		/* If the character we got isn't a hexadecimal digit, or
1330
1331
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1332
1333
		retval = kbinput;
	    break;
1334
1335
	case 6:
	    /* Six digits: add the digit we got to the 1's position of
1336
1337
	     * the Unicode sequence holder, and save the corresponding
	     * Unicode value as the result. */
1338
	    if ('0' <= kbinput && kbinput <= '9') {
1339
1340
		uni += (kbinput - '0');
		retval = uni;
1341
1342
	    } else if ('a' <= tolower(kbinput) && tolower(kbinput) <=
		'f') {
1343
1344
		uni += (tolower(kbinput) + 10 - 'a');
		retval = uni;
1345
	    } else
1346
		/* If the character we got isn't a hexadecimal digit, or
1347
1348
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1349
1350
1351
		retval = kbinput;
	    break;
	default:
1352
	    /* More than six digits: save the character we got as the
1353
1354
1355
1356
	     * result. */
	    retval = kbinput;
	    break;
    }
1357

1358
1359
    /* If we have a result, reset the Unicode digit counter and the
     * Unicode sequence holder. */
1360
    if (retval != ERR) {
1361
1362
	uni_digits = 0;
	uni = 0;
1363
    }
1364

1365
#ifdef DEBUG
1366
    fprintf(stderr, "get_unicode_kbinput(): kbinput = %d, uni_digits = %d, uni = %ld, retval = %ld\n", kbinput, uni_digits, uni, retval);
1367
1368
#endif

1369
1370
1371
1372
1373
1374
1375
1376
1377
    return retval;
}

/* Translate a control character sequence: turn an ASCII non-control
 * character into its corresponding control character. */
int get_control_kbinput(int kbinput)
{
    int retval;

1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
     /* Ctrl-Space (Ctrl-2, Ctrl-@, Ctrl-`) */
    if (kbinput == ' ')
	retval = kbinput - 32;
    /* Ctrl-/ (Ctrl-7, Ctrl-_) */
    else if (kbinput == '/')
	retval = kbinput - 16;
    /* Ctrl-2 (Ctrl-Space, Ctrl-@, Ctrl-`) */
    else if (kbinput == '2')
	retval = kbinput - 50;
    /* Ctrl-3 (Ctrl-[, Esc) to Ctrl-7 (Ctrl-/, Ctrl-_) */
1388
1389
1390
    else if ('3' <= kbinput && kbinput <= '7')
	retval = kbinput - 24;
    /* Ctrl-8 (Ctrl-?) */
1391
1392
    else if (kbinput == '8')
	retval = kbinput + 71;
1393
1394
1395
1396
1397
    /* Ctrl-? (Ctrl-8) */
    else if (kbinput == '?')
	retval = kbinput + 64;
    /* Ctrl-@ (Ctrl-Space, Ctrl-2, Ctrl-`) to Ctrl-_ (Ctrl-/, Ctrl-7) */
    else if ('@' <= kbinput && kbinput <= '_')
1398
	retval = kbinput - 64;
1399
1400
    /* Ctrl-` (Ctrl-2, Ctrl-Space, Ctrl-@) to Ctrl-~ (Ctrl-6, Ctrl-^) */
    else if ('`' <= kbinput && kbinput <= '~')
1401
1402
1403
1404
	retval = kbinput - 96;
    else
	retval = kbinput;

1405
#ifdef DEBUG
1406
    fprintf(stderr, "get_control_kbinput(): kbinput = %d, retval = %d\n", kbinput, retval);
1407
1408
#endif

1409
1410
    return retval;
}
1411

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1412
1413
/* Put the output-formatted characters in output back into the keystroke
 * buffer, so that they can be parsed and displayed as output again. */
1414
void unparse_kbinput(char *output, size_t output_len)
1415
{
1416
1417
    int *input;
    size_t i;
1418

1419
1420
1421
1422
1423
1424
1425
1426
    if (output_len == 0)
	return;

    input = (int *)nmalloc(output_len * sizeof(int));
    for (i = 0; i < output_len; i++)
	input[i] = (int)output[i];
    unget_input(input, output_len);
    free(input);
1427
1428
}

1429
/* Read in a stream of characters verbatim, and return the length of the
1430
1431
1432
1433
 * string in kbinput_len.  Assume nodelay(win) is FALSE. */
int *get_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
{
    int *retval;
1434

1435
    /* Turn off flow control characters if necessary so that we can type
1436
1437
     * them in verbatim, and turn the keypad off if necessary so that we
     * don't get extended keypad values. */
1438
1439
    if (ISSET(PRESERVE))
	disable_flow_control();
1440
1441
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, FALSE);
1442
1443
1444

    /* Read in a stream of characters and interpret it if possible. */
    retval = parse_verbatim_kbinput(win, kbinput_len);
1445
1446

    /* Turn flow control characters back on if necessary and turn the
1447
     * keypad back on if necessary now that we're done. */
1448
1449
    if (ISSET(PRESERVE))
	enable_flow_control();
1450
1451
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, TRUE);
1452

1453
    return retval;
1454
1455
}

1456
1457
/* Read in a stream of all available characters, and return the length
 * of the string in kbinput_len.  Translate the first few characters of
1458
1459
 * the input into the corresponding multibyte value if possible.  After
 * that, leave the input as-is. */ 
1460
int *parse_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
1461
{
1462
1463
    int *kbinput, *retval;
    long uni;
1464

1465
1466
1467
    /* Read in the first keystroke. */
    while ((kbinput = get_input(win, 1)) == NULL);

1468
    /* Check whether the first keystroke is a hexadecimal digit. */
1469
    uni = get_unicode_kbinput(*kbinput);
1470

1471
1472
    /* If the first keystroke isn't a hexadecimal digit, put back the
     * first keystroke. */
1473
    if (uni != ERR)
1474
	unget_input(kbinput, 1);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1475
1476
    /* Otherwise, read in keystrokes until we have a complete Unicode
     * sequence, and put back the corresponding Unicode value. */
1477
    else {
1478
1479
	char *uni_mb;
	int uni_mb_len, *seq, i;
1480

1481
	while (uni == ERR) {
1482
	    while ((kbinput = get_input(win, 1)) == NULL);
1483

1484
	    uni = get_unicode_kbinput(*kbinput);
1485
	}
1486

1487
1488
	/* Put back the multibyte equivalent of the Unicode value. */
	uni_mb = make_mbchar(uni, &uni_mb_len);
1489

1490
	seq = (int *)nmalloc(uni_mb_len * sizeof(int));
1491

1492
1493
	for (i = 0; i < uni_mb_len; i++)
	    seq[i] = (unsigned char)uni_mb[i];
1494

1495
	unget_input(seq, uni_mb_len);
1496
1497

	free(seq);
1498
	free(uni_mb);
1499
1500
    }

1501
    /* Get the complete sequence, and save the characters in it as the
1502
     * result. */
1503
    *kbinput_len = get_key_buffer_len();
1504
    retval = get_input(NULL, *kbinput_len);
1505
1506
1507
1508

    return retval;
}

1509
#ifndef DISABLE_MOUSE
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1510
1511
/* Check for a mouse event, and if one's taken place, save the
 * coordinates where it took place in mouse_x and mouse_y.  After that,
1512
1513
 * assuming allow_shortcuts is FALSE, if the shortcut list on the
 * bottom two lines of the screen is visible and the mouse event took
1514
1515
1516
 * place on it, figure out which shortcut was clicked and put back the
 * equivalent keystroke(s).  Return FALSE if no keystrokes were
 * put back, or TRUE if at least one was.  Assume that KEY_MOUSE has
1517
 * already been read in. */
1518
bool get_mouseinput(int *mouse_x, int *mouse_y, bool allow_shortcuts)
1519
1520
1521
1522
1523
1524
1525
1526
{
    MEVENT mevent;

    *mouse_x = -1;
    *mouse_y = -1;

    /* First, get the actual mouse event. */
    if (getmouse(&mevent) == ERR)
1527
	return FALSE;
1528
1529
1530
1531
1532

    /* Save the screen coordinates where the mouse event took place. */
    *mouse_x = mevent.x;
    *mouse_y = mevent.y;

1533
1534
1535
    /* If we're allowing shortcuts, the current shortcut list is being
     * displayed on the last two lines of the screen, and the mouse
     * event took place inside it, we need to figure out which shortcut
1536
     * was clicked and put back the equivalent keystroke(s) for it. */
1537
1538
    if (allow_shortcuts && !ISSET(NO_HELP) && wenclose(bottomwin,
	*mouse_y, *mouse_x)) {
1539
	int i, j;
1540
	size_t currslen;
1541
1542
1543
1544
1545
1546
1547
1548
	    /* The number of shortcuts in the current shortcut list. */
	const shortcut *s = currshortcut;
	    /* The actual shortcut we clicked on, starting at the first
	     * one in the current shortcut list. */

	/* Get the shortcut lists' length. */
	if (currshortcut == main_list)
	    currslen = MAIN_VISIBLE;
1549
	else {
1550
1551
	    currslen = length_of_list(currshortcut);

1552
1553
1554
1555
1556
1557
	    /* We don't show any more shortcuts than the main list
	     * does. */
	    if (currslen > MAIN_VISIBLE)
		currslen = MAIN_VISIBLE;
	}

1558
1559
1560
	/* Calculate the width of all of the shortcuts in the list
	 * except for the last two, which are longer by (COLS % i)
	 * columns so as to not waste space. */
1561
	if (currslen < 2)
1562
	    i = COLS / (MAIN_VISIBLE / 2);
1563
1564
1565
	else
	    i = COLS / ((currslen / 2) + (currslen % 2));

1566
	/* Calculate the y-coordinate relative to the beginning of
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1567
1568
	 * the shortcut list in bottomwin, i.e, with the sizes of
	 * topwin, edit, and the first line of bottomwin subtracted
1569
	 * out, and set j to it. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1570
	j = *mouse_y - (2 - no_more_space()) - editwinrows - 1;
1571

1572
1573
	/* If we're on the statusbar, don't do anything. */
	if (j < 0)
1574
	    return FALSE;
1575
1576
1577
1578

	/* Calculate the x-coordinate relative to the beginning of the
	 * shortcut list in bottomwin, and add it to j.  j should now be
	 * the index in the shortcut list of the shortcut we clicked. */
1579
	j = (*mouse_x / i) * 2 + j;
1580
1581
1582
1583
1584
1585

	/* Adjust j if we clicked in the last two shortcuts. */
	if ((j >= currslen) && (*mouse_x % i < COLS % i))
	    j -= 2;

	/* If we're beyond the last shortcut, don't do anything. */
1586
	if (j >= currslen)
1587
	    return FALSE;
1588
1589
1590
1591
1592
1593

	/* Go through the shortcut list to determine which shortcut was
	 * clicked. */
	for (; j > 0; j--)
	    s = s->next;

1594
1595
1596
	/* And put back the equivalent key.  Assume that each shortcut
	 * has, at the very least, an equivalent control key, an
	 * equivalent primary meta key sequence, or both. */
1597
	if (s->ctrlval != NANO_NO_KEY) {
1598
	    unget_kbinput(s->ctrlval, FALSE, FALSE);
1599
1600
	    return TRUE;
	} else if (s->metaval != NANO_NO_KEY) {
1601
	    unget_kbinput(s->metaval, TRUE, FALSE);
1602
1603
	    return TRUE;
	}
1604
    }
1605
    return FALSE;
1606
}
1607
1608
#endif /* !DISABLE_MOUSE */

1609
1610
1611
1612
1613
1614
1615
1616
/* Return the shortcut corresponding to the values of kbinput (the key
 * itself), meta_key (whether the key is a meta sequence), and func_key
 * (whether the key is a function key), if any.  The shortcut will be
 * the first one in the list (control key, meta key sequence, function
 * key, other meta key sequence) for the corresponding function.  For
 * example, passing in a meta key sequence that corresponds to a
 * function with a control key, a function key, and a meta key sequence
 * will return the control key corresponding to that function. */
1617
const shortcut *get_shortcut(const shortcut *s_list, int *kbinput, bool
1618
	*meta_key, bool *func_key)
1619
1620
1621
1622
{
    const shortcut *s = s_list;
    size_t slen = length_of_list(s_list);

1623
#ifdef DEBUG
1624
    fprintf(stderr, "get_shortcut(): kbinput = %d, meta_key = %d, func_key = %d\n", *kbinput, (int)*meta_key, (int)*func_key);
1625
1626
#endif

1627
1628
1629
1630
1631
1632
    /* Check for shortcuts. */
    for (; slen > 0; slen--) {
	/* We've found a shortcut if:
	 *
	 * 1. The key exists.
	 * 2. The key is a control key in the shortcut list.
1633
1634
1635
1636
1637
	 * 3. meta_key is TRUE and the key is the primary or
	 *    miscellaneous meta sequence in the shortcut list.
	 * 4. func_key is TRUE and the key is a function key in the
	 *    shortcut list. */

1638
1639
1640
1641
	if (*kbinput != NANO_NO_KEY && (*kbinput == s->ctrlval ||
		(*meta_key == TRUE && (*kbinput == s->metaval ||
		*kbinput == s->miscval)) || (*func_key == TRUE &&
		*kbinput == s->funcval))) {
1642
1643
1644
1645
1646
1647
1648
1649
	    break;
	}

	s = s->next;
    }

    /* Translate the shortcut to either its control key or its meta key
     * equivalent.  Assume that the shortcut has an equivalent control
1650
     * key, an equivalent primary meta key sequence, or both. */
1651
1652
1653
    if (slen > 0) {
	if (s->ctrlval != NANO_NO_KEY) {
	    *meta_key = FALSE;
1654
	    *func_key = FALSE;
1655
	    *kbinput = s->ctrlval;
1656
	    return s;
1657
1658
	} else if (s->metaval != NANO_NO_KEY) {
	    *meta_key = TRUE;
1659
	    *func_key = FALSE;
1660
	    *kbinput = s->metaval;
1661
	    return s;
1662
1663
1664
1665
1666
1667
	}
    }

    return NULL;
}

1668
#ifndef NANO_TINY
1669
1670
1671
/* Return the global toggle corresponding to the values of kbinput (the
 * key itself) and meta_key (whether the key is a meta sequence), if
 * any. */
1672
1673
1674
1675
const toggle *get_toggle(int kbinput, bool meta_key)
{
    const toggle *t = toggles;

1676
1677
1678
1679
#ifdef DEBUG
    fprintf(stderr, "get_toggle(): kbinput = %d, meta_key = %d\n", kbinput, (int)meta_key);
#endif

1680
1681
    /* Check for toggles. */
    for (; t != NULL; t = t->next) {
1682
1683
	/* We've found a toggle if the key exists, meta_key is TRUE, and
	 * the key is in the meta key toggle list. */
1684
	if (t->val != TOGGLE_NO_KEY && meta_key && kbinput == t->val)
1685
1686
1687
1688
1689
	    break;
    }

    return t;
}
1690
#endif /* !NANO_TINY */
1691

1692
1693
1694
1695
1696
1697
1698
1699
1700
/* Move to (x, y) in win, and display a line of n spaces with the
 * current attributes. */
void blank_line(WINDOW *win, int y, int x, int n)
{
    wmove(win, y, x);
    for (; n > 0; n--)
	waddch(win, ' ');
}

1701
/* Blank the first line of the top portion of the window. */
1702
void blank_titlebar(void)
Chris Allegretta's avatar
Chris Allegretta committed
1703
{
1704
    blank_line(topwin, 0, 0, COLS);
1705
1706
}

1707
1708
/* If the MORE_SPACE flag isn't set, blank the second line of the top
 * portion of the window. */
1709
1710
1711
void blank_topbar(void)
{
    if (!ISSET(MORE_SPACE))
1712
	blank_line(topwin, 1, 0, COLS);
1713
1714
}

1715
1716
/* Blank all the lines of the middle portion of the window, i.e, the
 * edit window. */
Chris Allegretta's avatar
Chris Allegretta committed
1717
1718
void blank_edit(void)
{
1719
    int i;
1720
    for (i = 0; i < editwinrows; i++)
1721
	blank_line(edit, i, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1722
1723
}

1724
/* Blank the first line of the bottom portion of the window. */
Chris Allegretta's avatar
Chris Allegretta committed
1725
1726
void blank_statusbar(void)
{
1727
    blank_line(bottomwin, 0, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1728
1729
}

1730
1731
/* If the NO_HELP flag isn't set, blank the last two lines of the bottom
 * portion of the window. */
1732
1733
1734
void blank_bottombars(void)
{
    if (!ISSET(NO_HELP)) {
1735
1736
	blank_line(bottomwin, 1, 0, COLS);
	blank_line(bottomwin, 2, 0, COLS);
1737
1738
1739
    }
}

1740
1741
1742
/* Check if the number of keystrokes needed to blank the statusbar has
 * been pressed.  If so, blank the statusbar, unless constant cursor
 * position display is on. */
1743
void check_statusblank(void)
Chris Allegretta's avatar
Chris Allegretta committed
1744
{
1745
    if (statusblank > 0)
1746
	statusblank--;
1747
1748

    if (statusblank == 0 && !ISSET(CONST_UPDATE)) {
1749
1750
1751
	blank_statusbar();
	wnoutrefresh(bottomwin);
	reset_cursor();
1752
	wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
1753
1754
1755
    }
}

1756
1757
1758
1759
/* Convert buf into a string that can be displayed on screen.  The
 * caller wants to display buf starting with column start_col, and
 * extending for at most len columns.  start_col is zero-based.  len is
 * one-based, so len == 0 means you get "" returned.  The returned
1760
1761
1762
1763
1764
 * string is dynamically allocated, and should be freed.  If dollars is
 * TRUE, the caller might put "$" at the beginning or end of the line if
 * it's too long. */
char *display_string(const char *buf, size_t start_col, size_t len, bool
	dollars)
1765
1766
{
    size_t start_index;
1767
	/* Index in buf of the first character shown. */
1768
    size_t column;
1769
	/* Screen column that start_index corresponds to. */
1770
1771
1772
1773
1774
1775
    size_t alloc_len;
	/* The length of memory allocated for converted. */
    char *converted;
	/* The string we return. */
    size_t index;
	/* Current position in converted. */
1776
    char *buf_mb;
1777
1778
    int buf_mb_len;

1779
1780
1781
1782
1783
    /* If dollars is TRUE, make room for the "$" at the end of the
     * line. */
    if (dollars && len > 0 && strlenpt(buf) > start_col + len)
	len--;

1784
1785
1786
    if (len == 0)
	return mallocstrcpy(NULL, "");

1787
1788
    buf_mb = charalloc(mb_cur_max());

1789
1790
    start_index = actual_x(buf, start_col);
    column = strnlenpt(buf, start_index);
1791

1792
    assert(column <= start_col);
1793

1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
    /* Make sure there's enough room for the initial character, whether
     * it's a multibyte control character, a non-control multibyte
     * character, a tab character, or a null terminator.  Rationale:
     *
     * multibyte control character followed by a null terminator:
     *     1 byte ('^') + mb_cur_max() bytes + 1 byte ('\0')
     * multibyte non-control character followed by a null terminator:
     *     mb_cur_max() bytes + 1 byte ('\0')
     * tab character followed by a null terminator:
     *     mb_cur_max() bytes + (tabsize - 1) bytes + 1 byte ('\0')
     *
     * Since tabsize has a minimum value of 1, it can substitute for 1
     * byte above. */
    alloc_len = (mb_cur_max() + tabsize + 1) * MAX_BUF_SIZE;
    converted = charalloc(alloc_len);
1809

1810
1811
    index = 0;

1812
1813
    if (buf[start_index] != '\t' && (column < start_col || (dollars &&
	column > 0))) {
1814
1815
	/* We don't display all of buf[start_index] since it starts to
	 * the left of the screen. */
1816
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1817

1818
	if (is_cntrl_mbchar(buf_mb)) {
1819
	    if (column < start_col) {
1820
1821
		char *ctrl_buf_mb = charalloc(mb_cur_max());
		int ctrl_buf_mb_len, i;
1822

1823
1824
		ctrl_buf_mb = control_mbrep(buf_mb, ctrl_buf_mb,
			&ctrl_buf_mb_len);
1825

1826
1827
		for (i = 0; i < ctrl_buf_mb_len; i++)
		    converted[index++] = ctrl_buf_mb[i];
1828

1829
		start_col += mbwidth(ctrl_buf_mb);
1830

1831
		free(ctrl_buf_mb);
1832

1833
		start_index += buf_mb_len;
1834
	    }
1835
	}
1836
#ifdef ENABLE_UTF8
1837
1838
1839
1840
1841
1842
	else if (using_utf8() && mbwidth(buf_mb) == 2) {
	    if (column >= start_col) {
		converted[index++] = ' ';
		start_col++;
	    }

1843
	    converted[index++] = ' ';
1844
	    start_col++;
1845
1846

	    start_index += buf_mb_len;
1847
	}
1848
#endif
1849
1850
    }

1851
    while (buf[start_index] != '\0') {
1852
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1853

1854
1855
1856
1857
1858
1859
1860
1861
	/* Make sure there's enough room for the next character, whether
	 * it's a multibyte control character, a non-control multibyte
	 * character, a tab character, or a null terminator. */
	if (index + mb_cur_max() + tabsize + 1 >= alloc_len - 1) {
	    alloc_len += (mb_cur_max() + tabsize + 1) * MAX_BUF_SIZE;
	    converted = charealloc(converted, alloc_len);
	}

1862
	/* If buf contains a tab character, interpret it. */
1863
	if (*buf_mb == '\t') {
1864
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
1865
1866
1867
1868
1869
1870
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i;

		for (i = 0; i < whitespace_len[0]; i++)
		    converted[index++] = whitespace[i];
	    } else
1871
#endif
1872
		converted[index++] = ' '; 
1873
	    start_col++;
1874
	    while (start_col % tabsize != 0) {
1875
		converted[index++] = ' ';
1876
1877
		start_col++;
	    }
1878
	/* If buf contains a control character, interpret it.  If buf
1879
1880
	 * contains an invalid multibyte control character, display it
	 * as such.*/
1881
	} else if (is_cntrl_mbchar(buf_mb)) {
1882
1883
	    char *ctrl_buf_mb = charalloc(mb_cur_max());
	    int ctrl_buf_mb_len, i;
1884

1885
	    converted[index++] = '^';
1886
1887
	    start_col++;

1888
1889
	    ctrl_buf_mb = control_mbrep(buf_mb, ctrl_buf_mb,
		&ctrl_buf_mb_len);
1890

1891
1892
	    for (i = 0; i < ctrl_buf_mb_len; i++)
		converted[index++] = ctrl_buf_mb[i];
1893

1894
	    start_col += mbwidth(ctrl_buf_mb);
1895

1896
	    free(ctrl_buf_mb);
1897
	/* If buf contains a space character, interpret it. */
1898
	} else if (*buf_mb == ' ') {
1899
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
1900
1901
1902
1903
1904
1905
1906
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i;

		for (i = whitespace_len[0]; i < whitespace_len[0] +
			whitespace_len[1]; i++)
		    converted[index++] = whitespace[i];
	    } else
1907
#endif
1908
		converted[index++] = ' '; 
1909
	    start_col++;
1910
1911
1912
	/* If buf contains a non-control character, interpret it.  If
	 * buf contains an invalid multibyte non-control character,
	 * display it as such. */
1913
	} else {
1914
1915
	    char *nctrl_buf_mb = charalloc(mb_cur_max());
	    int nctrl_buf_mb_len, i;
1916

1917
1918
	    nctrl_buf_mb = mbrep(buf_mb, nctrl_buf_mb,
		&nctrl_buf_mb_len);
1919

1920
1921
1922
1923
1924
1925
	    for (i = 0; i < nctrl_buf_mb_len; i++)
		converted[index++] = nctrl_buf_mb[i];

	    start_col += mbwidth(nctrl_buf_mb);

	    free(nctrl_buf_mb);
1926
1927
	}

1928
	start_index += buf_mb_len;
1929
1930
    }

1931
1932
    free(buf_mb);

1933
1934
1935
1936
    assert(alloc_len >= index + 1);

    /* Null terminate converted. */
    converted[index] = '\0';
1937
1938
1939

    /* Make sure converted takes up no more than len columns. */
    index = actual_x(converted, len);
1940
    null_at(&converted, index);
1941

1942
    return converted;
1943
1944
}

1945
1946
1947
1948
1949
1950
/* Display the path specified in path on the titlebar, along with the
 * current version of nano and whether the current file has been
 * modified.  If path is NULL, assume we're in normal editing mode and
 * display the current filename instead.  Otherwise, assume we're in the
 * file browser, and don't display whether the current file has been
 * modified. */
1951
void titlebar(const char *path)
Chris Allegretta's avatar
Chris Allegretta committed
1952
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1953
    int space = COLS;
1954
	/* The space we have available for display. */
1955
    size_t verlen = strlenpt(PACKAGE_STRING) + 1;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1956
1957
	/* The length of the version message in columns, plus one for
	 * padding. */
1958
    const char *prefix;
1959
	/* "DIR:", "File:", or "New Buffer".  Goes before filename. */
1960
    size_t prefixlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1961
	/* The length of the prefix in columns, plus one for padding. */
1962
    const char *state;
1963
1964
	/* "Modified", "View", or "".  Shows the state of this
	 * buffer. */
1965
    size_t statelen = 0;
1966
	/* The length of the state in columns, or the length of
1967
	 * "Modified" if the state is blank. */
1968
1969
    char *exppath = NULL;
	/* The file name, expanded for display. */
1970
    bool newfie = FALSE;
1971
	/* Do we say "New Buffer"? */
1972
    bool dots = FALSE;
1973
1974
	/* Do we put an ellipsis before the path? */

1975
    assert(path != NULL || openfile->filename != NULL);
Chris Allegretta's avatar
Chris Allegretta committed
1976

1977
    wattron(topwin, reverse_attr);
1978
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
1979

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1980
1981
1982
1983
    /* space has to be at least 4: two spaces before the version message,
     * at least one character of the version message, and one space
     * after the version message. */
    if (space < 4)
1984
1985
	space = 0;
    else {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1986
1987
1988
1989
	/* Limit verlen to 1/3 the length of the screen in columns,
	 * minus three columns for spaces. */
	if (verlen > (COLS / 3) - 3)
	    verlen = (COLS / 3) - 3;
1990
    }
Chris Allegretta's avatar
Chris Allegretta committed
1991

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1992
    if (space >= 4) {
1993
1994
	/* Add a space after the version message, and account for both
	 * it and the two spaces before it. */
1995
1996
	mvwaddnstr(topwin, 0, 2, PACKAGE_STRING,
		actual_x(PACKAGE_STRING, verlen));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1997
1998
1999
2000
	verlen += 3;

	/* Account for the full length of the version message. */
	space -= verlen;
2001
    }
Chris Allegretta's avatar
Chris Allegretta committed
2002

2003
2004
2005
2006
2007
2008
2009
2010
2011
#ifndef DISABLE_BROWSER
    /* Don't display the state if we're in the file browser. */
    if (path != NULL)
	state = "";
    else
#endif
	state = openfile->modified ? _("Modified") : ISSET(VIEW_MODE) ?
		_("View") : "";

2012
    statelen = strlenpt((state[0] != '\0') ? state : _("Modified"));
2013

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2014
2015
    /* If possible, add a space before state. */
    if (space > 0 && statelen < space)
2016
	statelen++;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2017
    else
2018
2019
2020
	goto the_end;

#ifndef DISABLE_BROWSER
2021
    /* path should be a directory if we're in the file browser. */
2022
2023
2024
2025
    if (path != NULL)
	prefix = _("DIR:");
    else
#endif
2026
    if (openfile->filename[0] == '\0') {
2027
	prefix = _("New Buffer");
2028
	newfie = TRUE;
2029
2030
    } else
	prefix = _("File:");
2031

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2032
    prefixlen = strnlenpt(prefix, space - statelen) + 1;
2033

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2034
    /* If newfie is FALSE, add a space after prefix. */
2035
    if (!newfie && prefixlen + statelen < space)
2036
2037
	prefixlen++;

2038
2039
    /* If we're not in the file browser, path should be the current
     * filename. */
2040
    if (path == NULL)
2041
	path = openfile->filename;
2042

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2043
    /* Account for the full lengths of the prefix and the state. */
2044
2045
2046
2047
    if (space >= prefixlen + statelen)
	space -= prefixlen + statelen;
    else
	space = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2048
	/* space is now the room we have for the filename. */
2049

2050
    if (!newfie) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2051
	size_t lenpt = strlenpt(path), start_col;
2052

2053
	dots = (lenpt >= space);
2054
2055
2056
2057
2058
2059
2060
2061

	if (dots) {
	    start_col = lenpt - space + 3;
	    space -= 3;
	} else
	    start_col = 0;

	exppath = display_string(path, start_col, space, FALSE);
2062
2063
2064
    }

    if (!dots) {
2065
2066
2067
	size_t exppathlen = newfie ? 0 : strlenpt(exppath);
	    /* The length of the expanded filename. */

2068
	/* There is room for the whole filename, so we center it. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2069
2070
	mvwaddnstr(topwin, 0, verlen + ((space - exppathlen) / 3),
		prefix, actual_x(prefix, prefixlen));
2071
	if (!newfie) {
2072
2073
2074
2075
2076
	    waddch(topwin, ' ');
	    waddstr(topwin, exppath);
	}
    } else {
	/* We will say something like "File: ...ename". */
2077
2078
	mvwaddnstr(topwin, 0, verlen - 1, prefix, actual_x(prefix,
		prefixlen));
2079
	if (space <= -3 || newfie)
2080
2081
	    goto the_end;
	waddch(topwin, ' ');
2082
2083
	waddnstr(topwin, "...", space + 3);
	if (space <= 0)
2084
	    goto the_end;
2085
	waddstr(topwin, exppath);
2086
2087
2088
2089
2090
    }

  the_end:
    free(exppath);

2091
    if (state[0] != '\0') {
2092
	if (statelen >= COLS - 1)
2093
2094
	    mvwaddnstr(topwin, 0, 0, state, actual_x(state, COLS));
	else {
2095
	    assert(COLS - statelen - 1 >= 0);
2096

2097
	    mvwaddnstr(topwin, 0, COLS - statelen - 1, state,
2098
		actual_x(state, statelen));
2099
	}
2100
    }
2101

2102
    wattroff(topwin, reverse_attr);
2103

2104
    wnoutrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
2105
    reset_cursor();
2106
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2107
2108
}

2109
2110
/* Mark the current file as modified if it isn't already, and then
 * update the titlebar to display the file's new status. */
2111
2112
void set_modified(void)
{
2113
2114
    if (!openfile->modified) {
	openfile->modified = TRUE;
2115
2116
2117
2118
	titlebar(NULL);
    }
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2119
2120
2121
/* Display a message on the statusbar, and set disable_cursorpos to
 * TRUE, so that the message won't be immediately overwritten if
 * constant cursor position display is on. */
2122
2123
2124
void statusbar(const char *msg, ...)
{
    va_list ap;
2125
2126
    char *bar, *foo;
    size_t start_x, foo_len;
2127
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2128
2129
    bool old_whitespace;
#endif
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143

    va_start(ap, msg);

    /* Curses mode is turned off.  If we use wmove() now, it will muck
     * up the terminal settings.  So we just use vfprintf(). */
    if (curses_ended) {
	vfprintf(stderr, msg, ap);
	va_end(ap);
	return;
    }

    /* Blank out the line. */
    blank_statusbar();

2144
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2145
2146
    old_whitespace = ISSET(WHITESPACE_DISPLAY);
    UNSET(WHITESPACE_DISPLAY);
2147
#endif
2148
2149
2150
2151
    bar = charalloc(mb_cur_max() * (COLS - 3));
    vsnprintf(bar, mb_cur_max() * (COLS - 3), msg, ap);
    va_end(ap);
    foo = display_string(bar, 0, COLS - 4, FALSE);
2152
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2153
2154
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);
2155
#endif
2156
2157
2158
    free(bar);
    foo_len = strlenpt(foo);
    start_x = (COLS - foo_len - 4) / 2;
2159

2160
    wmove(bottomwin, 0, start_x);
2161
    wattron(bottomwin, reverse_attr);
2162
2163
2164
2165
    waddstr(bottomwin, "[ ");
    waddstr(bottomwin, foo);
    free(foo);
    waddstr(bottomwin, " ]");
2166
    wattroff(bottomwin, reverse_attr);
2167
2168
2169
2170
2171
    wnoutrefresh(bottomwin);
    reset_cursor();
    wnoutrefresh(edit);
	/* Leave the cursor at its position in the edit window, not in
	 * the statusbar. */
2172

2173
    disable_cursorpos = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2174
2175
2176

    /* If we're doing quick statusbar blanking, and constant cursor
     * position display is off, blank the statusbar after only one
2177
2178
     * keystroke.  Otherwise, blank it after twenty-six keystrokes, as
     * Pico does. */
2179
    statusblank =
2180
#ifndef NANO_TINY
2181
	ISSET(QUICK_BLANK) && !ISSET(CONST_UPDATE) ? 1 :
2182
#endif
2183
	26;
2184
2185
}

2186
2187
/* Display the shortcut list in s on the last two rows of the bottom
 * portion of the window. */
2188
void bottombars(const shortcut *s)
Chris Allegretta's avatar
Chris Allegretta committed
2189
{
2190
    size_t i, colwidth, slen;
2191

Chris Allegretta's avatar
Chris Allegretta committed
2192
2193
2194
    if (ISSET(NO_HELP))
	return;

2195
2196
    if (s == main_list) {
	slen = MAIN_VISIBLE;
2197

2198
	assert(slen <= length_of_list(s));
2199
    } else {
2200
2201
	slen = length_of_list(s);

2202
	/* Don't show any more shortcuts than the main list does. */
2203
2204
2205
2206
	if (slen > MAIN_VISIBLE)
	    slen = MAIN_VISIBLE;
    }

2207
2208
2209
2210
    /* There will be this many characters per column, except for the
     * last two, which will be longer by (COLS % colwidth) columns so as
     * to not waste space.  We need at least three columns to display
     * anything properly. */
2211
    colwidth = COLS / ((slen / 2) + (slen % 2));
Chris Allegretta's avatar
Chris Allegretta committed
2212

2213
    blank_bottombars();
2214

2215
    for (i = 0; i < slen; i++, s = s->next) {
2216
	const char *keystr;
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
	char foo[4] = "";

	/* Yucky sentinel values that we can't handle a better way. */
	if (s->ctrlval == NANO_CONTROL_SPACE)
	    strcpy(foo, "^ ");
	else if (s->ctrlval == NANO_CONTROL_8)
	    strcpy(foo, "^?");
	/* Normal values.  Assume that the shortcut has an equivalent
	 * control key, meta key sequence, or both. */
	else if (s->ctrlval != NANO_NO_KEY)
	    sprintf(foo, "^%c", s->ctrlval + 64);
	else if (s->metaval != NANO_NO_KEY)
	    sprintf(foo, "M-%c", toupper(s->metaval));

	keystr = foo;
2232
2233

	wmove(bottomwin, 1 + i % 2, (i / 2) * colwidth);
2234
	onekey(keystr, s->desc, colwidth + (COLS % colwidth));
Chris Allegretta's avatar
Chris Allegretta committed
2235
    }
2236

2237
2238
    wnoutrefresh(bottomwin);
    reset_cursor();
2239
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2240
2241
}

2242
2243
2244
2245
2246
2247
/* Write a shortcut key to the help area at the bottom of the window.
 * keystroke is e.g. "^G" and desc is e.g. "Get Help".  We are careful
 * to write at most len characters, even if len is very small and
 * keystroke and desc are long.  Note that waddnstr(,,(size_t)-1) adds
 * the whole string!  We do not bother padding the entry with blanks. */
void onekey(const char *keystroke, const char *desc, size_t len)
Chris Allegretta's avatar
Chris Allegretta committed
2248
{
2249
2250
    size_t keystroke_len = strlenpt(keystroke) + 1;

2251
2252
    assert(keystroke != NULL && desc != NULL);

2253
    wattron(bottomwin, reverse_attr);
2254
    waddnstr(bottomwin, keystroke, actual_x(keystroke, len));
2255
    wattroff(bottomwin, reverse_attr);
2256
2257
2258
2259
2260
2261

    if (len > keystroke_len)
	len -= keystroke_len;
    else
	len = 0;

2262
2263
    if (len > 0) {
	waddch(bottomwin, ' ');
2264
	waddnstr(bottomwin, desc, actual_x(desc, len));
Chris Allegretta's avatar
Chris Allegretta committed
2265
2266
2267
    }
}

2268
2269
/* Reset current_y, based on the position of current, and put the cursor
 * in the edit window at (current_y, current_x). */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2270
2271
void reset_cursor(void)
{
2272
2273
    /* If we haven't opened any files yet, put the cursor in the top
     * left corner of the edit window and get out. */
2274
    if (openfile == NULL) {
2275
	wmove(edit, 0, 0);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2276
	return;
2277
    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2278

2279
2280
2281
    openfile->current_y = openfile->current->lineno -
	openfile->edittop->lineno;
    if (openfile->current_y < editwinrows) {
2282
	size_t xpt = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2283

2284
	wmove(edit, openfile->current_y, xpt - get_page_start(xpt));
2285
     }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2286
}
Chris Allegretta's avatar
Chris Allegretta committed
2287

2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
/* edit_draw() takes care of the job of actually painting a line into
 * the edit window.  fileptr is the line to be painted, at row line of
 * the window.  converted is the actual string to be written to the
 * window, with tabs and control characters replaced by strings of
 * regular characters.  start is the column number of the first
 * character of this page.  That is, the first character of converted
 * corresponds to character number actual_x(fileptr->data, start) of the
 * line. */
void edit_draw(const filestruct *fileptr, const char *converted, int
	line, size_t start)
Chris Allegretta's avatar
Chris Allegretta committed
2298
{
2299
#if !defined(NANO_TINY) || defined(ENABLE_COLOR)
2300
2301
2302
2303
2304
2305
2306
2307
2308
    size_t startpos = actual_x(fileptr->data, start);
	/* The position in fileptr->data of the leftmost character
	 * that displays at least partially on the window. */
    size_t endpos = actual_x(fileptr->data, start + COLS - 1) + 1;
	/* The position in fileptr->data of the first character that is
	 * completely off the window to the right.
	 *
	 * Note that endpos might be beyond the null terminator of the
	 * string. */
2309
2310
#endif

2311
    assert(openfile != NULL && fileptr != NULL && converted != NULL);
2312
    assert(strlenpt(converted) <= COLS);
2313

2314
    /* Just paint the string in any case (we'll add color or reverse on
2315
     * just the text that needs it). */
2316
    mvwaddstr(edit, line, 0, converted);
2317

Chris Allegretta's avatar
Chris Allegretta committed
2318
#ifdef ENABLE_COLOR
2319
2320
2321
2322
    /* If color syntaxes are available and turned on, we need to display
     * them. */
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX)) {
	const colortype *tmpcolor = openfile->colorstrings;
2323
2324
2325
2326
2327

	for (; tmpcolor != NULL; tmpcolor = tmpcolor->next) {
	    int x_start;
		/* Starting column for mvwaddnstr.  Zero-based. */
	    int paintlen;
2328
		/* Number of chars to paint on this line.  There are COLS
2329
		 * characters on a whole line. */
2330
	    size_t index;
2331
		/* Index in converted where we paint. */
2332
2333
2334
2335
	    regmatch_t startmatch;
		/* Match position for start_regex. */
	    regmatch_t endmatch;
		/* Match position for end_regex. */
2336
2337
2338
2339

	    if (tmpcolor->bright)
		wattron(edit, A_BOLD);
	    wattron(edit, COLOR_PAIR(tmpcolor->pairnum));
2340
2341
2342
	    /* Two notes about regexec().  A return value of zero means
	     * that there is a match.  Also, rm_eo is the first
	     * non-matching character after the match. */
2343
2344

	    /* First case, tmpcolor is a single-line expression. */
2345
	    if (tmpcolor->end == NULL) {
2346
2347
2348
		size_t k = 0;

		/* We increment k by rm_eo, to move past the end of the
2349
2350
2351
2352
2353
2354
2355
2356
		 * last match.  Even though two matches may overlap, we
		 * want to ignore them, so that we can highlight
		 * C-strings correctly. */
		while (k < endpos) {
		    /* Note the fifth parameter to regexec().  It says
		     * not to match the beginning-of-line character
		     * unless k is 0.  If regexec() returns REG_NOMATCH,
		     * there are no more matches in the line. */
2357
		    if (regexec(tmpcolor->start, &fileptr->data[k], 1,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2358
2359
			&startmatch, (k == 0) ? 0 : REG_NOTBOL) ==
			REG_NOMATCH)
2360
			break;
2361
2362
		    /* Translate the match to the beginning of the
		     * line. */
2363
2364
		    startmatch.rm_so += k;
		    startmatch.rm_eo += k;
2365
2366
		    if (startmatch.rm_so == startmatch.rm_eo) {
			startmatch.rm_eo++;
2367
2368
			statusbar(
				_("Refusing zero-length regex match"));
2369
		    } else if (startmatch.rm_so < endpos &&
2370
			startmatch.rm_eo > startpos) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2371
2372
			x_start = (startmatch.rm_so <= startpos) ? 0 :
				strnlenpt(fileptr->data,
2373
				startmatch.rm_so) - start;
2374

2375
2376
2377
			index = actual_x(converted, x_start);

			paintlen = actual_x(converted + index,
2378
2379
				strnlenpt(fileptr->data,
				startmatch.rm_eo) - start - x_start);
2380
2381
2382

			assert(0 <= x_start && 0 <= paintlen);

2383
2384
			mvwaddnstr(edit, line, x_start, converted +
				index, paintlen);
2385
		    }
2386
		    k = startmatch.rm_eo;
Chris Allegretta's avatar
Chris Allegretta committed
2387
		}
2388
	    } else {
2389
		/* This is a multi-line regex.  There are two steps.
2390
2391
2392
2393
2394
2395
		 * First, we have to see if the beginning of the line is
		 * colored by a start on an earlier line, and an end on
		 * this line or later.
		 *
		 * We find the first line before fileptr matching the
		 * start.  If every match on that line is followed by an
2396
2397
2398
2399
		 * end, then go to step two.  Otherwise, find the next
		 * line after start_line matching the end.  If that line
		 * is not before fileptr, then paint the beginning of
		 * this line. */
2400
		const filestruct *start_line = fileptr->prev;
2401
		    /* The first line before fileptr matching start. */
2402
		regoff_t start_col;
2403
		    /* Where it starts in that line. */
2404
2405
		const filestruct *end_line;

2406
		while (start_line != NULL && regexec(tmpcolor->start,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2407
2408
			start_line->data, 1, &startmatch, 0) ==
			REG_NOMATCH) {
2409
2410
		    /* If there is an end on this line, there is no need
		     * to look for starts on earlier lines. */
2411
2412
		    if (regexec(tmpcolor->end, start_line->data, 0,
			NULL, 0) == 0)
2413
2414
2415
			goto step_two;
		    start_line = start_line->prev;
		}
2416
2417
2418
2419
2420
2421
		if (startmatch.rm_so == startmatch.rm_eo) {
		    startmatch.rm_eo++;
		    statusbar(_("Refusing zero-length regex match"));
		} else {
		    /* No start found, so skip to the next step. */
		    if (start_line == NULL)
2422
			goto step_two;
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
		    /* Now start_line is the first line before fileptr
		     * containing a start match.  Is there a start on
		     * this line not followed by an end on this line? */
		    start_col = 0;
		    while (TRUE) {
			start_col += startmatch.rm_so;
			startmatch.rm_eo -= startmatch.rm_so;
			if (regexec(tmpcolor->end, start_line->data +
				start_col + startmatch.rm_eo, 0, NULL,
				(start_col + startmatch.rm_eo == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH)
			    /* No end found after this start. */
			    break;
			start_col++;
			if (regexec(tmpcolor->start, start_line->data +
				start_col, 1, &startmatch,
				REG_NOTBOL) == REG_NOMATCH)
			    /* No later start on this line. */
			    goto step_two;
		    }
		    /* Indeed, there is a start not followed on this
		     * line by an end. */

		    /* We have already checked that there is no end
		     * before fileptr and after the start.  Is there an
		     * end after the start at all?  We don't paint
		     * unterminated starts. */
		    end_line = fileptr;
		    while (end_line != NULL && regexec(tmpcolor->end,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2452
			end_line->data, 1, &endmatch, 0) == REG_NOMATCH)
2453
			end_line = end_line->next;
2454

2455
2456
		    /* No end found, or it is too early. */
		    if (end_line == NULL || (end_line == fileptr &&
2457
			endmatch.rm_eo <= startpos))
2458
			goto step_two;
2459

2460
2461
2462
2463
2464
2465
		    /* Now paint the start of fileptr. */
		    if (end_line != fileptr)
			/* If the start of fileptr is on a different
			 * line from the end, paintlen is -1, meaning
			 * that everything on the line gets painted. */
			paintlen = -1;
2466
		    else
2467
2468
2469
2470
2471
2472
			/* Otherwise, paintlen is the expanded location
			 * of the end of the match minus the expanded
			 * location of the beginning of the page. */
			paintlen = actual_x(converted,
				strnlenpt(fileptr->data,
				endmatch.rm_eo) - start);
2473

2474
		    mvwaddnstr(edit, line, 0, converted, paintlen);
2475

2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
  step_two:
		    /* Second step, we look for starts on this line. */
		    start_col = 0;

		    while (start_col < endpos) {
			if (regexec(tmpcolor->start, fileptr->data +
				start_col, 1, &startmatch, (start_col ==
				0) ? 0 : REG_NOTBOL) == REG_NOMATCH ||
				start_col + startmatch.rm_so >= endpos)
			    /* No more starts on this line. */
			    break;
			/* Translate the match to be relative to the
2488
			 * beginning of the line. */
2489
2490
2491
2492
			startmatch.rm_so += start_col;
			startmatch.rm_eo += start_col;

			x_start = (startmatch.rm_so <= startpos) ? 0 :
2493
				strnlenpt(fileptr->data,
2494
				startmatch.rm_so) - start;
2495

2496
			index = actual_x(converted, x_start);
2497

2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
			if (regexec(tmpcolor->end, fileptr->data +
				startmatch.rm_eo, 1, &endmatch,
				(startmatch.rm_eo == 0) ? 0 :
				REG_NOTBOL) == 0) {
			    /* Translate the end match to be relative to
			     * the beginning of the line. */
			    endmatch.rm_so += startmatch.rm_eo;
			    endmatch.rm_eo += startmatch.rm_eo;
			    /* There is an end on this line.  But does
			     * it appear on this page, and is the match
			     * more than zero characters long? */
			    if (endmatch.rm_eo > startpos &&
				endmatch.rm_eo > startmatch.rm_so) {
				paintlen = actual_x(converted + index,
					strnlenpt(fileptr->data,
					endmatch.rm_eo) - start -
					x_start);
2515

2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
				assert(0 <= x_start && x_start < COLS);

				mvwaddnstr(edit, line, x_start,
					converted + index, paintlen);
			    }
			} else {
			    /* There is no end on this line.  But we
			     * haven't yet looked for one on later
			     * lines. */
			    end_line = fileptr->next;

			    while (end_line != NULL &&
2528
2529
				regexec(tmpcolor->end, end_line->data,
				0, NULL, 0) == REG_NOMATCH)
2530
				end_line = end_line->next;
2531

2532
2533
			    if (end_line != NULL) {
				assert(0 <= x_start && x_start < COLS);
2534

2535
2536
2537
2538
2539
2540
2541
				mvwaddnstr(edit, line, x_start,
					converted + index, -1);
				/* We painted to the end of the line, so
				 * don't bother checking any more
				 * starts. */
				break;
			    }
2542
			}
2543
			start_col = startmatch.rm_so + 1;
2544
		    }
2545
2546
		}
	    }
2547

2548
2549
	    wattroff(edit, A_BOLD);
	    wattroff(edit, COLOR_PAIR(tmpcolor->pairnum));
2550
	}
2551
    }
2552
#endif /* ENABLE_COLOR */
2553

2554
#ifndef NANO_TINY
2555
    /* If the mark is on, we need to display it. */
2556
    if (openfile->mark_set && (fileptr->lineno <=
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2557
	openfile->mark_begin->lineno || fileptr->lineno <=
2558
	openfile->current->lineno) && (fileptr->lineno >=
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2559
	openfile->mark_begin->lineno || fileptr->lineno >=
2560
	openfile->current->lineno)) {
2561
	/* fileptr is at least partially selected. */
2562
	const filestruct *top;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2563
	    /* Either current or mark_begin, whichever is first. */
2564
	size_t top_x;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2565
	    /* current_x or mark_begin_x, corresponding to top. */
2566
2567
	const filestruct *bot;
	size_t bot_x;
2568
	int x_start;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2569
	    /* Starting column for mvwaddnstr().  Zero-based. */
2570
	int paintlen;
2571
	    /* Number of chars to paint on this line.  There are COLS
2572
	     * characters on a whole line. */
2573
	size_t index;
2574
	    /* Index in converted where we paint. */
2575

2576
	mark_order(&top, &top_x, &bot, &bot_x, NULL);
2577
2578
2579
2580
2581

	if (top->lineno < fileptr->lineno || top_x < startpos)
	    top_x = startpos;
	if (bot->lineno > fileptr->lineno || bot_x > endpos)
	    bot_x = endpos;
Chris Allegretta's avatar
Chris Allegretta committed
2582

2583
	/* The selected bit of fileptr is on this page. */
2584
2585
	if (top_x < endpos && bot_x > startpos) {
	    assert(startpos <= top_x);
2586
2587
2588
2589

	    /* x_start is the expanded location of the beginning of the
	     * mark minus the beginning of the page. */
	    x_start = strnlenpt(fileptr->data, top_x) - start;
2590
2591

	    if (bot_x >= endpos)
2592
2593
2594
2595
		/* If the end of the mark is off the page, paintlen is
		 * -1, meaning that everything on the line gets
		 * painted. */
		paintlen = -1;
2596
	    else
2597
2598
2599
		/* Otherwise, paintlen is the expanded location of the
		 * end of the mark minus the expanded location of the
		 * beginning of the mark. */
2600
2601
		paintlen = strnlenpt(fileptr->data, bot_x) -
			(x_start + start);
2602
2603
2604
2605
2606
2607
2608
2609

	    /* If x_start is before the beginning of the page, shift
	     * paintlen x_start characters to compensate, and put
	     * x_start at the beginning of the page. */
	    if (x_start < 0) {
		paintlen += x_start;
		x_start = 0;
	    }
2610
2611
2612

	    assert(x_start >= 0 && x_start <= strlen(converted));

2613
	    index = actual_x(converted, x_start);
2614

2615
2616
2617
	    if (paintlen > 0)
		paintlen = actual_x(converted + index, paintlen);

2618
	    wattron(edit, reverse_attr);
2619
	    mvwaddnstr(edit, line, x_start, converted + index,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2620
		paintlen);
2621
	    wattroff(edit, reverse_attr);
Chris Allegretta's avatar
Chris Allegretta committed
2622
	}
2623
    }
2624
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
2625
2626
}

2627
/* Just update one line in the edit buffer.  This is basically a wrapper
2628
2629
 * for edit_draw().  The line will be displayed starting with
 * fileptr->data[index].  Likely arguments are current_x or zero. */
2630
void update_line(const filestruct *fileptr, size_t index)
Chris Allegretta's avatar
Chris Allegretta committed
2631
{
2632
    int line;
2633
	/* The line in the edit window that we want to update. */
2634
2635
2636
2637
    char *converted;
	/* fileptr->data converted to have tabs and control characters
	 * expanded. */
    size_t page_start;
Chris Allegretta's avatar
Chris Allegretta committed
2638

2639
    assert(fileptr != NULL);
2640

2641
    line = fileptr->lineno - openfile->edittop->lineno;
Chris Allegretta's avatar
Chris Allegretta committed
2642

2643
2644
    /* We assume the line numbers are valid.  Is that really true? */
    assert(line < 0 || line == check_linenumbers(fileptr));
2645

2646
2647
    if (line < 0 || line >= editwinrows)
	return;
2648

2649
    /* First, blank out the line. */
2650
    blank_line(edit, line, 0, COLS);
2651

2652
2653
    /* Next, convert variables that index the line to their equivalent
     * positions in the expanded line. */
2654
    index = strnlenpt(fileptr->data, index);
2655
    page_start = get_page_start(index);
2656

2657
2658
    /* Expand the line, replacing tabs with spaces, and control
     * characters with their displayed forms. */
2659
    converted = display_string(fileptr->data, page_start, COLS, TRUE);
Chris Allegretta's avatar
Chris Allegretta committed
2660

2661
    /* Paint the line. */
2662
    edit_draw(fileptr, converted, line, page_start);
2663
    free(converted);
Chris Allegretta's avatar
Chris Allegretta committed
2664

2665
    if (page_start > 0)
Chris Allegretta's avatar
Chris Allegretta committed
2666
	mvwaddch(edit, line, 0, '$');
2667
    if (strlenpt(fileptr->data) > page_start + COLS)
2668
	mvwaddch(edit, line, COLS - 1, '$');
Chris Allegretta's avatar
Chris Allegretta committed
2669
2670
}

2671
2672
/* Return TRUE if we need an update after moving horizontally, and FALSE
 * otherwise.  We need one if the mark is on or if old_pww and
2673
 * placewewant are on different pages. */
2674
bool need_horizontal_update(size_t old_pww)
2675
2676
{
    return
2677
#ifndef NANO_TINY
2678
	openfile->mark_set ||
2679
#endif
2680
2681
	get_page_start(old_pww) !=
	get_page_start(openfile->placewewant);
2682
2683
}

2684
2685
2686
2687
/* Return TRUE if we need an update after moving vertically, and FALSE
 * otherwise.  We need one if the mark is on or if old_pww and
 * placewewant are on different pages. */
bool need_vertical_update(size_t old_pww)
2688
2689
{
    return
2690
#ifndef NANO_TINY
2691
	openfile->mark_set ||
2692
#endif
2693
2694
	get_page_start(old_pww) !=
	get_page_start(openfile->placewewant);
2695
2696
2697
2698
2699
}

/* Scroll the edit window in the given direction and the given number
 * of lines, and draw new lines on the blank lines left after the
 * scrolling.  direction is the direction to scroll, either UP or DOWN,
2700
 * and nlines is the number of lines to scroll.  We change edittop, and
2701
2702
 * assume that current and current_x are up to date.  We also assume
 * that scrollok(edit) is FALSE. */
2703
void edit_scroll(scroll_dir direction, ssize_t nlines)
2704
{
2705
    bool do_redraw = need_vertical_update(0);
2706
    const filestruct *foo;
2707
    ssize_t i;
2708

2709
2710
    /* Don't bother scrolling less than one line. */
    if (nlines < 1)
2711
2712
	return;

2713
2714
2715
    /* Part 1: nlines is the number of lines we're going to scroll the
     * text of the edit window. */

2716
    /* Move the top line of the edit window up or down (depending on the
2717
2718
     * value of direction) nlines lines, or as many lines as we can if
     * there are fewer than nlines lines available. */
2719
2720
    for (i = nlines; i > 0; i--) {
	if (direction == UP) {
2721
	    if (openfile->edittop == openfile->fileage)
2722
		break;
2723
	    openfile->edittop = openfile->edittop->prev;
2724
	} else {
2725
	    if (openfile->edittop == openfile->filebot)
2726
		break;
2727
	    openfile->edittop = openfile->edittop->next;
2728
2729
2730
	}
    }

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2731
    /* Limit nlines to the number of lines we could scroll. */
2732
    nlines -= i;
2733

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2734
2735
2736
    /* Don't bother scrolling zero lines or more than the number of
     * lines in the edit window minus one; in both cases, get out, and
     * in the latter case, call edit_refresh() beforehand. */
2737
2738
2739
2740
2741
2742
2743
    if (nlines == 0)
	return;

    if (nlines >= editwinrows) {
	edit_refresh();
	return;
    }
2744
2745
2746

    /* Scroll the text of the edit window up or down nlines lines,
     * depending on the value of direction. */
2747
2748
2749
2750
    scrollok(edit, TRUE);
    wscrl(edit, (direction == UP) ? -nlines : nlines);
    scrollok(edit, FALSE);

2751
2752
2753
    /* Part 2: nlines is the number of lines in the scrolled region of
     * the edit window that we need to draw. */

2754
2755
2756
2757
2758
    /* If the top or bottom line of the file is now visible in the edit
     * window, we need to draw the entire edit window. */
    if ((direction == UP && openfile->edittop == openfile->fileage) ||
	(direction == DOWN && openfile->edittop->lineno + editwinrows -
	1 >= openfile->filebot->lineno))
2759
	nlines = editwinrows;
2760

2761
2762
2763
2764
2765
2766
    /* If the scrolled region contains only one line, and the line
     * before it is visible in the edit window, we need to draw it too.
     * If the scrolled region contains more than one line, and the lines
     * before and after the scrolled region are visible in the edit
     * window, we need to draw them too. */
    nlines += (nlines == 1) ? 1 : 2;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2767

2768
2769
    if (nlines > editwinrows)
	nlines = editwinrows;
2770
2771
2772

    /* If we scrolled up, we're on the line before the scrolled
     * region. */
2773
    foo = openfile->edittop;
2774

2775
2776
    /* If we scrolled down, move down to the line before the scrolled
     * region. */
2777
    if (direction == DOWN) {
2778
	for (i = editwinrows - nlines; i > 0 && foo != NULL; i--)
2779
2780
2781
	    foo = foo->next;
    }

2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
    /* Draw new lines on any blank lines before or inside the scrolled
     * region.  If we scrolled down and we're on the top line, or if we
     * scrolled up and we're on the bottom line, the line won't be
     * blank, so we don't need to draw it unless the mark is on or we're
     * not on the first page. */
    for (i = nlines; i > 0 && foo != NULL; i--) {
	if ((i == nlines && direction == DOWN) || (i == 1 &&
		direction == UP)) {
	    if (do_redraw)
		update_line(foo, (foo == openfile->current) ?
			openfile->current_x : 0);
	} else
	    update_line(foo, (foo == openfile->current) ?
2795
		openfile->current_x : 0);
2796
	foo = foo->next;
2797
2798
2799
2800
    }
}

/* Update any lines between old_current and current that need to be
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2801
 * updated.  Use this if we've moved without changing any text. */
2802
void edit_redraw(const filestruct *old_current, size_t old_pww)
2803
{
2804
    bool do_redraw = need_vertical_update(0) ||
2805
	need_vertical_update(old_pww);
2806
    const filestruct *foo = NULL;
2807

2808
2809
    /* If either old_current or current is offscreen, scroll the edit
     * window until it's onscreen and get out. */
2810
2811
2812
2813
2814
    if (old_current->lineno < openfile->edittop->lineno ||
	old_current->lineno >= openfile->edittop->lineno +
	editwinrows || openfile->current->lineno <
	openfile->edittop->lineno || openfile->current->lineno >=
	openfile->edittop->lineno + editwinrows) {
2815
2816
2817
	filestruct *old_edittop = openfile->edittop;
	ssize_t nlines;

2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
#ifndef NANO_TINY
	/* If the mark is on, update all the lines between old_current
	 * and the old last line of the edit window. */
	if (openfile->mark_set) {
	    ssize_t old_last_lineno = (old_edittop->lineno +
		editwinrows <= openfile->filebot->lineno) ?
		old_edittop->lineno + editwinrows :
		openfile->filebot->lineno;

	    foo = old_current;

	    while (foo->lineno != old_last_lineno) {
		update_line(foo, 0);

		foo = (foo->lineno > old_last_lineno) ? foo->prev :
			foo->next;
	    }
	}
#endif /* !NANO_TINY */

2838
2839
2840
2841
	/* Put edittop in range of current, get the difference in lines
	 * between the original edittop and the current edittop, and
	 * then restore the original edittop. */
	edit_update(
2842
#ifndef NANO_TINY
2843
2844
2845
2846
2847
2848
2849
2850
		ISSET(SMOOTH_SCROLL) ? NONE :
#endif
		CENTER);

	nlines = openfile->edittop->lineno - old_edittop->lineno;

	openfile->edittop = old_edittop;

2851
2852
2853
2854
2855
	/* Update old_current if we're not on the first page and/or
	 * we're not on the same page as before. */
	if (do_redraw)
	    update_line(old_current, 0);

2856
2857
	/* Scroll the edit window up or down until edittop is in range
	 * of current. */
2858
2859
2860
2861
2862
	if (nlines < 0)
	    edit_scroll(UP, -nlines);
	else
	    edit_scroll(DOWN, nlines);

2863
2864
#ifndef NANO_TINY
	/* If the mark is on, update all the lines between the old last
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2865
	 * line of the edit window and edittop. */
2866
	if (openfile->mark_set) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2867
	    while (foo != openfile->edittop) {
2868
2869
		update_line(foo, 0);

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2870
		foo = (foo->lineno > openfile->edittop->lineno) ?
2871
2872
2873
2874
2875
			foo->prev : foo->next;
	    }
	}
#endif /* !NANO_TINY */

2876
2877
2878
	return;
    }

2879
2880
2881
    /* Update old_current and current if we're not on the first page
     * and/or we're not on the same page as before.  If the mark is on,
     * update all the lines between old_current and current too. */
2882
    foo = old_current;
2883

2884
    while (foo != openfile->current) {
2885
	if (do_redraw)
2886
	    update_line(foo, 0);
2887

2888
#ifndef NANO_TINY
2889
	if (!openfile->mark_set)
2890
2891
#endif
	    break;
2892

2893
#ifndef NANO_TINY
2894
2895
	foo = (foo->lineno > openfile->current->lineno) ? foo->prev :
		foo->next;
2896
#endif
2897
    }
2898

2899
    if (do_redraw)
2900
	update_line(openfile->current, openfile->current_x);
2901
2902
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2903
2904
/* Refresh the screen without changing the position of lines.  Use this
 * if we've moved and changed text. */
Chris Allegretta's avatar
Chris Allegretta committed
2905
2906
void edit_refresh(void)
{
2907
2908
    const filestruct *foo;
    int nlines;
2909

2910
2911
2912
    if (openfile->current->lineno < openfile->edittop->lineno ||
	openfile->current->lineno >= openfile->edittop->lineno +
	editwinrows)
2913
2914
	/* Put the top line of the edit window in range of the current
	 * line. */
2915
	edit_update(
2916
#ifndef NANO_TINY
2917
		ISSET(SMOOTH_SCROLL) ? NONE :
2918
2919
#endif
		CENTER);
Chris Allegretta's avatar
Chris Allegretta committed
2920

2921
2922
    foo = openfile->edittop;

2923
#ifdef DEBUG
2924
    fprintf(stderr, "edit_refresh(): edittop->lineno = %ld\n", (long)openfile->edittop->lineno);
2925
#endif
2926

2927
    for (nlines = 0; nlines < editwinrows && foo != NULL; nlines++) {
2928
	update_line(foo, (foo == openfile->current) ?
2929
		openfile->current_x : 0);
2930
2931
2932
	foo = foo->next;
    }

2933
    for (; nlines < editwinrows; nlines++)
2934
2935
2936
	blank_line(edit, nlines, 0, COLS);

    reset_cursor();
2937
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2938
2939
}

2940
2941
2942
2943
/* Move edittop to put it in range of current, keeping current in the
 * same place.  location determines how we move it: if it's CENTER, we
 * center current, and if it's NONE, we put current current_y lines
 * below edittop. */
2944
void edit_update(update_type location)
Chris Allegretta's avatar
Chris Allegretta committed
2945
{
2946
    filestruct *foo = openfile->current;
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
    int goal;

    /* If location is CENTER, we move edittop up (editwinrows / 2)
     * lines.  This puts current at the center of the screen.  If
     * location is NONE, we move edittop up current_y lines if current_y
     * is in range of the screen, 0 lines if current_y is less than 0,
     * or (editwinrows - 1) lines if current_y is greater than
     * (editwinrows - 1).  This puts current at the same place on the
     * screen as before, or at the top or bottom of the screen if
     * edittop is beyond either. */
    if (location == CENTER)
	goal = editwinrows / 2;
    else {
	goal = openfile->current_y;
2961

2962
2963
2964
	/* Limit goal to (editwinrows - 1) lines maximum. */
	if (goal > editwinrows - 1)
	    goal = editwinrows - 1;
Chris Allegretta's avatar
Chris Allegretta committed
2965
    }
2966

2967
    for (; goal > 0 && foo->prev != NULL; goal--)
2968
2969
	foo = foo->prev;

2970
    openfile->edittop = foo;
Chris Allegretta's avatar
Chris Allegretta committed
2971
2972
}

2973
/* Unconditionally redraw the entire screen. */
2974
void total_redraw(void)
2975
{
2976
2977
2978
2979
2980
2981
2982
2983
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 3: Slang doesn't define
     * curscr. */
    SLsmg_touch_screen();
    SLsmg_refresh();
#else
    wrefresh(curscr);
#endif
2984
2985
}

2986
2987
/* Unconditionally redraw the entire screen, and then refresh it using
 * the current file. */
2988
2989
void total_refresh(void)
{
2990
    total_redraw();
2991
    titlebar(NULL);
2992
    edit_refresh();
2993
    bottombars(currshortcut);
2994
2995
}

2996
2997
/* Display the main shortcut list on the last two rows of the bottom
 * portion of the window. */
2998
2999
3000
3001
3002
void display_main_list(void)
{
    bottombars(main_list);
}

3003
3004
3005
3006
3007
3008
/* If constant is TRUE, we display the current cursor position only if
 * disable_cursorpos is FALSE.  Otherwise, we display it
 * unconditionally and set disable_cursorpos to FALSE.  If constant is
 * TRUE and disable_cursorpos is TRUE, we also set disable_cursorpos to
 * FALSE, so that we leave the current statusbar alone this time, and
 * display the current cursor position next time. */
3009
void do_cursorpos(bool constant)
Chris Allegretta's avatar
Chris Allegretta committed
3010
{
3011
    filestruct *f;
3012
    char c;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3013
    size_t i, cur_xpt = xplustabs() + 1;
3014
    size_t cur_lenpt = strlenpt(openfile->current->data) + 1;
3015
    int linepct, colpct, charpct;
Chris Allegretta's avatar
Chris Allegretta committed
3016

3017
    assert(openfile->fileage != NULL && openfile->current != NULL);
3018

3019
    f = openfile->current->next;
3020
    c = openfile->current->data[openfile->current_x];
3021
3022

    openfile->current->next = NULL;
3023
    openfile->current->data[openfile->current_x] = '\0';
3024
3025
3026

    i = get_totsize(openfile->fileage, openfile->current);

3027
    openfile->current->data[openfile->current_x] = c;
3028
    openfile->current->next = f;
3029

3030
3031
    if (constant && disable_cursorpos) {
	disable_cursorpos = FALSE;
3032
	return;
3033
    }
Chris Allegretta's avatar
Chris Allegretta committed
3034

3035
3036
    /* Display the current cursor position on the statusbar, and set 
     * disable_cursorpos to FALSE. */
3037
3038
    linepct = 100 * openfile->current->lineno /
	openfile->filebot->lineno;
3039
    colpct = 100 * cur_xpt / cur_lenpt;
3040
3041
    charpct = (openfile->totsize == 0) ? 0 : 100 * i /
	openfile->totsize;
3042
3043

    statusbar(
3044
	_("line %ld/%ld (%d%%), col %lu/%lu (%d%%), char %lu/%lu (%d%%)"),
3045
	(long)openfile->current->lineno,
3046
	(long)openfile->filebot->lineno, linepct,
3047
	(unsigned long)cur_xpt, (unsigned long)cur_lenpt, colpct,
3048
	(unsigned long)i, (unsigned long)openfile->totsize, charpct);
3049

3050
    disable_cursorpos = FALSE;
Chris Allegretta's avatar
Chris Allegretta committed
3051
3052
}

3053
/* Unconditionally display the current cursor position. */
3054
void do_cursorpos_void(void)
3055
{
3056
    do_cursorpos(FALSE);
3057
3058
}

3059
3060
/* Highlight the current word being replaced or spell checked.  We
 * expect word to have tabs and control characters expanded. */
3061
void do_replace_highlight(bool highlight, const char *word)
Chris Allegretta's avatar
Chris Allegretta committed
3062
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3063
    size_t y = xplustabs(), word_len = strlenpt(word);
Chris Allegretta's avatar
Chris Allegretta committed
3064

3065
    y = get_page_start(y) + COLS - y;
3066
	/* Now y is the number of columns that we can display on this
3067
	 * line. */
Chris Allegretta's avatar
Chris Allegretta committed
3068

3069
3070
3071
3072
3073
    assert(y > 0);

    if (word_len > y)
	y--;

Chris Allegretta's avatar
Chris Allegretta committed
3074
    reset_cursor();
Chris Allegretta's avatar
Chris Allegretta committed
3075

3076
    if (highlight)
3077
	wattron(edit, reverse_attr);
Chris Allegretta's avatar
Chris Allegretta committed
3078

3079
#ifdef HAVE_REGEX_H
3080
3081
    /* This is so we can show zero-length regexes. */
    if (word_len == 0)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3082
	waddch(edit, ' ');
3083
    else
3084
#endif
3085
	waddnstr(edit, word, actual_x(word, y));
3086
3087
3088

    if (word_len > y)
	waddch(edit, '$');
Chris Allegretta's avatar
Chris Allegretta committed
3089

3090
    if (highlight)
3091
	wattroff(edit, reverse_attr);
Chris Allegretta's avatar
Chris Allegretta committed
3092
3093
}

3094
#ifdef NANO_EXTRA
3095
#define CREDIT_LEN 55
3096
3097
#define XLCREDIT_LEN 8

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3098
3099
/* Easter egg: Display credits.  Assume nodelay(edit) and scrollok(edit)
 * are FALSE. */
3100
3101
void do_credits(void)
{
3102
3103
    bool old_more_space = ISSET(MORE_SPACE);
    bool old_no_help = ISSET(NO_HELP);
3104
    int kbinput = ERR, crpos = 0, xlpos = 0;
3105
3106
3107
    const char *credits[CREDIT_LEN] = {
	NULL,				/* "The nano text editor" */
	NULL,				/* "version" */
Chris Allegretta's avatar
Chris Allegretta committed
3108
3109
	VERSION,
	"",
3110
	NULL,				/* "Brought to you by:" */
Chris Allegretta's avatar
Chris Allegretta committed
3111
3112
3113
3114
3115
	"Chris Allegretta",
	"Jordi Mallach",
	"Adam Rogoyski",
	"Rob Siemborski",
	"Rocco Corsi",
3116
	"David Lawrence Ramsey",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3117
	"David Benbennick",
3118
	"Mike Frysinger",
Chris Allegretta's avatar
Chris Allegretta committed
3119
3120
	"Ken Tyler",
	"Sven Guckes",
3121
	NULL,				/* credits[15], handled below. */
Chris Allegretta's avatar
Chris Allegretta committed
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
	"Pauli Virtanen",
	"Daniele Medri",
	"Clement Laforet",
	"Tedi Heriyanto",
	"Bill Soudan",
	"Christian Weisgerber",
	"Erik Andersen",
	"Big Gaute",
	"Joshua Jensen",
	"Ryan Krebs",
	"Albert Chin",
	"",
3134
	NULL,				/* "Special thanks to:" */
Chris Allegretta's avatar
Chris Allegretta committed
3135
3136
3137
3138
3139
3140
	"Plattsburgh State University",
	"Benet Laboratories",
	"Amy Allegretta",
	"Linda Young",
	"Jeremy Robichaud",
	"Richard Kolb II",
3141
	NULL,				/* "The Free Software Foundation" */
Chris Allegretta's avatar
Chris Allegretta committed
3142
	"Linus Torvalds",
3143
	NULL,				/* "For ncurses:" */
3144
3145
3146
3147
	"Thomas Dickey",
	"Pavel Curtis",
	"Zeyd Ben-Halim",
	"Eric S. Raymond",
3148
3149
3150
3151
3152
3153
	NULL,				/* "and anyone else we forgot..." */
	NULL,				/* "Thank you for using nano!" */
	"",
	"",
	"",
	"",
3154
	"(c) 1999-2004 Chris Allegretta",
3155
	"(c) 2005-2006 David Lawrence Ramsey",
3156
3157
3158
3159
	"",
	"",
	"",
	"",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3160
	"http://www.nano-editor.org/"
3161
3162
    };

3163
    const char *xlcredits[XLCREDIT_LEN] = {
3164
3165
3166
3167
3168
3169
3170
3171
	N_("The nano text editor"),
	N_("version"),
	N_("Brought to you by:"),
	N_("Special thanks to:"),
	N_("The Free Software Foundation"),
	N_("For ncurses:"),
	N_("and anyone else we forgot..."),
	N_("Thank you for using nano!")
3172
    };
3173

3174
    /* credits[15]: Make sure this name is displayed properly, since we
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3175
3176
     * can't dynamically assign it above, using Unicode 00F6 (Latin
     * Small Letter O with Diaresis) if applicable. */
3177
    credits[15] =
3178
#ifdef ENABLE_UTF8
3179
	 using_utf8() ? "Florian K\xC3\xB6nig" :
3180
3181
3182
#endif
	"Florian K\xF6nig";

3183
3184
3185
3186
3187
3188
    if (!old_more_space || !old_no_help) {
	SET(MORE_SPACE);
	SET(NO_HELP);
	window_init();
    }

3189
3190
    curs_set(0);
    nodelay(edit, TRUE);
3191

3192
    blank_titlebar();
3193
    blank_topbar();
Chris Allegretta's avatar
Chris Allegretta committed
3194
    blank_edit();
3195
3196
    blank_statusbar();
    blank_bottombars();
3197

3198
    wrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
3199
    wrefresh(edit);
3200
    wrefresh(bottomwin);
3201
    napms(700);
3202

3203
    for (crpos = 0; crpos < CREDIT_LEN + editwinrows / 2; crpos++) {
3204
	if ((kbinput = wgetch(edit)) != ERR)
3205
	    break;
3206

3207
	if (crpos < CREDIT_LEN) {
3208
	    const char *what;
3209
3210
	    size_t start_x;

3211
	    if (credits[crpos] == NULL) {
3212
		assert(0 <= xlpos && xlpos < XLCREDIT_LEN);
3213

3214
		what = _(xlcredits[xlpos]);
3215
		xlpos++;
3216
	    } else
3217
		what = credits[crpos];
3218

3219
	    start_x = COLS / 2 - strlenpt(what) / 2 - 1;
3220
3221
	    mvwaddstr(edit, editwinrows - 1 - (editwinrows % 2),
		start_x, what);
3222
	}
3223

3224
3225
3226
3227
	wrefresh(edit);

	if ((kbinput = wgetch(edit)) != ERR)
	    break;
3228
	napms(700);
3229

3230
	scrollok(edit, TRUE);
3231
	wscrl(edit, 1);
3232
	scrollok(edit, FALSE);
3233
	wrefresh(edit);
3234

3235
	if ((kbinput = wgetch(edit)) != ERR)
3236
	    break;
3237
	napms(700);
3238

3239
	scrollok(edit, TRUE);
3240
	wscrl(edit, 1);
3241
	scrollok(edit, FALSE);
3242
	wrefresh(edit);
3243
3244
    }

3245
3246
3247
    if (kbinput != ERR)
	ungetch(kbinput);

3248
3249
3250
3251
3252
3253
    if (!old_more_space || !old_no_help) {
	UNSET(MORE_SPACE);
	UNSET(NO_HELP);
	window_init();
    }

3254
    curs_set(1);
3255
    nodelay(edit, FALSE);
3256

3257
    total_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
3258
}
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3259
#endif /* NANO_EXTRA */