winio.c 98.8 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
#include "revision.h"
25

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

32
33
34
35
36
37
#ifdef REVISION
#define BRANDING REVISION
#else
#define BRANDING PACKAGE_STRING
#endif

38
static int *key_buffer = NULL;
39
40
	/* The keystroke buffer, containing all the keystrokes we
	 * haven't handled yet at a given point. */
41
static size_t key_buffer_len = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
42
	/* The length of the keystroke buffer. */
43
44
static bool solitary = FALSE;
	/* Whether an Esc arrived by itself -- not as leader of a sequence. */
45
static int statusblank = 0;
46
	/* The number of keystrokes left before we blank the statusbar. */
47
static bool suppress_cursorpos = FALSE;
48
	/* Should we skip constant position display for one keystroke? */
49
50
static bool seen_wide = FALSE;
	/* Whether we've seen a multicolumn character in the current line. */
51

52
#ifndef NANO_TINY
53
54
55
56
57
58
59
60
61
62
63
64
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;
}
65
#endif
66

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

126
/* Read in a sequence of keystrokes from win and save them in the
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
127
128
 * keystroke buffer.  This should only be called when the keystroke
 * buffer is empty. */
129
void get_key_buffer(WINDOW *win)
130
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
131
    int input;
132
    size_t errcount = 0;
133
134
135
136
137

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

138
139
140
141
    /* Just before reading in the first character, display any pending
     * screen updates. */
    doupdate();

142
    /* Read in the first character using whatever mode we're in. */
143
144
    input = wgetch(win);

145
#ifndef NANO_TINY
146
147
    if (the_window_resized()) {
	ungetch(input);
148
	input = KEY_WINCH;
149
    }
150
151
#endif

152
153
154
155
156
157
158
159
160
161
162
    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);

163
#ifndef NANO_TINY
164
	if (the_window_resized()) {
165
166
	    input = KEY_WINCH;
	    break;
167
	}
168
169
#endif
	input = wgetch(win);
170
    }
171

172
173
    /* Increment the length of the keystroke buffer, and save the value
     * of the keystroke at the end of it. */
174
    key_buffer_len++;
175
176
    key_buffer = (int *)nmalloc(sizeof(int));
    key_buffer[0] = input;
177

178
179
180
181
182
183
184
#ifndef NANO_TINY
    /* If we got SIGWINCH, get out immediately since the win argument is
     * no longer valid. */
    if (input == KEY_WINCH)
	return;
#endif

185
186
187
188
    /* Read in the remaining characters using non-blocking input. */
    nodelay(win, TRUE);

    while (TRUE) {
189
	input = wgetch(win);
190

191
	/* If there aren't any more characters, stop reading. */
192
	if (input == ERR)
193
194
	    break;

195
196
	/* Otherwise, increment the length of the keystroke buffer, and
	 * save the value of the keystroke at the end of it. */
197
	key_buffer_len++;
198
199
200
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
	key_buffer[key_buffer_len - 1] = input;
201
202
    }

203
204
205
    /* Restore waiting mode if it was on. */
    if (!nodelay_mode)
	nodelay(win, FALSE);
206
207

#ifdef DEBUG
208
209
    {
	size_t i;
210
	fprintf(stderr, "\nget_key_buffer(): the sequence of hex codes:");
211
212
213
214
	for (i = 0; i < key_buffer_len; i++)
	    fprintf(stderr, " %3x", key_buffer[i]);
	fprintf(stderr, "\n");
    }
215
#endif
216
}
217

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
218
/* Return the length of the keystroke buffer. */
219
size_t get_key_buffer_len(void)
220
221
222
223
{
    return key_buffer_len;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
224
/* Add the keystrokes in input to the keystroke buffer. */
225
void unget_input(int *input, size_t input_len)
226
227
{
    /* If input is empty, get out. */
228
    if (input_len == 0)
229
230
	return;

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
231
232
    /* If adding input would put the keystroke buffer beyond maximum
     * capacity, only add enough of input to put it at maximum
233
     * capacity. */
234
235
    if (key_buffer_len + input_len < key_buffer_len)
	input_len = (size_t)-1 - key_buffer_len;
236

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
237
238
239
    /* 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. */
240
241
242
    key_buffer_len += input_len;
    key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
	sizeof(int));
243

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
244
245
    /* If the keystroke buffer wasn't empty before, move its beginning
     * forward far enough so that we can add input to its beginning. */
246
247
248
    if (key_buffer_len > input_len)
	memmove(key_buffer + input_len, key_buffer,
		(key_buffer_len - input_len) * sizeof(int));
249

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
250
    /* Copy input to the beginning of the keystroke buffer. */
251
    memcpy(key_buffer, input, input_len * sizeof(int));
252
253
}

254
/* Put back the character stored in kbinput, putting it in byte range
255
256
 * beforehand.  If metakey is TRUE, put back the Escape character after
 * putting back kbinput.  If funckey is TRUE, put back the function key
257
 * (a value outside byte range) without putting it in byte range. */
258
void unget_kbinput(int kbinput, bool metakey, bool funckey)
259
{
260
    if (!funckey)
261
	kbinput = (char)kbinput;
262

263
    unget_input(&kbinput, 1);
264

265
    if (metakey) {
266
267
	kbinput = NANO_CONTROL_3;
	unget_input(&kbinput, 1);
268
269
270
    }
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
271
272
273
/* 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
274
 * anything else.  If the keystroke buffer is (still) empty, return NULL. */
275
int *get_input(WINDOW *win, size_t input_len)
276
{
277
    int *input;
278

279
280
    if (key_buffer_len == 0 && win != NULL)
	get_key_buffer(win);
281

282
283
    if (key_buffer_len == 0)
	return NULL;
284

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
285
286
    /* If input_len is greater than the length of the keystroke buffer,
     * only read the number of characters in the keystroke buffer. */
287
288
289
    if (input_len > key_buffer_len)
	input_len = key_buffer_len;

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
290
291
292
    /* Subtract input_len from the length of the keystroke buffer, and
     * allocate input so that it has enough room for input_len
     * keystrokes. */
293
    key_buffer_len -= input_len;
294
    input = (int *)nmalloc(input_len * sizeof(int));
295

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
296
297
    /* Copy input_len keystrokes from the beginning of the keystroke
     * buffer into input. */
298
    memcpy(input, key_buffer, input_len * sizeof(int));
299

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
300
    /* If the keystroke buffer is empty, mark it as such. */
301
302
303
    if (key_buffer_len == 0) {
	free(key_buffer);
	key_buffer = NULL;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
304
305
306
    /* 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. */
307
308
    } else {
	memmove(key_buffer, key_buffer + input_len, key_buffer_len *
309
310
311
		sizeof(int));
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
312
313
314
    }

    return input;
315
316
}

317
/* Read in a single keystroke, ignoring any that are invalid. */
318
int get_kbinput(WINDOW *win)
319
320
321
{
    int kbinput;

322
    /* Extract one keystroke from the input stream. */
323
    while ((kbinput = parse_kbinput(win)) == ERR)
324
	;
325

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

330
331
332
    return kbinput;
}

333
334
335
336
337
338
339
/* Extract a single keystroke from the input stream.  Translate escape
 * sequences and extended keypad codes into their corresponding values.
 * Set meta_key to TRUE when we get a meta key sequence, and set func_key
 * to TRUE when we get a function key.  Supported extended keypad values
 * are: [arrow key], Ctrl-[arrow key], Shift-[arrow key], Enter, Backspace,
 * the editing keypad (Insert, Delete, Home, End, PageUp, and PageDown),
 * the function keys (F1-F16), and the numeric keypad with NumLock off. */
340
int parse_kbinput(WINDOW *win)
341
{
342
    static int escapes = 0, byte_digits = 0;
343
    static bool double_esc = FALSE;
344
    int *kbinput, retval = ERR;
345

346
347
    meta_key = FALSE;
    func_key = FALSE;
348

349
    /* Read in a character. */
350
351
352
353
354
355
    kbinput = get_input(win, 1);

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

    while (kbinput == NULL)
356
	kbinput = get_input(win, 1);
357

358
359
360
361
362
363
    switch (*kbinput) {
	case ERR:
	    break;
	case NANO_CONTROL_3:
	    /* Increment the escape counter. */
	    escapes++;
364
365
366
	    /* If there are four consecutive escapes, discard three of them. */
	    if (escapes > 3)
		escapes = 1;
367
	    solitary = (escapes == 1 && get_key_buffer_len() == 0);
368
	    /* Wait for more input. */
369
370
371
372
	    break;
	default:
	    switch (escapes) {
		case 0:
373
		    /* One non-escape: normal input mode. */
374
		    retval = *kbinput;
375
376
		    break;
		case 1:
377
		    /* Reset the escape counter. */
378
		    escapes = 0;
379
380
		    if ((*kbinput != 'O' && *kbinput != 'o' && *kbinput != '[') ||
				get_key_buffer_len() == 0 || *key_buffer == 0x1B) {
381
382
			/* One escape followed by a single non-escape:
			 * meta key sequence mode. */
383
384
			if (!solitary || (*kbinput >= 0x20 && *kbinput < 0x7F))
			    meta_key = TRUE;
385
			retval = tolower(*kbinput);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
386
		    } else
387
388
			/* One escape followed by a non-escape, and there
			 * are more codes waiting: escape sequence mode. */
389
			retval = parse_escape_sequence(win, *kbinput);
390
391
		    break;
		case 2:
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
		    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
			}
			double_esc = FALSE;
			escapes = 0;
		    } else if (get_key_buffer_len() == 0) {
413
414
415
			if (('0' <= *kbinput && *kbinput <= '2' &&
				byte_digits == 0) || ('0' <= *kbinput &&
				*kbinput <= '9' && byte_digits > 0)) {
416
417
418
419
420
421
			    /* 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. */
422
423
424
425
426
			    int byte;

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

427
428
429
430
			    /* 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. */
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
			    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. */
456
			    escapes = 0;
457
458
			    if (byte_digits == 0)
				/* Two escapes followed by a non-decimal
459
460
461
462
				 * 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. */
463
464
				retval = get_control_kbinput(*kbinput);
			    else {
465
466
467
				/* An invalid digit in the middle of a byte
				 * sequence: reset the byte sequence counter
				 * and save the code we got as the result. */
468
469
470
				byte_digits = 0;
				retval = *kbinput;
			    }
471
			}
472
473
		    } else if (*kbinput == '[' && key_buffer_len > 0 &&
				'A' <= *key_buffer && *key_buffer <= 'D') {
474
475
			/* This is an iTerm2 sequence: ^[ ^[ [ X. */
			double_esc = TRUE;
476
		    } else {
477
478
479
			/* Two escapes followed by a non-escape, and there
			 * are more codes waiting: combined meta and escape
			 * sequence mode. */
480
			escapes = 0;
481
			meta_key = TRUE;
482
			retval = parse_escape_sequence(win, *kbinput);
483
		    }
484
		    break;
485
486
487
488
		case 3:
		    /* Reset the escape counter. */
		    escapes = 0;
		    if (get_key_buffer_len() == 0)
489
490
			/* Three escapes followed by a non-escape, and no
			 * other codes are waiting: normal input mode. */
491
492
			retval = *kbinput;
		    else
493
494
495
496
			/* 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. */
497
			retval = get_control_kbinput(
498
				parse_escape_sequence(win, *kbinput));
499
		    break;
500
501
	    }
    }
