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

23
#include "proto.h"
24
#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
static int statusblank = 0;
44
	/* The number of keystrokes left before we blank the statusbar. */
45
static bool suppress_cursorpos = FALSE;
46
	/* Should we skip constant position display for one keystroke? */
47
48
static bool seen_wide = FALSE;
	/* Whether we've seen a multicolumn character in the current line. */
49

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

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

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

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

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

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

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

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

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

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

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

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

    while (TRUE) {
187
	input = wgetch(win);
188

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

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

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

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

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

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

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

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

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

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

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

261
    unget_input(&kbinput, 1);
262

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

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

277
278
    if (key_buffer_len == 0 && win != NULL)
	get_key_buffer(win);
279

280
281
    if (key_buffer_len == 0)
	return NULL;
282

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

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

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

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

    return input;
313
314
}

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

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

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

328
329
330
    return kbinput;
}

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

344
345
    meta_key = FALSE;
    func_key = FALSE;
346

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

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

    while (kbinput == NULL)
354
	kbinput = get_input(win, 1);
355

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

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

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

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

640
641
642
643
644
645
646
#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

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

#ifdef DEBUG
654
    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);
655
656
#endif

657
658
    free(kbinput);

659
    /* Return the result. */
660
661
662
    return retval;
}

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

1079
    return ERR;
1080
1081
}

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

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

    free(seq);

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

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

    return retval;
}

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

1149
1150
    /* Increment the byte digit counter. */
    byte_digits++;
1151

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

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

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

    return retval;
}

1213
#ifdef ENABLE_UTF8
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1214
/* If the character in kbinput is a valid hexadecimal digit, multiply it
1215
 * by factor and add the result to uni, and return ERR to signify okay. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1216
1217
1218
1219
1220
1221
1222
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
1223
1224
	/* The character isn't hexadecimal; give it as the result. */
	return (long)kbinput;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1225

1226
    return ERR;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1227
1228
}

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

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

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

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

1299
#ifdef DEBUG
1300
    fprintf(stderr, "get_unicode_kbinput(): kbinput = %d, uni_digits = %d, uni = %ld, retval = %ld\n", kbinput, uni_digits, uni, retval);
1301
1302
#endif

1303
1304
    return retval;
}
1305
#endif /* ENABLE_UTF8 */
1306

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

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

1334
#ifdef DEBUG
1335
    fprintf(stderr, "get_control_kbinput(): kbinput = %d, retval = %d\n", kbinput, retval);
1336
1337
#endif

1338
1339
    return retval;
}
1340

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

1348
1349
1350
1351
    if (output_len == 0)
	return;

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

1353
1354
    for (i = 0; i < output_len; i++)
	input[i] = (int)output[i];
1355

1356
    unget_input(input, output_len);
1357

1358
    free(input);
1359
1360
}

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

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

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

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

1385
    return retval;
1386
1387
}

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

1396
    /* Read in the first keystroke. */
1397
1398
    while ((kbinput = get_input(win, 1)) == NULL)
	;
1399

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

	/* 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) {
1424
1425
		while ((kbinput = get_input(win, 1)) == NULL)
		    ;
1426
1427
		uni = get_unicode_kbinput(*kbinput);
	    }
1428

1429
1430
1431
	    /* Put back the multibyte equivalent of the Unicode
	     * value. */
	    uni_mb = make_mbchar(uni, &uni_mb_len);
1432

1433
	    seq = (int *)nmalloc(uni_mb_len * sizeof(int));
1434

1435
1436
	    for (i = 0; i < uni_mb_len; i++)
		seq[i] = (unsigned char)uni_mb[i];
1437

1438
	    unget_input(seq, uni_mb_len);
1439

1440
1441
	    free(seq);
	    free(uni_mb);
1442
	}
1443
    } else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1444
1445
#endif /* ENABLE_UTF8 */

1446
1447
	/* Put back the first keystroke. */
	unget_input(kbinput, 1);
1448

1449
1450
    free(kbinput);

1451
    /* Get the complete sequence, and save the characters in it as the
1452
     * result. */
1453
    *kbinput_len = get_key_buffer_len();
1454
    retval = get_input(NULL, *kbinput_len);
1455
1456
1457
1458

    return retval;
}

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

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

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

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

1491
1492
    in_bottomwin = wenclose(bottomwin, *mouse_y, *mouse_x);

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

1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
	    /* 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;
	    }
1524

1525
	    /* Get the shortcut lists' length. */
1526
	    if (currmenu == MMAIN)
1527
		currslen = MAIN_VISIBLE;
1528
	    else {
1529
		currslen = length_of_list(currmenu);
1530

1531
1532
1533
1534
1535
		/* We don't show any more shortcuts than the main list
		 * does. */
		if (currslen > MAIN_VISIBLE)
		    currslen = MAIN_VISIBLE;
	    }
1536

1537
1538
1539
1540
1541
1542
1543
1544
	    /* 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));

1545
1546
	    /* Calculate the one-based index in the shortcut list. */
	    j = (*mouse_x / i) * 2 + *mouse_y;
1547

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

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

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

1593
1594
1595
1596
	if (in_bottomwin)
	    /* Translate the mouse event coordinates so that they're
	     * relative to bottomwin. */
	    wmouse_trafo(bottomwin, mouse_y, mouse_x, FALSE);
1597

1598
	if (in_edit || (in_bottomwin && *mouse_y == 0)) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1599
1600
	    int i;

1601
1602
1603
1604
1605
	    /* 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) ?
1606
			sc_seq_or(do_up_void, 0) : sc_seq_or(do_down_void, 0),
1607
			FALSE, FALSE);
1608
1609
1610
1611
1612
1613
1614

	    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;
1615
1616
    }
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1617
1618
1619

    /* Ignore all other mouse events. */
    return 2;
1620
}
1621
1622
#endif /* !DISABLE_MOUSE */

1623
1624
1625
1626
/* 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. */
1627
const sc *get_shortcut(int *kbinput)
1628
{
1629
    sc *s;
1630

1631
#ifdef DEBUG
1632
    fprintf(stderr, "get_shortcut(): kbinput = %d, meta_key = %s -- ", *kbinput, meta_key ? "TRUE" : "FALSE");
1633
1634
#endif

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

    return NULL;
}

1652
1653
1654
1655
1656
/* 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
1657

1658
1659
1660
1661
    for (; n > 0; n--)
	waddch(win, ' ');
}

1662
/* Blank the first line of the top portion of the window. */
1663
void blank_titlebar(void)
Chris Allegretta's avatar
Chris Allegretta committed
1664
{
1665
    blank_line(topwin, 0, 0, COLS);
1666
1667
}

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

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

1682
    for (i = 0; i < editwinrows; i++)
1683
	blank_line(edit, i, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1684
1685
}

