winio.c 101 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
2
3
/**************************************************************************
 *   winio.c                                                              *
 *                                                                        *
4
 *   Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,  *
5
 *   2008, 2009, 2010, 2011, 2013, 2014 Free Software Foundation, Inc.    *
Chris Allegretta's avatar
Chris Allegretta committed
6
7
 *   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 *
8
 *   the Free Software Foundation; either version 3, or (at your option)  *
Chris Allegretta's avatar
Chris Allegretta committed
9
10
 *   any later version.                                                   *
 *                                                                        *
11
12
13
14
 *   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
15
16
17
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program; if not, write to the Free Software          *
18
19
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA            *
 *   02110-1301, USA.                                                     *
Chris Allegretta's avatar
Chris Allegretta committed
20
21
22
 *                                                                        *
 **************************************************************************/

23
#include "proto.h"
24

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

31
static int *key_buffer = NULL;
32
33
	/* The keystroke buffer, containing all the keystrokes we
	 * haven't handled yet at a given point. */
34
static size_t key_buffer_len = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
35
	/* The length of the keystroke buffer. */
36
static int statusblank = 0;
37
	/* The number of keystrokes left before we blank the statusbar. */
38
static bool suppress_cursorpos = FALSE;
39
40
	/* Should we temporarily disable constant cursor position
	 * display? */
41
42
static bool seen_wide = FALSE;
	/* Whether we've seen a multicolumn character in the current line. */
43

44
#ifndef NANO_TINY
45
46
47
48
49
50
51
52
53
54
55
56
static sig_atomic_t last_sigwinch_counter = 0;

/* Did we receive a SIGWINCH since we were last called? */
bool the_window_resized(void)
{
    if (sigwinch_counter == last_sigwinch_counter)
	return FALSE;

    last_sigwinch_counter = sigwinch_counter;
    regenerate_screen();
    return TRUE;
}
57
#endif
58

59
60
61
62
63
64
65
66
67
68
69
70
/* 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.
71
 * - NANO_CONTROL_8 is Ctrl-8 (Ctrl-?), which is Delete under ASCII,
72
73
 *   ANSI, VT100, and VT220, and which is Backspace under VT320.
 *
74
 * Note: VT220 and VT320 also generate Esc [ 3 ~ for Delete.  By
75
76
 * default, xterm assumes it's running on a VT320 and generates Ctrl-8
 * (Ctrl-?) for Backspace and Esc [ 3 ~ for Delete.  This causes
77
 * problems for VT100-derived terminals such as the FreeBSD console,
78
 * which expect Ctrl-H for Backspace and Ctrl-8 (Ctrl-?) for Delete, and
79
80
81
82
83
84
85
86
87
 * 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
88
89
90
 * console, the FreeBSD console, the Mach console, xterm, rxvt, Eterm,
 * and Terminal.  Among these, there are several conflicts and
 * omissions, outlined as follows:
91
92
93
94
95
96
 *
 * - 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
97
 *   keypad key, because the latter has no value when NumLock is off.)
98
99
100
101
 * - 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.)
102
 * - F9 on FreeBSD console == PageDown on Mach console; the former is
103
104
105
 *   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.)
106
 * - F10 on FreeBSD console == PageUp on Mach console; the former is
107
 *   omitted.  (Same as above.)
108
 * - F13 on FreeBSD console == End on Mach console; the former is
109
 *   omitted.  (Same as above.)
110
111
112
113
114
115
 * - 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
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
116
 *   omitted.  (Same as above.) */
117

118
/* Read in a sequence of keystrokes from win and save them in the
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
119
120
 * keystroke buffer.  This should only be called when the keystroke
 * buffer is empty. */
121
void get_key_buffer(WINDOW *win)
122
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
123
    int input;
124
    size_t errcount = 0;
125
126
127
128
129

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

130
131
132
133
    /* Just before reading in the first character, display any pending
     * screen updates. */
    doupdate();

134
    /* Read in the first character using whatever mode we're in. */
135
136
    input = wgetch(win);

137
138
139
140
141
#ifndef NANO_TINY
    if (the_window_resized())
	input = KEY_WINCH;
#endif

142
143
144
145
146
147
148
149
150
151
152
    if (input == ERR && nodelay_mode)
	return;

    while (input == ERR) {
	/* If we've failed to get a character MAX_BUF_SIZE times in a row,
	 * assume our input source is gone and die gracefully.  We could
	 * check if errno is set to EIO ("Input/output error") and die in
	 * that case, but it's not always set properly.  Argh. */
	if (++errcount == MAX_BUF_SIZE)
	    handle_hupterm(0);

153
#ifndef NANO_TINY
154
	if (the_window_resized()) {
155
156
	    input = KEY_WINCH;
	    break;
157
	}
158
159
#endif
	input = wgetch(win);
160
    }
161

162
163
    /* Increment the length of the keystroke buffer, and save the value
     * of the keystroke at the end of it. */
164
    key_buffer_len++;
165
166
    key_buffer = (int *)nmalloc(sizeof(int));
    key_buffer[0] = input;
167

168
169
170
171
172
173
174
#ifndef NANO_TINY
    /* If we got SIGWINCH, get out immediately since the win argument is
     * no longer valid. */
    if (input == KEY_WINCH)
	return;
#endif

175
176
177
178
    /* Read in the remaining characters using non-blocking input. */
    nodelay(win, TRUE);

    while (TRUE) {
179
	input = wgetch(win);
180

181
	/* If there aren't any more characters, stop reading. */
182
	if (input == ERR)
183
184
	    break;

185
186
	/* Otherwise, increment the length of the keystroke buffer, and
	 * save the value of the keystroke at the end of it. */
187
	key_buffer_len++;
188
189
190
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
	key_buffer[key_buffer_len - 1] = input;
191
192
    }

193
194
195
    /* Restore waiting mode if it was on. */
    if (!nodelay_mode)
	nodelay(win, FALSE);
196
197

#ifdef DEBUG
198
199
    {
	size_t i;
200
	fprintf(stderr, "\nget_key_buffer(): the sequence of hex codes:");
201
202
203
204
	for (i = 0; i < key_buffer_len; i++)
	    fprintf(stderr, " %3x", key_buffer[i]);
	fprintf(stderr, "\n");
    }
205
#endif
206
}
207

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
208
/* Return the length of the keystroke buffer. */
209
size_t get_key_buffer_len(void)
210
211
212
213
{
    return key_buffer_len;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
214
/* Add the keystrokes in input to the keystroke buffer. */
215
void unget_input(int *input, size_t input_len)
216
217
{
    /* If input is empty, get out. */
218
    if (input_len == 0)
219
220
	return;

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
221
222
    /* If adding input would put the keystroke buffer beyond maximum
     * capacity, only add enough of input to put it at maximum
223
     * capacity. */
224
225
    if (key_buffer_len + input_len < key_buffer_len)
	input_len = (size_t)-1 - key_buffer_len;
226

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
227
228
229
    /* 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. */
230
231
232
    key_buffer_len += input_len;
    key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
	sizeof(int));
233

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
234
235
    /* If the keystroke buffer wasn't empty before, move its beginning
     * forward far enough so that we can add input to its beginning. */
236
237
238
    if (key_buffer_len > input_len)
	memmove(key_buffer + input_len, key_buffer,
		(key_buffer_len - input_len) * sizeof(int));
239

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
240
    /* Copy input to the beginning of the keystroke buffer. */
241
    memcpy(key_buffer, input, input_len * sizeof(int));
242
243
}

244
/* Put back the character stored in kbinput, putting it in byte range
245
246
 * beforehand.  If metakey is TRUE, put back the Escape character after
 * putting back kbinput.  If funckey is TRUE, put back the function key
247
 * (a value outside byte range) without putting it in byte range. */