502

503
    if (retval != ERR) {
504
	switch (retval) {
505
506
507
508
#ifdef KEY_SLEFT
	    /* Slang doesn't support KEY_SLEFT. */
	    case KEY_SLEFT:
#endif
509
	    case KEY_LEFT:
510
		retval = sc_seq_or(do_left, *kbinput);
511
		break;
512
513
514
515
#ifdef KEY_SRIGHT
	    /* Slang doesn't support KEY_SRIGHT. */
	    case KEY_SRIGHT:
#endif
516
	    case KEY_RIGHT:
517
		retval = sc_seq_or(do_right, *kbinput);
518
		break;
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#ifdef KEY_SUP
	    /* ncurses and Slang don't support KEY_SUP. */
	    case KEY_SUP:
#endif
	    case KEY_UP:
		retval = sc_seq_or(do_up_void, *kbinput);
		break;
#ifdef KEY_SDOWN
	    /* ncurses and Slang don't support KEY_SDOWN. */
	    case KEY_SDOWN:
#endif
	    case KEY_DOWN:
		retval = sc_seq_or(do_down_void, *kbinput);
		break;
533
534
535
536
#ifdef KEY_SHOME
	    /* HP-UX 10-11 and Slang don't support KEY_SHOME. */
	    case KEY_SHOME:
#endif
537
#ifdef KEY_HOME
538
	    case KEY_HOME:
539
540
#endif
	    case KEY_A1:	/* Home (7) on keypad with NumLock off. */
541
		retval = sc_seq_or(do_home, *kbinput);
542
		break;
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#ifdef KEY_SEND
	    /* HP-UX 10-11 and Slang don't support KEY_SEND. */
	    case KEY_SEND:
#endif
#ifdef KEY_END
	    case KEY_END:
#endif
	    case KEY_C1:	/* End (1) on keypad with NumLock off. */
		retval = sc_seq_or(do_end, *kbinput);
		break;
	    case KEY_PPAGE:
	    case KEY_A3:	/* PageUp (9) on keypad with NumLock off. */
		retval = sc_seq_or(do_page_up, *kbinput);
		break;
	    case KEY_NPAGE:
558
	    case KEY_C3:	/* PageDown (3) on keypad with NumLock off. */
559
560
561
562
563
564
		retval = sc_seq_or(do_page_down, *kbinput);
		break;

	    case KEY_ENTER:
		retval = sc_seq_or(do_enter, *kbinput);
		break;
565
	    case KEY_BACKSPACE:
566
		retval = sc_seq_or(do_backspace, *kbinput);
567
		break;
568
569
570
#ifdef KEY_SDC
	    /* Slang doesn't support KEY_SDC. */
	    case KEY_SDC:
571
572
#endif
	    case NANO_CONTROL_8:
573
		if (ISSET(REBIND_DELETE))
574
		    retval = sc_seq_or(do_delete, *kbinput);
575
		else
576
		    retval = sc_seq_or(do_backspace, *kbinput);
577
		break;
578
579
580
#ifdef KEY_SIC
	    /* Slang doesn't support KEY_SIC. */
	    case KEY_SIC:
581
		retval = sc_seq_or(do_insertfile_void, *kbinput);
582
		break;
583
#endif
584
585
586
587
#ifdef KEY_SBEG
	    /* Slang doesn't support KEY_SBEG. */
	    case KEY_SBEG:
#endif
588
589
#ifdef KEY_BEG
	    /* Slang doesn't support KEY_BEG. */
590
591
592
	    case KEY_BEG:
#endif
	    case KEY_B2:	/* Center (5) on keypad with NumLock off. */
593
594
		retval = ERR;
		break;
595
#ifdef KEY_CANCEL
596
597
598
#ifdef KEY_SCANCEL
	    /* Slang doesn't support KEY_SCANCEL. */
	    case KEY_SCANCEL:
599
#endif
600
601
	    /* Slang doesn't support KEY_CANCEL. */
	    case KEY_CANCEL:
602
		retval = first_sc_for(currmenu, do_cancel)->seq;
603
604
		break;
#endif
605
#ifdef KEY_SUSPEND
606
607
608
609
610
611
#ifdef KEY_SSUSPEND
	    /* Slang doesn't support KEY_SSUSPEND. */
	    case KEY_SSUSPEND:
#endif
	    /* Slang doesn't support KEY_SUSPEND. */
	    case KEY_SUSPEND:
612
		retval = sc_seq_or(do_suspend_void, 0);
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
		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;
633
#endif
634
	}
635

636
637
638
639
640
641
642
#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

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

#ifdef DEBUG
650
    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);
651
652
#endif

653
654
    free(kbinput);

655
    /* Return the result. */
656
657
658
    return retval;
}

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

1075
    return ERR;
1076
1077
}

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

1097
/* Interpret the escape sequence in the keystroke buffer, the first
1098
1099
 * character of which is kbinput.  Assume that the keystroke buffer
 * isn't empty, and that the initial escape has already been read in. */
1100
int parse_escape_sequence(WINDOW *win, int kbinput)
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
{
    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);
1111
    retval = convert_sequence(seq, seq_len);
1112
1113
1114

    free(seq);

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

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

    return retval;
}

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

1145
1146
    /* Increment the byte digit counter. */
    byte_digits++;
1147

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

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

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

    return retval;
}

1209
#ifdef ENABLE_UTF8
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1210
/* If the character in kbinput is a valid hexadecimal digit, multiply it
1211
 * by factor and add the result to uni, and return ERR to signify okay. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1212
1213
1214
1215
1216
1217
1218
long add_unicode_digit(int kbinput, long factor, long *uni)
{
    if ('0' <= kbinput && kbinput <= '9')
	*uni += (kbinput - '0') * factor;
    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
	*uni += (tolower(kbinput) - 'a' + 10) * factor;
    else
1219
1220
	/* The character isn't hexadecimal; give it as the result. */
	return (long)kbinput;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1221

1222
    return ERR;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1223
1224
}

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

1234
    /* Increment the Unicode digit counter. */
1235
    uni_digits++;
1236

1237
    switch (uni_digits) {
1238
	case 1:
1239
1240
	    /* First digit: This must be zero or one.  Put it in the
	     * 0x100000's position of the Unicode sequence holder. */
1241
	    if ('0' <= kbinput && kbinput <= '1')
1242
		uni = (kbinput - '0') * 0x100000;
1243
	    else
1244
1245
		/* This isn't the first digit of a Unicode sequence.
		 * Return this character as the result. */
1246
1247
1248
		retval = kbinput;
	    break;
	case 2:
1249
1250
1251
1252
1253
1254
	    /* 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);
1255
	    else
1256
1257
		/* This isn't the second digit of a Unicode sequence.
		 * Return this character as the result. */
1258
1259
1260
		retval = kbinput;
	    break;
	case 3:
1261
1262
1263
1264
	    /* 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);
1265
	    break;
1266
	case 4:
1267
1268
1269
1270
	    /* 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);
1271
	    break;
1272
	case 5:
1273
1274
1275
	    /* 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);
1276
	    break;
1277
	case 6:
1278
1279
1280
1281
1282
1283
	    /* 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)
1284
		retval = uni;
1285
1286
	    break;
    }
1287

1288
1289
    /* If we have a result, reset the Unicode digit counter and the
     * Unicode sequence holder. */
1290
    if (retval != ERR) {
1291
1292
	uni_digits = 0;
	uni = 0;
1293
    }
1294

1295
#ifdef DEBUG
1296
    fprintf(stderr, "get_unicode_kbinput(): kbinput = %d, uni_digits = %d, uni = %ld, retval = %ld\n", kbinput, uni_digits, uni, retval);
1297
1298
#endif

1299
1300
    return retval;
}
1301
#endif /* ENABLE_UTF8 */
1302

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

1309
    /* Ctrl-Space (Ctrl-2, Ctrl-@, Ctrl-`) */
1310
1311
    if (kbinput == ' ' || kbinput == '2')
	retval = NANO_CONTROL_SPACE;
1312
1313
    /* Ctrl-/ (Ctrl-7, Ctrl-_) */
    else if (kbinput == '/')