1686
/* Blank the first line of the bottom portion of the window. */
Chris Allegretta's avatar
Chris Allegretta committed
1687
1688
void blank_statusbar(void)
{
1689
    blank_line(bottomwin, 0, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1690
1691
}

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

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

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

1747
1748
1749
1750
1751
    /* If dollars is TRUE, make room for the "$" at the end of the
     * line. */
    if (dollars && len > 0 && strlenpt(buf) > start_col + len)
	len--;

1752
1753
1754
    if (len == 0)
	return mallocstrcpy(NULL, "");

1755
1756
    buf_mb = charalloc(mb_cur_max());

1757
1758
    start_index = actual_x(buf, start_col);
    column = strnlenpt(buf, start_index);
1759

1760
    assert(column <= start_col);
1761

1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
    /* Make sure there's enough room for the initial character, whether
     * it's a multibyte control character, a non-control multibyte
     * character, a tab character, or a null terminator.  Rationale:
     *
     * multibyte control character followed by a null terminator:
     *     1 byte ('^') + mb_cur_max() bytes + 1 byte ('\0')
     * multibyte non-control character followed by a null terminator:
     *     mb_cur_max() bytes + 1 byte ('\0')
     * tab character followed by a null terminator:
     *     mb_cur_max() bytes + (tabsize - 1) bytes + 1 byte ('\0')
     *
     * Since tabsize has a minimum value of 1, it can substitute for 1
     * byte above. */
    alloc_len = (mb_cur_max() + tabsize + 1) * MAX_BUF_SIZE;
    converted = charalloc(alloc_len);
1777

1778
    index = 0;
1779
    seen_wide = FALSE;
1780

1781
1782
    if (buf[start_index] != '\0' && buf[start_index] != '\t' &&
	(column < start_col || (dollars && column > 0))) {
1783
1784
	/* We don't display all of buf[start_index] since it starts to
	 * the left of the screen. */
1785
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1786

1787
	if (is_cntrl_mbchar(buf_mb)) {
1788
	    if (column < start_col) {
1789
1790
		char *character = charalloc(mb_cur_max());
		int charlen, i;
1791

1792
		character = control_mbrep(buf_mb, character, &charlen);
1793

1794
1795
		for (i = 0; i < charlen; i++)
		    converted[index++] = character[i];
1796

1797
		start_col += mbwidth(character);
1798

1799
		free(character);
1800

1801
		start_index += buf_mb_len;
1802
	    }
1803
	}
1804
#ifdef ENABLE_UTF8
1805
1806
1807
1808
1809
1810
	else if (using_utf8() && mbwidth(buf_mb) == 2) {
	    if (column >= start_col) {
		converted[index++] = ' ';
		start_col++;
	    }

1811
	    converted[index++] = ' ';
1812
	    start_col++;
1813
1814

	    start_index += buf_mb_len;
1815
	}
1816
#endif
1817
1818
    }

1819
    while (buf[start_index] != '\0') {
1820
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1821

1822
1823
1824
	if (mbwidth(buf + start_index) > 1)
	    seen_wide = TRUE;

1825
1826
1827
1828
1829
1830
1831
1832
	/* Make sure there's enough room for the next character, whether
	 * it's a multibyte control character, a non-control multibyte
	 * character, a tab character, or a null terminator. */
	if (index + mb_cur_max() + tabsize + 1 >= alloc_len - 1) {
	    alloc_len += (mb_cur_max() + tabsize + 1) * MAX_BUF_SIZE;
	    converted = charealloc(converted, alloc_len);
	}

1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
	if (*buf_mb == ' ') {
	    /* 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++;
	} else if (*buf_mb == '\t') {
1846
	    /* Show a tab as a visible character, or as as a space. */
1847
#ifndef NANO_TINY
1848
	    if (ISSET(WHITESPACE_DISPLAY)) {
1849
		int i = 0;
1850

1851
1852
		while (i < whitespace_len[0])
		    converted[index++] = whitespace[i++];
1853
	    } else
1854
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1855
		converted[index++] = ' ';
1856
	    start_col++;
1857
	    /* Fill the tab up with the required number of spaces. */
1858
	    while (start_col % tabsize != 0) {
1859
		converted[index++] = ' ';
1860
1861
		start_col++;
	    }
1862
	/* If buf contains a control character, interpret it. */
1863
	} else if (is_cntrl_mbchar(buf_mb)) {
1864
1865
	    char *character = charalloc(mb_cur_max());
	    int charlen, i;
1866

1867
	    converted[index++] = '^';
1868
1869
	    start_col++;

1870
	    character = control_mbrep(buf_mb, character, &charlen);
1871

1872
1873
	    for (i = 0; i < charlen; i++)
		converted[index++] = character[i];
1874

1875
	    start_col += mbwidth(character);
1876

1877
	    free(character);
1878
1879
	/* If buf contains a non-control character, interpret it.  If buf
	 * contains an invalid multibyte sequence, display it as such. */
1880
	} else {
1881
1882
	    char *character = charalloc(mb_cur_max());
	    int charlen, i;
1883

1884
#ifdef ENABLE_UTF8
1885
1886
1887
	    /* Make sure an invalid sequence-starter byte is properly
	     * terminated, so that it doesn't pick up lingering bytes
	     * of any previous content. */
1888
1889
1890
	    if (using_utf8() && buf_mb_len == 1)
		buf_mb[1] = '\0';
#endif
1891
	    character = mbrep(buf_mb, character, &charlen);
1892

1893
1894
	    for (i = 0; i < charlen; i++)
		converted[index++] = character[i];
1895

1896
	    start_col += mbwidth(character);
1897

1898
	    free(character);
1899
1900
	}

1901
	start_index += buf_mb_len;
1902
1903
    }

1904
1905
    free(buf_mb);

1906
1907
    assert(alloc_len >= index + 1);

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1908
    /* Null-terminate converted. */
1909
    converted[index] = '\0';
1910
1911
1912

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

1915
    return converted;
1916
1917
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1918
1919
1920
1921
1922
1923
/* 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. */
1924
void titlebar(const char *path)
Chris Allegretta's avatar
Chris Allegretta committed
1925
{
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
    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. */
1938

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

1941
1942
1943
    if (interface_color_pair[TITLE_BAR].bright)
	wattron(topwin, A_BOLD);
    wattron(topwin, interface_color_pair[TITLE_BAR].pairnum);
1944

1945
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
1946

1947
1948
1949
    /* 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
1950

1951
    /* Figure out the path, prefix and state strings. */
1952
#ifndef DISABLE_BROWSER
1953
1954
1955
1956
    if (path != NULL)
	prefix = _("DIR:");
    else
#endif
1957
1958
1959
1960
1961
1962
1963
    {
	if (openfile->filename[0] == '\0')
	    path = _("New Buffer");
	else {
	    path = openfile->filename;
	    prefix = _("File:");
	}
1964

1965
1966
1967
1968
	if (openfile->modified)
	    state = _("Modified");
	else if (ISSET(VIEW_MODE))
	    state = _("View");
1969

1970
1971
	pluglen = strlenpt(_("Modified")) + 1;
    }
1972

1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
    /* 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;
1983
1984
    }

1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
    /* 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;
1997
1998
1999
	}
    }

2000
2001
2002
2003
    /* If we have side spaces left, center the path name. */
    if (verlen > 0)
	offset = verlen + (COLS - (verlen + pluglen + statelen) -
					(prefixlen + pathlen)) / 2;
2004

2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
    /* 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);
2022
    }
2023

2024
2025
2026
2027
2028
2029
    /* 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));

2030
2031
    wattroff(topwin, A_BOLD);
    wattroff(topwin, interface_color_pair[TITLE_BAR].pairnum);
2032

2033
    wnoutrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
2034
    reset_cursor();
2035
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2036
2037
}

2038
2039
2040
2041
2042
2043
/* Display a normal message on the statusbar, quietly. */
void statusbar(const char *msg)
{
    statusline(HUSH, msg);
}

2044
/* Display a message on the statusbar, and set suppress_cursorpos to
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2045
2046
 * TRUE, so that the message won't be immediately overwritten if
 * constant cursor position display is on. */
2047
void statusline(message_type importance, const char *msg, ...)
2048
2049
{
    va_list ap;
2050
    char *bar, *foo;
Benno Schulenberg's avatar
Benno Schulenberg committed
2051
    size_t start_x;
2052
2053
2054
2055
#ifndef NANO_TINY
    bool old_whitespace = ISSET(WHITESPACE_DISPLAY);

    UNSET(WHITESPACE_DISPLAY);
2056
#endif
2057
2058
2059
2060
2061

    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(). */
2062
    if (isendwin()) {
2063
2064
2065
2066
2067
	vfprintf(stderr, msg, ap);
	va_end(ap);
	return;
    }

2068
2069
2070
2071
2072
2073
2074
    /* 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)
2075
2076
	napms(1200);

2077
    if (importance == ALERT)
2078
	beep();
2079
2080

    lastmessage = importance;
2081

2082
2083
2084
    /* Turn the cursor off while fiddling in the statusbar. */
    curs_set(0);

2085
2086
    blank_statusbar();

2087
2088
2089
2090
    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
2091
    free(bar);
2092
2093

#ifndef NANO_TINY
2094
2095
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);
2096
#endif
Benno Schulenberg's avatar
Benno Schulenberg committed
2097
    start_x = (COLS - strlenpt(foo) - 4) / 2;
2098

2099
    wmove(bottomwin, 0, start_x);
2100
2101
2102
    if (interface_color_pair[STATUS_BAR].bright)
	wattron(bottomwin, A_BOLD);
    wattron(bottomwin, interface_color_pair[STATUS_BAR].pairnum);
2103
2104
2105
2106
    waddstr(bottomwin, "[ ");
    waddstr(bottomwin, foo);
    free(foo);
    waddstr(bottomwin, " ]");
2107
2108
    wattroff(bottomwin, A_BOLD);
    wattroff(bottomwin, interface_color_pair[STATUS_BAR].pairnum);
2109

2110
    /* Push the message to the screen straightaway. */
2111
    wnoutrefresh(bottomwin);
2112
    doupdate();
2113

2114
    suppress_cursorpos = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2115

2116
    /* If we're doing quick statusbar blanking, blank it after just one
2117
2118
     * keystroke.  Otherwise, blank it after twenty-six keystrokes, as
     * Pico does. */
2119
#ifndef NANO_TINY
2120
2121
2122
    if (ISSET(QUICK_BLANK))
	statusblank = 1;
    else
2123
#endif
2124
	statusblank = 26;
2125
2126
}

2127
2128
/* Display the shortcut list corresponding to menu on the last two rows
 * of the bottom portion of the window. */
2129
void bottombars(int menu)
Chris Allegretta's avatar
Chris Allegretta committed
2130
{
2131
    size_t i, colwidth, slen;
2132
2133
    subnfunc *f;
    const sc *s;
2134

2135
2136
2137
    /* Set the global variable to the given menu. */
    currmenu = menu;

Chris Allegretta's avatar
Chris Allegretta committed
2138
2139
2140
    if (ISSET(NO_HELP))
	return;

2141
    if (menu == MMAIN) {
2142
	slen = MAIN_VISIBLE;
2143

2144
	assert(slen <= length_of_list(menu));
2145
    } else {
2146
	slen = length_of_list(menu);
2147

2148
	/* Don't show any more shortcuts than the main list does. */
2149
2150
2151
2152
	if (slen > MAIN_VISIBLE)
	    slen = MAIN_VISIBLE;
    }

2153
2154
2155
2156
    /* 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. */
2157
    colwidth = COLS / ((slen / 2) + (slen % 2));
Chris Allegretta's avatar
Chris Allegretta committed
2158

2159
    blank_bottombars();
2160

2161
2162
2163
#ifdef DEBUG
    fprintf(stderr, "In bottombars, and slen == \"%d\"\n", (int) slen);
#endif
2164

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

2167
#ifdef DEBUG
2168
	fprintf(stderr, "Checking menu items....");
2169
#endif
2170
	if ((f->menus & menu) == 0)
2171
	    continue;
2172

2173
#ifdef DEBUG
2174
	fprintf(stderr, "found one! f->menus = %x, desc = \"%s\"\n", f->menus, f->desc);
2175
#endif
2176
2177
	s = first_sc_for(menu, f->scfunc);
	if (s == NULL) {
2178
2179
2180
#ifdef DEBUG
	    fprintf(stderr, "Whoops, guess not, no shortcut key found for func!\n");
#endif
2181
2182
	    continue;
	}
2183
	wmove(bottomwin, 1 + i % 2, (i / 2) * colwidth);
2184
#ifdef DEBUG
2185
	fprintf(stderr, "Calling onekey with keystr \"%s\" and desc \"%s\"\n", s->keystr, f->desc);
2186
#endif
2187
	onekey(s->keystr, _(f->desc), colwidth + (COLS % colwidth));
2188
	i++;
Chris Allegretta's avatar
Chris Allegretta committed
2189
    }
2190

2191
2192
    wnoutrefresh(bottomwin);
    reset_cursor();
2193
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2194
2195
}