248
void unget_kbinput(int kbinput, bool metakey, bool funckey)
249
{
250
    if (!funckey)
251
	kbinput = (char)kbinput;
252

253
    unget_input(&kbinput, 1);
254

255
    if (metakey) {
256
257
	kbinput = NANO_CONTROL_3;
	unget_input(&kbinput, 1);
258
259
260
    }
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
261
262
263
/* 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
264
 * anything else.  If the keystroke buffer is (still) empty, return NULL. */
265
int *get_input(WINDOW *win, size_t input_len)
266
{
267
    int *input;
268

269
270
    if (key_buffer_len == 0 && win != NULL)
	get_key_buffer(win);
271

272
273
    if (key_buffer_len == 0)
	return NULL;
274

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
275
276
    /* If input_len is greater than the length of the keystroke buffer,
     * only read the number of characters in the keystroke buffer. */
277
278
279
    if (input_len > key_buffer_len)
	input_len = key_buffer_len;

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
280
281
282
    /* Subtract input_len from the length of the keystroke buffer, and
     * allocate input so that it has enough room for input_len
     * keystrokes. */
283
    key_buffer_len -= input_len;
284
    input = (int *)nmalloc(input_len * sizeof(int));
285

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
286
287
    /* Copy input_len keystrokes from the beginning of the keystroke
     * buffer into input. */
288
    memcpy(input, key_buffer, input_len * sizeof(int));
289

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
290
    /* If the keystroke buffer is empty, mark it as such. */
291
292
293
    if (key_buffer_len == 0) {
	free(key_buffer);
	key_buffer = NULL;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
294
295
296
    /* 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. */
297
298
    } else {
	memmove(key_buffer, key_buffer + input_len, key_buffer_len *
299
300
301
		sizeof(int));
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
302
303
304
    }

    return input;
305
306
}

307
308
/* 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
309
310
 * sequences, and/or extended keypad values.  Supported extended keypad
 * values consist of
311
312
313
 * [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
314
 * off. */
315
int get_kbinput(WINDOW *win)
316
317
318
319
320
{
    int kbinput;

    /* Read in a character and interpret it.  Continue doing this until
     * we get a recognized value or sequence. */
321
    while ((kbinput = parse_kbinput(win)) == ERR)
322
	;
323

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
324
325
326
    /* If we read from the edit window, blank the statusbar if we need
     * to. */
    if (win == edit)
327
328
	check_statusblank();

329
330
331
332
333
334
    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
335
 * a function key. */
336
int parse_kbinput(WINDOW *win)
337
{
338
    static int escapes = 0, byte_digits = 0;
339
    static bool double_esc = FALSE;
340
    int *kbinput, retval = ERR;
341

342
343
    meta_key = FALSE;
    func_key = FALSE;
344

345
    /* Read in a character. */
346
347
348
349
350
351
    kbinput = get_input(win, 1);

    if (kbinput == NULL && nodelay_mode)
	return 0;

    while (kbinput == NULL)
352
	kbinput = get_input(win, 1);
353

354
355
356
357
358
359
    switch (*kbinput) {
	case ERR:
	    break;
	case NANO_CONTROL_3:
	    /* Increment the escape counter. */
	    escapes++;
360
361
362
363
	    /* If there are four consecutive escapes, discard three of them. */
	    if (escapes > 3)
		escapes = 1;
	    /* Wait for more input. */
364
365
366
367
	    break;
	default:
	    switch (escapes) {
		case 0:
368
		    /* One non-escape: normal input mode. */
369
		    retval = *kbinput;
370
371
		    break;
		case 1:
372
		    /* Reset the escape counter. */
373
		    escapes = 0;
374
		    if (get_key_buffer_len() == 0 || key_buffer[0] == 0x1b) {
375
376
			/* One escape followed by a single non-escape:
			 * meta key sequence mode. */
377
			meta_key = TRUE;
378
			retval = tolower(*kbinput);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
379
		    } else
380
381
			/* One escape followed by a non-escape, and there
			 * are more codes waiting: escape sequence mode. */
382
			retval = parse_escape_sequence(win, *kbinput);
383
384
		    break;
		case 2:
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
		    if (double_esc) {
			/* An "ESC ESC [ X" sequence from Option+arrow. */
			switch (*kbinput) {
			    case 'A':
				retval = KEY_HOME;
				break;
			    case 'B':
				retval = KEY_END;
				break;
#ifndef NANO_TINY
			    case 'C':
				retval = controlright;
				break;
			    case 'D':
				retval = controlleft;
				break;
#endif
			    default:
				retval = ERR;
				break;
			}
			double_esc = FALSE;
			escapes = 0;
		    } else if (get_key_buffer_len() == 0) {
409
410
411
			if (('0' <= *kbinput && *kbinput <= '2' &&
				byte_digits == 0) || ('0' <= *kbinput &&
				*kbinput <= '9' && byte_digits > 0)) {
412
413
414
415
416
417
			    /* Two escapes followed by one or more decimal
			     * digits, and there aren't any other codes
			     * waiting: byte sequence mode.  If the range
			     * of the byte sequence is limited to 2XX (the
			     * first digit is between '0' and '2' and the
			     * others between '0' and '9', interpret it. */
418
419
420
421
422
			    int byte;

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

423
424
425
426
			    /* If we've read in a complete byte sequence,
			     * reset the escape counter and the byte sequence
			     * counter, and put the obtained byte value back
			     * into the key buffer. */
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
			    if (byte != ERR) {
				char *byte_mb;
				int byte_mb_len, *seq, i;

				escapes = 0;
				byte_digits = 0;

				/* Put back the multibyte equivalent of
				 * the byte value. */
				byte_mb = make_mbchar((long)byte,
					&byte_mb_len);

				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);
			    }
			} else {
			    /* Reset the escape counter. */
452
			    escapes = 0;
453
454
			    if (byte_digits == 0)
				/* Two escapes followed by a non-decimal
455
456
457
458
				 * digit (or a decimal digit that would
				 * create a byte sequence greater than 2XX)
				 * and there aren't any other codes waiting:
				 * control character sequence mode. */
459
460
				retval = get_control_kbinput(*kbinput);
			    else {
461
462
463
				/* An invalid digit in the middle of a byte
				 * sequence: reset the byte sequence counter
				 * and save the code we got as the result. */
464
465
466
				byte_digits = 0;
				retval = *kbinput;
			    }
467
			}
468
469
470
		    } else if (*kbinput=='[') {
			/* This is an iTerm2 sequence: ^[ ^[ [ X. */
			double_esc = TRUE;
471
		    } else {
472
473
474
			/* Two escapes followed by a non-escape, and there
			 * are more codes waiting: combined meta and escape
			 * sequence mode. */
475
			escapes = 0;
476
			meta_key = TRUE;
477
			retval = parse_escape_sequence(win, *kbinput);
478
		    }
479
		    break;
480
481
482
483
		case 3:
		    /* Reset the escape counter. */
		    escapes = 0;
		    if (get_key_buffer_len() == 0)
484
485
			/* Three escapes followed by a non-escape, and no
			 * other codes are waiting: normal input mode. */
486
487
			retval = *kbinput;
		    else
488
489
490
491
			/* Three escapes followed by a non-escape, and more
			 * codes are waiting: combined control character and
			 * escape sequence mode.  First interpret the escape
			 * sequence, then the result as a control sequence. */
492
			retval = get_control_kbinput(
493
				parse_escape_sequence(win, *kbinput));
494
		    break;
495
496
	    }
    }
497

498
    if (retval != ERR) {
499
500
	switch (retval) {
	    case NANO_CONTROL_8:
501
502
		retval = ISSET(REBIND_DELETE) ? sc_seq_or(do_delete, 0) :
			sc_seq_or(do_backspace, 0);
503
504
		break;
	    case KEY_DOWN:
505
506
507
508
#ifdef KEY_SDOWN
	    /* ncurses and Slang don't support KEY_SDOWN. */
	    case KEY_SDOWN:
#endif
509
		retval = sc_seq_or(do_down_void, *kbinput);
510
511
		break;
	    case KEY_UP:
512
513
514
515
#ifdef KEY_SUP
	    /* ncurses and Slang don't support KEY_SUP. */
	    case KEY_SUP:
#endif
516
		retval = sc_seq_or(do_up_void, *kbinput);
517
518
		break;
	    case KEY_LEFT:
519
520
521
522
#ifdef KEY_SLEFT
	    /* Slang doesn't support KEY_SLEFT. */
	    case KEY_SLEFT:
#endif
523
		retval = sc_seq_or(do_left, *kbinput);
524
525
		break;
	    case KEY_RIGHT:
526
527
528
529
#ifdef KEY_SRIGHT
	    /* Slang doesn't support KEY_SRIGHT. */
	    case KEY_SRIGHT:
#endif
530
		retval = sc_seq_or(do_right, *kbinput);
531
		break;
532
533
534
535
536
537
#ifdef KEY_SHOME
	    /* HP-UX 10-11 and Slang don't support KEY_SHOME. */
	    case KEY_SHOME:
#endif
	    case KEY_A1:	/* Home (7) on numeric keypad with
				 * NumLock off. */
538
		retval = sc_seq_or(do_home, *kbinput);
539
		break;
540
	    case KEY_BACKSPACE:
541
		retval = sc_seq_or(do_backspace, *kbinput);
542
		break;
543
544
545
546
#ifdef KEY_SDC
	    /* Slang doesn't support KEY_SDC. */
	    case KEY_SDC:
		if (ISSET(REBIND_DELETE))
547
		    retval = sc_seq_or(do_delete, *kbinput);
548
		else
549
		    retval = sc_seq_or(do_backspace, *kbinput);
550
		break;
551
#endif
552
553
554
#ifdef KEY_SIC
	    /* Slang doesn't support KEY_SIC. */
	    case KEY_SIC:
555
		retval = sc_seq_or(do_insertfile_void, *kbinput);
556
		break;
557
#endif
558
	    case KEY_C3:	/* PageDown (4) on numeric keypad with
559
				 * NumLock off. */
560
		retval = sc_seq_or(do_page_down, *kbinput);
561
562
563
		break;
	    case KEY_A3:	/* PageUp (9) on numeric keypad with
				 * NumLock off. */
564
		retval = sc_seq_or(do_page_up, *kbinput);
565
566
		break;
	    case KEY_ENTER:
567
		retval = sc_seq_or(do_enter, *kbinput);
568
569
570
571
572
573
574
		break;
	    case KEY_B2:	/* Center (5) on numeric keypad with
				 * NumLock off. */
		retval = ERR;
		break;
	    case KEY_C1:	/* End (1) on numeric keypad with
				 * NumLock off. */
575
576
577
578
#ifdef KEY_SEND
	    /* HP-UX 10-11 and Slang don't support KEY_SEND. */
	    case KEY_SEND:
#endif
579
		retval = sc_seq_or(do_end, *kbinput);
580
581
582
583
584
585
586
587
		break;
#ifdef KEY_BEG
	    /* Slang doesn't support KEY_BEG. */
	    case KEY_BEG:	/* Center (5) on numeric keypad with
				 * NumLock off. */
		retval = ERR;
		break;
#endif
588
589
590
#ifdef KEY_CANCEL
	    /* Slang doesn't support KEY_CANCEL. */
	    case KEY_CANCEL:
591
592
593
#ifdef KEY_SCANCEL
	    /* Slang doesn't support KEY_SCANCEL. */
	    case KEY_SCANCEL:
594
#endif
595
		retval = first_sc_for(currmenu, do_cancel)->seq;
596
597
598
599
600
601
602
603
604
605
606
607
		break;
#endif
#ifdef KEY_SBEG
	    /* Slang doesn't support KEY_SBEG. */
	    case KEY_SBEG:	/* Center (5) on numeric keypad with
				 * NumLock off. */
		retval = ERR;
		break;
#endif
#ifdef KEY_SSUSPEND
	    /* Slang doesn't support KEY_SSUSPEND. */
	    case KEY_SSUSPEND:
608
		retval = sc_seq_or(do_suspend_void, 0);
609
610
611
612
613
		break;
#endif
#ifdef KEY_SUSPEND
	    /* Slang doesn't support KEY_SUSPEND. */
	    case KEY_SUSPEND:
614
		retval = sc_seq_or(do_suspend_void, 0);
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
		break;
#endif
#ifdef PDCURSES
	    case KEY_SHIFT_L:
	    case KEY_SHIFT_R:
	    case KEY_CONTROL_L:
	    case KEY_CONTROL_R:
	    case KEY_ALT_L:
	    case KEY_ALT_R:
		retval = ERR;
		break;
#endif
#if !defined(NANO_TINY) && defined(KEY_RESIZE)
	    /* Since we don't change the default SIGWINCH handler when
	     * NANO_TINY is defined, KEY_RESIZE is never generated.
	     * Also, Slang and SunOS 5.7-5.9 don't support
	     * KEY_RESIZE. */
	    case KEY_RESIZE:
		retval = ERR;
		break;
635
#endif
636
	}
637

638
639
640
641
642
643
644
#ifndef NANO_TINY
	if (retval == controlleft)
	    retval = sc_seq_or(do_prev_word_void, 0);
	else if (retval == controlright)
	    retval = sc_seq_or(do_next_word_void, 0);
#endif

645
	/* If our result is an extended keypad value (i.e. a value
646
	 * outside of byte range), set func_key to TRUE. */
647
	if (retval != ERR)
648
	    func_key = !is_byte(retval);
649
    }
650
651

#ifdef DEBUG
652
    fprintf(stderr, "parse_kbinput(): kbinput = %d, meta_key = %s, func_key = %s, escapes = %d, byte_digits = %d, retval = %d\n", *kbinput, meta_key ? "TRUE" : "FALSE", func_key ? "TRUE" : "FALSE", escapes, byte_digits, retval);
653
654
#endif

655
656
    free(kbinput);

657
    /* Return the result. */
658
659
660
    return retval;
}

661
/* Translate escape sequences, most of which correspond to extended
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
662
 * keypad values, into their corresponding key values.  These sequences
663
664
 * are generated when the keypad doesn't support the needed keys.
 * Assume that Escape has already been read in. */
665
int convert_sequence(const int *seq, size_t seq_len)
666
{
667
    if (seq_len > 1) {
668
	switch (seq[0]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
669
	    case 'O':
670
		switch (seq[1]) {
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
		    case '1':
			if (seq_len >= 3) {
			    switch (seq[2]) {
				case ';':
    if (seq_len >= 4) {
	switch (seq[3]) {
	    case '2':
		if (seq_len >= 5) {
		    switch (seq[4]) {
			case 'A': /* Esc O 1 ; 2 A == Shift-Up on
				   * Terminal. */
			case 'B': /* Esc O 1 ; 2 B == Shift-Down on
				   * Terminal. */
			case 'C': /* Esc O 1 ; 2 C == Shift-Right on
				   * Terminal. */
			case 'D': /* Esc O 1 ; 2 D == Shift-Left on
				   * Terminal. */
688
			    return arrow_from_abcd(seq[4]);
689
			case 'P': /* Esc O 1 ; 2 P == F13 on Terminal. */
690
			    return KEY_F(13);
691
			case 'Q': /* Esc O 1 ; 2 Q == F14 on Terminal. */
692
			    return KEY_F(14);
693
			case 'R': /* Esc O 1 ; 2 R == F15 on Terminal. */
694
			    return KEY_F(15);
695
			case 'S': /* Esc O 1 ; 2 S == F16 on Terminal. */
696
			    return KEY_F(16);
697
698
699
700
701
702
		    }
		}
		break;
	    case '5':
		if (seq_len >= 5) {
		    switch (seq[4]) {
703
704
			case 'A': /* Esc O 1 ; 5 A == Ctrl-Up on Terminal. */
			case 'B': /* Esc O 1 ; 5 B == Ctrl-Down on Terminal. */
705
			    return arrow_from_abcd(seq[4]);
706
			case 'C': /* Esc O 1 ; 5 C == Ctrl-Right on Terminal. */
707
			    return CONTROL_RIGHT;
708
			case 'D': /* Esc O 1 ; 5 D == Ctrl-Left on Terminal. */
709
			    return CONTROL_LEFT;
710
711
712
713
714
715
716
717
718
		    }
		}
		break;
	}
    }
				    break;
			    }
			}
			break;
719
		    case '2':
720
			if (seq_len >= 3) {
721
			    switch (seq[2]) {
722
				case 'P': /* Esc O 2 P == F13 on xterm. */
723
				    return KEY_F(13);
724
				case 'Q': /* Esc O 2 Q == F14 on xterm. */
725
				    return KEY_F(14);
726
				case 'R': /* Esc O 2 R == F15 on xterm. */
727
				    return KEY_F(15);
728
				case 'S': /* Esc O 2 S == F16 on xterm. */
729
				    return KEY_F(16);
730
731
			    }
			}
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
732
			break;
733
		    case 'A': /* Esc O A == Up on VT100/VT320/xterm. */
734
735
736
		    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. */
737
			return arrow_from_abcd(seq[1]);
738
739
		    case 'E': /* Esc O E == Center (5) on numeric keypad
			       * with NumLock off on xterm. */
740
			return KEY_B2;
741
		    case 'F': /* Esc O F == End on xterm/Terminal. */
742
			return sc_seq_or(do_end, 0);
743
		    case 'H': /* Esc O H == Home on xterm/Terminal. */
744
			return sc_seq_or(do_home, 0);
745
		    case 'M': /* Esc O M == Enter on numeric keypad with
746
			       * NumLock off on VT100/VT220/VT320/xterm/
747
			       * rxvt/Eterm. */
748
			return sc_seq_or(do_home, 0);
749
		    case 'P': /* Esc O P == F1 on VT100/VT220/VT320/Mach
750
			       * console. */
751
			return KEY_F(1);
752
		    case 'Q': /* Esc O Q == F2 on VT100/VT220/VT320/Mach
753
			       * console. */
754
			return KEY_F(2);
755
		    case 'R': /* Esc O R == F3 on VT100/VT220/VT320/Mach
756
			       * console. */
757
			return KEY_F(3);
758
		    case 'S': /* Esc O S == F4 on VT100/VT220/VT320/Mach
759
			       * console. */
760
			return KEY_F(4);
761
		    case 'T': /* Esc O T == F5 on Mach console. */
762
			return KEY_F(5);
763
		    case 'U': /* Esc O U == F6 on Mach console. */
764
			return KEY_F(6);
765
		    case 'V': /* Esc O V == F7 on Mach console. */
766
			return KEY_F(7);
767
		    case 'W': /* Esc O W == F8 on Mach console. */
768
			return KEY_F(8);
769
		    case 'X': /* Esc O X == F9 on Mach console. */
770
			return KEY_F(9);
771
		    case 'Y': /* Esc O Y == F10 on Mach console. */
772
			return KEY_F(10);
773
774
		    case 'a': /* Esc O a == Ctrl-Up on rxvt. */
		    case 'b': /* Esc O b == Ctrl-Down on rxvt. */
775
			return arrow_from_abcd(seq[1]);
776
		    case 'c': /* Esc O c == Ctrl-Right on rxvt. */
777
			return CONTROL_RIGHT;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
778
		    case 'd': /* Esc O d == Ctrl-Left on rxvt. */
779
			return CONTROL_LEFT;
780
		    case 'j': /* Esc O j == '*' on numeric keypad with
781
			       * NumLock off on VT100/VT220/VT320/xterm/
782
			       * rxvt/Eterm/Terminal. */
783
			return '*';
784
		    case 'k': /* Esc O k == '+' on numeric keypad with
785
			       * NumLock off on VT100/VT220/VT320/xterm/
786
			       * rxvt/Eterm/Terminal. */
787
			return '+';
788
		    case 'l': /* Esc O l == ',' on numeric keypad with
789
			       * NumLock off on VT100/VT220/VT320/xterm/
790
			       * rxvt/Eterm/Terminal. */
791
			return ',';
792
		    case 'm': /* Esc O m == '-' on numeric keypad with
793
			       * NumLock off on VT100/VT220/VT320/xterm/
794
			       * rxvt/Eterm/Terminal. */
795
			return '-';
796
		    case 'n': /* Esc O n == Delete (.) on numeric keypad
797
			       * with NumLock off on VT100/VT220/VT320/
798
			       * xterm/rxvt/Eterm/Terminal. */
799
			return sc_seq_or(do_delete, 0);
800
		    case 'o': /* Esc O o == '/' on numeric keypad with
801
			       * NumLock off on VT100/VT220/VT320/xterm/
802
			       * rxvt/Eterm/Terminal. */
803
			return '/';
804
		    case 'p': /* Esc O p == Insert (0) on numeric keypad
805
			       * with NumLock off on VT100/VT220/VT320/
806
			       * rxvt/Eterm/Terminal. */
807
			return sc_seq_or(do_insertfile_void, 0);
808
		    case 'q': /* Esc O q == End (1) on numeric keypad
809
			       * with NumLock off on VT100/VT220/VT320/
810
			       * rxvt/Eterm/Terminal. */
811
			return sc_seq_or(do_end, 0);
812
		    case 'r': /* Esc O r == Down (2) on numeric keypad
813
			       * with NumLock off on VT100/VT220/VT320/
814
			       * rxvt/Eterm/Terminal. */
815
			return sc_seq_or(do_down_void, 0);
816
		    case 's': /* Esc O s == PageDown (3) on numeric
817
			       * keypad with NumLock off on VT100/VT220/
818
			       * VT320/rxvt/Eterm/Terminal. */
819
			return sc_seq_or(do_page_down, 0);
820
		    case 't': /* Esc O t == Left (4) on numeric keypad
821
			       * with NumLock off on VT100/VT220/VT320/
822
			       * rxvt/Eterm/Terminal. */
823
			return sc_seq_or(do_left, 0);
824
		    case 'u': /* Esc O u == Center (5) on numeric keypad
825
826
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt/Eterm. */
827
			return KEY_B2;
828
		    case 'v': /* Esc O v == Right (6) on numeric keypad
829
			       * with NumLock off on VT100/VT220/VT320/
830
			       * rxvt/Eterm/Terminal. */
831
			return sc_seq_or(do_right, 0);
832
		    case 'w': /* Esc O w == Home (7) on numeric keypad
833
			       * with NumLock off on VT100/VT220/VT320/
834
			       * rxvt/Eterm/Terminal. */
835
			return sc_seq_or(do_home, 0);
836
		    case 'x': /* Esc O x == Up (8) on numeric keypad
837
			       * with NumLock off on VT100/VT220/VT320/
838
			       * rxvt/Eterm/Terminal. */
839
			return sc_seq_or(do_up_void, 0);
840
		    case 'y': /* Esc O y == PageUp (9) on numeric keypad
841
			       * with NumLock off on VT100/VT220/VT320/
842
			       * rxvt/Eterm/Terminal. */
843
			return sc_seq_or(do_page_up, 0);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
844
845
846
		}
		break;
	    case 'o':
847
		switch (seq[1]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
848
849
		    case 'a': /* Esc o a == Ctrl-Up on Eterm. */
		    case 'b': /* Esc o b == Ctrl-Down on Eterm. */
850
			return arrow_from_abcd(seq[1]);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
851
		    case 'c': /* Esc o c == Ctrl-Right on Eterm. */
852
			return CONTROL_RIGHT;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
853
		    case 'd': /* Esc o d == Ctrl-Left on Eterm. */
854
			return CONTROL_LEFT;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
855
856
857
		}
		break;
	    case '[':
858
		switch (seq[1]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
859
		    case '1':
860
			if (seq_len >= 3) {
861
			    switch (seq[2]) {
862
				case '1': /* Esc [ 1 1 ~ == F1 on rxvt/Eterm. */
863
				    return KEY_F(1);
864
				case '2': /* Esc [ 1 2 ~ == F2 on rxvt/Eterm. */
865
				    return KEY_F(2);
866
				case '3': /* Esc [ 1 3 ~ == F3 on rxvt/Eterm. */
867
				    return KEY_F(3);
868
				case '4': /* Esc [ 1 4 ~ == F4 on rxvt/Eterm. */
869
				    return KEY_F(4);
870
871
				case '5': /* Esc [ 1 5 ~ == F5 on xterm/
					   * rxvt/Eterm. */
872
				    return KEY_F(5);
873
				case '7': /* Esc [ 1 7 ~ == F6 on
874
875
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
876
				    return KEY_F(6);
877
				case '8': /* Esc [ 1 8 ~ == F7 on
878
879
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
880
				    return KEY_F(7);
881
				case '9': /* Esc [ 1 9 ~ == F8 on
882
883
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
884
				    return KEY_F(8);
885
				case ';':
886
    if (seq_len >= 4) {
887
	switch (seq[3]) {
888
	    case '2':
889
		if (seq_len >= 5) {
890
		    switch (seq[4]) {
891
892
893
894
			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. */
895
			    return arrow_from_abcd(seq[4]);
896
897
898
899
		    }
		}
		break;
	    case '5':
900
		if (seq_len >= 5) {
901
		    switch (seq[4]) {
902
903
			case 'A': /* Esc [ 1 ; 5 A == Ctrl-Up on xterm. */
			case 'B': /* Esc [ 1 ; 5 B == Ctrl-Down on xterm. */
904
			    return arrow_from_abcd(seq[4]);
905
			case 'C': /* Esc [ 1 ; 5 C == Ctrl-Right on xterm. */
906
			    return CONTROL_RIGHT;
907
			case 'D': /* Esc [ 1 ; 5 D == Ctrl-Left on xterm. */
908
			    return CONTROL_LEFT;
909
910
911
912
913
914
		    }
		}
		break;
	}
    }
				    break;
915
916
				default: /* Esc [ 1 ~ == Home on
					  * VT320/Linux console. */
917
				    return sc_seq_or(do_home, 0);
918
919
920
921
			    }
			}
			break;
		    case '2':
922
			if (seq_len >= 3) {
923
			    switch (seq[2]) {
924
925
				case '0': /* Esc [ 2 0 ~ == F9 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
926
				    return KEY_F(9);
927
928
				case '1': /* Esc [ 2 1 ~ == F10 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
929
				    return KEY_F(10);
930
931
				case '3': /* Esc [ 2 3 ~ == F11 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
932
				    return KEY_F(11);
933
934
				case '4': /* Esc [ 2 4 ~ == F12 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
935
				    return KEY_F(12);
936
937
				case '5': /* Esc [ 2 5 ~ == F13 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
938
				    return KEY_F(13);
939
940
				case '6': /* Esc [ 2 6 ~ == F14 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
941
				    return KEY_F(14);
942
943
				case '8': /* Esc [ 2 8 ~ == F15 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
944
				    return KEY_F(15);
945
946
				case '9': /* Esc [ 2 9 ~ == F16 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
947
				    return KEY_F(16);
948
949
				default: /* Esc [ 2 ~ == Insert on VT220/VT320/
					  * Linux console/xterm/Terminal. */
950
				    return sc_seq_or(do_insertfile_void, 0);
951
			    }
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
952
953
			}
			break;
954
		    case '3': /* Esc [ 3 ~ == Delete on VT220/VT320/
955
			       * Linux console/xterm/Terminal. */
956
			return sc_seq_or(do_delete, 0);
957
		    case '4': /* Esc [ 4 ~ == End on VT220/VT320/Linux
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
958
			       * console/xterm. */
959
			return sc_seq_or(do_end, 0);
960
		    case '5': /* Esc [ 5 ~ == PageUp on VT220/VT320/
961
962
			       * Linux console/xterm/Terminal;
			       * Esc [ 5 ^ == PageUp on Eterm. */
963
			return sc_seq_or(do_page_up, 0);
964
		    case '6': /* Esc [ 6 ~ == PageDown on VT220/VT320/
965
			       * Linux console/xterm/Terminal;
966
			       * Esc [ 6 ^ == PageDown on Eterm. */
967
			return sc_seq_or(do_page_down, 0);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
968
		    case '7': /* Esc [ 7 ~ == Home on rxvt. */
969
			return sc_seq_or(do_home, 0);
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
970
		    case '8': /* Esc [ 8 ~ == End on rxvt. */
971
			return sc_seq_or(do_end, 0);
972
		    case '9': /* Esc [ 9 == Delete on Mach console. */
973
			return sc_seq_or(do_delete, 0);
974
		    case '@': /* Esc [ @ == Insert on Mach console. */
975
			return sc_seq_or(do_insertfile_void, 0);
976
		    case 'A': /* Esc [ A == Up on ANSI/VT220/Linux
977
			       * console/FreeBSD console/Mach console/
978
			       * rxvt/Eterm/Terminal. */
979
		    case 'B': /* Esc [ B == Down on ANSI/VT220/Linux
980
			       * console/FreeBSD console/Mach console/
981
			       * rxvt/Eterm/Terminal. */
982
		    case 'C': /* Esc [ C == Right on ANSI/VT220/Linux
983
			       * console/FreeBSD console/Mach console/
984
			       * rxvt/Eterm/Terminal. */
985
		    case 'D': /* Esc [ D == Left on ANSI/VT220/Linux
986
			       * console/FreeBSD console/Mach console/
987
			       * rxvt/Eterm/Terminal. */
988
			return arrow_from_abcd(seq[1]);
989
		    case 'E': /* Esc [ E == Center (5) on numeric keypad
990
991
			       * with NumLock off on FreeBSD console/
			       * Terminal. */
992
			return KEY_B2;
993
		    case 'F': /* Esc [ F == End on FreeBSD console/Eterm. */
994
			return sc_seq_or(do_end, 0);
995
		    case 'G': /* Esc [ G == PageDown on FreeBSD console. */
996
			return sc_seq_or(do_page_down, 0);
997
		    case 'H': /* Esc [ H == Home on ANSI/VT220/FreeBSD
998
			       * console/Mach console/Eterm. */
999
			return sc_seq_or(do_home, 0);
1000
		    case 'I': /* Esc [ I == PageUp on FreeBSD console. */
1001
			return sc_seq_or(do_page_up, 0);
1002
		    case 'L': /* Esc [ L == Insert on ANSI/FreeBSD console. */
1003
			return sc_seq_or(do_insertfile_void, 0);
1004
		    case 'M': /* Esc [ M == F1 on FreeBSD console. */
1005
			return KEY_F(1);
1006
		    case 'N': /* Esc [ N == F2 on FreeBSD console. */
1007
			return KEY_F(2);
1008
		    case 'O':
1009
			if (seq_len >= 3) {
1010
			    switch (seq[2]) {
1011
				case 'P': /* Esc [ O P == F1 on xterm. */
1012
				    return KEY_F(1);
1013
				case 'Q': /* Esc [ O Q == F2 on xterm. */
1014
				    return KEY_F(2);
1015
				case 'R': /* Esc [ O R == F3 on xterm. */
1016
				    return KEY_F(3);
1017
				case 'S': /* Esc [ O S == F4 on xterm. */
1018
				    return KEY_F(4);
1019
			    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1020
			} else
1021
			    /* Esc [ O == F3 on FreeBSD console. */
1022
			    return KEY_F(3);
1023
1024
			break;
		    case 'P': /* Esc [ P == F4 on FreeBSD console. */
1025
			return KEY_F(4);
1026
		    case 'Q': /* Esc [ Q == F5 on FreeBSD console. */
1027
			return KEY_F(5);
1028
		    case 'R': /* Esc [ R == F6 on FreeBSD console. */
1029
			return KEY_F(6);
1030
		    case 'S': /* Esc [ S == F7 on FreeBSD console. */
1031
			return KEY_F(7);
1032
		    case 'T': /* Esc [ T == F8 on FreeBSD console. */
1033
			return KEY_F(8);
1034
		    case 'U': /* Esc [ U == PageDown on Mach console. */
1035
			return sc_seq_or(do_page_down, 0);
1036
		    case 'V': /* Esc [ V == PageUp on Mach console. */
1037
			return sc_seq_or(do_page_up, 0);
1038
		    case 'W': /* Esc [ W == F11 on FreeBSD console. */
1039
			return KEY_F(11);
1040
		    case 'X': /* Esc [ X == F12 on FreeBSD console. */
1041
			return KEY_F(12);
1042
		    case 'Y': /* Esc [ Y == End on Mach console. */
1043
			return sc_seq_or(do_end, 0);
1044
		    case 'Z': /* Esc [ Z == F14 on FreeBSD console. */
1045
			return KEY_F(14);
1046
		    case 'a': /* Esc [ a == Shift-Up on rxvt/Eterm. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1047
		    case 'b': /* Esc [ b == Shift-Down on rxvt/Eterm. */
1048
		    case 'c': /* Esc [ c == Shift-Right on rxvt/Eterm. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1049
		    case 'd': /* Esc [ d == Shift-Left on rxvt/Eterm. */
1050
			return arrow_from_abcd(seq[1]);
1051
		    case '[':
1052
			if (seq_len >= 3) {
1053
			    switch (seq[2]) {
1054
1055
				case 'A': /* Esc [ [ A == F1 on Linux
					   * console. */
1056
				    return KEY_F(1);
1057
1058
				case 'B': /* Esc [ [ B == F2 on Linux
					   * console. */
1059
				    return KEY_F(2);
1060
1061
				case 'C': /* Esc [ [ C == F3 on Linux
					   * console. */
1062
				    return KEY_F(3);
1063
1064
				case 'D': /* Esc [ [ D == F4 on Linux
					   * console. */
1065
				    return KEY_F(4);
1066
1067
				case 'E': /* Esc [ [ E == F5 on Linux
					   * console. */
1068
				    return KEY_F(5);
1069
1070
			    }
			}
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1071
1072
1073
1074
			break;
		}
		break;
	}