1314
	retval = NANO_CONTROL_7;
1315
    /* Ctrl-3 (Ctrl-[, Esc) to Ctrl-7 (Ctrl-/, Ctrl-_) */
1316
1317
1318
    else if ('3' <= kbinput && kbinput <= '7')
	retval = kbinput - 24;
    /* Ctrl-8 (Ctrl-?) */
1319
1320
    else if (kbinput == '8' || kbinput == '?')
	retval = NANO_CONTROL_8;
1321
1322
    /* Ctrl-@ (Ctrl-Space, Ctrl-2, Ctrl-`) to Ctrl-_ (Ctrl-/, Ctrl-7) */
    else if ('@' <= kbinput && kbinput <= '_')
1323
	retval = kbinput - '@';
1324
1325
    /* Ctrl-` (Ctrl-2, Ctrl-Space, Ctrl-@) to Ctrl-~ (Ctrl-6, Ctrl-^) */
    else if ('`' <= kbinput && kbinput <= '~')
1326
	retval = kbinput - '`';
1327
1328
1329
    else
	retval = kbinput;

1330
#ifdef DEBUG
1331
    fprintf(stderr, "get_control_kbinput(): kbinput = %d, retval = %d\n", kbinput, retval);
1332
1333
#endif

1334
1335
    return retval;
}
1336

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1337
1338
/* Put the output-formatted characters in output back into the keystroke
 * buffer, so that they can be parsed and displayed as output again. */
1339
void unparse_kbinput(char *output, size_t output_len)
1340
{
1341
1342
    int *input;
    size_t i;
1343

1344
1345
1346
1347
    if (output_len == 0)
	return;

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

1349
1350
    for (i = 0; i < output_len; i++)
	input[i] = (int)output[i];
1351

1352
    unget_input(input, output_len);
1353

1354
    free(input);
1355
1356
}

1357
/* Read in a stream of characters verbatim, and return the length of the
1358
1359
1360
1361
 * string in kbinput_len.  Assume nodelay(win) is FALSE. */
int *get_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
{
    int *retval;
1362

1363
    /* Turn off flow control characters if necessary so that we can type
1364
1365
     * them in verbatim, and turn the keypad off if necessary so that we
     * don't get extended keypad values. */
1366
1367
    if (ISSET(PRESERVE))
	disable_flow_control();
1368
1369
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, FALSE);
1370
1371
1372

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

    /* Turn flow control characters back on if necessary and turn the
1375
     * keypad back on if necessary now that we're done. */
1376
1377
    if (ISSET(PRESERVE))
	enable_flow_control();
1378
1379
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, TRUE);
1380

1381
    return retval;
1382
1383
}

1384
1385
/* Read in a stream of all available characters, and return the length
 * of the string in kbinput_len.  Translate the first few characters of
1386
 * the input into the corresponding multibyte value if possible.  After
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1387
 * that, leave the input as-is. */
1388
int *parse_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
1389
{
1390
    int *kbinput, *retval;
1391

1392
    /* Read in the first keystroke. */
1393
1394
    while ((kbinput = get_input(win, 1)) == NULL)
	;
1395

1396
#ifdef ENABLE_UTF8
1397
1398
1399
    if (using_utf8()) {
	/* Check whether the first keystroke is a valid hexadecimal
	 * digit. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1400
	long uni = get_unicode_kbinput(*kbinput);
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419

	/* 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) {
1420
1421
		while ((kbinput = get_input(win, 1)) == NULL)
		    ;
1422
1423
		uni = get_unicode_kbinput(*kbinput);
	    }
1424

1425
1426
1427
	    /* Put back the multibyte equivalent of the Unicode
	     * value. */
	    uni_mb = make_mbchar(uni, &uni_mb_len);
1428

1429
	    seq = (int *)nmalloc(uni_mb_len * sizeof(int));
1430

1431
1432
	    for (i = 0; i < uni_mb_len; i++)
		seq[i] = (unsigned char)uni_mb[i];
1433

1434
	    unget_input(seq, uni_mb_len);
1435

1436
1437
	    free(seq);
	    free(uni_mb);
1438
	}
1439
    } else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1440
1441
#endif /* ENABLE_UTF8 */

1442
1443
	/* Put back the first keystroke. */
	unget_input(kbinput, 1);
1444

1445
1446
    free(kbinput);

1447
    /* Get the complete sequence, and save the characters in it as the
1448
     * result. */
1449
    *kbinput_len = get_key_buffer_len();
1450
    retval = get_input(NULL, *kbinput_len);
1451
1452
1453
1454

    return retval;
}

1455
#ifndef DISABLE_MOUSE
1456
/* Handle any mouse event that may have occurred.  We currently handle
1457
1458
1459
1460
1461
1462
1463
 * 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
1464
1465
1466
1467
1468
1469
 * 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. */
1470
int get_mouseinput(int *mouse_x, int *mouse_y, bool allow_shortcuts)
1471
1472
{
    MEVENT mevent;
1473
    bool in_bottomwin;
1474
    subnfunc *f;
1475
1476
1477
1478
1479
1480

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

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

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

1487
1488
    in_bottomwin = wenclose(bottomwin, *mouse_y, *mouse_x);

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1489
    /* Handle releases/clicks of the first mouse button. */
1490
    if (mevent.bstate & (BUTTON1_RELEASED | BUTTON1_CLICKED)) {
1491
1492
	/* If we're allowing shortcuts, the current shortcut list is
	 * being displayed on the last two lines of the screen, and the
1493
1494
1495
	 * 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. */
1496
	if (allow_shortcuts && !ISSET(NO_HELP) && in_bottomwin) {
1497
1498
1499
1500
	    int i;
		/* The width of all the shortcuts, except for the last
		 * two, in the shortcut list in bottomwin. */
	    int j;
1501
		/* The calculated index number of the clicked item. */
1502
1503
1504
1505
	    size_t currslen;
		/* The number of shortcuts in the current shortcut
		 * list. */

1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
	    /* 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;
	    }
1520

1521
	    /* Get the shortcut lists' length. */
1522
	    if (currmenu == MMAIN)
1523
		currslen = MAIN_VISIBLE;
1524
	    else {
1525
		currslen = length_of_list(currmenu);
1526

1527
1528
1529
1530
1531
		/* We don't show any more shortcuts than the main list
		 * does. */
		if (currslen > MAIN_VISIBLE)
		    currslen = MAIN_VISIBLE;
	    }
1532

1533
1534
1535
1536
1537
1538
1539
1540
	    /* 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));

1541
1542
	    /* Calculate the one-based index in the shortcut list. */
	    j = (*mouse_x / i) * 2 + *mouse_y;
1543

1544
1545
	    /* Adjust the index if we hit the last two wider ones. */
	    if ((j > currslen) && (*mouse_x % i < COLS % i))
1546
		j -= 2;
1547
1548
1549
#ifdef DEBUG
	    fprintf(stderr, "Calculated %i as index in shortcut list, currmenu = %x.\n", j, currmenu);
#endif
1550
1551
	    /* Ignore releases/clicks of the first mouse button beyond
	     * the last shortcut. */
1552
	    if (j > currslen)
1553
		return 2;
1554

1555
1556
	    /* Go through the list of functions to determine which
	     * shortcut in the current menu we released/clicked on. */
1557
	    for (f = allfuncs; f != NULL; f = f->next) {
1558
		if ((f->menus & currmenu) == 0)
1559
1560
		    continue;
		if (first_sc_for(currmenu, f->scfunc) == NULL)
1561
		    continue;
1562
1563
		/* Tick off an actually shown shortcut. */
		j -= 1;
1564
1565
		if (j == 0)
		    break;
1566
	    }
1567
#ifdef DEBUG
1568
	    fprintf(stderr, "Stopped on func %ld present in menus %x\n", (long)f->scfunc, f->menus);
1569
#endif
1570

1571
	    /* And put the corresponding key into the keyboard buffer. */
1572
	    if (f != NULL) {
1573
		const sc *s = first_sc_for(currmenu, f->scfunc);
1574
		unget_kbinput(s->seq, s->type == META, s->type == FKEY);
1575
	    }
1576
	    return 1;
1577
	} else
1578
1579
	    /* Handle releases/clicks of the first mouse button that
	     * aren't on the current shortcut list elsewhere. */
1580
	    return 0;
1581
    }
1582
1583
#if NCURSES_MOUSE_VERSION >= 2
    /* Handle presses of the fourth mouse button (upward rolls of the
1584
1585
1586
     * 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
1587
	bool in_edit = wenclose(edit, *mouse_y, *mouse_x);
1588

1589
1590
1591
1592
	if (in_bottomwin)
	    /* Translate the mouse event coordinates so that they're
	     * relative to bottomwin. */
	    wmouse_trafo(bottomwin, mouse_y, mouse_x, FALSE);
1593

1594
	if (in_edit || (in_bottomwin && *mouse_y == 0)) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1595
1596
	    int i;

1597
1598
1599
1600
1601
	    /* 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) ?
1602
			sc_seq_or(do_up_void, 0) : sc_seq_or(do_down_void, 0),
1603
			FALSE, FALSE);
1604
1605
1606
1607
1608
1609
1610

	    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;
1611
1612
    }
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1613
1614
1615

    /* Ignore all other mouse events. */
    return 2;
1616
}
1617
1618
#endif /* !DISABLE_MOUSE */