2196
2197
/* 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
2198
 * to write at most length characters, even if length is very small and
2199
2200
 * keystroke and desc are long.  Note that waddnstr(,,(size_t)-1) adds
 * the whole string!  We do not bother padding the entry with blanks. */
2201
void onekey(const char *keystroke, const char *desc, int length)
Chris Allegretta's avatar
Chris Allegretta committed
2202
{
2203
2204
    assert(keystroke != NULL && desc != NULL);

2205
2206
2207
    if (interface_color_pair[KEY_COMBO].bright)
	wattron(bottomwin, A_BOLD);
    wattron(bottomwin, interface_color_pair[KEY_COMBO].pairnum);
2208
    waddnstr(bottomwin, keystroke, actual_x(keystroke, length));
2209
2210
    wattroff(bottomwin, A_BOLD);
    wattroff(bottomwin, interface_color_pair[KEY_COMBO].pairnum);
2211

2212
    length -= strlenpt(keystroke) + 1;
2213

2214
    if (length > 0) {
2215
	waddch(bottomwin, ' ');
2216
2217
2218
	if (interface_color_pair[FUNCTION_TAG].bright)
	    wattron(bottomwin, A_BOLD);
	wattron(bottomwin, interface_color_pair[FUNCTION_TAG].pairnum);
2219
	waddnstr(bottomwin, desc, actual_x(desc, length));
2220
2221
	wattroff(bottomwin, A_BOLD);
	wattroff(bottomwin, interface_color_pair[FUNCTION_TAG].pairnum);
Chris Allegretta's avatar
Chris Allegretta committed
2222
2223
2224
    }
}