1075
1076
    }

1077
    return ERR;
1078
1079
}

1080
/* Return the equivalent arrow key value for the case-insensitive
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1081
 * letters A (up), B (down), C (right), and D (left).  These are common
1082
 * to many escape sequences. */
1083
int arrow_from_abcd(int kbinput)
1084
1085
1086
{
    switch (tolower(kbinput)) {
	case 'a':
1087
	    return sc_seq_or(do_up_void, 0);
1088
	case 'b':
1089
	    return sc_seq_or(do_down_void, 0);
1090
	case 'c':
1091
	    return sc_seq_or(do_right, 0);
1092
	case 'd':
1093
	    return sc_seq_or(do_left, 0);
1094
1095
1096
1097
1098
	default:
	    return ERR;
    }
}

1099
/* Interpret the escape sequence in the keystroke buffer, the first
1100
1101
 * character of which is kbinput.  Assume that the keystroke buffer
 * isn't empty, and that the initial escape has already been read in. */
1102
int parse_escape_sequence(WINDOW *win, int kbinput)
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
{
    int retval, *seq;
    size_t seq_len;

    /* 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);
1113
    retval = convert_sequence(seq, seq_len);
1114
1115
1116

    free(seq);

1117
    /* If we got an unrecognized escape sequence, notify the user. */
1118
    if (retval == ERR) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1119
	if (win == edit) {
1120
1121
	    /* TRANSLATORS: This refers to a sequence of escape codes
	     * (from the keyboard) that nano does not know about. */
1122
	    statusline(ALERT, _("Unknown sequence"));
1123
	    suppress_cursorpos = FALSE;
1124
	    alerted = FALSE;
1125
1126
1127
1128
	    if (currmenu == MMAIN) {
		reset_cursor();
		curs_set(1);
	    }
1129
1130
1131
	}
    }

1132
#ifdef DEBUG
1133
1134
    fprintf(stderr, "parse_escape_sequence(): kbinput = %d, seq_len = %lu, retval = %d\n",
		kbinput, (unsigned long)seq_len, retval);
1135
1136
1137
1138
1139
#endif

    return retval;
}

1140
1141
/* Translate a byte sequence: turn a three-digit decimal number (from
 * 000 to 255) into its corresponding byte value. */
1142
int get_byte_kbinput(int kbinput)
1143
{
1144
    static int byte_digits = 0, byte = 0;
1145
    int retval = ERR;
1146

1147
1148
    /* Increment the byte digit counter. */
    byte_digits++;
1149

1150
    switch (byte_digits) {
1151
	case 1:
1152
1153
	    /* First digit: This must be from zero to two.  Put it in
	     * the 100's position of the byte sequence holder. */
1154
	    if ('0' <= kbinput && kbinput <= '2')
1155
		byte = (kbinput - '0') * 100;
1156
	    else
1157
1158
		/* This isn't the start of a byte sequence.  Return this
		 * character as the result. */
1159
1160
1161
		retval = kbinput;
	    break;
	case 2:
1162
1163
1164
1165
	    /* Second digit: This must be from zero to five if the first
	     * was two, and may be any decimal value if the first was
	     * zero or one.  Put it in the 10's position of the byte
	     * sequence holder. */
1166
1167
1168
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 200 &&
		'6' <= kbinput && kbinput <= '9'))
		byte += (kbinput - '0') * 10;
1169
	    else
1170
1171
		/* This isn't the second digit of a byte sequence.
		 * Return this character as the result. */
1172
1173
1174
		retval = kbinput;
	    break;
	case 3:
1175
	    /* Third digit: This must be from zero to five if the first
1176
1177
1178
	     * was two and the second was five, and may be any decimal
	     * value otherwise.  Put it in the 1's position of the byte
	     * sequence holder. */
1179
1180
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 250 &&
		'6' <= kbinput && kbinput <= '9')) {
1181
		byte += kbinput - '0';
1182
		/* The byte sequence is complete. */
1183
		retval = byte;
1184
	    } else
1185
1186
		/* This isn't the third digit of a byte sequence.
		 * Return this character as the result. */
1187
1188
		retval = kbinput;
	    break;
1189
	default:
1190
1191
1192
	    /* If there are more than three digits, return this
	     * character as the result.  (Maybe we should produce an
	     * error instead?) */
1193
1194
1195
1196
1197
1198
1199
1200
	    retval = kbinput;
	    break;
    }

    /* If we have a result, reset the byte digit counter and the byte
     * sequence holder. */
    if (retval != ERR) {
	byte_digits = 0;
1201
	byte = 0;
1202
1203
1204
    }

#ifdef DEBUG
1205
    fprintf(stderr, "get_byte_kbinput(): kbinput = %d, byte_digits = %d, byte = %d, retval = %d\n", kbinput, byte_digits, byte, retval);
1206
1207
1208
1209
1210
#endif

    return retval;
}

1211
#ifdef ENABLE_UTF8
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
/* If the character in kbinput is a valid hexadecimal digit, multiply it
 * by factor and add the result to uni. */
long add_unicode_digit(int kbinput, long factor, long *uni)
{
    long retval = ERR;

    if ('0' <= kbinput && kbinput <= '9')
	*uni += (kbinput - '0') * factor;
    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
	*uni += (tolower(kbinput) - 'a' + 10) * factor;
    else
	/* If this character isn't a valid hexadecimal value, save it as
	 * the result. */
	retval = kbinput;

    return retval;
}

1230
/* Translate a Unicode sequence: turn a six-digit hexadecimal number
1231
 * (from 000000 to 10FFFF, case-insensitive) into its corresponding
1232
 * multibyte value. */