1619
1620
1621
1622
/* 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. */
1623
const sc *get_shortcut(int *kbinput)
1624
{
1625
    sc *s;
1626

1627
#ifdef DEBUG
1628
    fprintf(stderr, "get_shortcut(): kbinput = %d, meta_key = %s -- ", *kbinput, meta_key ? "TRUE" : "FALSE");
1629
1630
#endif

1631
    for (s = sclist; s != NULL; s = s->next) {
1632
	if ((s->menus & currmenu) && *kbinput == s->seq
1633
		&& meta_key == (s->type == META)) {
1634
#ifdef DEBUG
1635
	    fprintf (stderr, "matched seq \"%s\", and btw meta was %d (menu is %x from %x)\n",
1636
				s->keystr, meta_key, currmenu, s->menus);
1637
#endif
1638
	    return s;
1639
1640
	}
    }
1641
#ifdef DEBUG
1642
    fprintf (stderr, "matched nothing, btw meta was %d\n", meta_key);
1643
#endif
1644
1645
1646
1647

    return NULL;
}

1648
1649
1650
1651
1652
/* 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
1653

1654
1655
1656
1657
    for (; n > 0; n--)
	waddch(win, ' ');
}

1658
/* Blank the first line of the top portion of the window. */
1659
void blank_titlebar(void)
Chris Allegretta's avatar
Chris Allegretta committed
1660
{
1661
    blank_line(topwin, 0, 0, COLS);
1662
1663
}

1664
1665
/* If the MORE_SPACE flag isn't set, blank the second line of the top
 * portion of the window. */
1666
1667
1668
void blank_topbar(void)
{
    if (!ISSET(MORE_SPACE))
1669
	blank_line(topwin, 1, 0, COLS);
1670
1671
}

1672
/* Blank all the lines of the middle portion of the window, i.e. the
1673
 * edit window. */
Chris Allegretta's avatar
Chris Allegretta committed
1674
1675
void blank_edit(void)
{
1676
    int i;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1677

1678
    for (i = 0; i < editwinrows; i++)
1679
	blank_line(edit, i, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1680
1681
}

1682
/* Blank the first line of the bottom portion of the window. */
Chris Allegretta's avatar
Chris Allegretta committed
1683
1684
void blank_statusbar(void)
{
1685
    blank_line(bottomwin, 0, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1686
1687
}

1688
1689
/* If the NO_HELP flag isn't set, blank the last two lines of the bottom
 * portion of the window. */
1690
1691
1692
void blank_bottombars(void)
{
    if (!ISSET(NO_HELP)) {
1693
1694
	blank_line(bottomwin, 1, 0, COLS);
	blank_line(bottomwin, 2, 0, COLS);
1695
1696
1697
    }
}

1698
1699
/* Check if the number of keystrokes needed to blank the statusbar has
 * been pressed.  If so, blank the statusbar, unless constant cursor
1700
 * position display is on and we are in the editing screen. */
1701
void check_statusblank(void)
Chris Allegretta's avatar
Chris Allegretta committed
1702
{
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
    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
1717
1718
1719
    }
}

1720
1721
1722
1723
/* 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
1724
1725
1726
1727
1728
 * 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)
1729
1730
{
    size_t start_index;
1731
	/* Index in buf of the first character shown. */
1732
    size_t column;
1733
	/* Screen column that start_index corresponds to. */
1734
1735
1736
1737
    char *converted;
	/* The string we return. */
    size_t index;
	/* Current position in converted. */
1738

1739
1740
1741
1742
1743
    /* If dollars is TRUE, make room for the "$" at the end of the
     * line. */
    if (dollars && len > 0 && strlenpt(buf) > start_col + len)
	len--;

1744
1745
1746
1747
1748
    if (len == 0)
	return mallocstrcpy(NULL, "");

    start_index = actual_x(buf, start_col);
    column = strnlenpt(buf, start_index);
1749

1750
    assert(column <= start_col);
1751

1752
1753
    /* Allocate enough space to hold the entire converted buffer. */
    converted = charalloc(strlen(buf) * (mb_cur_max() + tabsize) + 1);
1754

1755
    index = 0;
1756
    seen_wide = FALSE;
1757
    buf += start_index;
1758

1759
    if (*buf != '\0' && *buf != '\t' &&
1760
	(column < start_col || (dollars && column > 0))) {
1761
	/* We don't display the complete first character as it starts to
1762
	 * the left of the screen. */
1763
	if (is_cntrl_mbchar(buf)) {
1764
	    if (column < start_col) {
1765
		converted[index++] = control_mbrep(buf);
1766
		start_col++;
1767
		buf += parse_mbchar(buf, NULL, NULL);
1768
	    }
1769
	}
1770
#ifdef ENABLE_UTF8
1771
	else if (using_utf8() && mbwidth(buf) == 2) {
1772
1773
1774
1775
1776
	    if (column >= start_col) {
		converted[index++] = ' ';
		start_col++;
	    }

1777
	    converted[index++] = ' ';
1778
	    start_col++;
1779

1780
	    buf += parse_mbchar(buf, NULL, NULL);
1781
	}
1782
#endif
1783
1784
    }

1785
    while (*buf != '\0') {
1786
	int charlength, charwidth = 1;
1787

1788
	if (*buf == ' ') {
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
	    /* Show a space as a visible character, or as a space. */
#ifndef NANO_TINY
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i = whitespace_len[0];

		while (i < whitespace_len[0] + whitespace_len[1])
		    converted[index++] = whitespace[i++];
	    } else
#endif
		converted[index++] = ' ';
	    start_col++;
1800
1801
	    buf++;
	    continue;
1802
	} else if (*buf == '\t') {
1803
	    /* Show a tab as a visible character, or as as a space. */
1804
#ifndef NANO_TINY
1805
	    if (ISSET(WHITESPACE_DISPLAY)) {
1806
		int i = 0;
1807

1808
1809
		while (i < whitespace_len[0])
		    converted[index++] = whitespace[i++];
1810
	    } else
1811
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1812
		converted[index++] = ' ';
1813
	    start_col++;
1814
	    /* Fill the tab up with the required number of spaces. */
1815
	    while (start_col % tabsize != 0) {
1816
		converted[index++] = ' ';
1817
1818
		start_col++;
	    }
1819
1820
1821
1822
	    buf++;
	    continue;
	}

1823
	charlength = length_of_char(buf, &charwidth);
1824

1825
	/* If buf contains a control character, represent it. */
1826
	if (is_cntrl_mbchar(buf)) {
1827
	    converted[index++] = '^';
1828
	    converted[index++] = control_mbrep(buf);
1829
	    start_col += 2;
1830
1831
1832
	    buf += charlength;
	    continue;
	}
1833

1834
1835
1836
1837
	/* If buf contains a valid non-control character, simply copy it. */
	if (charlength > 0) {
	    for (; charlength > 0; charlength--)
		converted[index++] = *(buf++);
1838

1839
1840
	    start_col += charwidth;
	    if (charwidth > 1)
1841
		seen_wide = TRUE;
1842
1843

	    continue;
1844
1845
	}

1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
	/* Represent an invalid sequence with the Replacement Character. */
	converted[index++] = '\xEF';
	converted[index++] = '\xBF';
	converted[index++] = '\xBD';

	start_col += 1;
	buf++;

	/* For invalid codepoints, skip extra bytes. */
	if (charlength < -1)
	   buf += charlength + 7;
1857
1858
    }

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1859
    /* Null-terminate converted. */
1860
    converted[index] = '\0';
1861
1862
1863

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

1866
    return converted;
1867
1868
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1869
1870
1871
1872
1873
1874
/* 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. */
1875
void titlebar(const char *path)
Chris Allegretta's avatar
Chris Allegretta committed
1876
{
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
    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. */
1889

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

1892
    wattron(topwin, interface_color_pair[TITLE_BAR]);
1893

1894
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
1895

1896
1897
1898
    /* 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
1899

1900
    /* Figure out the path, prefix and state strings. */
1901
#ifndef DISABLE_BROWSER
1902
1903
1904
1905
    if (path != NULL)
	prefix = _("DIR:");
    else
#endif
1906
1907
1908
1909
1910
1911
1912
    {
	if (openfile->filename[0] == '\0')
	    path = _("New Buffer");
	else {
	    path = openfile->filename;
	    prefix = _("File:");
	}
1913

1914
1915
1916
1917
	if (openfile->modified)
	    state = _("Modified");
	else if (ISSET(VIEW_MODE))
	    state = _("View");
1918

1919
1920
	pluglen = strlenpt(_("Modified")) + 1;
    }
1921

1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
    /* 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;
1932
1933
    }

1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
    /* 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;
1946
1947
1948
	}
    }

1949
1950
1951
1952
    /* If we have side spaces left, center the path name. */
    if (verlen > 0)
	offset = verlen + (COLS - (verlen + pluglen + statelen) -
					(prefixlen + pathlen)) / 2;
1953

1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
    /* 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);
1971
    }
1972

1973
1974
1975
1976
1977
1978
    /* 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));

1979
    wattroff(topwin, interface_color_pair[TITLE_BAR]);
1980

1981
    wnoutrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
1982
    reset_cursor();
1983
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
1984
1985
}

1986
1987
1988
1989
1990
1991
/* Display a normal message on the statusbar, quietly. */
void statusbar(const char *msg)
{
    statusline(HUSH, msg);
}

1992
/* Display a message on the statusbar, and set suppress_cursorpos to
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1993
1994
 * TRUE, so that the message won't be immediately overwritten if
 * constant cursor position display is on. */
1995
void statusline(message_type importance, const char *msg, ...)
1996
1997
{
    va_list ap;
1998
    char *bar, *foo;
Benno Schulenberg's avatar
Benno Schulenberg committed
1999
    size_t start_x;
2000
2001
2002
2003
#ifndef NANO_TINY
    bool old_whitespace = ISSET(WHITESPACE_DISPLAY);

    UNSET(WHITESPACE_DISPLAY);
2004
#endif
2005
2006
2007
2008
2009

    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(). */
2010
    if (isendwin()) {
2011
2012
2013
2014
2015
	vfprintf(stderr, msg, ap);
	va_end(ap);
	return;
    }

2016
2017
2018
2019
2020
2021
2022
    /* If there already was an alert message, ignore lesser ones. */
    if ((lastmessage == ALERT && importance != ALERT) ||
		(lastmessage == MILD && importance == HUSH))
	return;

    /* Delay another alert message, to allow an earlier one to be noticed. */
    if (lastmessage == ALERT)
2023
2024
	napms(1200);

2025
    if (importance == ALERT)
2026
	beep();
2027
2028

    lastmessage = importance;
2029

2030
2031
2032
    /* Turn the cursor off while fiddling in the statusbar. */
    curs_set(0);

2033
2034
    blank_statusbar();

2035
2036
2037
2038
    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
2039
    free(bar);
2040
2041

#ifndef NANO_TINY
2042
2043
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);
2044
#endif
Benno Schulenberg's avatar
Benno Schulenberg committed
2045
    start_x = (COLS - strlenpt(foo) - 4) / 2;
2046

2047
    wmove(bottomwin, 0, start_x);
2048
    wattron(bottomwin, interface_color_pair[STATUS_BAR]);
2049
2050
2051
2052
    waddstr(bottomwin, "[ ");
    waddstr(bottomwin, foo);
    free(foo);
    waddstr(bottomwin, " ]");
2053
    wattroff(bottomwin, interface_color_pair[STATUS_BAR]);
2054

2055
    /* Push the message to the screen straightaway. */
2056
    wnoutrefresh(bottomwin);
2057
    doupdate();
2058

2059
    suppress_cursorpos = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2060

2061
    /* If we're doing quick statusbar blanking, blank it after just one
2062
2063
     * keystroke.  Otherwise, blank it after twenty-six keystrokes, as
     * Pico does. */
2064
#ifndef NANO_TINY
2065
2066
2067
    if (ISSET(QUICK_BLANK))
	statusblank = 1;
    else
2068
#endif
2069
	statusblank = 26;
2070
2071
}