2225
2226
/* 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
2227
2228
void reset_cursor(void)
{
2229
    size_t xpt = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2230

2231
#ifndef NANO_TINY
2232
    if (ISSET(SOFTWRAP)) {
2233
	filestruct *line = openfile->edittop;
2234
2235
	openfile->current_y = 0;

2236
2237
2238
2239
	while (line != NULL && line != openfile->current) {
	    openfile->current_y += strlenpt(line->data) / COLS + 1;
	    line = line->next;
	}
2240
	openfile->current_y += xpt / COLS;
2241

2242
	if (openfile->current_y < editwinrows)
2243
	    wmove(edit, openfile->current_y, xpt % COLS);
2244
2245
2246
    } else
#endif
    {
2247
	openfile->current_y = openfile->current->lineno -
2248
				openfile->edittop->lineno;
2249
2250
2251
2252

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

2255
2256
2257
2258
2259
2260
2261
2262
/* 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. */
2263
void edit_draw(filestruct *fileptr, const char *converted, int
2264
	line, size_t start)
Chris Allegretta's avatar
Chris Allegretta committed
2265
{
2266
#if !defined(NANO_TINY) || !defined(DISABLE_COLOR)
2267
2268
2269
2270
2271
2272
2273
2274
2275
    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. */
2276
2277
#endif

2278
    assert(openfile != NULL && fileptr != NULL && converted != NULL);
2279
    assert(strlenpt(converted) <= COLS);
2280

2281
2282
2283
    /* 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);
2284

2285
#ifndef USE_SLANG
2286
2287
2288
    /* 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. */
2289
2290
    if (seen_wide)
	wredrawln(edit, line, 1);
2291
#endif
2292

2293
#ifndef DISABLE_COLOR
2294
2295
2296
    /* If color syntaxes are available and turned on, we need to display
     * them. */
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX)) {
2297
	const colortype *varnish = openfile->colorstrings;
2298

2299
2300
2301
2302
	/* If there are multiline regexes, make sure there is a cache. */
	if (openfile->syntax->nmultis > 0)
	    alloc_multidata_if_needed(fileptr);

2303
	for (; varnish != NULL; varnish = varnish->next) {
2304
2305
	    int x_start;
		/* Starting column for mvwaddnstr.  Zero-based. */
2306
	    int paintlen = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2307
2308
		/* Number of chars to paint on this line.  There are
		 * COLS characters on a whole line. */
2309
	    size_t index;
2310
		/* Index in converted where we paint. */
2311
2312
2313
2314
	    regmatch_t startmatch;
		/* Match position for start_regex. */
	    regmatch_t endmatch;
		/* Match position for end_regex. */
2315

2316
	    if (varnish->bright)
2317
		wattron(edit, A_BOLD);
2318
	    wattron(edit, COLOR_PAIR(varnish->pairnum));
2319
2320
2321
	    /* 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. */
2322

2323
2324
	    /* First case: varnish is a single-line expression. */
	    if (varnish->end == NULL) {
2325
2326
2327
		size_t k = 0;

		/* We increment k by rm_eo, to move past the end of the
2328
		 * last match.  Even though two matches may overlap, we
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2329
2330
		 * want to ignore them, so that we can highlight e.g. C
		 * strings correctly. */
2331
2332
2333
		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
2334
2335
2336
		     * unless k is zero.  If regexec() returns
		     * REG_NOMATCH, there are no more matches in the
		     * line. */
2337
		    if (regexec(varnish->start, &fileptr->data[k], 1,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2338
2339
			&startmatch, (k == 0) ? 0 : REG_NOTBOL) ==
			REG_NOMATCH)
2340
			break;
2341
2342
		    /* Translate the match to the beginning of the
		     * line. */
2343
2344
		    startmatch.rm_so += k;
		    startmatch.rm_eo += k;
2345
2346
2347

		    /* Skip over a zero-length regex match. */
		    if (startmatch.rm_so == startmatch.rm_eo)
2348
			startmatch.rm_eo++;
2349
		    else if (startmatch.rm_so < endpos &&
2350
			startmatch.rm_eo > startpos) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2351
2352
			x_start = (startmatch.rm_so <= startpos) ? 0 :
				strnlenpt(fileptr->data,
2353
				startmatch.rm_so) - start;
2354

2355
2356
2357
			index = actual_x(converted, x_start);

			paintlen = actual_x(converted + index,
2358
2359
				strnlenpt(fileptr->data,
				startmatch.rm_eo) - start - x_start);
2360
2361
2362

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

2363
			mvwaddnstr(edit, line, x_start, converted +
2364
				index, paintlen);
2365
		    }
2366
		    k = startmatch.rm_eo;
Chris Allegretta's avatar
Chris Allegretta committed
2367
		}
2368
	    } else {	/* Second case: varnish is a multiline expression. */
2369
		const filestruct *start_line = fileptr->prev;
2370
		    /* The first line before fileptr that matches 'start'. */
2371
		size_t start_col;
2372
		    /* Where the match starts in that line. */
2373
		const filestruct *end_line;
2374
		    /* The line that matches 'end'. */
2375

2376
		/* First see if the multidata was maybe already calculated. */
2377
		if (fileptr->multidata[varnish->id] == CNONE)
2378
		    goto tail_of_loop;
2379
		else if (fileptr->multidata[varnish->id] == CWHOLELINE) {
2380
		    mvwaddnstr(edit, line, 0, converted, -1);
2381
		    goto tail_of_loop;
2382
2383
		} else if (fileptr->multidata[varnish->id] == CBEGINBEFORE) {
		    regexec(varnish->end, fileptr->data, 1, &endmatch, 0);
2384
2385
		    /* If the coloured part is scrolled off, skip it. */
		    if (endmatch.rm_eo <= startpos)
2386
			goto tail_of_loop;
2387
2388
2389
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
			endmatch.rm_eo) - start);
		    mvwaddnstr(edit, line, 0, converted, paintlen);
2390
		    goto tail_of_loop;
2391
		} if (fileptr->multidata[varnish->id] == -1)
2392
		    /* Assume this until proven otherwise below. */
2393
		    fileptr->multidata[varnish->id] = CNONE;
2394

2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
		/* 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. */