1233
long get_unicode_kbinput(int kbinput)
1234
{
1235
1236
1237
    static int uni_digits = 0;
    static long uni = 0;
    long retval = ERR;
1238

1239
    /* Increment the Unicode digit counter. */
1240
    uni_digits++;
1241

1242
    switch (uni_digits) {
1243
	case 1:
1244
1245
	    /* First digit: This must be zero or one.  Put it in the
	     * 0x100000's position of the Unicode sequence holder. */
1246
	    if ('0' <= kbinput && kbinput <= '1')
1247
		uni = (kbinput - '0') * 0x100000;
1248
	    else
1249
1250
		/* This isn't the first digit of a Unicode sequence.
		 * Return this character as the result. */
1251
1252
1253
		retval = kbinput;
	    break;
	case 2:
1254
1255
1256
1257
1258
1259
	    /* Second digit: This must be zero if the first was one, and
	     * may be any hexadecimal value if the first was zero.  Put
	     * it in the 0x10000's position of the Unicode sequence
	     * holder. */
	    if (uni == 0 || '0' == kbinput)
		retval = add_unicode_digit(kbinput, 0x10000, &uni);
1260
	    else
1261
1262
		/* This isn't the second digit of a Unicode sequence.
		 * Return this character as the result. */
1263
1264
1265
		retval = kbinput;
	    break;
	case 3:
1266
1267
1268
1269
	    /* Third digit: This may be any hexadecimal value.  Put it
	     * in the 0x1000's position of the Unicode sequence
	     * holder. */
	    retval = add_unicode_digit(kbinput, 0x1000, &uni);
1270
	    break;
1271
	case 4:
1272
1273
1274
1275
	    /* Fourth digit: This may be any hexadecimal value.  Put it
	     * in the 0x100's position of the Unicode sequence
	     * holder. */
	    retval = add_unicode_digit(kbinput, 0x100, &uni);
1276
	    break;
1277
	case 5:
1278
1279
1280
	    /* Fifth digit: This may be any hexadecimal value.  Put it
	     * in the 0x10's position of the Unicode sequence holder. */
	    retval = add_unicode_digit(kbinput, 0x10, &uni);
1281
	    break;
1282
	case 6:
1283
1284
1285
1286
1287
1288
	    /* Sixth digit: This may be any hexadecimal value.  Put it
	     * in the 0x1's position of the Unicode sequence holder. */
	    retval = add_unicode_digit(kbinput, 0x1, &uni);
	    /* If this character is a valid hexadecimal value, then the
	     * Unicode sequence is complete. */
	    if (retval == ERR)
1289
		retval = uni;
1290
1291
	    break;
	default:
1292
1293
1294
	    /* If there are more than six digits, return this character
	     * as the result.  (Maybe we should produce an error
	     * instead?) */
1295
1296
1297
	    retval = kbinput;
	    break;
    }
1298

1299
1300
    /* If we have a result, reset the Unicode digit counter and the
     * Unicode sequence holder. */
1301
    if (retval != ERR) {
1302
1303
	uni_digits = 0;
	uni = 0;
1304
    }
1305

1306
#ifdef DEBUG
1307
    fprintf(stderr, "get_unicode_kbinput(): kbinput = %d, uni_digits = %d, uni = %ld, retval = %ld\n", kbinput, uni_digits, uni, retval);
1308
1309
#endif

1310
1311
    return retval;
}
1312
#endif /* ENABLE_UTF8 */
1313

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

1320
    /* Ctrl-Space (Ctrl-2, Ctrl-@, Ctrl-`) */
1321
1322
    if (kbinput == ' ' || kbinput == '2')
	retval = NANO_CONTROL_SPACE;
1323
1324
    /* Ctrl-/ (Ctrl-7, Ctrl-_) */
    else if (kbinput == '/')
1325
	retval = NANO_CONTROL_7;
1326
    /* Ctrl-3 (Ctrl-[, Esc) to Ctrl-7 (Ctrl-/, Ctrl-_) */
1327
1328
1329
    else if ('3' <= kbinput && kbinput <= '7')
	retval = kbinput - 24;
    /* Ctrl-8 (Ctrl-?) */
1330
1331
    else if (kbinput == '8' || kbinput == '?')
	retval = NANO_CONTROL_8;
1332
1333
    /* Ctrl-@ (Ctrl-Space, Ctrl-2, Ctrl-`) to Ctrl-_ (Ctrl-/, Ctrl-7) */
    else if ('@' <= kbinput && kbinput <= '_')
1334
	retval = kbinput - '@';
1335
1336
    /* Ctrl-` (Ctrl-2, Ctrl-Space, Ctrl-@) to Ctrl-~ (Ctrl-6, Ctrl-^) */
    else if ('`' <= kbinput && kbinput <= '~')
1337
	retval = kbinput - '`';
1338
1339
1340
    else
	retval = kbinput;

1341
#ifdef DEBUG
1342
    fprintf(stderr, "get_control_kbinput(): kbinput = %d, retval = %d\n", kbinput, retval);
1343
1344
#endif

1345
1346
    return retval;
}
1347

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1348
1349
/* Put the output-formatted characters in output back into the keystroke
 * buffer, so that they can be parsed and displayed as output again. */
1350
void unparse_kbinput(char *output, size_t output_len)
1351
{
1352
1353
    int *input;
    size_t i;
1354

1355
1356
1357
1358
    if (output_len == 0)
	return;

    input = (int *)nmalloc(output_len * sizeof(int));
1359

1360
1361
    for (i = 0; i < output_len; i++)
	input[i] = (int)output[i];
1362

1363
    unget_input(input, output_len);
1364

1365
    free(input);
1366
1367
}

1368
/* Read in a stream of characters verbatim, and return the length of the
1369
1370
1371
1372
 * string in kbinput_len.  Assume nodelay(win) is FALSE. */
int *get_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
{
    int *retval;
1373

1374
    /* Turn off flow control characters if necessary so that we can type
1375
1376
     * them in verbatim, and turn the keypad off if necessary so that we
     * don't get extended keypad values. */
1377
1378
    if (ISSET(PRESERVE))
	disable_flow_control();
1379
1380
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, FALSE);
1381
1382
1383

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

    /* Turn flow control characters back on if necessary and turn the
1386
     * keypad back on if necessary now that we're done. */
1387
1388
    if (ISSET(PRESERVE))
	enable_flow_control();
1389
1390
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, TRUE);
1391

1392
    return retval;
1393
1394
}

1395
1396
/* Read in a stream of all available characters, and return the length
 * of the string in kbinput_len.  Translate the first few characters of
1397
 * the input into the corresponding multibyte value if possible.  After
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1398
 * that, leave the input as-is. */
1399
int *parse_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
1400
{
1401
    int *kbinput, *retval;
1402

1403
    /* Read in the first keystroke. */
1404
1405
    while ((kbinput = get_input(win, 1)) == NULL)
	;
1406

1407
#ifdef ENABLE_UTF8
1408
1409
1410
    if (using_utf8()) {
	/* Check whether the first keystroke is a valid hexadecimal
	 * digit. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1411
	long uni = get_unicode_kbinput(*kbinput);
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430

	/* If the first keystroke isn't a valid hexadecimal digit, put
	 * back the first keystroke. */
	if (uni != ERR)
	    unget_input(kbinput, 1);

	/* Otherwise, read in keystrokes until we have a complete
	 * Unicode sequence, and put back the corresponding Unicode
	 * value. */
	else {
	    char *uni_mb;
	    int uni_mb_len, *seq, i;

	    if (win == edit)
		/* TRANSLATORS: This is displayed during the input of a
		 * six-digit hexadecimal Unicode character code. */
		statusbar(_("Unicode Input"));

	    while (uni == ERR) {
1431
1432
		while ((kbinput = get_input(win, 1)) == NULL)
		    ;
1433
1434
		uni = get_unicode_kbinput(*kbinput);
	    }
1435

1436
1437
1438
	    /* Put back the multibyte equivalent of the Unicode
	     * value. */
	    uni_mb = make_mbchar(uni, &uni_mb_len);
1439

1440
	    seq = (int *)nmalloc(uni_mb_len * sizeof(int));
1441

1442
1443
	    for (i = 0; i < uni_mb_len; i++)
		seq[i] = (unsigned char)uni_mb[i];
1444

1445
	    unget_input(seq, uni_mb_len);
1446

1447
1448
	    free(seq);
	    free(uni_mb);
1449
	}
1450
    } else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1451
1452
#endif /* ENABLE_UTF8 */

1453
1454
	/* Put back the first keystroke. */
	unget_input(kbinput, 1);
1455

1456
1457
    free(kbinput);

1458
    /* Get the complete sequence, and save the characters in it as the
1459
     * result. */
1460
    *kbinput_len = get_key_buffer_len();
1461
    retval = get_input(NULL, *kbinput_len);
1462
1463
1464
1465

    return retval;
}

1466
#ifndef DISABLE_MOUSE
1467
/* Handle any mouse event that may have occurred.  We currently handle
1468
1469
1470
1471
1472
1473
1474
 * releases/clicks of the first mouse button.  If allow_shortcuts is
 * TRUE, releasing/clicking on a visible shortcut will put back the
 * keystroke associated with that shortcut.  If NCURSES_MOUSE_VERSION is
 * at least 2, we also currently handle presses of the fourth mouse
 * button (upward rolls of the mouse wheel) by putting back the
 * keystrokes to move up, and presses of the fifth mouse button
 * (downward rolls of the mouse wheel) by putting back the keystrokes to
1475
1476
1477
1478
1479
1480
 * move down.  We also store the coordinates of a mouse event that needs
 * to be handled in mouse_x and mouse_y, relative to the entire screen.
 * Return -1 on error, 0 if the mouse event needs to be handled, 1 if
 * it's been handled by putting back keystrokes that need to be handled.
 * or 2 if it's been ignored.  Assume that KEY_MOUSE has already been
 * read in. */
1481
int get_mouseinput(int *mouse_x, int *mouse_y, bool allow_shortcuts)
1482
1483
{
    MEVENT mevent;
1484
    bool in_bottomwin;
1485
    subnfunc *f;
1486
1487
1488
1489
1490
1491

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

    /* First, get the actual mouse event. */
    if (getmouse(&mevent) == ERR)
1492
	return -1;
1493

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

1498
1499
    in_bottomwin = wenclose(bottomwin, *mouse_y, *mouse_x);

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1500
    /* Handle releases/clicks of the first mouse button. */
1501
    if (mevent.bstate & (BUTTON1_RELEASED | BUTTON1_CLICKED)) {
1502
1503
	/* If we're allowing shortcuts, the current shortcut list is
	 * being displayed on the last two lines of the screen, and the
1504
1505
1506
	 * first mouse button was released on/clicked inside it, we need
	 * to figure out which shortcut was released on/clicked and put
	 * back the equivalent keystroke(s) for it. */
1507
	if (allow_shortcuts && !ISSET(NO_HELP) && in_bottomwin) {
1508
1509
1510
1511
	    int i;
		/* The width of all the shortcuts, except for the last
		 * two, in the shortcut list in bottomwin. */
	    int j;
1512
		/* The calculated index number of the clicked item. */
1513
1514
1515
1516
	    size_t currslen;
		/* The number of shortcuts in the current shortcut
		 * list. */

1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
	    /* Translate the mouse event coordinates so that they're
	     * relative to bottomwin. */
	    wmouse_trafo(bottomwin, mouse_y, mouse_x, FALSE);

	    /* Handle releases/clicks of the first mouse button on the
	     * statusbar elsewhere. */
	    if (*mouse_y == 0) {
		/* Restore the untranslated mouse event coordinates, so
		 * that they're relative to the entire screen again. */
		*mouse_x = mevent.x;
		*mouse_y = mevent.y;

		return 0;
	    }
1531

1532
	    /* Get the shortcut lists' length. */
1533
	    if (currmenu == MMAIN)
1534
		currslen = MAIN_VISIBLE;
1535
	    else {
1536
		currslen = length_of_list(currmenu);
1537

1538
1539
1540
1541
1542
		/* We don't show any more shortcuts than the main list
		 * does. */
		if (currslen > MAIN_VISIBLE)
		    currslen = MAIN_VISIBLE;
	    }
1543

1544
1545
1546
1547
1548
1549
1550
1551
	    /* 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. */
	    if (currslen < 2)
		i = COLS / (MAIN_VISIBLE / 2);
	    else
		i = COLS / ((currslen / 2) + (currslen % 2));

1552
1553
	    /* Calculate the one-based index in the shortcut list. */
	    j = (*mouse_x / i) * 2 + *mouse_y;
1554

1555
1556
	    /* Adjust the index if we hit the last two wider ones. */
	    if ((j > currslen) && (*mouse_x % i < COLS % i))
1557
		j -= 2;
1558
1559
1560
#ifdef DEBUG
	    fprintf(stderr, "Calculated %i as index in shortcut list, currmenu = %x.\n", j, currmenu);
#endif
1561
1562
	    /* Ignore releases/clicks of the first mouse button beyond
	     * the last shortcut. */
1563
	    if (j > currslen)
1564
		return 2;
1565

1566
1567
	    /* Go through the list of functions to determine which
	     * shortcut in the current menu we released/clicked on. */
1568
	    for (f = allfuncs; f != NULL; f = f->next) {
1569
		if ((f->menus & currmenu) == 0)
1570
1571
		    continue;
		if (first_sc_for(currmenu, f->scfunc) == NULL)
1572
		    continue;
1573
1574
		/* Tick off an actually shown shortcut. */
		j -= 1;
1575
1576
		if (j == 0)
		    break;
1577
	    }
1578
#ifdef DEBUG
1579
	    fprintf(stderr, "Stopped on func %ld present in menus %x\n", (long)f->scfunc, f->menus);
1580
#endif
1581

1582
	    /* And put the corresponding key into the keyboard buffer. */
1583
	    if (f != NULL) {
1584
		const sc *s = first_sc_for(currmenu, f->scfunc);
1585
		unget_kbinput(s->seq, s->type == META, s->type == FKEY);
1586
	    }
1587
	    return 1;
1588
	} else
1589
1590
	    /* Handle releases/clicks of the first mouse button that
	     * aren't on the current shortcut list elsewhere. */
1591
	    return 0;
1592
    }
1593
1594
#if NCURSES_MOUSE_VERSION >= 2
    /* Handle presses of the fourth mouse button (upward rolls of the
1595
1596
1597
     * mouse wheel) and presses of the fifth mouse button (downward
     * rolls of the mouse wheel) . */
    else if (mevent.bstate & (BUTTON4_PRESSED | BUTTON5_PRESSED)) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1598
	bool in_edit = wenclose(edit, *mouse_y, *mouse_x);
1599

1600
1601
1602
1603
	if (in_bottomwin)
	    /* Translate the mouse event coordinates so that they're
	     * relative to bottomwin. */
	    wmouse_trafo(bottomwin, mouse_y, mouse_x, FALSE);
1604

1605
	if (in_edit || (in_bottomwin && *mouse_y == 0)) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1606
1607
	    int i;

1608
1609
1610
1611
1612
	    /* One upward roll of the mouse wheel is equivalent to
	     * moving up three lines, and one downward roll of the mouse
	     * wheel is equivalent to moving down three lines. */
	    for (i = 0; i < 3; i++)
		unget_kbinput((mevent.bstate & BUTTON4_PRESSED) ?
1613
			sc_seq_or(do_up_void, 0) : sc_seq_or(do_down_void, 0),
1614
			FALSE, FALSE);
1615
1616
1617
1618
1619
1620
1621

	    return 1;
	} else
	    /* Ignore presses of the fourth mouse button and presses of
	     * the fifth mouse buttons that aren't on the edit window or
	     * the statusbar. */
	    return 2;
1622
1623
    }
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1624
1625
1626

    /* Ignore all other mouse events. */
    return 2;