2072
2073
/* Display the shortcut list corresponding to menu on the last two rows
 * of the bottom portion of the window. */
2074
void bottombars(int menu)
Chris Allegretta's avatar
Chris Allegretta committed
2075
{
2076
    size_t i, colwidth, slen;
2077
2078
    subnfunc *f;
    const sc *s;
2079

2080
2081
2082
    /* Set the global variable to the given menu. */
    currmenu = menu;

Chris Allegretta's avatar
Chris Allegretta committed
2083
2084
2085
    if (ISSET(NO_HELP))
	return;

2086
    if (menu == MMAIN) {
2087
	slen = MAIN_VISIBLE;
2088

2089
	assert(slen <= length_of_list(menu));
2090
    } else {
2091
	slen = length_of_list(menu);
2092

2093
	/* Don't show any more shortcuts than the main list does. */
2094
2095
2096
2097
	if (slen > MAIN_VISIBLE)
	    slen = MAIN_VISIBLE;
    }

2098
2099
2100
2101
    /* 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. */
2102
    colwidth = COLS / ((slen / 2) + (slen % 2));
Chris Allegretta's avatar
Chris Allegretta committed
2103

2104
    blank_bottombars();
2105

2106
2107
2108
#ifdef DEBUG
    fprintf(stderr, "In bottombars, and slen == \"%d\"\n", (int) slen);
#endif
2109

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

2112
#ifdef DEBUG
2113
	fprintf(stderr, "Checking menu items....");
2114
#endif
2115
	if ((f->menus & menu) == 0)
2116
	    continue;
2117

2118
#ifdef DEBUG
2119
	fprintf(stderr, "found one! f->menus = %x, desc = \"%s\"\n", f->menus, f->desc);
2120
#endif
2121
2122
	s = first_sc_for(menu, f->scfunc);
	if (s == NULL) {
2123
2124
2125
#ifdef DEBUG
	    fprintf(stderr, "Whoops, guess not, no shortcut key found for func!\n");
#endif
2126
2127
	    continue;
	}
2128
	wmove(bottomwin, 1 + i % 2, (i / 2) * colwidth);
2129
#ifdef DEBUG
2130
	fprintf(stderr, "Calling onekey with keystr \"%s\" and desc \"%s\"\n", s->keystr, f->desc);
2131
#endif
2132
	onekey(s->keystr, _(f->desc), colwidth + (COLS % colwidth));
2133
	i++;
Chris Allegretta's avatar
Chris Allegretta committed
2134
    }
2135

2136
2137
    wnoutrefresh(bottomwin);
    reset_cursor();
2138
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2139
2140
}

2141
2142
/* 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
2143
 * to write at most length characters, even if length is very small and
2144
2145
 * keystroke and desc are long.  Note that waddnstr(,,(size_t)-1) adds
 * the whole string!  We do not bother padding the entry with blanks. */
2146
void onekey(const char *keystroke, const char *desc, int length)
Chris Allegretta's avatar
Chris Allegretta committed
2147
{
2148
2149
    assert(keystroke != NULL && desc != NULL);

2150
    wattron(bottomwin, interface_color_pair[KEY_COMBO]);
2151
    waddnstr(bottomwin, keystroke, actual_x(keystroke, length));
2152
    wattroff(bottomwin, interface_color_pair[KEY_COMBO]);
2153

2154
    length -= strlenpt(keystroke) + 1;
2155

2156
    if (length > 0) {
2157
	waddch(bottomwin, ' ');
2158
	wattron(bottomwin, interface_color_pair[FUNCTION_TAG]);
2159
	waddnstr(bottomwin, desc, actual_x(desc, length));
2160
	wattroff(bottomwin, interface_color_pair[FUNCTION_TAG]);
Chris Allegretta's avatar
Chris Allegretta committed
2161
2162
2163
    }
}

2164
2165
/* 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
2166
2167
void reset_cursor(void)
{
2168
    size_t xpt = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2169

2170
#ifndef NANO_TINY
2171
    if (ISSET(SOFTWRAP)) {
2172
	filestruct *line = openfile->edittop;
2173
2174
	openfile->current_y = 0;

2175
2176
2177
2178
	while (line != NULL && line != openfile->current) {
	    openfile->current_y += strlenpt(line->data) / COLS + 1;
	    line = line->next;
	}
2179
	openfile->current_y += xpt / COLS;
2180

2181
	if (openfile->current_y < editwinrows)
2182
	    wmove(edit, openfile->current_y, xpt % COLS);
2183
2184
2185
    } else
#endif
    {
2186
	openfile->current_y = openfile->current->lineno -
2187
				openfile->edittop->lineno;
2188
2189
2190
2191

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

2194
2195
2196
2197
2198
2199
2200
2201
/* 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. */
2202
void edit_draw(filestruct *fileptr, const char *converted, int
2203
	line, size_t start)
Chris Allegretta's avatar
Chris Allegretta committed
2204
{
2205
#if !defined(NANO_TINY) || !defined(DISABLE_COLOR)
2206
2207
2208
2209
2210
2211
2212
2213
2214
    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. */
2215
2216
#endif

2217
    assert(openfile != NULL && fileptr != NULL && converted != NULL);
2218
    assert(strlenpt(converted) <= COLS);
2219

2220
2221
2222
    /* 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);
2223

2224
#ifndef USE_SLANG
2225
2226
2227
    /* 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. */
2228
2229
    if (seen_wide)
	wredrawln(edit, line, 1);
2230
#endif
2231

2232
#ifndef DISABLE_COLOR
2233
2234
2235
    /* If color syntaxes are available and turned on, we need to display
     * them. */
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX)) {
2236
	const colortype *varnish = openfile->colorstrings;
2237

2238
2239
2240
2241
	/* If there are multiline regexes, make sure there is a cache. */
	if (openfile->syntax->nmultis > 0)
	    alloc_multidata_if_needed(fileptr);

2242
	for (; varnish != NULL; varnish = varnish->next) {
2243
2244
	    int x_start;
		/* Starting column for mvwaddnstr.  Zero-based. */
2245
	    int paintlen = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2246
2247
		/* Number of chars to paint on this line.  There are
		 * COLS characters on a whole line. */
2248
	    size_t index;
2249
		/* Index in converted where we paint. */
2250
2251
2252
2253
	    regmatch_t startmatch;
		/* Match position for start_regex. */
	    regmatch_t endmatch;
		/* Match position for end_regex. */
2254

2255
	    if (varnish->bright)
2256
		wattron(edit, A_BOLD);
2257
	    wattron(edit, COLOR_PAIR(varnish->pairnum));
2258
2259
2260
	    /* 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. */
2261

2262
2263
	    /* First case: varnish is a single-line expression. */
	    if (varnish->end == NULL) {
2264
2265
2266
		size_t k = 0;

		/* We increment k by rm_eo, to move past the end of the
2267
		 * last match.  Even though two matches may overlap, we
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2268
2269
		 * want to ignore them, so that we can highlight e.g. C
		 * strings correctly. */
2270
2271
2272
		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
2273
2274
2275
		     * unless k is zero.  If regexec() returns
		     * REG_NOMATCH, there are no more matches in the
		     * line. */
2276
		    if (regexec(varnish->start, &fileptr->data[k], 1,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2277
2278
			&startmatch, (k == 0) ? 0 : REG_NOTBOL) ==
			REG_NOMATCH)
2279
			break;
2280
2281
		    /* Translate the match to the beginning of the
		     * line. */
2282
2283
		    startmatch.rm_so += k;
		    startmatch.rm_eo += k;
2284
2285
2286

		    /* Skip over a zero-length regex match. */
		    if (startmatch.rm_so == startmatch.rm_eo)
2287
			startmatch.rm_eo++;
2288
		    else if (startmatch.rm_so < endpos &&
2289
			startmatch.rm_eo > startpos) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2290
2291
			x_start = (startmatch.rm_so <= startpos) ? 0 :
				strnlenpt(fileptr->data,
2292
				startmatch.rm_so) - start;
2293

2294
2295
2296
			index = actual_x(converted, x_start);

			paintlen = actual_x(converted + index,
2297
2298
				strnlenpt(fileptr->data,
				startmatch.rm_eo) - start - x_start);
2299
2300
2301

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

2302
			mvwaddnstr(edit, line, x_start, converted +
2303
				index, paintlen);
2304
		    }
2305
		    k = startmatch.rm_eo;
Chris Allegretta's avatar
Chris Allegretta committed
2306
		}
2307
	    } else {	/* Second case: varnish is a multiline expression. */
2308
		const filestruct *start_line = fileptr->prev;
2309
		    /* The first line before fileptr that matches 'start'. */
2310
		size_t start_col;
2311
		    /* Where the match starts in that line. */
2312
		const filestruct *end_line;
2313
		    /* The line that matches 'end'. */
2314

2315
		/* First see if the multidata was maybe already calculated. */
2316
		if (fileptr->multidata[varnish->id] == CNONE)
2317
		    goto tail_of_loop;
2318
		else if (fileptr->multidata[varnish->id] == CWHOLELINE) {
2319
		    mvwaddnstr(edit, line, 0, converted, -1);
2320
		    goto tail_of_loop;
2321
2322
		} else if (fileptr->multidata[varnish->id] == CBEGINBEFORE) {
		    regexec(varnish->end, fileptr->data, 1, &endmatch, 0);
2323
2324
		    /* If the coloured part is scrolled off, skip it. */
		    if (endmatch.rm_eo <= startpos)
2325
			goto tail_of_loop;
2326
2327
2328
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
			endmatch.rm_eo) - start);
		    mvwaddnstr(edit, line, 0, converted, paintlen);