2405
		while (start_line != NULL && regexec(varnish->start,
2406
2407
2408
			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. */
2409
		    if (regexec(varnish->end, start_line->data, 0, NULL, 0) == 0)
2410
2411
2412
			goto step_two;
		    start_line = start_line->prev;
		}
2413

2414
2415
2416
2417
		/* If no start was found, skip to the next step. */
		if (start_line == NULL)
		    goto step_two;

2418
		/* If a found start has been qualified as an end earlier,
2419
		 * believe it and skip to the next step. */
2420
		if (start_line->multidata != NULL &&
2421
2422
			(start_line->multidata[varnish->id] == CBEGINBEFORE ||
			start_line->multidata[varnish->id] == CSTARTENDHERE))
2423
2424
		    goto step_two;

2425
		/* Skip over a zero-length regex match. */
2426
		if (startmatch.rm_so == startmatch.rm_eo)
2427
2428
		    goto tail_of_loop;

2429
2430
2431
2432
2433
2434
2435
		/* 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;
2436
		    if (regexec(varnish->end, start_line->data +
2437
2438
2439
				start_col + startmatch.rm_eo, 0, NULL,
				(start_col + startmatch.rm_eo == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH)
2440
2441
2442
			/* No end found after this start. */
			break;
		    start_col++;
2443
2444
		    if (regexec(varnish->start, start_line->data + start_col,
				1, &startmatch, REG_NOTBOL) == REG_NOMATCH)
2445
2446
2447
2448
2449
2450
2451
2452
2453
			/* 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;
2454
		while (end_line != NULL && regexec(varnish->end,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2455
			end_line->data, 1, &endmatch, 0) == REG_NOMATCH)
2456
		    end_line = end_line->next;
2457

2458
2459
2460
2461
		/* 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) {
2462
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2463
2464
		    goto step_two;
		}
2465

2466
2467
2468
2469
2470
2471
2472
		/* 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;
2473
		    fileptr->multidata[varnish->id] = CWHOLELINE;
2474
#ifdef DEBUG
2475
    fprintf(stderr, "  Marking for id %i  line %i as CWHOLELINE\n", varnish->id, line);
2476
#endif
2477
2478
2479
		} else {
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
						endmatch.rm_eo) - start);
2480
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2481
#ifdef DEBUG
2482
    fprintf(stderr, "  Marking for id %i  line %i as CBEGINBEFORE\n", varnish->id, line);
2483
#endif
2484
2485
2486
2487
2488
2489
		}
		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;
2490
  step_two:
2491
2492
2493
2494
2495
		/* 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) {
2496
		    if (regexec(varnish->start, fileptr->data + start_col,
2497
2498
				1, &startmatch, (start_col == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH ||
2499
				start_col + startmatch.rm_so >= endpos)
2500
2501
			/* No more starts on this line. */
			break;
2502

2503
2504
2505
2506
2507
2508
2509
		    /* 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,
2510
				startmatch.rm_so) - start;
2511

2512
		    index = actual_x(converted, x_start);
2513

2514
		    if (regexec(varnish->end, fileptr->data +
2515
				startmatch.rm_eo, 1, &endmatch,
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
				(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 &&
2526
				endmatch.rm_eo > startmatch.rm_so) {
2527
			    paintlen = actual_x(converted + index,
2528
					strnlenpt(fileptr->data,
2529
					endmatch.rm_eo) - start - x_start);
2530

2531
			    assert(0 <= x_start && x_start < COLS);
2532

2533
			    mvwaddnstr(edit, line, x_start,
2534
					converted + index, paintlen);
2535
			    if (paintlen > 0) {
2536
				fileptr->multidata[varnish->id] = CSTARTENDHERE;
2537
#ifdef DEBUG
2538
    fprintf(stderr, "  Marking for id %i  line %i as CSTARTENDHERE\n", varnish->id, line);
2539
#endif
2540
			    }
2541
2542
			}
			start_col = endmatch.rm_eo;
2543
2544
2545
			/* Skip over a zero-length match. */
			if (endmatch.rm_so == endmatch.rm_eo)
			    start_col += 1;
2546
2547
2548
2549
		    } else {
			/* There is no end on this line.  But we haven't yet
			 * looked for one on later lines. */
			end_line = fileptr->next;
2550

2551
			while (end_line != NULL &&
2552
				regexec(varnish->end, end_line->data,
2553
				0, NULL, 0) == REG_NOMATCH)
2554
			    end_line = end_line->next;
2555

2556
2557
2558
			/* If there is no end, we're done on this line. */
			if (end_line == NULL)
			    break;
2559

2560
2561
2562
2563
			assert(0 <= x_start && x_start < COLS);

			/* Paint the rest of the line. */
			mvwaddnstr(edit, line, x_start, converted + index, -1);
2564
			fileptr->multidata[varnish->id] = CENDAFTER;
2565
#ifdef DEBUG
2566
    fprintf(stderr, "  Marking for id %i  line %i as CENDAFTER\n", varnish->id, line);
2567
#endif
2568
2569
2570
			/* We've painted to the end of the line, so don't
			 * bother checking for any more starts. */
			break;
2571
		    }
2572
2573
		}
	    }
2574
  tail_of_loop:
2575
	    wattroff(edit, A_BOLD);
2576
	    wattroff(edit, COLOR_PAIR(varnish->pairnum));
2577
	}
2578
    }
2579
#endif /* !DISABLE_COLOR */
2580

2581
#ifndef NANO_TINY
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
    /* 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. */
2593
	int x_start;
2594
	    /* The starting column for mvwaddnstr().  Zero-based. */
2595
	int paintlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2596
2597
	    /* Number of characters to paint on this line.  There are
	     * COLS characters on a whole line. */
2598
	size_t index;
2599
	    /* Index in converted where we paint. */
2600

2601
	mark_order(&top, &top_x, &bot, &bot_x, NULL);
2602
2603
2604
2605
2606

	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
2607

2608
	/* Only paint if the marked bit of fileptr is on this page. */