1627
}
1628
1629
#endif /* !DISABLE_MOUSE */

1630
1631
1632
1633
/* Return the shortcut that corresponds to the values of kbinput (the
 * key itself) and meta_key (whether the key is a meta sequence).  The
 * returned shortcut will be the first in the list that corresponds to
 * the given sequence. */
1634
const sc *get_shortcut(int *kbinput)
1635
{
1636
    sc *s;
1637

1638
#ifdef DEBUG
1639
    fprintf(stderr, "get_shortcut(): kbinput = %d, meta_key = %s -- ", *kbinput, meta_key ? "TRUE" : "FALSE");
1640
1641
#endif

1642
    for (s = sclist; s != NULL; s = s->next) {
1643
	if ((s->menus & currmenu) && *kbinput == s->seq
1644
		&& meta_key == (s->type == META)) {
1645
#ifdef DEBUG
1646
	    fprintf (stderr, "matched seq \"%s\", and btw meta was %d (menu is %x from %x)\n",
1647
				s->keystr, meta_key, currmenu, s->menus);
1648
#endif
1649
	    return s;
1650
1651
	}
    }
1652
#ifdef DEBUG
1653
    fprintf (stderr, "matched nothing, btw meta was %d\n", meta_key);
1654
#endif
1655
1656
1657
1658

    return NULL;
}

1659
1660
1661
1662
1663
/* 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);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1664

1665
1666
1667
1668
    for (; n > 0; n--)
	waddch(win, ' ');
}

1669
/* Blank the first line of the top portion of the window. */
1670
void blank_titlebar(void)
Chris Allegretta's avatar
Chris Allegretta committed
1671
{
1672
    blank_line(topwin, 0, 0, COLS);
1673
1674
}

1675
1676
/* If the MORE_SPACE flag isn't set, blank the second line of the top
 * portion of the window. */
1677
1678
1679
void blank_topbar(void)
{
    if (!ISSET(MORE_SPACE))
1680
	blank_line(topwin, 1, 0, COLS);
1681
1682
}

1683
/* Blank all the lines of the middle portion of the window, i.e. the
1684
 * edit window. */
Chris Allegretta's avatar
Chris Allegretta committed
1685
1686
void blank_edit(void)
{
1687
    int i;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1688

1689
    for (i = 0; i < editwinrows; i++)
1690
	blank_line(edit, i, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1691
1692
}

1693
/* Blank the first line of the bottom portion of the window. */
Chris Allegretta's avatar
Chris Allegretta committed
1694
1695
void blank_statusbar(void)
{
1696
    blank_line(bottomwin, 0, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1697
1698
}

1699
1700
/* If the NO_HELP flag isn't set, blank the last two lines of the bottom
 * portion of the window. */
1701
1702
1703
void blank_bottombars(void)
{
    if (!ISSET(NO_HELP)) {
1704
1705
	blank_line(bottomwin, 1, 0, COLS);
	blank_line(bottomwin, 2, 0, COLS);
1706
1707
1708
    }
}

1709
1710
/* Check if the number of keystrokes needed to blank the statusbar has
 * been pressed.  If so, blank the statusbar, unless constant cursor
1711
 * position display is on and we are in the editing screen. */
1712
void check_statusblank(void)
Chris Allegretta's avatar
Chris Allegretta committed
1713
{
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
    if (statusblank == 0)
	return;

    statusblank--;

    /* When editing and 'constantshow' is active, skip the blanking. */
    if (currmenu == MMAIN && ISSET(CONST_UPDATE))
	return;

    if (statusblank == 0) {
	blank_statusbar();
	wnoutrefresh(bottomwin);
	reset_cursor();
	wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
1728
1729
1730
    }
}

1731
1732
1733
1734
/* 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
1735
1736
1737
1738
1739
 * 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)
1740
1741
{
    size_t start_index;
1742
	/* Index in buf of the first character shown. */
1743
    size_t column;
1744
	/* Screen column that start_index corresponds to. */
1745
1746
1747
1748
1749
1750
    size_t alloc_len;
	/* The length of memory allocated for converted. */
    char *converted;
	/* The string we return. */
    size_t index;
	/* Current position in converted. */
1751
    char *buf_mb;
1752
1753
    int buf_mb_len;

1754
1755
1756
1757
1758
    /* If dollars is TRUE, make room for the "$" at the end of the
     * line. */
    if (dollars && len > 0 && strlenpt(buf) > start_col + len)
	len--;

1759
1760
1761
    if (len == 0)
	return mallocstrcpy(NULL, "");

1762
1763
    buf_mb = charalloc(mb_cur_max());

1764
1765
    start_index = actual_x(buf, start_col);
    column = strnlenpt(buf, start_index);
1766

1767
    assert(column <= start_col);
1768

1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
    /* 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);
1784

1785
    index = 0;
1786
    seen_wide = FALSE;
1787

1788
1789
    if (buf[start_index] != '\0' && buf[start_index] != '\t' &&
	(column < start_col || (dollars && column > 0))) {
1790
1791
	/* We don't display all of buf[start_index] since it starts to
	 * the left of the screen. */
1792
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1793

1794
	if (is_cntrl_mbchar(buf_mb)) {
1795
	    if (column < start_col) {
1796
1797
		char *ctrl_buf_mb = charalloc(mb_cur_max());
		int ctrl_buf_mb_len, i;
1798

1799
1800
		ctrl_buf_mb = control_mbrep(buf_mb, ctrl_buf_mb,
			&ctrl_buf_mb_len);
1801

1802
1803
		for (i = 0; i < ctrl_buf_mb_len; i++)
		    converted[index++] = ctrl_buf_mb[i];
1804

1805
		start_col += mbwidth(ctrl_buf_mb);
1806

1807
		free(ctrl_buf_mb);
1808

1809
		start_index += buf_mb_len;
1810
	    }
1811
	}
1812
#ifdef ENABLE_UTF8
1813
1814
1815
1816
1817
1818
	else if (using_utf8() && mbwidth(buf_mb) == 2) {
	    if (column >= start_col) {
		converted[index++] = ' ';
		start_col++;
	    }

1819
	    converted[index++] = ' ';
1820
	    start_col++;
1821
1822

	    start_index += buf_mb_len;
1823
	}
1824
#endif
1825
1826
    }

1827
    while (buf[start_index] != '\0') {
1828
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1829

1830
1831
1832
	if (mbwidth(buf + start_index) > 1)
	    seen_wide = TRUE;

1833
1834
1835
1836
1837
1838
1839
1840
	/* 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);
	}

1841
	/* If buf contains a tab character, interpret it. */
1842
	if (*buf_mb == '\t') {
1843
#ifndef NANO_TINY
1844
1845
1846
1847
1848
1849
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i;

		for (i = 0; i < whitespace_len[0]; i++)
		    converted[index++] = whitespace[i];
	    } else
1850
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1851
		converted[index++] = ' ';
1852
	    start_col++;
1853
	    while (start_col % tabsize != 0) {
1854
		converted[index++] = ' ';
1855
1856
		start_col++;
	    }
1857
	/* If buf contains a control character, interpret it. */
1858
	} else if (is_cntrl_mbchar(buf_mb)) {
1859
1860
	    char *ctrl_buf_mb = charalloc(mb_cur_max());
	    int ctrl_buf_mb_len, i;
1861

1862
	    converted[index++] = '^';
1863
1864
	    start_col++;

1865
1866
	    ctrl_buf_mb = control_mbrep(buf_mb, ctrl_buf_mb,
		&ctrl_buf_mb_len);
1867

1868
1869
	    for (i = 0; i < ctrl_buf_mb_len; i++)
		converted[index++] = ctrl_buf_mb[i];
1870

1871
	    start_col += mbwidth(ctrl_buf_mb);
1872

1873
	    free(ctrl_buf_mb);
1874
	/* If buf contains a space character, interpret it. */
1875
	} else if (*buf_mb == ' ') {
1876
#ifndef NANO_TINY
1877
1878
1879
1880
1881
1882
1883
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i;

		for (i = whitespace_len[0]; i < whitespace_len[0] +
			whitespace_len[1]; i++)
		    converted[index++] = whitespace[i];
	    } else
1884
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1885
		converted[index++] = ' ';
1886
	    start_col++;
1887
1888
	/* If buf contains a non-control character, interpret it.  If buf
	 * contains an invalid multibyte sequence, display it as such. */
1889
	} else {
1890
1891
	    char *nctrl_buf_mb = charalloc(mb_cur_max());
	    int nctrl_buf_mb_len, i;
1892

1893
#ifdef ENABLE_UTF8
1894
1895
1896
	    /* Make sure an invalid sequence-starter byte is properly
	     * terminated, so that it doesn't pick up lingering bytes
	     * of any previous content. */
1897
1898
1899
	    if (using_utf8() && buf_mb_len == 1)
		buf_mb[1] = '\0';
#endif
1900

1901
1902
	    nctrl_buf_mb = mbrep(buf_mb, nctrl_buf_mb,
		&nctrl_buf_mb_len);
1903

1904
1905
1906
1907
1908
1909
	    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);
1910
1911
	}

1912
	start_index += buf_mb_len;
1913
1914
    }

1915
1916
    free(buf_mb);

1917
1918
    assert(alloc_len >= index + 1);

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1919
    /* Null-terminate converted. */
1920
    converted[index] = '\0';
1921
1922
1923

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

1926
    return converted;
1927
1928
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1929
1930
1931
1932
1933
1934
/* If path is NULL, we're in normal editing mode, so display the current
 * version of nano, the current filename, and whether the current file
 * has been modified on the titlebar.  If path isn't NULL, we're in the
 * file browser, and path contains the directory to start the file
 * browser in, so display the current version of nano and the contents
 * of path on the titlebar. */
1935
void titlebar(const char *path)
Chris Allegretta's avatar
Chris Allegretta committed
1936
{
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
    size_t verlen, prefixlen, pathlen, statelen;
	/* The width of the different titlebar elements, in columns. */
    size_t pluglen = 0;
	/* The width that "Modified" would take up. */
    size_t offset = 0;
	/* The position at which the center part of the titlebar starts. */
    const char *prefix = "";
	/* What is shown before the path -- "File:", "DIR:", or "". */
    const char *state = "";
	/* The state of the current buffer -- "Modified", "View", or "". */
    char *fragment;
	/* The tail part of the pathname when dottified. */
1949

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

1952
1953
1954
    if (interface_color_pair[TITLE_BAR].bright)
	wattron(topwin, A_BOLD);
    wattron(topwin, interface_color_pair[TITLE_BAR].pairnum);
1955

1956
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
1957

1958
1959
1960
    /* Do as Pico: if there is not enough width available for all items,
     * first sacrifice the version string, then eat up the side spaces,
     * then sacrifice the prefix, and only then start dottifying. */
Chris Allegretta's avatar
Chris Allegretta committed
1961

1962
    /* Figure out the path, prefix and state strings. */
1963
#ifndef DISABLE_BROWSER
1964
1965
1966
1967
    if (path != NULL)
	prefix = _("DIR:");
    else
#endif
1968
1969
1970
1971
1972
1973
1974
    {
	if (openfile->filename[0] == '\0')
	    path = _("New Buffer");
	else {
	    path = openfile->filename;
	    prefix = _("File:");
	}
1975

1976
1977
1978
1979
	if (openfile->modified)
	    state = _("Modified");
	else if (ISSET(VIEW_MODE))
	    state = _("View");
1980

1981
1982
	pluglen = strlenpt(_("Modified")) + 1;
    }
1983

1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
    /* Determine the widths of the four elements, including their padding. */
    verlen = strlenpt(BRANDING) + 3;
    prefixlen = strlenpt(prefix);
    if (prefixlen > 0)
	prefixlen++;
    pathlen= strlenpt(path);
    statelen = strlenpt(state) + 2;
    if (statelen > 2) {
	pathlen++;
	pluglen = 0;
1994
1995
    }

1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
    /* Only print the version message when there is room for it. */
    if (verlen + prefixlen + pathlen + pluglen + statelen <= COLS)
	mvwaddstr(topwin, 0, 2, BRANDING);
    else {
	verlen = 2;
	/* If things don't fit yet, give up the placeholder. */
	if (verlen + prefixlen + pathlen + pluglen + statelen > COLS)
	    pluglen = 0;
	/* If things still don't fit, give up the side spaces. */
	if (verlen + prefixlen + pathlen + pluglen + statelen > COLS) {
	    verlen = 0;
	    statelen -= 2;
2008
2009
2010
	}
    }

2011
2012
2013
2014
    /* If we have side spaces left, center the path name. */
    if (verlen > 0)
	offset = verlen + (COLS - (verlen + pluglen + statelen) -
					(prefixlen + pathlen)) / 2;
2015

2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
    /* Only print the prefix when there is room for it. */
    if (verlen + prefixlen + pathlen + pluglen + statelen <= COLS) {
	mvwaddstr(topwin, 0, offset, prefix);
	if (prefixlen > 0)
	    waddstr(topwin, " ");
    } else
	wmove(topwin, 0, offset);

    /* Print the full path if there's room; otherwise, dottify it. */
    if (pathlen + pluglen + statelen <= COLS)
	waddstr(topwin, path);
    else if (5 + statelen <= COLS) {
	waddstr(topwin, "...");
	fragment = display_string(path, 3 + pathlen - COLS + statelen,
					COLS - statelen, FALSE);
	waddstr(topwin, fragment);
	free(fragment);
2033
    }
2034

2035
2036
2037
2038
2039
2040
    /* Right-align the state if there's room; otherwise, trim it. */
    if (statelen > 0 && statelen <= COLS)
	mvwaddstr(topwin, 0, COLS - statelen, state);
    else if (statelen > 0)
	mvwaddnstr(topwin, 0, 0, state, actual_x(state, COLS));

2041
2042
    wattroff(topwin, A_BOLD);
    wattroff(topwin, interface_color_pair[TITLE_BAR].pairnum);
2043

2044
    wnoutrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
2045
    reset_cursor();
2046
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2047
2048
}

2049
2050
2051
2052
2053
2054
/* Display a normal message on the statusbar, quietly. */
void statusbar(const char *msg)
{
    statusline(HUSH, msg);
}

2055
/* Display a message on the statusbar, and set suppress_cursorpos to
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2056
2057
 * TRUE, so that the message won't be immediately overwritten if
 * constant cursor position display is on. */
2058
void statusline(bool sound, const char *msg, ...)
2059
2060
{
    va_list ap;
2061
    char *bar, *foo;
Benno Schulenberg's avatar
Benno Schulenberg committed
2062
    size_t start_x;
2063
2064
2065
2066
#ifndef NANO_TINY
    bool old_whitespace = ISSET(WHITESPACE_DISPLAY);

    UNSET(WHITESPACE_DISPLAY);
2067
#endif
2068
2069
2070
2071
2072

    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(). */
2073
    if (isendwin()) {
2074
2075
2076
2077
2078
	vfprintf(stderr, msg, ap);
	va_end(ap);
	return;
    }

2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
    /* If there already was an important message, ignore a normal one and
     * delay another important one, to allow the earlier one to be noticed. */
    if (alerted) {
	if (sound == HUSH)
	    return;
	napms(1200);
    }

    if (sound == ALERT) {
	beep();
	alerted = TRUE;
    }

2092
2093
2094
    /* Turn the cursor off while fiddling in the statusbar. */
    curs_set(0);

2095
2096
    blank_statusbar();

2097
2098
2099
2100
    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);
Benno Schulenberg's avatar
Benno Schulenberg committed
2101
    free(bar);
2102
2103

#ifndef NANO_TINY
2104
2105
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);
2106
#endif
Benno Schulenberg's avatar
Benno Schulenberg committed
2107
    start_x = (COLS - strlenpt(foo) - 4) / 2;