2329
		    goto tail_of_loop;
2330
		} if (fileptr->multidata[varnish->id] == -1)
2331
		    /* Assume this until proven otherwise below. */
2332
		    fileptr->multidata[varnish->id] = CNONE;
2333

2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
		/* 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. */

2344
		while (start_line != NULL && regexec(varnish->start,
2345
2346
2347
			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. */
2348
		    if (regexec(varnish->end, start_line->data, 0, NULL, 0) == 0)
2349
2350
2351
			goto step_two;
		    start_line = start_line->prev;
		}
2352

2353
2354
2355
2356
		/* If no start was found, skip to the next step. */
		if (start_line == NULL)
		    goto step_two;

2357
		/* If a found start has been qualified as an end earlier,
2358
		 * believe it and skip to the next step. */
2359
		if (start_line->multidata != NULL &&
2360
2361
			(start_line->multidata[varnish->id] == CBEGINBEFORE ||
			start_line->multidata[varnish->id] == CSTARTENDHERE))
2362
2363
		    goto step_two;

2364
		/* Skip over a zero-length regex match. */
2365
		if (startmatch.rm_so == startmatch.rm_eo)
2366
2367
		    goto tail_of_loop;

2368
2369
2370
2371
2372
2373
2374
		/* 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;
2375
		    if (regexec(varnish->end, start_line->data +
2376
2377
2378
				start_col + startmatch.rm_eo, 0, NULL,
				(start_col + startmatch.rm_eo == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH)
2379
2380
2381
			/* No end found after this start. */
			break;
		    start_col++;
2382
2383
		    if (regexec(varnish->start, start_line->data + start_col,
				1, &startmatch, REG_NOTBOL) == REG_NOMATCH)
2384
2385
2386
2387
2388
2389
2390
2391
2392
			/* 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;
2393
		while (end_line != NULL && regexec(varnish->end,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2394
			end_line->data, 1, &endmatch, 0) == REG_NOMATCH)
2395
		    end_line = end_line->next;
2396

2397
2398
2399
2400
		/* 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) {
2401
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2402
2403
		    goto step_two;
		}
2404

2405
2406
2407
2408
2409
2410
2411
		/* 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;
2412
		    fileptr->multidata[varnish->id] = CWHOLELINE;
2413
#ifdef DEBUG
2414
    fprintf(stderr, "  Marking for id %i  line %i as CWHOLELINE\n", varnish->id, line);
2415
#endif
2416
2417
2418
		} else {
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
						endmatch.rm_eo) - start);
2419
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2420
#ifdef DEBUG
2421
    fprintf(stderr, "  Marking for id %i  line %i as CBEGINBEFORE\n", varnish->id, line);
2422
#endif
2423
2424
2425
2426
2427
2428
		}
		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;
2429
  step_two:
2430
2431
2432
2433
2434
		/* 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) {
2435
		    if (regexec(varnish->start, fileptr->data + start_col,
2436
2437
				1, &startmatch, (start_col == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH ||
2438
				start_col + startmatch.rm_so >= endpos)
2439
2440
			/* No more starts on this line. */
			break;
2441

2442
2443
2444
2445
2446
2447
2448
		    /* 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,
2449
				startmatch.rm_so) - start;
2450

2451
		    index = actual_x(converted, x_start);
2452

2453
		    if (regexec(varnish->end, fileptr->data +
2454
				startmatch.rm_eo, 1, &endmatch,
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
				(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 &&
2465
				endmatch.rm_eo > startmatch.rm_so) {
2466
			    paintlen = actual_x(converted + index,
2467
					strnlenpt(fileptr->data,
2468
					endmatch.rm_eo) - start - x_start);
2469

2470
			    assert(0 <= x_start && x_start < COLS);
2471

2472
			    mvwaddnstr(edit, line, x_start,
2473
					converted + index, paintlen);
2474
			    if (paintlen > 0) {
2475
				fileptr->multidata[varnish->id] = CSTARTENDHERE;
2476
#ifdef DEBUG
2477
    fprintf(stderr, "  Marking for id %i  line %i as CSTARTENDHERE\n", varnish->id, line);
2478
#endif
2479
			    }
2480
2481
			}
			start_col = endmatch.rm_eo;
2482
2483
2484
			/* Skip over a zero-length match. */
			if (endmatch.rm_so == endmatch.rm_eo)
			    start_col += 1;
2485
2486
2487
2488
		    } else {
			/* There is no end on this line.  But we haven't yet
			 * looked for one on later lines. */
			end_line = fileptr->next;
2489

2490
			while (end_line != NULL &&
2491
				regexec(varnish->end, end_line->data,
2492
				0, NULL, 0) == REG_NOMATCH)
2493
			    end_line = end_line->next;
2494

2495
2496
2497
			/* If there is no end, we're done on this line. */
			if (end_line == NULL)
			    break;
2498

2499
2500
2501
2502
			assert(0 <= x_start && x_start < COLS);

			/* Paint the rest of the line. */
			mvwaddnstr(edit, line, x_start, converted + index, -1);
2503
			fileptr->multidata[varnish->id] = CENDAFTER;
2504
#ifdef DEBUG
2505
    fprintf(stderr, "  Marking for id %i  line %i as CENDAFTER\n", varnish->id, line);
2506
#endif
2507
2508
2509
			/* We've painted to the end of the line, so don't
			 * bother checking for any more starts. */
			break;
2510
		    }
2511
2512
		}
	    }
2513
  tail_of_loop:
2514
	    wattroff(edit, A_BOLD);
2515
	    wattroff(edit, COLOR_PAIR(varnish->pairnum));
2516
	}
2517
    }
2518
#endif /* !DISABLE_COLOR */
2519