2609
2610
	if (top_x < endpos && bot_x > startpos) {
	    assert(startpos <= top_x);
2611
2612
2613
2614

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

2616
2617
2618
2619
2620
	    /* 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. */
2621
2622
2623
	    if (bot_x >= endpos)
		paintlen = -1;
	    else
2624
		paintlen = strnlenpt(fileptr->data, bot_x) - (x_start + start);
2625
2626
2627
2628
2629
2630
2631
2632

	    /* 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;
	    }
2633
2634
2635

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

2636
	    index = actual_x(converted, x_start);
2637

2638
2639
2640
	    if (paintlen > 0)
		paintlen = actual_x(converted + index, paintlen);

2641
	    wattron(edit, hilite_attribute);
2642
	    mvwaddnstr(edit, line, x_start, converted + index, paintlen);
2643
	    wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
2644
	}
2645
    }
2646
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
2647
2648
}

2649
/* Just update one line in the edit buffer.  This is basically a wrapper
2650
 * for edit_draw().  The line will be displayed starting with
2651
 * fileptr->data[index].  Likely arguments are current_x or zero.
2652
 * Returns: Number of additional lines consumed (needed for SOFTWRAP). */
2653
int update_line(filestruct *fileptr, size_t index)
Chris Allegretta's avatar
Chris Allegretta committed
2654
{
2655
    int line = 0;
2656
	/* The line in the edit window that we want to update. */
2657
    int extralinesused = 0;
2658
2659
2660
2661
    char *converted;
	/* fileptr->data converted to have tabs and control characters
	 * expanded. */
    size_t page_start;
Chris Allegretta's avatar
Chris Allegretta committed
2662

2663
    assert(fileptr != NULL);
2664

2665
#ifndef NANO_TINY
2666
    if (ISSET(SOFTWRAP)) {
2667
2668
	filestruct *tmp;

2669
2670
	for (tmp = openfile->edittop; tmp && tmp != fileptr; tmp = tmp->next)
	    line += (strlenpt(tmp->data) / COLS) + 1;
2671
    } else
2672
#endif
2673
2674
	line = fileptr->lineno - openfile->edittop->lineno;

2675
    if (line < 0 || line >= editwinrows)
Chris Allegretta's avatar
Chris Allegretta committed
2676
	return 1;
2677

2678
    /* First, blank out the line. */
2679
    blank_line(edit, line, 0, COLS);
2680

2681
2682
    /* Next, convert variables that index the line to their equivalent
     * positions in the expanded line. */
2683
#ifndef NANO_TINY
2684
2685
2686
    if (ISSET(SOFTWRAP))
	index = 0;
    else
2687
#endif
2688
	index = strnlenpt(fileptr->data, index);
2689
    page_start = get_page_start(index);
2690

2691
2692
    /* Expand the line, replacing tabs with spaces, and control
     * characters with their displayed forms. */
2693
2694
2695
#ifdef NANO_TINY
    converted = display_string(fileptr->data, page_start, COLS, TRUE);
#else
2696
2697
2698
    converted = display_string(fileptr->data, page_start, COLS, !ISSET(SOFTWRAP));
#ifdef DEBUG
    if (ISSET(SOFTWRAP) && strlen(converted) >= COLS - 2)
2699
	fprintf(stderr, "update_line(): converted(1) line = %s\n", converted);
2700
#endif
2701
#endif /* !NANO_TINY */
2702

2703
    /* Paint the line. */
2704
    edit_draw(fileptr, converted, line, page_start);
2705
    free(converted);
Chris Allegretta's avatar
Chris Allegretta committed
2706

2707
#ifndef NANO_TINY
2708
    if (!ISSET(SOFTWRAP)) {
2709
#endif
2710
2711
2712
2713
	if (page_start > 0)
	    mvwaddch(edit, line, 0, '$');
	if (strlenpt(fileptr->data) > page_start + COLS)
	    mvwaddch(edit, line, COLS - 1, '$');
2714
#ifndef NANO_TINY
2715
    } else {
2716
	size_t full_length = strlenpt(fileptr->data);
2717
	for (index += COLS; index <= full_length && line < editwinrows - 1; index += COLS) {
2718
2719
	    line++;
#ifdef DEBUG
2720
	    fprintf(stderr, "update_line(): softwrap code, moving to %d index %lu\n", line, (unsigned long)index);
2721
#endif
2722
	    blank_line(edit, line, 0, COLS);
2723
2724

	    /* Expand the line, replacing tabs with spaces, and control
2725
	     * characters with their displayed forms. */
2726
2727
2728
2729
2730
	    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
2731
2732
2733

	    /* Paint the line. */
	    edit_draw(fileptr, converted, line, index);
2734
	    free(converted);
2735
2736
2737
	    extralinesused++;
	}
    }
2738
#endif /* !NANO_TINY */
2739
    return extralinesused;
Chris Allegretta's avatar
Chris Allegretta committed
2740
2741
}

2742
2743
2744
2745
/* 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)
2746
2747
{
    return
2748
#ifndef NANO_TINY
2749
	openfile->mark_set ||
2750
#endif
2751
	get_page_start(pww_save) != get_page_start(openfile->placewewant);
2752
2753
}

2754
/* When edittop changes, try and figure out how many lines
2755
 * we really have to work with (i.e. set maxrows). */
2756
2757
2758
2759
2760
void compute_maxrows(void)
{
    int n;
    filestruct *foo = openfile->edittop;

2761
2762
2763
2764
2765
    if (!ISSET(SOFTWRAP)) {
	maxrows = editwinrows;
	return;
    }

2766
2767
    maxrows = 0;
    for (n = 0; n < editwinrows && foo; n++) {
2768
	maxrows++;
2769
	n += strlenpt(foo->data) / COLS;
2770
2771
2772
	foo = foo->next;
    }

2773
2774
2775
    if (n < editwinrows)
	maxrows += editwinrows - n;

2776
#ifdef DEBUG
2777
    fprintf(stderr, "compute_maxrows(): maxrows = %d\n", maxrows);
2778
2779
2780
#endif
}

2781
2782
/* 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
2783
2784
 * scrolling.  direction is the direction to scroll, either UPWARD or
 * DOWNWARD, and nlines is the number of lines to scroll.  We change
2785
2786
 * edittop, and assume that current and current_x are up to date.  We
 * also assume that scrollok(edit) is FALSE. */
2787
void edit_scroll(scroll_dir direction, ssize_t nlines)
2788
{
2789
    ssize_t i;
2790
    filestruct *foo;
2791

2792
    assert(nlines > 0);
2793

2794
2795
2796
    /* Part 1: nlines is the number of lines we're going to scroll the
     * text of the edit window. */

2797
    /* Move the top line of the edit window up or down (depending on the
2798
2799
     * value of direction) nlines lines, or as many lines as we can if
     * there are fewer than nlines lines available. */
2800
    for (i = nlines; i > 0; i--) {
2801
	if (direction == UPWARD) {
2802
	    if (openfile->edittop == openfile->fileage)
2803
		break;
2804
	    openfile->edittop = openfile->edittop->prev;
2805
	} else {
2806
	    if (openfile->edittop == openfile->filebot)
2807
		break;
2808
	    openfile->edittop = openfile->edittop->next;
2809
	}
2810
2811

#ifndef NANO_TINY
2812
	/* Don't over-scroll on long lines. */
2813
	if (ISSET(SOFTWRAP) && direction == UPWARD) {
2814
	    ssize_t len = strlenpt(openfile->edittop->data) / COLS;
2815
	    i -= len;
2816
	    if (len > 0)
2817
		refresh_needed = TRUE;
2818
	}
2819
#endif
2820
2821
    }

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

2825
2826
2827
2828
    /* Don't bother scrolling zero lines, nor more than the window can hold. */
    if (nlines == 0)
	return;
    if (nlines >= editwinrows)
2829
	refresh_needed = TRUE;
2830

2831
    if (refresh_needed == TRUE)
2832
	return;
2833
2834
2835

    /* Scroll the text of the edit window up or down nlines lines,
     * depending on the value of direction. */
2836
    scrollok(edit, TRUE);
2837
    wscrl(edit, (direction == UPWARD) ? -nlines : nlines);
2838
2839
    scrollok(edit, FALSE);

2840
2841
2842
    /* Part 2: nlines is the number of lines in the scrolled region of
     * the edit window that we need to draw. */

2843
2844
    /* If the top or bottom line of the file is now visible in the edit
     * window, we need to draw the entire edit window. */
2845
2846
    if ((direction == UPWARD && openfile->edittop ==
	openfile->fileage) || (direction == DOWNWARD &&
2847
2848
	openfile->edittop->lineno + editwinrows - 1 >=
	openfile->filebot->lineno))
2849
	nlines = editwinrows;
2850

2851
2852
2853
2854
2855
2856
    /* 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
2857

2858
2859
    if (nlines > editwinrows)
	nlines = editwinrows;
2860
2861
2862

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

2865
2866
    /* If we scrolled down, move down to the line before the scrolled
     * region. */
2867
    if (direction == DOWNWARD) {
2868
	for (i = editwinrows - nlines; i > 0 && foo != NULL; i--)
2869
2870
2871
	    foo = foo->next;
    }

2872
2873
2874
2875
2876
2877
    /* 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--) {
2878
2879
	if ((i == nlines && direction == DOWNWARD) || (i == 1 &&
		direction == UPWARD)) {
2880
	    if (need_screen_update(0))
2881
2882
2883
2884
		update_line(foo, (foo == openfile->current) ?
			openfile->current_x : 0);
	} else
	    update_line(foo, (foo == openfile->current) ?
2885
		openfile->current_x : 0);
2886
	foo = foo->next;
2887
    }
2888
    compute_maxrows();
2889
2890
2891
}

/* Update any lines between old_current and current that need to be
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2892
 * updated.  Use this if we've moved without changing any text. */
2893
void edit_redraw(filestruct *old_current)
2894
{
2895
2896
2897
2898
    size_t was_pww = openfile->placewewant;

    openfile->placewewant = xplustabs();

2899
2900
    /* If the current line is offscreen, scroll until it's onscreen. */
    if (openfile->current->lineno >= openfile->edittop->lineno + maxrows ||
2901
		openfile->current->lineno < openfile->edittop->lineno) {
2902
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : FLOWING);
2903
	refresh_needed = TRUE;
2904
    }
2905

2906
#ifndef NANO_TINY
2907
2908
2909
    /* If the mark is on, update all lines between old_current and current. */
    if (openfile->mark_set) {
	filestruct *foo = old_current;
2910

2911
	while (foo != openfile->current) {
2912
	    update_line(foo, 0);
2913

2914
2915
2916
	    foo = (foo->lineno > openfile->current->lineno) ?
			foo->prev : foo->next;
	}
2917
2918
2919
2920
2921
2922
    } 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);
2923
2924
2925
2926
2927

    /* 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))
2928
	update_line(openfile->current, openfile->current_x);
2929
2930
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2931
2932
/* 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
2933
2934
void edit_refresh(void)
{
2935
    filestruct *foo;
2936
    int nlines;
2937

2938
    /* Figure out what maxrows should really be. */
2939
    compute_maxrows();
2940

2941
2942
    if (openfile->current->lineno < openfile->edittop->lineno ||
	openfile->current->lineno >= openfile->edittop->lineno +
2943
2944
	maxrows) {
#ifdef DEBUG
2945
2946
	fprintf(stderr, "edit_refresh(): line = %ld, edittop %ld + maxrows %d\n",
		(long)openfile->current->lineno, (long)openfile->edittop->lineno, maxrows);
2947
2948
#endif

2949
	/* Make sure the current line is on the screen. */
2950
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : STATIONARY);
2951
    }