2108

2109
    wmove(bottomwin, 0, start_x);
2110
2111
2112
    if (interface_color_pair[STATUS_BAR].bright)
	wattron(bottomwin, A_BOLD);
    wattron(bottomwin, interface_color_pair[STATUS_BAR].pairnum);
2113
2114
2115
2116
    waddstr(bottomwin, "[ ");
    waddstr(bottomwin, foo);
    free(foo);
    waddstr(bottomwin, " ]");
2117
2118
    wattroff(bottomwin, A_BOLD);
    wattroff(bottomwin, interface_color_pair[STATUS_BAR].pairnum);
2119

2120
    wnoutrefresh(bottomwin);
2121

2122
    suppress_cursorpos = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2123

2124
2125
2126
    /* Push the message to the screen straightaway. */
    doupdate();

2127
    /* If we're doing quick statusbar blanking, blank it after just one
2128
2129
     * keystroke.  Otherwise, blank it after twenty-six keystrokes, as
     * Pico does. */
2130
#ifndef NANO_TINY
2131
2132
2133
    if (ISSET(QUICK_BLANK))
	statusblank = 1;
    else
2134
#endif
2135
	statusblank = 26;
2136
2137
}

2138
2139
/* Display the shortcut list corresponding to menu on the last two rows
 * of the bottom portion of the window. */
2140
void bottombars(int menu)
Chris Allegretta's avatar
Chris Allegretta committed
2141
{
2142
    size_t i, colwidth, slen;
2143
2144
    subnfunc *f;
    const sc *s;
2145

2146
2147
2148
    /* Set the global variable to the given menu. */
    currmenu = menu;

Chris Allegretta's avatar
Chris Allegretta committed
2149
2150
2151
    if (ISSET(NO_HELP))
	return;

2152
    if (menu == MMAIN) {
2153
	slen = MAIN_VISIBLE;
2154

2155
	assert(slen <= length_of_list(menu));
2156
    } else {
2157
	slen = length_of_list(menu);
2158

2159
	/* Don't show any more shortcuts than the main list does. */
2160
2161
2162
2163
	if (slen > MAIN_VISIBLE)
	    slen = MAIN_VISIBLE;
    }

2164
2165
2166
2167
    /* 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. */
2168
    colwidth = COLS / ((slen / 2) + (slen % 2));
Chris Allegretta's avatar
Chris Allegretta committed
2169

2170
    blank_bottombars();
2171

2172
2173
2174
#ifdef DEBUG
    fprintf(stderr, "In bottombars, and slen == \"%d\"\n", (int) slen);
#endif
2175

2176
    for (f = allfuncs, i = 0; i < slen && f != NULL; f = f->next) {
2177

2178
#ifdef DEBUG
2179
	fprintf(stderr, "Checking menu items....");
2180
#endif
2181
	if ((f->menus & menu) == 0)
2182
	    continue;
2183

2184
#ifdef DEBUG
2185
	fprintf(stderr, "found one! f->menus = %x, desc = \"%s\"\n", f->menus, f->desc);
2186
#endif
2187
2188
	s = first_sc_for(menu, f->scfunc);
	if (s == NULL) {
2189
2190
2191
#ifdef DEBUG
	    fprintf(stderr, "Whoops, guess not, no shortcut key found for func!\n");
#endif
2192
2193
	    continue;
	}
2194
	wmove(bottomwin, 1 + i % 2, (i / 2) * colwidth);
2195
#ifdef DEBUG
2196
	fprintf(stderr, "Calling onekey with keystr \"%s\" and desc \"%s\"\n", s->keystr, f->desc);
2197
#endif
2198
	onekey(s->keystr, _(f->desc), colwidth + (COLS % colwidth));
2199
	i++;
Chris Allegretta's avatar
Chris Allegretta committed
2200
    }
2201

2202
2203
    wnoutrefresh(bottomwin);
    reset_cursor();
2204
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2205
2206
}

2207
2208
/* 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
2209
 * to write at most length characters, even if length is very small and
2210
2211
 * keystroke and desc are long.  Note that waddnstr(,,(size_t)-1) adds
 * the whole string!  We do not bother padding the entry with blanks. */
2212
void onekey(const char *keystroke, const char *desc, int length)
Chris Allegretta's avatar
Chris Allegretta committed
2213
{
2214
2215
    assert(keystroke != NULL && desc != NULL);

2216
2217
2218
    if (interface_color_pair[KEY_COMBO].bright)
	wattron(bottomwin, A_BOLD);
    wattron(bottomwin, interface_color_pair[KEY_COMBO].pairnum);
2219
    waddnstr(bottomwin, keystroke, actual_x(keystroke, length));
2220
2221
    wattroff(bottomwin, A_BOLD);
    wattroff(bottomwin, interface_color_pair[KEY_COMBO].pairnum);
2222

2223
    length -= strlenpt(keystroke) + 1;
2224

2225
    if (length > 0) {
2226
	waddch(bottomwin, ' ');
2227
2228
2229
	if (interface_color_pair[FUNCTION_TAG].bright)
	    wattron(bottomwin, A_BOLD);
	wattron(bottomwin, interface_color_pair[FUNCTION_TAG].pairnum);
2230
	waddnstr(bottomwin, desc, actual_x(desc, length));
2231
2232
	wattroff(bottomwin, A_BOLD);
	wattroff(bottomwin, interface_color_pair[FUNCTION_TAG].pairnum);
Chris Allegretta's avatar
Chris Allegretta committed
2233
2234
2235
    }
}

2236
2237
/* Redetermine current_y from the position of current relative to edittop,
 * and put the cursor in the edit window at (current_y, current_x). */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2238
2239
void reset_cursor(void)
{
2240
    size_t xpt = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2241

2242
#ifndef NANO_TINY
2243
    if (ISSET(SOFTWRAP)) {
2244
	filestruct *line = openfile->edittop;
2245
2246
	openfile->current_y = 0;

2247
2248
2249
2250
	while (line != NULL && line != openfile->current) {
	    openfile->current_y += strlenpt(line->data) / COLS + 1;
	    line = line->next;
	}
2251
	openfile->current_y += xpt / COLS;
2252

2253
	if (openfile->current_y < editwinrows)
2254
	    wmove(edit, openfile->current_y, xpt % COLS);
2255
2256
2257
    } else
#endif
    {
2258
	openfile->current_y = openfile->current->lineno -
2259
				openfile->edittop->lineno;
2260
2261
2262
2263

	if (openfile->current_y < editwinrows)
	    wmove(edit, openfile->current_y, xpt - get_page_start(xpt));
    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2264
}
Chris Allegretta's avatar
Chris Allegretta committed
2265

2266
2267
2268
2269
2270
2271
2272
2273
/* 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. */
2274
void edit_draw(filestruct *fileptr, const char *converted, int
2275
	line, size_t start)
Chris Allegretta's avatar
Chris Allegretta committed
2276
{
2277
#if !defined(NANO_TINY) || !defined(DISABLE_COLOR)
2278
2279
2280
2281
2282
2283
2284
2285
2286
    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. */
2287
2288
#endif

2289
    assert(openfile != NULL && fileptr != NULL && converted != NULL);
2290
    assert(strlenpt(converted) <= COLS);
2291

2292
2293
2294
    /* First simply paint the line -- then we'll add colors or the
     * marking highlight on just the pieces that need it. */
    mvwaddstr(edit, line, 0, converted);
2295

2296
#ifndef USE_SLANG
2297
2298
2299
    /* Tell ncurses to really redraw the line without trying to optimize
     * for what it thinks is already there, because it gets it wrong in
     * the case of a wide character in column zero.  See bug #31743. */
2300
2301
    if (seen_wide)
	wredrawln(edit, line, 1);
2302
#endif
2303

2304
#ifndef DISABLE_COLOR
2305
2306
2307
    /* If color syntaxes are available and turned on, we need to display
     * them. */
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX)) {
2308
	const colortype *varnish = openfile->colorstrings;
2309

2310
2311
2312
2313
	/* If there are multiline regexes, make sure there is a cache. */
	if (openfile->syntax->nmultis > 0)
	    alloc_multidata_if_needed(fileptr);

2314
	for (; varnish != NULL; varnish = varnish->next) {
2315
2316
	    int x_start;
		/* Starting column for mvwaddnstr.  Zero-based. */
2317
	    int paintlen = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2318
2319
		/* Number of chars to paint on this line.  There are
		 * COLS characters on a whole line. */
2320
	    size_t index;
2321
		/* Index in converted where we paint. */
2322
2323
2324
2325
	    regmatch_t startmatch;
		/* Match position for start_regex. */
	    regmatch_t endmatch;
		/* Match position for end_regex. */
2326

2327
	    if (varnish->bright)
2328
		wattron(edit, A_BOLD);
2329
	    wattron(edit, COLOR_PAIR(varnish->pairnum));
2330
2331
2332
	    /* 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. */
2333

2334
2335
	    /* First case: varnish is a single-line expression. */
	    if (varnish->end == NULL) {
2336
2337
2338
		size_t k = 0;

		/* We increment k by rm_eo, to move past the end of the
2339
		 * last match.  Even though two matches may overlap, we
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2340
2341
		 * want to ignore them, so that we can highlight e.g. C
		 * strings correctly. */
2342
2343
2344
		while (k < endpos) {
		    /* Note the fifth parameter to regexec().  It says
		     * not to match the beginning-of-line character
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2345
2346
2347
		     * unless k is zero.  If regexec() returns
		     * REG_NOMATCH, there are no more matches in the
		     * line. */
2348
		    if (regexec(varnish->start, &fileptr->data[k], 1,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2349
2350
			&startmatch, (k == 0) ? 0 : REG_NOTBOL) ==
			REG_NOMATCH)
2351
			break;
2352
2353
		    /* Translate the match to the beginning of the
		     * line. */
2354
2355
		    startmatch.rm_so += k;
		    startmatch.rm_eo += k;
2356
2357
2358

		    /* Skip over a zero-length regex match. */
		    if (startmatch.rm_so == startmatch.rm_eo)
2359
			startmatch.rm_eo++;
2360
		    else if (startmatch.rm_so < endpos &&
2361
			startmatch.rm_eo > startpos) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2362
2363
			x_start = (startmatch.rm_so <= startpos) ? 0 :
				strnlenpt(fileptr->data,
2364
				startmatch.rm_so) - start;
2365

2366
2367
2368
			index = actual_x(converted, x_start);

			paintlen = actual_x(converted + index,
2369
2370
				strnlenpt(fileptr->data,
				startmatch.rm_eo) - start - x_start);
2371
2372
2373

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

2374
			mvwaddnstr(edit, line, x_start, converted +
2375
				index, paintlen);
2376
		    }
2377
		    k = startmatch.rm_eo;
Chris Allegretta's avatar
Chris Allegretta committed
2378
		}
2379
	    } else {	/* Second case: varnish is a multiline expression. */
2380
		const filestruct *start_line = fileptr->prev;
2381
		    /* The first line before fileptr that matches 'start'. */
2382
		regoff_t start_col;
2383
		    /* Where the match starts in that line. */
2384
		const filestruct *end_line;
2385
		    /* The line that matches 'end'. */
2386

2387
		/* First see if the multidata was maybe already calculated. */
2388
		if (fileptr->multidata[varnish->id] == CNONE)
2389
		    goto tail_of_loop;
2390
		else if (fileptr->multidata[varnish->id] == CWHOLELINE) {
2391
		    mvwaddnstr(edit, line, 0, converted, -1);
2392
		    goto tail_of_loop;
2393
2394
		} else if (fileptr->multidata[varnish->id] == CBEGINBEFORE) {
		    regexec(varnish->end, fileptr->data, 1, &endmatch, 0);
2395
2396
		    /* If the coloured part is scrolled off, skip it. */
		    if (endmatch.rm_eo <= startpos)
2397
			goto tail_of_loop;
2398
2399
2400
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
			endmatch.rm_eo) - start);
		    mvwaddnstr(edit, line, 0, converted, paintlen);
2401
		    goto tail_of_loop;
2402
		} if (fileptr->multidata[varnish->id] == -1)
2403
		    /* Assume this until proven otherwise below. */
2404
		    fileptr->multidata[varnish->id] = CNONE;
2405

2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
		/* There is no precalculated multidata, so find it out now.
		 * First check if the beginning of the line is colored by a
		 * start on an earlier line, and an end on this line or later.
		 *
		 * So: find the first line before fileptr matching the start.
		 * If every match on that line is followed by an end, then go
		 * to step two.  Otherwise, find a line after start_line that
		 * matches the end.  If that line is not before fileptr, then
		 * paint the beginning of this line. */

2416
		while (start_line != NULL && regexec(varnish->start,
2417
2418
2419
			start_line->data, 1, &startmatch, 0) == REG_NOMATCH) {
		    /* There is no start; but if there is an end on this line,
		     * there is no need to look for starts on earlier lines. */
2420
		    if (regexec(varnish->end, start_line->data, 0, NULL, 0) == 0)
2421
2422
2423
			goto step_two;
		    start_line = start_line->prev;
		}
2424

2425
2426
2427
2428
		/* If no start was found, skip to the next step. */
		if (start_line == NULL)
		    goto step_two;

2429
		/* If a found start has been qualified as an end earlier,
2430
		 * believe it and skip to the next step. */
2431
		if (start_line->multidata != NULL &&
2432
2433
			(start_line->multidata[varnish->id] == CBEGINBEFORE ||
			start_line->multidata[varnish->id] == CSTARTENDHERE))
2434
2435
		    goto step_two;

2436
		/* Skip over a zero-length regex match. */
2437
		if (startmatch.rm_so == startmatch.rm_eo)
2438
2439
		    goto tail_of_loop;

2440
2441
2442
2443
2444
2445
2446
		/* Now start_line is the first line before fileptr containing
		 * a start match.  Is there a start on that line not followed
		 * by an end on that line? */
		start_col = 0;
		while (TRUE) {
		    start_col += startmatch.rm_so;
		    startmatch.rm_eo -= startmatch.rm_so;
2447
		    if (regexec(varnish->end, start_line->data +
2448
2449
2450
				start_col + startmatch.rm_eo, 0, NULL,
				(start_col + startmatch.rm_eo == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH)
2451
2452
2453
			/* No end found after this start. */
			break;
		    start_col++;
2454
		    if (regexec(varnish->start, start_line->data +
2455
2456
				start_col, 1, &startmatch,
				REG_NOTBOL) == REG_NOMATCH)
2457
2458
2459
2460
2461
2462
2463
2464
2465
			/* No later start on this line. */
			goto step_two;
		}
		/* Indeed, there is a start without an end on that line. */

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

2470
2471
2472
2473
		/* If no end was found, or it is too early, next step. */
		if (end_line == NULL)
		    goto step_two;
		if (end_line == fileptr && endmatch.rm_eo <= startpos) {
2474
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2475
2476
		    goto step_two;
		}
2477

2478
2479
2480
2481
2482
2483
2484
		/* Now paint the start of fileptr.  If the start of fileptr
		 * is on a different line from the end, paintlen is -1, which
		 * means that everything on the line gets painted.  Otherwise,
		 * paintlen is the expanded location of the end of the match
		 * minus the expanded location of the beginning of the page. */
		if (end_line != fileptr) {
		    paintlen = -1;
2485
		    fileptr->multidata[varnish->id] = CWHOLELINE;
2486
#ifdef DEBUG
2487
    fprintf(stderr, "  Marking for id %i  line %i as CWHOLELINE\n", varnish->id, line);
2488
#endif
2489
2490
2491
		} else {
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
						endmatch.rm_eo) - start);
2492
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2493
#ifdef DEBUG
2494
    fprintf(stderr, "  Marking for id %i  line %i as CBEGINBEFORE\n", varnish->id, line);
2495
#endif
2496
2497
2498
2499
2500
2501
		}
		mvwaddnstr(edit, line, 0, converted, paintlen);
		/* If the whole line has been painted, don't bother looking
		 * for any more starts. */
		if (paintlen < 0)
		    goto tail_of_loop;