2520
#ifndef NANO_TINY
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
    /* If the mark is on, and fileptr is at least partially selected, we
     * need to paint it. */
    if (openfile->mark_set &&
		(fileptr->lineno <= openfile->mark_begin->lineno ||
		fileptr->lineno <= openfile->current->lineno) &&
		(fileptr->lineno >= openfile->mark_begin->lineno ||
		fileptr->lineno >= openfile->current->lineno)) {
	const filestruct *top, *bot;
	    /* The lines where the marked region begins and ends. */
	size_t top_x, bot_x;
	    /* The x positions where the marked region begins and ends. */
2532
	int x_start;
2533
	    /* The starting column for mvwaddnstr().  Zero-based. */
2534
	int paintlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2535
2536
	    /* Number of characters to paint on this line.  There are
	     * COLS characters on a whole line. */
2537
	size_t index;
2538
	    /* Index in converted where we paint. */
2539

2540
	mark_order(&top, &top_x, &bot, &bot_x, NULL);
2541
2542
2543
2544
2545

	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
2546

2547
	/* Only paint if the marked bit of fileptr is on this page. */
2548
2549
	if (top_x < endpos && bot_x > startpos) {
	    assert(startpos <= top_x);
2550
2551
2552
2553

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

2555
2556
2557
2558
2559
	    /* 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. */
2560
2561
2562
	    if (bot_x >= endpos)
		paintlen = -1;
	    else
2563
		paintlen = strnlenpt(fileptr->data, bot_x) - (x_start + start);
2564
2565
2566
2567
2568
2569
2570
2571

	    /* 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;
	    }
2572
2573
2574

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

2575
	    index = actual_x(converted, x_start);
2576

2577
2578
2579
	    if (paintlen > 0)
		paintlen = actual_x(converted + index, paintlen);

2580
	    wattron(edit, hilite_attribute);
2581
	    mvwaddnstr(edit, line, x_start, converted + index, paintlen);
2582
	    wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
2583
	}
2584
    }
2585
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
2586
2587
}

2588
/* Just update one line in the edit buffer.  This is basically a wrapper
2589
 * for edit_draw().  The line will be displayed starting with
2590
 * fileptr->data[index].  Likely arguments are current_x or zero.
2591
 * Returns: Number of additional lines consumed (needed for SOFTWRAP). */
2592
int update_line(filestruct *fileptr, size_t index)
Chris Allegretta's avatar
Chris Allegretta committed
2593
{
2594
    int line = 0;
2595
	/* The line in the edit window that we want to update. */
2596
    int extralinesused = 0;
2597
2598
2599
2600
    char *converted;
	/* fileptr->data converted to have tabs and control characters
	 * expanded. */
    size_t page_start;
Chris Allegretta's avatar
Chris Allegretta committed
2601

2602
    assert(fileptr != NULL);
2603

2604
#ifndef NANO_TINY
2605
    if (ISSET(SOFTWRAP)) {
2606
2607
	filestruct *tmp;

2608
2609
	for (tmp = openfile->edittop; tmp && tmp != fileptr; tmp = tmp->next)
	    line += (strlenpt(tmp->data) / COLS) + 1;
2610
    } else
2611
#endif
2612
2613
	line = fileptr->lineno - openfile->edittop->lineno;

2614
    if (line < 0 || line >= editwinrows)
Chris Allegretta's avatar
Chris Allegretta committed
2615
	return 1;
2616

2617
    /* First, blank out the line. */
2618
    blank_line(edit, line, 0, COLS);
2619

2620
2621
    /* Next, convert variables that index the line to their equivalent
     * positions in the expanded line. */
2622
#ifndef NANO_TINY
2623
2624
2625
    if (ISSET(SOFTWRAP))
	index = 0;
    else
2626
#endif
2627
	index = strnlenpt(fileptr->data, index);
2628
    page_start = get_page_start(index);
2629

2630
2631
    /* Expand the line, replacing tabs with spaces, and control
     * characters with their displayed forms. */
2632
2633
2634
#ifdef NANO_TINY
    converted = display_string(fileptr->data, page_start, COLS, TRUE);
#else
2635
2636
2637
    converted = display_string(fileptr->data, page_start, COLS, !ISSET(SOFTWRAP));
#ifdef DEBUG
    if (ISSET(SOFTWRAP) && strlen(converted) >= COLS - 2)
2638
	fprintf(stderr, "update_line(): converted(1) line = %s\n", converted);
2639
#endif
2640
#endif /* !NANO_TINY */
2641

2642
    /* Paint the line. */
2643
    edit_draw(fileptr, converted, line, page_start);
2644
    free(converted);
Chris Allegretta's avatar
Chris Allegretta committed
2645

2646
#ifndef NANO_TINY
2647
    if (!ISSET(SOFTWRAP)) {
2648
#endif
2649
2650
2651
2652
	if (page_start > 0)
	    mvwaddch(edit, line, 0, '$');
	if (strlenpt(fileptr->data) > page_start + COLS)
	    mvwaddch(edit, line, COLS - 1, '$');
2653
#ifndef NANO_TINY
2654
    } else {
2655
	size_t full_length = strlenpt(fileptr->data);
2656
	for (index += COLS; index <= full_length && line < editwinrows - 1; index += COLS) {
2657
2658
	    line++;
#ifdef DEBUG
2659
	    fprintf(stderr, "update_line(): softwrap code, moving to %d index %lu\n", line, (unsigned long)index);
2660
#endif
2661
	    blank_line(edit, line, 0, COLS);
2662
2663

	    /* Expand the line, replacing tabs with spaces, and control
2664
	     * characters with their displayed forms. */
2665
2666
2667
2668
2669
	    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
2670
2671
2672

	    /* Paint the line. */
	    edit_draw(fileptr, converted, line, index);
2673
	    free(converted);
2674
2675
2676
	    extralinesused++;
	}
    }
2677
#endif /* !NANO_TINY */
2678
    return extralinesused;
Chris Allegretta's avatar
Chris Allegretta committed
2679
2680
}

2681
2682
2683
2684
/* 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)
2685
2686
{
    return
2687
#ifndef NANO_TINY
2688
	openfile->mark_set ||
2689
#endif
2690
	get_page_start(pww_save) != get_page_start(openfile->placewewant);
2691
2692
}

2693
/* When edittop changes, try and figure out how many lines
2694
 * we really have to work with (i.e. set maxrows). */
2695
2696
2697
2698
2699
void compute_maxrows(void)
{
    int n;
    filestruct *foo = openfile->edittop;

2700
2701
2702
2703
2704
    if (!ISSET(SOFTWRAP)) {
	maxrows = editwinrows;
	return;
    }

2705
2706
    maxrows = 0;
    for (n = 0; n < editwinrows && foo; n++) {
2707
	maxrows++;
2708
	n += strlenpt(foo->data) / COLS;
2709
2710
2711
	foo = foo->next;
    }

2712
2713
2714
    if (n < editwinrows)
	maxrows += editwinrows - n;

2715
#ifdef DEBUG
2716
    fprintf(stderr, "compute_maxrows(): maxrows = %d\n", maxrows);
2717
2718
2719
#endif
}

2720
2721
/* 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
2722
2723
 * scrolling.  direction is the direction to scroll, either UPWARD or
 * DOWNWARD, and nlines is the number of lines to scroll.  We change
2724
2725
 * edittop, and assume that current and current_x are up to date.  We
 * also assume that scrollok(edit) is FALSE. */
2726
void edit_scroll(scroll_dir direction, ssize_t nlines)
2727
{
2728
    ssize_t i;
2729
    filestruct *foo;
2730

2731
    assert(nlines > 0);
2732

2733
2734
2735
    /* Part 1: nlines is the number of lines we're going to scroll the
     * text of the edit window. */

2736
    /* Move the top line of the edit window up or down (depending on the
2737
2738
     * value of direction) nlines lines, or as many lines as we can if
     * there are fewer than nlines lines available. */
2739
    for (i = nlines; i > 0; i--) {
2740
	if (direction == UPWARD) {
2741
	    if (openfile->edittop == openfile->fileage)
2742
		break;
2743
	    openfile->edittop = openfile->edittop->prev;
2744
	} else {
2745
	    if (openfile->edittop == openfile->filebot)
2746
		break;
2747
	    openfile->edittop = openfile->edittop->next;
2748
	}
2749
2750

#ifndef NANO_TINY
2751
	/* Don't over-scroll on long lines. */
2752
	if (ISSET(SOFTWRAP) && direction == UPWARD) {
2753
	    ssize_t len = strlenpt(openfile->edittop->data) / COLS;
2754
	    i -= len;
2755
	    if (len > 0)
2756
		refresh_needed = TRUE;
2757
	}
2758
#endif
2759
2760
    }

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

2764
2765
2766
2767
    /* Don't bother scrolling zero lines, nor more than the window can hold. */
    if (nlines == 0)
	return;
    if (nlines >= editwinrows)
2768
	refresh_needed = TRUE;
2769

2770
    if (refresh_needed == TRUE)
2771
	return;
2772
2773
2774

    /* Scroll the text of the edit window up or down nlines lines,
     * depending on the value of direction. */
2775
    scrollok(edit, TRUE);
2776
    wscrl(edit, (direction == UPWARD) ? -nlines : nlines);
2777
2778
    scrollok(edit, FALSE);

2779
2780
2781
    /* Part 2: nlines is the number of lines in the scrolled region of
     * the edit window that we need to draw. */

2782
2783
    /* If the top or bottom line of the file is now visible in the edit
     * window, we need to draw the entire edit window. */
2784
2785
    if ((direction == UPWARD && openfile->edittop ==
	openfile->fileage) || (direction == DOWNWARD &&
2786
2787
	openfile->edittop->lineno + editwinrows - 1 >=
	openfile->filebot->lineno))
2788
	nlines = editwinrows;
2789

2790
2791
2792
2793
2794
2795
    /* 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
2796

2797
2798
    if (nlines > editwinrows)
	nlines = editwinrows;
2799
2800
2801

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

2804
2805
    /* If we scrolled down, move down to the line before the scrolled
     * region. */
2806
    if (direction == DOWNWARD) {
2807
	for (i = editwinrows - nlines; i > 0 && foo != NULL; i--)
2808
2809
2810
	    foo = foo->next;
    }

2811
2812
2813
2814
2815
2816
    /* 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--) {
2817
2818
	if ((i == nlines && direction == DOWNWARD) || (i == 1 &&
		direction == UPWARD)) {
2819
	    if (need_screen_update(0))
2820
2821
2822
2823
		update_line(foo, (foo == openfile->current) ?
			openfile->current_x : 0);
	} else
	    update_line(foo, (foo == openfile->current) ?
2824
		openfile->current_x : 0);
2825
	foo = foo->next;
2826
    }
2827
    compute_maxrows();
2828
2829
2830
}

/* Update any lines between old_current and current that need to be
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2831
 * updated.  Use this if we've moved without changing any text. */
2832
void edit_redraw(filestruct *old_current)
2833
{
2834
2835
2836
2837
    size_t was_pww = openfile->placewewant;

    openfile->placewewant = xplustabs();

2838
2839
    /* If the current line is offscreen, scroll until it's onscreen. */
    if (openfile->current->lineno >= openfile->edittop->lineno + maxrows ||
2840
		openfile->current->lineno < openfile->edittop->lineno) {
2841
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : FLOWING);
2842
	refresh_needed = TRUE;
2843
    }
2844

2845
#ifndef NANO_TINY
2846
2847
2848
    /* If the mark is on, update all lines between old_current and current. */
    if (openfile->mark_set) {
	filestruct *foo = old_current;
2849

2850
	while (foo != openfile->current) {
2851
	    update_line(foo, 0);
2852

2853
2854
2855
	    foo = (foo->lineno > openfile->current->lineno) ?
			foo->prev : foo->next;
	}
2856
2857
2858
2859
2860
2861
    } 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);
2862
2863
2864
2865
2866

    /* 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))
2867
	update_line(openfile->current, openfile->current_x);
2868
2869
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2870
2871
/* 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
2872
2873
void edit_refresh(void)
{
2874
    filestruct *foo;
2875
    int nlines;
2876

2877
    /* Figure out what maxrows should really be. */
2878
    compute_maxrows();
2879

2880
2881
    if (openfile->current->lineno < openfile->edittop->lineno ||
	openfile->current->lineno >= openfile->edittop->lineno +
2882
2883
	maxrows) {
#ifdef DEBUG
2884
2885
	fprintf(stderr, "edit_refresh(): line = %ld, edittop %ld + maxrows %d\n",
		(long)openfile->current->lineno, (long)openfile->edittop->lineno, maxrows);
2886
2887
#endif

2888
	/* Make sure the current line is on the screen. */
2889
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : STATIONARY);
2890
    }
Chris Allegretta's avatar
Chris Allegretta committed
2891

2892
2893
    foo = openfile->edittop;

2894
#ifdef DEBUG
2895
    fprintf(stderr, "edit_refresh(): edittop->lineno = %ld\n", (long)openfile->edittop->lineno);
2896
#endif
2897

2898
    for (nlines = 0; nlines < editwinrows && foo != NULL; nlines++) {
2899
	nlines += update_line(foo, (foo == openfile->current) ?
2900
		openfile->current_x : 0);
2901
2902
2903
	foo = foo->next;
    }

2904
    for (; nlines < editwinrows; nlines++)
2905
2906
2907
	blank_line(edit, nlines, 0, COLS);

    reset_cursor();
2908
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2909
2910
}