Chris Allegretta's avatar
Chris Allegretta committed
2952

2953
2954
    foo = openfile->edittop;

2955
#ifdef DEBUG
2956
    fprintf(stderr, "edit_refresh(): edittop->lineno = %ld\n", (long)openfile->edittop->lineno);
2957
#endif
2958

2959
    for (nlines = 0; nlines < editwinrows && foo != NULL; nlines++) {
2960
	nlines += update_line(foo, (foo == openfile->current) ?
2961
		openfile->current_x : 0);
2962
2963
2964
	foo = foo->next;
    }

2965
    for (; nlines < editwinrows; nlines++)
2966
2967
2968
	blank_line(edit, nlines, 0, COLS);

    reset_cursor();
2969
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2970
2971
}

2972
2973
2974
2975
2976
2977
/* 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
2978
{
2979
    int goal = 0;
2980

2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
    /* 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)
2991
	goal = editwinrows / 2;
2992
    else if (manner == FLOWING) {
2993
	if (openfile->current->lineno >= openfile->edittop->lineno)
2994
2995
	    goal = editwinrows - 1;
    } else {
2996
	goal = openfile->current_y;
2997

2998
	/* Limit goal to (editwinrows - 1) lines maximum. */
2999
3000
	if (goal > editwinrows - 1)
	    goal = editwinrows - 1;
Chris Allegretta's avatar
Chris Allegretta committed
3001
    }
3002

3003
3004
3005
3006
3007
    openfile->edittop = openfile->current;

    while (goal > 0 && openfile->edittop->prev != NULL) {
	openfile->edittop = openfile->edittop->prev;
	goal --;
3008
#ifndef NANO_TINY
3009
3010
	if (ISSET(SOFTWRAP))
	    goal -= strlenpt(openfile->edittop->data) / COLS;
3011
#endif
3012
    }
3013
#ifdef DEBUG
3014
    fprintf(stderr, "edit_update(): setting edittop to lineno %ld\n", (long)openfile->edittop->lineno);
3015
#endif
3016
    compute_maxrows();
Chris Allegretta's avatar
Chris Allegretta committed
3017
3018
}

3019
/* Unconditionally redraw the entire screen. */
3020
void total_redraw(void)
3021
{
3022
3023
3024
3025
3026
3027
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 4: Slang doesn't define
     * curscr. */
    SLsmg_touch_screen();
    SLsmg_refresh();
#else
3028
    wrefresh(curscr);
3029
#endif
3030
3031
}

3032
3033
/* Unconditionally redraw the entire screen, and then refresh it using
 * the current file. */
3034
3035
void total_refresh(void)
{
3036
    total_redraw();
3037
    titlebar(NULL);
3038
    edit_refresh();
3039
    bottombars(currmenu);
3040
3041
}

3042
3043
/* Display the main shortcut list on the last two rows of the bottom
 * portion of the window. */
3044
3045
void display_main_list(void)
{
3046
#ifndef DISABLE_COLOR
3047
3048
    if (openfile->syntax &&
		(openfile->syntax->formatter || openfile->syntax->linter))
3049
	set_lint_or_format_shortcuts();
3050
3051
3052
3053
    else
	set_spell_shortcuts();
#endif

3054
    bottombars(MMAIN);
3055
3056
}