2502
  step_two:
2503
2504
2505
2506
2507
		/* Second step: look for starts on this line, but start
		 * looking only after an end match, if there is one. */
		start_col = (paintlen == 0) ? 0 : endmatch.rm_eo;

		while (start_col < endpos) {
2508
		    if (regexec(varnish->start, fileptr->data + start_col,
2509
2510
				1, &startmatch, (start_col == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH ||
2511
				start_col + startmatch.rm_so >= endpos)
2512
2513
			/* No more starts on this line. */
			break;
2514

2515
2516
2517
2518
2519
2520
2521
		    /* Translate the match to be relative to the
		     * beginning of the line. */
		    startmatch.rm_so += start_col;
		    startmatch.rm_eo += start_col;

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

2524
		    index = actual_x(converted, x_start);
2525

2526
		    if (regexec(varnish->end, fileptr->data +
2527
				startmatch.rm_eo, 1, &endmatch,
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
				(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 &&
2538
				endmatch.rm_eo > startmatch.rm_so) {
2539
			    paintlen = actual_x(converted + index,
2540
					strnlenpt(fileptr->data,
2541
					endmatch.rm_eo) - start - x_start);
2542

2543
			    assert(0 <= x_start && x_start < COLS);
2544

2545
			    mvwaddnstr(edit, line, x_start,
2546
					converted + index, paintlen);
2547
			    if (paintlen > 0) {
2548
				fileptr->multidata[varnish->id] = CSTARTENDHERE;
2549
#ifdef DEBUG
2550
    fprintf(stderr, "  Marking for id %i  line %i as CSTARTENDHERE\n", varnish->id, line);
2551
#endif
2552
			    }
2553
2554
			}
			start_col = endmatch.rm_eo;
2555
2556
2557
			/* Skip over a zero-length match. */
			if (endmatch.rm_so == endmatch.rm_eo)
			    start_col += 1;
2558
2559
2560
2561
		    } else {
			/* There is no end on this line.  But we haven't yet
			 * looked for one on later lines. */
			end_line = fileptr->next;
2562

2563
			while (end_line != NULL &&
2564
				regexec(varnish->end, end_line->data,
2565
				0, NULL, 0) == REG_NOMATCH)
2566
			    end_line = end_line->next;
2567

2568
2569
2570
			/* If there is no end, we're done on this line. */
			if (end_line == NULL)
			    break;
2571

2572
2573
2574
2575
			assert(0 <= x_start && x_start < COLS);

			/* Paint the rest of the line. */
			mvwaddnstr(edit, line, x_start, converted + index, -1);
2576
			fileptr->multidata[varnish->id] = CENDAFTER;
2577
#ifdef DEBUG
2578
    fprintf(stderr, "  Marking for id %i  line %i as CENDAFTER\n", varnish->id, line);
2579
#endif
2580
2581
2582
			/* We've painted to the end of the line, so don't
			 * bother checking for any more starts. */
			break;
2583
		    }
2584
2585
		}
	    }
2586
  tail_of_loop:
2587
	    wattroff(edit, A_BOLD);
2588
	    wattroff(edit, COLOR_PAIR(varnish->pairnum));
2589
	}
2590
    }
2591
#endif /* !DISABLE_COLOR */
2592

2593
#ifndef NANO_TINY
2594
    /* If the mark is on, we need to display it. */