2911
2912
2913
2914
2915
2916
/* 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
2917
{
2918
    int goal = 0;
2919

2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
    /* 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)
2930
	goal = editwinrows / 2;
2931
    else if (manner == FLOWING) {
2932
	if (openfile->current->lineno >= openfile->edittop->lineno)
2933
2934
	    goal = editwinrows - 1;
    } else {
2935
	goal = openfile->current_y;
2936

2937
	/* Limit goal to (editwinrows - 1) lines maximum. */
2938
2939
	if (goal > editwinrows - 1)
	    goal = editwinrows - 1;
Chris Allegretta's avatar
Chris Allegretta committed
2940
    }
2941

2942
2943
2944
2945
2946
    openfile->edittop = openfile->current;

    while (goal > 0 && openfile->edittop->prev != NULL) {
	openfile->edittop = openfile->edittop->prev;
	goal --;
2947
#ifndef NANO_TINY
2948
2949
	if (ISSET(SOFTWRAP))
	    goal -= strlenpt(openfile->edittop->data) / COLS;
2950
#endif
2951
    }
2952
#ifdef DEBUG
2953
    fprintf(stderr, "edit_update(): setting edittop to lineno %ld\n", (long)openfile->edittop->lineno);
2954
#endif
2955
    compute_maxrows();
Chris Allegretta's avatar
Chris Allegretta committed
2956
2957
}

2958
/* Unconditionally redraw the entire screen. */
2959
void total_redraw(void)
2960
{
2961
2962
2963
2964
2965
2966
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 4: Slang doesn't define
     * curscr. */
    SLsmg_touch_screen();
    SLsmg_refresh();
#else
2967
    wrefresh(curscr);
2968
#endif
2969
2970
}

2971
2972
/* Unconditionally redraw the entire screen, and then refresh it using
 * the current file. */
2973
2974
void total_refresh(void)
{
2975
    total_redraw();
2976
    titlebar(NULL);
2977
    edit_refresh();
2978
    bottombars(currmenu);
2979
2980
}

2981
2982
/* Display the main shortcut list on the last two rows of the bottom
 * portion of the window. */
2983
2984
void display_main_list(void)
{
2985
#ifndef DISABLE_COLOR
2986
2987
    if (openfile->syntax &&
		(openfile->syntax->formatter || openfile->syntax->linter))
2988
	set_lint_or_format_shortcuts();
2989
2990
2991
2992
    else
	set_spell_shortcuts();
#endif

2993
    bottombars(MMAIN);
2994
2995
}

2996
/* If constant is TRUE, we display the current cursor position only if
2997
2998
 * suppress_cursorpos is FALSE.  If constant is FALSE, we display the
 * position always.  In any case we reset suppress_cursorpos to FALSE. */
2999
void do_cursorpos(bool constant)
Chris Allegretta's avatar
Chris Allegretta committed
3000
{
3001
    filestruct *f;
3002
    char c;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3003
    size_t i, cur_xpt = xplustabs() + 1;
3004
    size_t cur_lenpt = strlenpt(openfile->current->data) + 1;
3005
    int linepct, colpct, charpct;
Chris Allegretta's avatar
Chris Allegretta committed
3006

3007
    assert(openfile->fileage != NULL && openfile->current != NULL);
3008

3009
    /* Determine the size of the file up to the cursor. */
3010
    f = openfile->current->next;
3011
    c = openfile->current->data[openfile->current_x];
3012
3013

    openfile->current->next = NULL;
3014
    openfile->current->data[openfile->current_x] = '\0';
3015
3016
3017

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

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

3021
    /* If the position needs to be suppressed, don't suppress it next time. */
3022
    if (suppress_cursorpos && constant) {
3023
	suppress_cursorpos = FALSE;
3024
	return;
3025
    }
Chris Allegretta's avatar
Chris Allegretta committed
3026

3027
    /* Display the current cursor position on the statusbar. */
3028
    linepct = 100 * openfile->current->lineno / openfile->filebot->lineno;
3029
    colpct = 100 * cur_xpt / cur_lenpt;
3030
    charpct = (openfile->totsize == 0) ? 0 : 100 * i / openfile->totsize;
3031

3032
    statusline(HUSH,
3033
	_("line %ld/%ld (%d%%), col %lu/%lu (%d%%), char %lu/%lu (%d%%)"),
3034
	(long)openfile->current->lineno,
3035
	(long)openfile->filebot->lineno, linepct,
3036
	(unsigned long)cur_xpt, (unsigned long)cur_lenpt, colpct,
3037
	(unsigned long)i, (unsigned long)openfile->totsize, charpct);
3038
3039
3040

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

3043
/* Unconditionally display the current cursor position. */
3044
void do_cursorpos_void(void)
3045
{
3046
    do_cursorpos(FALSE);
3047
3048
}

3049
3050
void enable_nodelay(void)
{
3051
3052
    nodelay_mode = TRUE;
    nodelay(edit, TRUE);
3053
3054
3055
3056
}

void disable_nodelay(void)
{
3057
3058
    nodelay_mode = FALSE;
    nodelay(edit, FALSE);
3059
3060
}

3061
3062
/* Highlight the current word being replaced or spell checked.  We
 * expect word to have tabs and control characters expanded. */
3063
void spotlight(bool active, const char *word)
Chris Allegretta's avatar
Chris Allegretta committed
3064
{
3065
    size_t word_len = strlenpt(word), room;
Chris Allegretta's avatar
Chris Allegretta committed
3066

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

3070
    assert(room > 0);
3071

3072
3073
    if (word_len > room)
	room--;
3074

Chris Allegretta's avatar
Chris Allegretta committed
3075
    reset_cursor();
3076
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
3077

3078
    if (active)
3079
	wattron(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3080

3081
    /* This is so we can show zero-length matches. */
3082
    if (word_len == 0)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3083
	waddch(edit, ' ');
3084
    else
3085
	waddnstr(edit, word, actual_x(word, room));
3086

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

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

3094
#ifndef DISABLE_EXTRA
3095
3096
#define CREDIT_LEN 54
#define XLCREDIT_LEN 9
3097

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

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

3174
3175
3176
3177
3178
3179
    if (!old_more_space || !old_no_help) {
	SET(MORE_SPACE);
	SET(NO_HELP);
	window_init();
    }

3180
3181
    curs_set(0);
    nodelay(edit, TRUE);
3182

3183
    blank_titlebar();
3184
    blank_topbar();
Chris Allegretta's avatar
Chris Allegretta committed
3185
    blank_edit();
3186
3187
    blank_statusbar();
    blank_bottombars();
3188

3189
    wrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
3190
    wrefresh(edit);
3191
    wrefresh(bottomwin);
3192
    napms(700);
3193

3194
    for (crpos = 0; crpos < CREDIT_LEN + editwinrows / 2; crpos++) {
3195
	if ((kbinput = wgetch(edit)) != ERR)
3196
	    break;
3197

3198
	if (crpos < CREDIT_LEN) {
3199
	    const char *what;
3200
3201
	    size_t start_x;

3202
	    if (credits[crpos] == NULL) {
3203
		assert(0 <= xlpos && xlpos < XLCREDIT_LEN);
3204

3205
		what = _(xlcredits[xlpos]);
3206
		xlpos++;
3207
	    } else
3208
		what = credits[crpos];
3209

3210
	    start_x = COLS / 2 - strlenpt(what) / 2 - 1;
3211
3212
	    mvwaddstr(edit, editwinrows - 1 - (editwinrows % 2),
		start_x, what);
3213
	}
3214

3215
3216
3217
3218
	wrefresh(edit);

	if ((kbinput = wgetch(edit)) != ERR)
	    break;
3219
	napms(700);
3220

3221
	scrollok(edit, TRUE);
3222
	wscrl(edit, 1);
3223
	scrollok(edit, FALSE);
3224
	wrefresh(edit);
3225

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

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

3236
3237
3238
    if (kbinput != ERR)
	ungetch(kbinput);

3239
    if (!old_more_space)
3240
	UNSET(MORE_SPACE);
3241
    if (!old_no_help)
3242
	UNSET(NO_HELP);
3243
    window_init();
3244

3245
    nodelay(edit, FALSE);
3246

3247
    total_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
3248
}
3249
#endif /* !DISABLE_EXTRA */