3057
/* If constant is TRUE, we display the current cursor position only if
3058
3059
 * suppress_cursorpos is FALSE.  If constant is FALSE, we display the
 * position always.  In any case we reset suppress_cursorpos to FALSE. */
3060
void do_cursorpos(bool constant)
Chris Allegretta's avatar
Chris Allegretta committed
3061
{
3062
    filestruct *f;
3063
    char c;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3064
    size_t i, cur_xpt = xplustabs() + 1;
3065
    size_t cur_lenpt = strlenpt(openfile->current->data) + 1;
3066
    int linepct, colpct, charpct;
Chris Allegretta's avatar
Chris Allegretta committed
3067

3068
    assert(openfile->fileage != NULL && openfile->current != NULL);
3069

3070
    /* Determine the size of the file up to the cursor. */
3071
    f = openfile->current->next;
3072
    c = openfile->current->data[openfile->current_x];
3073
3074

    openfile->current->next = NULL;
3075
    openfile->current->data[openfile->current_x] = '\0';
3076
3077
3078

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

3079
    openfile->current->data[openfile->current_x] = c;
3080
    openfile->current->next = f;
3081

3082
    /* If the position needs to be suppressed, don't suppress it next time. */
3083
    if (suppress_cursorpos && constant) {
3084
	suppress_cursorpos = FALSE;
3085
	return;
3086
    }
Chris Allegretta's avatar
Chris Allegretta committed
3087

3088
    /* Display the current cursor position on the statusbar. */
3089
    linepct = 100 * openfile->current->lineno / openfile->filebot->lineno;
3090
    colpct = 100 * cur_xpt / cur_lenpt;
3091
    charpct = (openfile->totsize == 0) ? 0 : 100 * i / openfile->totsize;
3092

3093
    statusline(HUSH,
3094
	_("line %ld/%ld (%d%%), col %lu/%lu (%d%%), char %lu/%lu (%d%%)"),
3095
	(long)openfile->current->lineno,
3096
	(long)openfile->filebot->lineno, linepct,
3097
	(unsigned long)cur_xpt, (unsigned long)cur_lenpt, colpct,
3098
	(unsigned long)i, (unsigned long)openfile->totsize, charpct);
3099
3100
3101

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

3104
/* Unconditionally display the current cursor position. */
3105
void do_cursorpos_void(void)
3106
{
3107
    do_cursorpos(FALSE);
3108
3109
}

3110
3111
void enable_nodelay(void)
{
3112
3113
    nodelay_mode = TRUE;
    nodelay(edit, TRUE);
3114
3115
3116
3117
}

void disable_nodelay(void)
{
3118
3119
    nodelay_mode = FALSE;
    nodelay(edit, FALSE);
3120
3121
}

3122
3123
/* Highlight the current word being replaced or spell checked.  We
 * expect word to have tabs and control characters expanded. */
3124
void spotlight(bool active, const char *word)
Chris Allegretta's avatar
Chris Allegretta committed
3125
{
3126
    size_t word_len = strlenpt(word), room;
Chris Allegretta's avatar
Chris Allegretta committed
3127

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

3131
    assert(room > 0);
3132

3133
3134
    if (word_len > room)
	room--;
3135

Chris Allegretta's avatar
Chris Allegretta committed
3136
    reset_cursor();
3137
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
3138

3139
    if (active)
3140
	wattron(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3141

3142
    /* This is so we can show zero-length matches. */
3143
    if (word_len == 0)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3144
	waddch(edit, ' ');
3145
    else
3146
	waddnstr(edit, word, actual_x(word, room));
3147

3148
    if (word_len > room)
3149
	waddch(edit, '$');
Chris Allegretta's avatar
Chris Allegretta committed
3150

3151
    if (active)
3152
	wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3153
3154
}

3155
#ifndef DISABLE_EXTRA
3156
3157
#define CREDIT_LEN 54
#define XLCREDIT_LEN 9
3158

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

3223
    const char *xlcredits[XLCREDIT_LEN] = {
3224
3225
3226
3227
3228
	N_("The nano text editor"),
	N_("version"),
	N_("Brought to you by:"),
	N_("Special thanks to:"),
	N_("The Free Software Foundation"),
3229
	N_("the many translators and the TP"),
3230
3231
3232
	N_("For ncurses:"),
	N_("and anyone else we forgot..."),
	N_("Thank you for using nano!")
3233
    };
3234

3235
3236
3237
3238
3239
3240
    if (!old_more_space || !old_no_help) {
	SET(MORE_SPACE);
	SET(NO_HELP);
	window_init();
    }

3241
3242
    curs_set(0);
    nodelay(edit, TRUE);
3243

3244
    blank_titlebar();
3245
    blank_topbar();
Chris Allegretta's avatar
Chris Allegretta committed
3246
    blank_edit();
3247
3248
    blank_statusbar();
    blank_bottombars();
3249

3250
    wrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
3251
    wrefresh(edit);
3252
    wrefresh(bottomwin);
3253
    napms(700);
3254

3255
    for (crpos = 0; crpos < CREDIT_LEN + editwinrows / 2; crpos++) {
3256
	if ((kbinput = wgetch(edit)) != ERR)
3257
	    break;
3258

3259
	if (crpos < CREDIT_LEN) {
3260
	    const char *what;
3261
3262
	    size_t start_x;

3263
	    if (credits[crpos] == NULL) {
3264
		assert(0 <= xlpos && xlpos < XLCREDIT_LEN);
3265

3266
		what = _(xlcredits[xlpos]);
3267
		xlpos++;
3268
	    } else
3269
		what = credits[crpos];
3270

3271
	    start_x = COLS / 2 - strlenpt(what) / 2 - 1;
3272
3273
	    mvwaddstr(edit, editwinrows - 1 - (editwinrows % 2),
		start_x, what);
3274
	}
3275

3276
3277
3278
3279
	wrefresh(edit);

	if ((kbinput = wgetch(edit)) != ERR)
	    break;
3280
	napms(700);
3281

3282
	scrollok(edit, TRUE);
3283
	wscrl(edit, 1);
3284
	scrollok(edit, FALSE);
3285
	wrefresh(edit);
3286

3287
	if ((kbinput = wgetch(edit)) != ERR)
3288
	    break;
3289
	napms(700);
3290

3291
	scrollok(edit, TRUE);
3292
	wscrl(edit, 1);
3293
	scrollok(edit, FALSE);
3294
	wrefresh(edit);
3295
3296
    }

3297
3298
3299
    if (kbinput != ERR)
	ungetch(kbinput);

3300
    if (!old_more_space)
3301
	UNSET(MORE_SPACE);
3302
    if (!old_no_help)
3303
	UNSET(NO_HELP);
3304
    window_init();
3305

3306
    nodelay(edit, FALSE);
3307

3308
    total_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
3309
}
3310
#endif /* !DISABLE_EXTRA */