2595
    if (openfile->mark_set && (fileptr->lineno <=
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2596
	openfile->mark_begin->lineno || fileptr->lineno <=
2597
	openfile->current->lineno) && (fileptr->lineno >=
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2598
	openfile->mark_begin->lineno || fileptr->lineno >=
2599
	openfile->current->lineno)) {
2600
	/* fileptr is at least partially selected. */
2601
	const filestruct *top;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2602
	    /* Either current or mark_begin, whichever is first. */
2603
	size_t top_x;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2604
	    /* current_x or mark_begin_x, corresponding to top. */
2605
2606
	const filestruct *bot;
	size_t bot_x;
2607
	int x_start;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2608
	    /* Starting column for mvwaddnstr().  Zero-based. */
2609
	int paintlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2610
2611
	    /* Number of characters to paint on this line.  There are
	     * COLS characters on a whole line. */
2612
	size_t index;
2613
	    /* Index in converted where we paint. */
2614

2615
	mark_order(&top, &top_x, &bot, &bot_x, NULL);
2616
2617
2618
2619
2620

	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
2621

2622
	/* The selected bit of fileptr is on this page. */
2623
2624
	if (top_x < endpos && bot_x > startpos) {
	    assert(startpos <= top_x);
2625
2626
2627
2628

	    /* 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;
2629

2630
2631
2632
2633
2634
	    /* If the end of the mark is off the page, paintlen is -1,
	     * meaning that everything on the line gets painted.
	     * Otherwise, paintlen is the expanded location of the end
	     * of the mark minus the expanded location of the beginning
	     * of the mark. */
2635
2636
2637
2638
2639
	    if (bot_x >= endpos)
		paintlen = -1;
	    else
		paintlen = strnlenpt(fileptr->data, bot_x) - (x_start +
			start);
2640
2641
2642
2643
2644
2645
2646
2647

	    /* 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;
	    }
2648
2649
2650

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

2651
	    index = actual_x(converted, x_start);
2652

2653
2654
2655
	    if (paintlen > 0)
		paintlen = actual_x(converted + index, paintlen);

2656
	    wattron(edit, hilite_attribute);
2657
	    mvwaddnstr(edit, line, x_start, converted + index,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2658
		paintlen);
2659
	    wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
2660
	}
2661
    }
2662
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
2663
2664
}

2665
/* Just update one line in the edit buffer.  This is basically a wrapper
2666
 * for edit_draw().  The line will be displayed starting with
2667
 * fileptr->data[index].  Likely arguments are current_x or zero.
2668
 * Returns: Number of additional lines consumed (needed for SOFTWRAP). */
2669
int update_line(filestruct *fileptr, size_t index)
Chris Allegretta's avatar
Chris Allegretta committed
2670
{
2671
    int line = 0;
2672
	/* The line in the edit window that we want to update. */
2673
    int extralinesused = 0;
2674
2675
2676
2677
    char *converted;
	/* fileptr->data converted to have tabs and control characters
	 * expanded. */
    size_t page_start;
Chris Allegretta's avatar
Chris Allegretta committed
2678

2679
    assert(fileptr != NULL);
2680

2681
#ifndef NANO_TINY
2682
    if (ISSET(SOFTWRAP)) {
2683
2684
	filestruct *tmp;

2685
2686
	for (tmp = openfile->edittop; tmp && tmp != fileptr; tmp = tmp->next)
	    line += (strlenpt(tmp->data) / COLS) + 1;
2687
    } else
2688
#endif
2689
2690
	line = fileptr->lineno - openfile->edittop->lineno;

2691
    if (line < 0 || line >= editwinrows)
Chris Allegretta's avatar
Chris Allegretta committed
2692
	return 1;
2693

2694
    /* First, blank out the line. */
2695
    blank_line(edit, line, 0, COLS);
2696

2697
2698
    /* Next, convert variables that index the line to their equivalent
     * positions in the expanded line. */
2699
#ifndef NANO_TINY
2700
2701
2702
    if (ISSET(SOFTWRAP))
	index = 0;
    else
2703
#endif
2704
	index = strnlenpt(fileptr->data, index);
2705
    page_start = get_page_start(index);
2706

2707
2708
    /* Expand the line, replacing tabs with spaces, and control
     * characters with their displayed forms. */
2709
2710
2711
#ifdef NANO_TINY
    converted = display_string(fileptr->data, page_start, COLS, TRUE);
#else
2712
2713
2714
    converted = display_string(fileptr->data, page_start, COLS, !ISSET(SOFTWRAP));
#ifdef DEBUG
    if (ISSET(SOFTWRAP) && strlen(converted) >= COLS - 2)
2715
	fprintf(stderr, "update_line(): converted(1) line = %s\n", converted);
2716
#endif
2717
#endif /* !NANO_TINY */
2718

2719
    /* Paint the line. */
2720
    edit_draw(fileptr, converted, line, page_start);
2721
    free(converted);
Chris Allegretta's avatar
Chris Allegretta committed
2722

2723
#ifndef NANO_TINY
2724
    if (!ISSET(SOFTWRAP)) {
2725
#endif
2726
2727
2728
2729
	if (page_start > 0)
	    mvwaddch(edit, line, 0, '$');
	if (strlenpt(fileptr->data) > page_start + COLS)
	    mvwaddch(edit, line, COLS - 1, '$');
2730
#ifndef NANO_TINY
2731
    } else {
2732
	size_t full_length = strlenpt(fileptr->data);
2733
	for (index += COLS; index <= full_length && line < editwinrows - 1; index += COLS) {
2734
2735
	    line++;
#ifdef DEBUG
2736
	    fprintf(stderr, "update_line(): softwrap code, moving to %d index %lu\n", line, (unsigned long)index);
2737
#endif
2738
	    blank_line(edit, line, 0, COLS);
2739
2740

	    /* Expand the line, replacing tabs with spaces, and control
2741
	     * characters with their displayed forms. */
2742
2743
2744
2745
2746
	    converted = display_string(fileptr->data, index, COLS, !ISSET(SOFTWRAP));
#ifdef DEBUG
	    if (ISSET(SOFTWRAP) && strlen(converted) >= COLS - 2)
		fprintf(stderr, "update_line(): converted(2) line = %s\n", converted);
#endif
2747
2748
2749

	    /* Paint the line. */
	    edit_draw(fileptr, converted, line, index);
2750
	    free(converted);
2751
2752
2753
	    extralinesused++;
	}
    }
2754
#endif /* !NANO_TINY */
2755
    return extralinesused;
Chris Allegretta's avatar
Chris Allegretta committed
2756
2757
}

2758
2759
2760
2761
/* Return TRUE if we need an update after moving the cursor, and
 * FALSE otherwise.  We need an update if the mark is on, or if
 * pww_save and placewewant are on different pages. */
bool need_screen_update(size_t pww_save)
2762
2763
{
    return
2764
#ifndef NANO_TINY
2765
	openfile->mark_set ||
2766
#endif
2767
	get_page_start(pww_save) != get_page_start(openfile->placewewant);
2768
2769
}

2770
/* When edittop changes, try and figure out how many lines
2771
 * we really have to work with (i.e. set maxrows). */
2772
2773
2774
2775
2776
void compute_maxrows(void)
{
    int n;
    filestruct *foo = openfile->edittop;

2777
2778
2779
2780
2781
    if (!ISSET(SOFTWRAP)) {
	maxrows = editwinrows;
	return;
    }

2782
2783
    maxrows = 0;
    for (n = 0; n < editwinrows && foo; n++) {
2784
	maxrows++;
2785
	n += strlenpt(foo->data) / COLS;
2786
2787
2788
	foo = foo->next;
    }

2789
2790
2791
    if (n < editwinrows)
	maxrows += editwinrows - n;

2792
#ifdef DEBUG
2793
    fprintf(stderr, "compute_maxrows(): maxrows = %d\n", maxrows);
2794
2795
2796
#endif
}

2797
2798
/* 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
2799
2800
 * scrolling.  direction is the direction to scroll, either UPWARD or
 * DOWNWARD, and nlines is the number of lines to scroll.  We change
2801
2802
 * edittop, and assume that current and current_x are up to date.  We
 * also assume that scrollok(edit) is FALSE. */
2803
void edit_scroll(scroll_dir direction, ssize_t nlines)
2804
{
2805
    ssize_t i;
2806
    filestruct *foo;
2807

2808
    assert(nlines > 0);
2809

2810
2811
2812
    /* Part 1: nlines is the number of lines we're going to scroll the
     * text of the edit window. */

2813
    /* Move the top line of the edit window up or down (depending on the
2814
2815
     * value of direction) nlines lines, or as many lines as we can if
     * there are fewer than nlines lines available. */
2816
    for (i = nlines; i > 0; i--) {
2817
	if (direction == UPWARD) {
2818
	    if (openfile->edittop == openfile->fileage)
2819
		break;
2820
	    openfile->edittop = openfile->edittop->prev;
2821
	} else {
2822
	    if (openfile->edittop == openfile->filebot)
2823
		break;
2824
	    openfile->edittop = openfile->edittop->next;
2825
	}
2826
2827

#ifndef NANO_TINY
2828
	/* Don't over-scroll on long lines. */
2829
	if (ISSET(SOFTWRAP) && direction == UPWARD) {
2830
	    ssize_t len = strlenpt(openfile->edittop->data) / COLS;
2831
	    i -= len;
2832
	    if (len > 0)
2833
		refresh_needed = TRUE;
2834
	}
2835
#endif
2836
2837
    }

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

2841
2842
2843
2844
    /* Don't bother scrolling zero lines, nor more than the window can hold. */
    if (nlines == 0)
	return;
    if (nlines >= editwinrows)
2845
	refresh_needed = TRUE;
2846

2847
    if (refresh_needed == TRUE)
2848
	return;
2849
2850
2851

    /* Scroll the text of the edit window up or down nlines lines,
     * depending on the value of direction. */
2852
    scrollok(edit, TRUE);
2853
    wscrl(edit, (direction == UPWARD) ? -nlines : nlines);
2854
2855
    scrollok(edit, FALSE);

2856
2857
2858
    /* Part 2: nlines is the number of lines in the scrolled region of
     * the edit window that we need to draw. */

2859
2860
    /* If the top or bottom line of the file is now visible in the edit
     * window, we need to draw the entire edit window. */
2861
2862
    if ((direction == UPWARD && openfile->edittop ==
	openfile->fileage) || (direction == DOWNWARD &&
2863
2864
	openfile->edittop->lineno + editwinrows - 1 >=
	openfile->filebot->lineno))
2865
	nlines = editwinrows;
2866

2867
2868
2869
2870
2871
2872
    /* 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
2873

2874
2875
    if (nlines > editwinrows)
	nlines = editwinrows;
2876
2877
2878

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

2881
2882
    /* If we scrolled down, move down to the line before the scrolled
     * region. */
2883
    if (direction == DOWNWARD) {
2884
	for (i = editwinrows - nlines; i > 0 && foo != NULL; i--)
2885
2886
2887
	    foo = foo->next;
    }

2888
2889
2890
2891
2892
2893
    /* 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--) {
2894
2895
	if ((i == nlines && direction == DOWNWARD) || (i == 1 &&
		direction == UPWARD)) {
2896
	    if (need_screen_update(0))
2897
2898
2899
2900
		update_line(foo, (foo == openfile->current) ?
			openfile->current_x : 0);
	} else
	    update_line(foo, (foo == openfile->current) ?
2901
		openfile->current_x : 0);
2902
	foo = foo->next;
2903
    }
2904
    compute_maxrows();
2905
2906
2907
}

/* Update any lines between old_current and current that need to be
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2908
 * updated.  Use this if we've moved without changing any text. */
2909
void edit_redraw(filestruct *old_current)
2910
{
2911
2912
2913
2914
    size_t was_pww = openfile->placewewant;

    openfile->placewewant = xplustabs();

2915
2916
    /* If the current line is offscreen, scroll until it's onscreen. */
    if (openfile->current->lineno >= openfile->edittop->lineno + maxrows ||
2917
		openfile->current->lineno < openfile->edittop->lineno) {
2918
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : FLOWING);
2919
	refresh_needed = TRUE;
2920
    }
2921

2922
#ifndef NANO_TINY
2923
2924
2925
    /* If the mark is on, update all lines between old_current and current. */
    if (openfile->mark_set) {
	filestruct *foo = old_current;
2926

2927
	while (foo != openfile->current) {
2928
	    update_line(foo, 0);
2929

2930
2931
2932
	    foo = (foo->lineno > openfile->current->lineno) ?
			foo->prev : foo->next;
	}
2933
2934
2935
2936
2937
2938
    } else
#endif
	/* Otherwise, update old_current only if it differs from current
	 * and was horizontally scrolled. */
	if (old_current != openfile->current && get_page_start(was_pww) > 0)
	    update_line(old_current, 0);
2939
2940
2941
2942
2943

    /* Update current if we've changed page, or if it differs from
     * old_current and needs to be horizontally scrolled. */
    if (need_screen_update(was_pww) || (old_current != openfile->current &&
			get_page_start(openfile->placewewant) > 0))
2944
	update_line(openfile->current, openfile->current_x);
2945
2946
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2947
2948
/* 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
2949
2950
void edit_refresh(void)
{
2951
    filestruct *foo;
2952
    int nlines;
2953

2954
    /* Figure out what maxrows should really be. */
2955
    compute_maxrows();
2956

2957
2958
    if (openfile->current->lineno < openfile->edittop->lineno ||
	openfile->current->lineno >= openfile->edittop->lineno +
2959
2960
	maxrows) {
#ifdef DEBUG
2961
2962
	fprintf(stderr, "edit_refresh(): line = %ld, edittop %ld + maxrows %d\n",
		(long)openfile->current->lineno, (long)openfile->edittop->lineno, maxrows);
2963
2964
#endif

2965
	/* Make sure the current line is on the screen. */
2966
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : STATIONARY);
2967
    }
Chris Allegretta's avatar
Chris Allegretta committed
2968

2969
2970
    foo = openfile->edittop;

2971
#ifdef DEBUG
2972
    fprintf(stderr, "edit_refresh(): edittop->lineno = %ld\n", (long)openfile->edittop->lineno);
2973
#endif
2974

2975
    for (nlines = 0; nlines < editwinrows && foo != NULL; nlines++) {
2976
	nlines += update_line(foo, (foo == openfile->current) ?
2977
		openfile->current_x : 0);
2978
2979
2980
	foo = foo->next;
    }

2981
    for (; nlines < editwinrows; nlines++)
2982
2983
2984
	blank_line(edit, nlines, 0, COLS);

    reset_cursor();
2985
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2986
2987
}

2988
2989
2990
2991
2992
2993
/* Move edittop so that current is on the screen.  manner says how it
 * should be moved: CENTERING means that current should end up in the
 * middle of the screen, STATIONARY means that it should stay at the
 * same vertical position, and FLOWING means that it should scroll no
 * more than needed to bring current into view. */
void edit_update(update_type manner)
Chris Allegretta's avatar
Chris Allegretta committed
2994
{
2995
    int goal = 0;
2996

2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
    /* If manner is CENTERING, move edittop half the number of window
     * lines back from current.  If manner is STATIONARY, move edittop
     * back current_y lines if current_y is in range of the screen,
     * 0 lines if current_y is below zero, or (editwinrows - 1) lines
     * if current_y is too big.  This puts current at the same place
     * on the screen as before, or at the top or bottom if current_y is
     * beyond either.  If manner is FLOWING, move edittop back 0 lines
     * or (editwinrows - 1) lines, depending or where current has moved.
     * This puts the cursor on the first or the last line. */
    if (manner == CENTERING)
3007
	goal = editwinrows / 2;
3008
    else if (manner == FLOWING) {
3009
	if (openfile->current->lineno >= openfile->edittop->lineno)
3010
3011
	    goal = editwinrows - 1;
    } else {
3012
	goal = openfile->current_y;
3013

3014
	/* Limit goal to (editwinrows - 1) lines maximum. */
3015
3016
	if (goal > editwinrows - 1)
	    goal = editwinrows - 1;
Chris Allegretta's avatar
Chris Allegretta committed
3017
    }
3018

3019
3020
3021
3022
3023
    openfile->edittop = openfile->current;

    while (goal > 0 && openfile->edittop->prev != NULL) {
	openfile->edittop = openfile->edittop->prev;
	goal --;
3024
#ifndef NANO_TINY
3025
3026
	if (ISSET(SOFTWRAP))
	    goal -= strlenpt(openfile->edittop->data) / COLS;
3027
#endif
3028
    }
3029
#ifdef DEBUG
3030
    fprintf(stderr, "edit_update(): setting edittop to lineno %ld\n", (long)openfile->edittop->lineno);
3031
#endif
3032
    compute_maxrows();
Chris Allegretta's avatar
Chris Allegretta committed
3033
3034
}

3035
/* Unconditionally redraw the entire screen. */
3036
void total_redraw(void)
3037
{
3038
3039
3040
3041
3042
3043
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 4: Slang doesn't define
     * curscr. */
    SLsmg_touch_screen();
    SLsmg_refresh();
#else
3044
    wrefresh(curscr);
3045
#endif
3046
3047
}

3048
3049
/* Unconditionally redraw the entire screen, and then refresh it using
 * the current file. */
3050
3051
void total_refresh(void)
{
3052
    total_redraw();
3053
    titlebar(NULL);
3054
    edit_refresh();
3055
    bottombars(currmenu);
3056
3057
}

3058
3059
/* Display the main shortcut list on the last two rows of the bottom
 * portion of the window. */
3060
3061
void display_main_list(void)
{
3062
#ifndef DISABLE_COLOR
3063
3064
3065
    if (openfile->syntax
	  && (openfile->syntax->formatter || openfile->syntax->linter))
	set_lint_or_format_shortcuts();
3066
3067
3068
3069
    else
	set_spell_shortcuts();
#endif

3070
    bottombars(MMAIN);
3071
3072
}

3073
/* If constant is TRUE, we display the current cursor position only if
3074
3075
 * suppress_cursorpos is FALSE.  If constant is FALSE, we display the
 * position always.  In any case we reset suppress_cursorpos to FALSE. */
3076
void do_cursorpos(bool constant)
Chris Allegretta's avatar
Chris Allegretta committed
3077
{
3078
    filestruct *f;
3079
    char c;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3080
    size_t i, cur_xpt = xplustabs() + 1;
3081
    size_t cur_lenpt = strlenpt(openfile->current->data) + 1;
3082
    int linepct, colpct, charpct;
Chris Allegretta's avatar
Chris Allegretta committed
3083

3084
    assert(openfile->fileage != NULL && openfile->current != NULL);
3085

3086
    /* Determine the size of the file up to the cursor. */
3087
    f = openfile->current->next;
3088
    c = openfile->current->data[openfile->current_x];
3089
3090

    openfile->current->next = NULL;
3091
    openfile->current->data[openfile->current_x] = '\0';
3092
3093
3094

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

3095
    openfile->current->data[openfile->current_x] = c;
3096
    openfile->current->next = f;
3097

3098
    /* If the position needs to be suppressed, don't suppress it next time. */
3099
    if (suppress_cursorpos && constant) {
3100
	suppress_cursorpos = FALSE;
3101
	return;
3102
    }
Chris Allegretta's avatar
Chris Allegretta committed
3103

3104
    /* Display the current cursor position on the statusbar. */
3105
    linepct = 100 * openfile->current->lineno / openfile->filebot->lineno;
3106
    colpct = 100 * cur_xpt / cur_lenpt;
3107
    charpct = (openfile->totsize == 0) ? 0 : 100 * i / openfile->totsize;
3108

3109
    statusline(HUSH,
3110
	_("line %ld/%ld (%d%%), col %lu/%lu (%d%%), char %lu/%lu (%d%%)"),
3111
	(long)openfile->current->lineno,
3112
	(long)openfile->filebot->lineno, linepct,
3113
	(unsigned long)cur_xpt, (unsigned long)cur_lenpt, colpct,
3114
	(unsigned long)i, (unsigned long)openfile->totsize, charpct);
3115
3116
3117

    /* Displaying the cursor position should not suppress it next time. */
    suppress_cursorpos = FALSE;
Chris Allegretta's avatar
Chris Allegretta committed
3118
3119
}

3120
/* Unconditionally display the current cursor position. */
3121
void do_cursorpos_void(void)
3122
{
3123
    do_cursorpos(FALSE);
3124
3125
}

3126
3127
void enable_nodelay(void)
{
3128
3129
    nodelay_mode = TRUE;
    nodelay(edit, TRUE);
3130
3131
3132
3133
}

void disable_nodelay(void)
{
3134
3135
    nodelay_mode = FALSE;
    nodelay(edit, FALSE);
3136
3137
}

3138
3139
/* Highlight the current word being replaced or spell checked.  We
 * expect word to have tabs and control characters expanded. */
3140
void spotlight(bool active, const char *word)
Chris Allegretta's avatar
Chris Allegretta committed
3141
{
3142
    size_t word_len = strlenpt(word), room;
Chris Allegretta's avatar
Chris Allegretta committed
3143

3144
3145
   /* Compute the number of columns that are available for the word. */
    room = COLS + get_page_start(xplustabs()) - xplustabs();
Chris Allegretta's avatar
Chris Allegretta committed
3146

3147
    assert(room > 0);
3148

3149
3150
    if (word_len > room)
	room--;
3151

Chris Allegretta's avatar
Chris Allegretta committed
3152
    reset_cursor();
3153
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
3154

3155
    if (active)
3156
	wattron(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3157

3158
    /* This is so we can show zero-length matches. */
3159
    if (word_len == 0)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3160
	waddch(edit, ' ');
3161
    else
3162
	waddnstr(edit, word, actual_x(word, room));
3163

3164
    if (word_len > room)
3165
	waddch(edit, '$');
Chris Allegretta's avatar
Chris Allegretta committed
3166

3167
    if (active)
3168
	wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3169
3170
}

3171
#ifndef DISABLE_EXTRA
3172
3173
#define CREDIT_LEN 54
#define XLCREDIT_LEN 9
3174

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3175
3176
/* Easter egg: Display credits.  Assume nodelay(edit) and scrollok(edit)
 * are FALSE. */
3177
3178
void do_credits(void)
{
3179
3180
    bool old_more_space = ISSET(MORE_SPACE);
    bool old_no_help = ISSET(NO_HELP);
3181
    int kbinput = ERR, crpos = 0, xlpos = 0;
3182
3183
3184
    const char *credits[CREDIT_LEN] = {
	NULL,				/* "The nano text editor" */
	NULL,				/* "version" */
Chris Allegretta's avatar
Chris Allegretta committed
3185
3186
	VERSION,
	"",
3187
	NULL,				/* "Brought to you by:" */
Chris Allegretta's avatar
Chris Allegretta committed
3188
3189
3190
3191
3192
	"Chris Allegretta",
	"Jordi Mallach",
	"Adam Rogoyski",
	"Rob Siemborski",
	"Rocco Corsi",
3193
	"David Lawrence Ramsey",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3194
	"David Benbennick",
Benno Schulenberg's avatar
Benno Schulenberg committed
3195
	"Mark Majeres",
3196
	"Mike Frysinger",
3197
	"Benno Schulenberg",
Chris Allegretta's avatar
Chris Allegretta committed
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
	"Ken Tyler",
	"Sven Guckes",
	"Bill Soudan",
	"Christian Weisgerber",
	"Erik Andersen",
	"Big Gaute",
	"Joshua Jensen",
	"Ryan Krebs",
	"Albert Chin",
	"",
3208
	NULL,				/* "Special thanks to:" */
3209
	"Monique, Brielle & Joseph",
Chris Allegretta's avatar
Chris Allegretta committed
3210
3211
3212
3213
3214
3215
	"Plattsburgh State University",
	"Benet Laboratories",
	"Amy Allegretta",
	"Linda Young",
	"Jeremy Robichaud",
	"Richard Kolb II",
3216
	NULL,				/* "The Free Software Foundation" */
Chris Allegretta's avatar
Chris Allegretta committed
3217
	"Linus Torvalds",
3218
	NULL,				/* "the many translators and the TP" */
3219
	NULL,				/* "For ncurses:" */
3220
3221
3222
3223
	"Thomas Dickey",
	"Pavel Curtis",
	"Zeyd Ben-Halim",
	"Eric S. Raymond",
3224
3225
3226
3227
3228
3229
	NULL,				/* "and anyone else we forgot..." */
	NULL,				/* "Thank you for using nano!" */
	"",
	"",
	"",
	"",
3230
	"(C) 1999 - 2016",
3231
	"Free Software Foundation, Inc.",
3232
3233
3234
3235
	"",
	"",
	"",
	"",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3236
	"http://www.nano-editor.org/"
3237
3238
    };

3239
    const char *xlcredits[XLCREDIT_LEN] = {
3240
3241
3242
3243
3244
	N_("The nano text editor"),
	N_("version"),
	N_("Brought to you by:"),
	N_("Special thanks to:"),
	N_("The Free Software Foundation"),
3245
	N_("the many translators and the TP"),
3246
3247
3248
	N_("For ncurses:"),
	N_("and anyone else we forgot..."),
	N_("Thank you for using nano!")
3249
    };
3250

3251
3252
3253
3254
3255
3256
    if (!old_more_space || !old_no_help) {
	SET(MORE_SPACE);
	SET(NO_HELP);
	window_init();
    }

3257
3258
    curs_set(0);
    nodelay(edit, TRUE);
3259

3260
    blank_titlebar();
3261
    blank_topbar();
Chris Allegretta's avatar
Chris Allegretta committed
3262
    blank_edit();
3263
3264
    blank_statusbar();
    blank_bottombars();
3265

3266
    wrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
3267
    wrefresh(edit);
3268
    wrefresh(bottomwin);
3269
    napms(700);
3270

3271
    for (crpos = 0; crpos < CREDIT_LEN + editwinrows / 2; crpos++) {
3272
	if ((kbinput = wgetch(edit)) != ERR)
3273
	    break;
3274

3275
	if (crpos < CREDIT_LEN) {
3276
	    const char *what;
3277
3278
	    size_t start_x;

3279
	    if (credits[crpos] == NULL) {
3280
		assert(0 <= xlpos && xlpos < XLCREDIT_LEN);
3281

3282
		what = _(xlcredits[xlpos]);
3283
		xlpos++;
3284
	    } else
3285
		what = credits[crpos];
3286

3287
	    start_x = COLS / 2 - strlenpt(what) / 2 - 1;
3288
3289
	    mvwaddstr(edit, editwinrows - 1 - (editwinrows % 2),
		start_x, what);
3290
	}
3291

3292
3293
3294
3295
	wrefresh(edit);

	if ((kbinput = wgetch(edit)) != ERR)
	    break;
3296
	napms(700);
3297

3298
	scrollok(edit, TRUE);
3299
	wscrl(edit, 1);
3300
	scrollok(edit, FALSE);
3301
	wrefresh(edit);
3302

3303
	if ((kbinput = wgetch(edit)) != ERR)
3304
	    break;
3305
	napms(700);
3306

3307
	scrollok(edit, TRUE);
3308
	wscrl(edit, 1);
3309
	scrollok(edit, FALSE);
3310
	wrefresh(edit);
3311
3312
    }

3313
3314
3315
    if (kbinput != ERR)
	ungetch(kbinput);

3316
    if (!old_more_space)
3317
	UNSET(MORE_SPACE);
3318
    if (!old_no_help)
3319
	UNSET(NO_HELP);
3320
    window_init();
3321

3322
    nodelay(edit, FALSE);
3323

3324
    total_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
3325
}
3326
#endif /* !DISABLE_EXTRA */