winio.c 99.3 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.    *
6
7
 *   Copyright (C) 2014, 2015, 2016 Benno Schulenberg                     *
 *                                                                        *
Chris Allegretta's avatar
Chris Allegretta committed
8
9
 *   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 *
10
 *   the Free Software Foundation; either version 3, or (at your option)  *
Chris Allegretta's avatar
Chris Allegretta committed
11
12
 *   any later version.                                                   *
 *                                                                        *
13
14
15
16
 *   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
17
18
19
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program; if not, write to the Free Software          *
20
21
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA            *
 *   02110-1301, USA.                                                     *
Chris Allegretta's avatar
Chris Allegretta committed
22
23
24
 *                                                                        *
 **************************************************************************/

25
#include "proto.h"
26
#include "revision.h"
27

28
#if defined(__linux__) && !defined(NANO_TINY)
29
#include <sys/ioctl.h>
30
#endif
31

32
#include <stdio.h>
Chris Allegretta's avatar
Chris Allegretta committed
33
34
#include <stdarg.h>
#include <string.h>
35
#include <unistd.h>
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
36
#include <ctype.h>
Chris Allegretta's avatar
Chris Allegretta committed
37

38
39
40
41
42
43
#ifdef REVISION
#define BRANDING REVISION
#else
#define BRANDING PACKAGE_STRING
#endif

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

60
#ifndef NANO_TINY
61
62
63
64
65
66
67
68
69
70
71
72
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;
}
73
#endif
74

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

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

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

141
142
143
144
    /* Just before reading in the first character, display any pending
     * screen updates. */
    doupdate();

145
    /* Read in the first character using whatever mode we're in. */
146
147
    input = wgetch(win);

148
#ifndef NANO_TINY
149
150
    if (the_window_resized()) {
	ungetch(input);
151
	input = KEY_WINCH;
152
    }
153
154
#endif

155
156
157
158
159
160
161
162
163
164
165
    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);

166
#ifndef NANO_TINY
167
	if (the_window_resized()) {
168
169
	    input = KEY_WINCH;
	    break;
170
	}
171
172
#endif
	input = wgetch(win);
173
    }
174

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

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

188
189
190
191
    /* Read in the remaining characters using non-blocking input. */
    nodelay(win, TRUE);

    while (TRUE) {
192
	input = wgetch(win);
193

194
	/* If there aren't any more characters, stop reading. */
195
	if (input == ERR)
196
197
	    break;

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

206
207
208
    /* Restore waiting mode if it was on. */
    if (!nodelay_mode)
	nodelay(win, FALSE);
209
210

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

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

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

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

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

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

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

257
258
259
/* Put the character given in kbinput back into the input stream.  If it
 * is a Meta key, also insert an Escape character in front of it. */
void unget_kbinput(int kbinput, bool metakey)
260
{
261
    unget_input(&kbinput, 1);
262

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

269
/* Try to read input_len codes from the keystroke buffer.  If the
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
270
 * keystroke buffer is empty and win isn't NULL, try to read in more
271
 * codes 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

283
    /* Limit the request to the number of available codes in the buffer. */
284
285
286
    if (input_len > key_buffer_len)
	input_len = key_buffer_len;

287
    /* Copy input_len codes from the head of the keystroke buffer. */
288
289
    input = (int *)nmalloc(input_len * sizeof(int));
    memcpy(input, key_buffer, input_len * sizeof(int));
290
    key_buffer_len -= input_len;
291

292
    /* If the keystroke buffer is now empty, mark it as such. */
293
294
295
296
    if (key_buffer_len == 0) {
	free(key_buffer);
	key_buffer = NULL;
    } else {
297
	/* Trim from the buffer the codes that were copied. */
298
	memmove(key_buffer, key_buffer + input_len, key_buffer_len *
299
300
301
		sizeof(int));
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
302
303
304
    }

    return input;
305
306
}

307
/* Read in a single keystroke, ignoring any that are invalid. */
308
int get_kbinput(WINDOW *win)
309
310
311
{
    int kbinput;

312
    /* Extract one keystroke from the input stream. */
313
    while ((kbinput = parse_kbinput(win)) == ERR)
314
	;
315

316
317
318
319
320
#ifdef DEBUG
    fprintf(stderr, "after parsing:  kbinput = %d, meta_key = %s\n",
	kbinput, meta_key ? "TRUE" : "FALSE");
#endif

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

325
326
327
    return kbinput;
}

328
329
/* Extract a single keystroke from the input stream.  Translate escape
 * sequences and extended keypad codes into their corresponding values.
330
 * Set meta_key to TRUE when appropriate.  Supported extended keypad values
331
332
333
 * 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. */
334
int parse_kbinput(WINDOW *win)
335
{
336
    static int escapes = 0, byte_digits = 0;
337
    static bool double_esc = FALSE;
338
    int *kbinput, keycode, retval = ERR;
339

340
    meta_key = FALSE;
341
    shift_held = FALSE;
342

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

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

    while (kbinput == NULL)
350
	kbinput = get_input(win, 1);
351

352
353
354
    keycode = *kbinput;
    free(kbinput);

355
356
357
358
359
#ifdef DEBUG
    fprintf(stderr, "before parsing:  keycode = %d, escapes = %d, byte_digits = %d\n",
	keycode, escapes, byte_digits);
#endif

360
361
362
    if (keycode == ERR)
	return ERR;

363
    if (keycode == ESC_CODE) {
364
365
366
367
368
369
370
	/* Increment the escape counter, but trim an overabundance. */
	escapes++;
	if (escapes > 3)
	    escapes = 1;
	/* Take note when an Esc arrived by itself. */
	solitary = (escapes == 1 && key_buffer_len == 0);
	return ERR;
371
372
    }

373
374
375
376
377
378
    switch (escapes) {
	case 0:
	    /* One non-escape: normal input mode. */
	    retval = keycode;
	    break;
	case 1:
379
380
381
	    if (keycode >= 0x80)
		retval = keycode;
	    else if ((keycode != 'O' && keycode != 'o' && keycode != '[') ||
382
			key_buffer_len == 0 || *key_buffer == ESC_CODE) {
383
384
385
386
387
388
389
390
391
		/* One escape followed by a single non-escape:
		 * meta key sequence mode. */
		if (!solitary || (keycode >= 0x20 && keycode < 0x7F))
		    meta_key = TRUE;
		retval = tolower(keycode);
	    } else
		/* One escape followed by a non-escape, and there
		 * are more codes waiting: escape sequence mode. */
		retval = parse_escape_sequence(win, keycode);
392
	    escapes = 0;
393
394
395
396
397
398
399
400
401
402
403
	    break;
	case 2:
	    if (double_esc) {
		/* An "ESC ESC [ X" sequence from Option+arrow. */
		switch (keycode) {
		    case 'A':
			retval = KEY_HOME;
			break;
		    case 'B':
			retval = KEY_END;
			break;
404
#ifndef NANO_TINY
405
406
407
408
409
410
		    case 'C':
			retval = controlright;
			break;
		    case 'D':
			retval = controlleft;
			break;
411
#endif
412
413
414
		}
		double_esc = FALSE;
		escapes = 0;
415
	    } else if (key_buffer_len == 0) {
416
417
418
419
420
421
422
423
424
425
426
427
428
429
		if (('0' <= keycode && keycode <= '2' &&
			byte_digits == 0) || ('0' <= keycode &&
			keycode <= '9' && byte_digits > 0)) {
		    /* 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. */
		    int byte;

		    byte_digits++;
		    byte = get_byte_kbinput(keycode);

430
431
		    /* If the decimal byte value is complete, convert it and
		     * put the obtained byte(s) back into the input buffer. */
432
433
434
435
		    if (byte != ERR) {
			char *byte_mb;
			int byte_mb_len, *seq, i;

436
437
			/* Convert the decimal code to one or two bytes. */
			byte_mb = make_mbchar((long)byte, &byte_mb_len);
438

439
			seq = (int *)nmalloc(byte_mb_len * sizeof(int));
440
441
442
443

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

444
			/* Insert the byte(s) into the input buffer. */
445
446
447
448
			unget_input(seq, byte_mb_len);

			free(byte_mb);
			free(seq);
449
450
451

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

498
499
500
    if (retval == ERR)
	return ERR;

501
502
503
504
505
506
507
508
509
#ifndef NANO_TINY
    if (retval == controlleft)
	return sc_seq_or(do_prev_word_void, 0);
    else if (retval == controlright)
	return sc_seq_or(do_next_word_void, 0);
    else if (retval == controlup)
	return sc_seq_or(do_prev_block, 0);
    else if (retval == controldown)
	return sc_seq_or(do_next_block, 0);
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    else if (retval == shiftcontrolleft) {
	shift_held = TRUE;
	return sc_seq_or(do_prev_word_void, 0);
    } else if (retval == shiftcontrolright) {
	shift_held = TRUE;
	return sc_seq_or(do_next_word_void, 0);
    } else if (retval == shiftcontrolup) {
	shift_held = TRUE;
	return sc_seq_or(do_prev_block, 0);
    } else if (retval == shiftcontroldown) {
	shift_held = TRUE;
	return sc_seq_or(do_next_block, 0);
    } else if (retval == shiftaltleft) {
	shift_held = TRUE;
	return sc_seq_or(do_home, 0);
    } else if (retval == shiftaltright) {
	shift_held = TRUE;
	return sc_seq_or(do_end, 0);
    } else if (retval == shiftaltup) {
	shift_held = TRUE;
	return sc_seq_or(do_page_up, 0);
    } else if (retval == shiftaltdown) {
	shift_held = TRUE;
	return sc_seq_or(do_page_down, 0);
    }
535
536
#endif

537
#if defined(__linux__) && !defined(NANO_TINY)
538
    /* When not running under X, check for the bare arrow keys whether
539
540
541
542
543
544
     * Shift/Ctrl/Alt are being held together with them. */
    unsigned char modifiers = 6;

    if (console && ioctl(0, TIOCLINUX, &modifiers) >= 0) {
	if (modifiers & 0x01)
	    shift_held =TRUE;
545

546
547
	/* Is Ctrl being held? */
	if (modifiers & 0x04) {
548
549
550
551
552
553
	    if (retval == KEY_UP)
		return sc_seq_or(do_prev_block, 0);
	    else if (retval == KEY_DOWN)
		return sc_seq_or(do_next_block, 0);
	    else if (retval == KEY_LEFT)
		return sc_seq_or(do_prev_word_void, 0);
554
	    else if (retval == KEY_RIGHT)
555
556
		return sc_seq_or(do_next_word_void, 0);
	}
557
558
559
560
561
562
563
564
565
566
567
568

	/* Are both Shift and Alt being held? */
	if ((modifiers & 0x09) == 0x09) {
	    if (retval == KEY_UP)
		return sc_seq_or(do_page_up, 0);
	    else if (retval == KEY_DOWN)
		return sc_seq_or(do_page_down, 0);
	    else if (retval == KEY_LEFT)
		return sc_seq_or(do_home, 0);
	    else if (retval == KEY_RIGHT)
		return sc_seq_or(do_end, 0);
	}
569
    }
570
#endif /* __linux__ && !NANO_TINY */
571

572
    switch (retval) {
573
#ifdef KEY_SLEFT
574
575
	/* Slang doesn't support KEY_SLEFT. */
	case KEY_SLEFT:
576
	    shift_held = TRUE;
577
	    return sc_seq_or(do_left, keycode);
578
#endif
579
#ifdef KEY_SRIGHT
580
581
	/* Slang doesn't support KEY_SRIGHT. */
	case KEY_SRIGHT:
582
	    shift_held = TRUE;
583
	    return sc_seq_or(do_right, keycode);
584
#endif
585
#ifdef KEY_SUP
586
587
	/* ncurses and Slang don't support KEY_SUP. */
	case KEY_SUP:
588
#endif
589
590
591
	case KEY_SR:	/* Scroll backward, on Xfce4-terminal. */
	    shift_held = TRUE;
	    return sc_seq_or(do_up_void, keycode);
592
#ifdef KEY_SDOWN
593
594
	/* ncurses and Slang don't support KEY_SDOWN. */
	case KEY_SDOWN:
595
#endif
596
597
598
	case KEY_SF:	/* Scroll forward, on Xfce4-terminal. */
	    shift_held = TRUE;
	    return sc_seq_or(do_down_void, keycode);
599
#ifdef KEY_SHOME
600
601
	/* HP-UX 10-11 and Slang don't support KEY_SHOME. */
	case KEY_SHOME:
602
	    shift_held = TRUE;
603
#endif
604
605
	case KEY_A1:	/* Home (7) on keypad with NumLock off. */
	    return sc_seq_or(do_home, keycode);
606
#ifdef KEY_SEND
607
608
	/* HP-UX 10-11 and Slang don't support KEY_SEND. */
	case KEY_SEND:
609
	    shift_held = TRUE;
610
#endif
611
612
	case KEY_C1:	/* End (1) on keypad with NumLock off. */
	    return sc_seq_or(do_end, keycode);
613
614
615
616
#ifndef NANO_TINY
	case SHIFT_PAGEUP:		/* Fake key, from Shift+Alt+Up. */
	    shift_held = TRUE;
#endif
617
618
	case KEY_A3:	/* PageUp (9) on keypad with NumLock off. */
	    return sc_seq_or(do_page_up, keycode);
619
620
621
622
#ifndef NANO_TINY
	case SHIFT_PAGEDOWN:	/* Fake key, from Shift+Alt+Down. */
	    shift_held = TRUE;
#endif
623
624
	case KEY_C3:	/* PageDown (3) on keypad with NumLock off. */
	    return sc_seq_or(do_page_down, keycode);
625
#ifdef KEY_SDC
626
627
	/* Slang doesn't support KEY_SDC. */
	case KEY_SDC:
628
#endif
629
	case DEL_CODE:
630
631
632
633
	    if (ISSET(REBIND_DELETE))
		return sc_seq_or(do_delete, keycode);
	    else
		return sc_seq_or(do_backspace, keycode);
634
#ifdef KEY_SIC
635
636
637
	/* Slang doesn't support KEY_SIC. */
	case KEY_SIC:
	    return sc_seq_or(do_insertfile_void, keycode);
638
#endif
639
#ifdef KEY_SBEG
640
641
	/* Slang doesn't support KEY_SBEG. */
	case KEY_SBEG:
642
#endif
643
#ifdef KEY_BEG
644
645
	/* Slang doesn't support KEY_BEG. */
	case KEY_BEG:
646
#endif
647
648
	case KEY_B2:	/* Center (5) on keypad with NumLock off. */
	    return ERR;
649
#ifdef KEY_CANCEL
650
#ifdef KEY_SCANCEL
651
652
	/* Slang doesn't support KEY_SCANCEL. */
	case KEY_SCANCEL:
653
#endif
654
655
656
	/* Slang doesn't support KEY_CANCEL. */
	case KEY_CANCEL:
	    return first_sc_for(currmenu, do_cancel)->keycode;
657
#endif
658
#ifdef KEY_SUSPEND
659
#ifdef KEY_SSUSPEND
660
661
	/* Slang doesn't support KEY_SSUSPEND. */
	case KEY_SSUSPEND:
662
#endif
663
664
665
	/* Slang doesn't support KEY_SUSPEND. */
	case KEY_SUSPEND:
	    return sc_seq_or(do_suspend_void, 0);
666
667
#endif
#ifdef PDCURSES
668
669
670
671
672
673
674
	case KEY_SHIFT_L:
	case KEY_SHIFT_R:
	case KEY_CONTROL_L:
	case KEY_CONTROL_R:
	case KEY_ALT_L:
	case KEY_ALT_R:
	    return ERR;
675
676
#endif
#if !defined(NANO_TINY) && defined(KEY_RESIZE)
677
678
679
680
681
	/* 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:
	    return ERR;
682
#endif
683
    }
684

685
686
687
    return retval;
}

688
/* Translate escape sequences, most of which correspond to extended
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
689
 * keypad values, into their corresponding key values.  These sequences
690
691
 * are generated when the keypad doesn't support the needed keys.
 * Assume that Escape has already been read in. */
692
int convert_sequence(const int *seq, size_t seq_len)
693
{
694
    if (seq_len > 1) {
695
	switch (seq[0]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
696
	    case 'O':
697
		switch (seq[1]) {
698
		    case '1':
699
700
			if (seq_len > 4  && seq[2] == ';') {

701
702
	switch (seq[3]) {
	    case '2':
703
704
705
706
707
		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. */
708
			shift_held = TRUE;
709
710
711
712
713
714
715
716
717
718
			return arrow_from_abcd(seq[4]);
		    case 'P': /* Esc O 1 ; 2 P == F13 on Terminal. */
			return KEY_F(13);
		    case 'Q': /* Esc O 1 ; 2 Q == F14 on Terminal. */
			return KEY_F(14);
		    case 'R': /* Esc O 1 ; 2 R == F15 on Terminal. */
			return KEY_F(15);
		    case 'S': /* Esc O 1 ; 2 S == F16 on Terminal. */
			return KEY_F(16);
		}
719
720
		break;
	    case '5':
721
722
723
724
725
726
727
728
729
730
		switch (seq[4]) {
		    case 'A': /* Esc O 1 ; 5 A == Ctrl-Up on Terminal. */
			return CONTROL_UP;
		    case 'B': /* Esc O 1 ; 5 B == Ctrl-Down on Terminal. */
			return CONTROL_DOWN;
		    case 'C': /* Esc O 1 ; 5 C == Ctrl-Right on Terminal. */
			return CONTROL_RIGHT;
		    case 'D': /* Esc O 1 ; 5 D == Ctrl-Left on Terminal. */
			return CONTROL_LEFT;
		}
731
732
		break;
	}
733

734
735
			}
			break;
736
		    case '2':
737
			if (seq_len >= 3) {
738
			    switch (seq[2]) {
739
				case 'P': /* Esc O 2 P == F13 on xterm. */
740
				    return KEY_F(13);
741
				case 'Q': /* Esc O 2 Q == F14 on xterm. */
742
				    return KEY_F(14);
743
				case 'R': /* Esc O 2 R == F15 on xterm. */
744
				    return KEY_F(15);
745
				case 'S': /* Esc O 2 S == F16 on xterm. */
746
				    return KEY_F(16);
747
748
			    }
			}
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
749
			break;
750
		    case 'A': /* Esc O A == Up on VT100/VT320/xterm. */
751
752
753
		    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. */
754
			return arrow_from_abcd(seq[1]);
755
756
		    case 'E': /* Esc O E == Center (5) on numeric keypad
			       * with NumLock off on xterm. */
757
			return KEY_B2;
758
		    case 'F': /* Esc O F == End on xterm/Terminal. */
759
			return KEY_END;
760
		    case 'H': /* Esc O H == Home on xterm/Terminal. */
761
			return KEY_HOME;
762
		    case 'M': /* Esc O M == Enter on numeric keypad with
763
			       * NumLock off on VT100/VT220/VT320/xterm/
764
			       * rxvt/Eterm. */
765
			return KEY_ENTER;
766
		    case 'P': /* Esc O P == F1 on VT100/VT220/VT320/Mach
767
			       * console. */
768
			return KEY_F(1);
769
		    case 'Q': /* Esc O Q == F2 on VT100/VT220/VT320/Mach
770
			       * console. */
771
			return KEY_F(2);
772
		    case 'R': /* Esc O R == F3 on VT100/VT220/VT320/Mach
773
			       * console. */
774
			return KEY_F(3);
775
		    case 'S': /* Esc O S == F4 on VT100/VT220/VT320/Mach
776
			       * console. */
777
			return KEY_F(4);
778
		    case 'T': /* Esc O T == F5 on Mach console. */
779
			return KEY_F(5);
780
		    case 'U': /* Esc O U == F6 on Mach console. */
781
			return KEY_F(6);
782
		    case 'V': /* Esc O V == F7 on Mach console. */
783
			return KEY_F(7);
784
		    case 'W': /* Esc O W == F8 on Mach console. */
785
			return KEY_F(8);
786
		    case 'X': /* Esc O X == F9 on Mach console. */
787
			return KEY_F(9);
788
		    case 'Y': /* Esc O Y == F10 on Mach console. */
789
			return KEY_F(10);
790
		    case 'a': /* Esc O a == Ctrl-Up on rxvt. */
791
			return CONTROL_UP;
792
		    case 'b': /* Esc O b == Ctrl-Down on rxvt. */
793
			return CONTROL_DOWN;
794
		    case 'c': /* Esc O c == Ctrl-Right on rxvt. */
795
			return CONTROL_RIGHT;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
796
		    case 'd': /* Esc O d == Ctrl-Left on rxvt. */
797
			return CONTROL_LEFT;
798
		    case 'j': /* Esc O j == '*' on numeric keypad with
799
			       * NumLock off on VT100/VT220/VT320/xterm/
800
			       * rxvt/Eterm/Terminal. */
801
			return '*';
802
		    case 'k': /* Esc O k == '+' on numeric keypad with
803
			       * NumLock off on VT100/VT220/VT320/xterm/
804
			       * rxvt/Eterm/Terminal. */
805
			return '+';
806
		    case 'l': /* Esc O l == ',' on numeric keypad with
807
			       * NumLock off on VT100/VT220/VT320/xterm/
808
			       * rxvt/Eterm/Terminal. */
809
			return ',';
810
		    case 'm': /* Esc O m == '-' on numeric keypad with
811
			       * NumLock off on VT100/VT220/VT320/xterm/
812
			       * rxvt/Eterm/Terminal. */
813
			return '-';
814
		    case 'n': /* Esc O n == Delete (.) on numeric keypad
815
			       * with NumLock off on VT100/VT220/VT320/
816
			       * xterm/rxvt/Eterm/Terminal. */
817
			return KEY_DC;
818
		    case 'o': /* Esc O o == '/' on numeric keypad with
819
			       * NumLock off on VT100/VT220/VT320/xterm/
820
			       * rxvt/Eterm/Terminal. */
821
			return '/';
822
		    case 'p': /* Esc O p == Insert (0) on numeric keypad
823
			       * with NumLock off on VT100/VT220/VT320/
824
			       * rxvt/Eterm/Terminal. */
825
			return KEY_IC;
826
		    case 'q': /* Esc O q == End (1) on numeric keypad
827
			       * with NumLock off on VT100/VT220/VT320/
828
			       * rxvt/Eterm/Terminal. */
829
			return KEY_END;
830
		    case 'r': /* Esc O r == Down (2) on numeric keypad
831
			       * with NumLock off on VT100/VT220/VT320/
832
			       * rxvt/Eterm/Terminal. */
833
			return KEY_DOWN;
834
		    case 's': /* Esc O s == PageDown (3) on numeric
835
			       * keypad with NumLock off on VT100/VT220/
836
			       * VT320/rxvt/Eterm/Terminal. */
837
			return KEY_NPAGE;
838
		    case 't': /* Esc O t == Left (4) on numeric keypad
839
			       * with NumLock off on VT100/VT220/VT320/
840
			       * rxvt/Eterm/Terminal. */
841
			return KEY_LEFT;
842
		    case 'u': /* Esc O u == Center (5) on numeric keypad
843
844
			       * with NumLock off on VT100/VT220/VT320/
			       * rxvt/Eterm. */
845
			return KEY_B2;
846
		    case 'v': /* Esc O v == Right (6) on numeric keypad
847
			       * with NumLock off on VT100/VT220/VT320/
848
			       * rxvt/Eterm/Terminal. */
849
			return KEY_RIGHT;
850
		    case 'w': /* Esc O w == Home (7) on numeric keypad
851
			       * with NumLock off on VT100/VT220/VT320/
852
			       * rxvt/Eterm/Terminal. */
853
			return KEY_HOME;
854
		    case 'x': /* Esc O x == Up (8) on numeric keypad
855
			       * with NumLock off on VT100/VT220/VT320/
856
			       * rxvt/Eterm/Terminal. */
857
			return KEY_UP;
858
		    case 'y': /* Esc O y == PageUp (9) on numeric keypad
859
			       * with NumLock off on VT100/VT220/VT320/
860
			       * rxvt/Eterm/Terminal. */
861
			return KEY_PPAGE;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
862
863
864
		}
		break;
	    case 'o':
865
		switch (seq[1]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
866
		    case 'a': /* Esc o a == Ctrl-Up on Eterm. */
867
			return CONTROL_UP;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
868
		    case 'b': /* Esc o b == Ctrl-Down on Eterm. */
869
			return CONTROL_DOWN;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
870
		    case 'c': /* Esc o c == Ctrl-Right on Eterm. */
871
			return CONTROL_RIGHT;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
872
		    case 'd': /* Esc o d == Ctrl-Left on Eterm. */
873
			return CONTROL_LEFT;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
874
875
876
		}
		break;
	    case '[':
877
		switch (seq[1]) {
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
878
		    case '1':
879
			if (seq_len > 3 && seq[3] == '~') {
880
			    switch (seq[2]) {
881
				case '1': /* Esc [ 1 1 ~ == F1 on rxvt/Eterm. */
882
				    return KEY_F(1);
883
				case '2': /* Esc [ 1 2 ~ == F2 on rxvt/Eterm. */
884
				    return KEY_F(2);
885
				case '3': /* Esc [ 1 3 ~ == F3 on rxvt/Eterm. */
886
				    return KEY_F(3);
887
				case '4': /* Esc [ 1 4 ~ == F4 on rxvt/Eterm. */
888
				    return KEY_F(4);
889
890
				case '5': /* Esc [ 1 5 ~ == F5 on xterm/
					   * rxvt/Eterm. */
891
				    return KEY_F(5);
892
				case '7': /* Esc [ 1 7 ~ == F6 on
893
894
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
895
				    return KEY_F(6);
896
				case '8': /* Esc [ 1 8 ~ == F7 on
897
898
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
899
				    return KEY_F(7);
900
				case '9': /* Esc [ 1 9 ~ == F8 on
901
902
					   * VT220/VT320/Linux console/
					   * xterm/rxvt/Eterm. */
903
				    return KEY_F(8);
904
905
906
			    }
			} else if (seq_len > 4 && seq[2] == ';') {

907
	switch (seq[3]) {
908
	    case '2':
909
910
911
912
913
		switch (seq[4]) {
		    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. */
914
			shift_held = TRUE;
915
916
			return arrow_from_abcd(seq[4]);
		}
917
		break;
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
#ifndef NANO_TINY
	    case '4':
		/* When the arrow keys are held together with Shift+Meta,
		 * act as if they are Home/End/PgUp/PgDown with Shift. */
		switch (seq[4]) {
		    case 'A': /* Esc [ 1 ; 4 A == Shift-Alt-Up on xterm. */
			return SHIFT_PAGEUP;
		    case 'B': /* Esc [ 1 ; 4 B == Shift-Alt-Down on xterm. */
			return SHIFT_PAGEDOWN;
		    case 'C': /* Esc [ 1 ; 4 C == Shift-Alt-Right on xterm. */
			return KEY_SEND;
		    case 'D': /* Esc [ 1 ; 4 D == Shift-Alt-Left on xterm. */
			return KEY_SHOME;
		}
		break;
#endif
934
	    case '5':
935
936
937
938
939
940
941
942
943
944
		switch (seq[4]) {
		    case 'A': /* Esc [ 1 ; 5 A == Ctrl-Up on xterm. */
			return CONTROL_UP;
		    case 'B': /* Esc [ 1 ; 5 B == Ctrl-Down on xterm. */
			return CONTROL_DOWN;
		    case 'C': /* Esc [ 1 ; 5 C == Ctrl-Right on xterm. */
			return CONTROL_RIGHT;
		    case 'D': /* Esc [ 1 ; 5 D == Ctrl-Left on xterm. */
			return CONTROL_LEFT;
		}
945
		break;
946
947
948
949
950
951
952
953
954
955
956
957
958
959
#ifndef NANO_TINY
	    case '6':
		switch (seq[4]) {
		    case 'A': /* Esc [ 1 ; 6 A == Shift-Ctrl-Up on xterm. */
			return shiftcontrolup;
		    case 'B': /* Esc [ 1 ; 6 B == Shift-Ctrl-Down on xterm. */
			return shiftcontroldown;
		    case 'C': /* Esc [ 1 ; 6 C == Shift-Ctrl-Right on xterm. */
			return shiftcontrolright;
		    case 'D': /* Esc [ 1 ; 6 D == Shift-Ctrl-Left on xterm. */
			return shiftcontrolleft;
		}
		break;
#endif
960
	}
961
962
963
964

			} else if (seq_len > 2 && seq[2] == '~')
			    /* Esc [ 1 ~ == Home on VT320/Linux console. */
			    return KEY_HOME;
965
966
			break;
		    case '2':
967
			if (seq_len > 3 && seq[3] == '~') {
968
			    switch (seq[2]) {
969
970
				case '0': /* Esc [ 2 0 ~ == F9 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
971
				    return KEY_F(9);
972
973
				case '1': /* Esc [ 2 1 ~ == F10 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
974
				    return KEY_F(10);
975
976
				case '3': /* Esc [ 2 3 ~ == F11 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
977
				    return KEY_F(11);
978
979
				case '4': /* Esc [ 2 4 ~ == F12 on VT220/VT320/
					   * Linux console/xterm/rxvt/Eterm. */
980
				    return KEY_F(12);
981
982
				case '5': /* Esc [ 2 5 ~ == F13 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
983
				    return KEY_F(13);
984
985
				case '6': /* Esc [ 2 6 ~ == F14 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
986
				    return KEY_F(14);
987
988
				case '8': /* Esc [ 2 8 ~ == F15 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
989
				    return KEY_F(15);
990
991
				case '9': /* Esc [ 2 9 ~ == F16 on VT220/VT320/
					   * Linux console/rxvt/Eterm. */
992
				    return KEY_F(16);
993
			    }
994
995
996
997
			} else if (seq_len > 2 && seq[2] == '~')
			    /* Esc [ 2 ~ == Insert on VT220/VT320/
			     * Linux console/xterm/Terminal. */
			    return KEY_IC;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
998
			break;
999
		    case '3': /* Esc [ 3 ~ == Delete on VT220/VT320/
1000
			       * Linux console/xterm/Terminal. */
1001
			return KEY_DC;
1002
		    case '4': /* Esc [ 4 ~ == End on VT220/VT320/Linux
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1003
			       * console/xterm. */
1004
			return KEY_END;
1005
		    case '5': /* Esc [ 5 ~ == PageUp on VT220/VT320/
1006
1007
			       * Linux console/xterm/Terminal;
			       * Esc [ 5 ^ == PageUp on Eterm. */
1008
			return KEY_PPAGE;
1009
		    case '6': /* Esc [ 6 ~ == PageDown on VT220/VT320/
1010
			       * Linux console/xterm/Terminal;
1011
			       * Esc [ 6 ^ == PageDown on Eterm. */
1012
			return KEY_NPAGE;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1013
		    case '7': /* Esc [ 7 ~ == Home on rxvt. */
1014
			return KEY_HOME;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1015
		    case '8': /* Esc [ 8 ~ == End on rxvt. */
1016
			return KEY_END;
1017
		    case '9': /* Esc [ 9 == Delete on Mach console. */
1018
			return KEY_DC;
1019
		    case '@': /* Esc [ @ == Insert on Mach console. */
1020
			return KEY_IC;
1021
		    case 'A': /* Esc [ A == Up on ANSI/VT220/Linux
1022
			       * console/FreeBSD console/Mach console/
1023
			       * rxvt/Eterm/Terminal. */
1024
		    case 'B': /* Esc [ B == Down on ANSI/VT220/Linux
1025
			       * console/FreeBSD console/Mach console/
1026
			       * rxvt/Eterm/Terminal. */
1027
		    case 'C': /* Esc [ C == Right on ANSI/VT220/Linux
1028
			       * console/FreeBSD console/Mach console/
1029
			       * rxvt/Eterm/Terminal. */
1030
		    case 'D': /* Esc [ D == Left on ANSI/VT220/Linux
1031
			       * console/FreeBSD console/Mach console/
1032
			       * rxvt/Eterm/Terminal. */
1033
			return arrow_from_abcd(seq[1]);
1034
		    case 'E': /* Esc [ E == Center (5) on numeric keypad
1035
1036
			       * with NumLock off on FreeBSD console/
			       * Terminal. */
1037
			return KEY_B2;
1038
		    case 'F': /* Esc [ F == End on FreeBSD console/Eterm. */
1039
			return KEY_END;
1040
		    case 'G': /* Esc [ G == PageDown on FreeBSD console. */
1041
			return KEY_NPAGE;
1042
		    case 'H': /* Esc [ H == Home on ANSI/VT220/FreeBSD
1043
			       * console/Mach console/Eterm. */
1044
			return KEY_HOME;
1045
		    case 'I': /* Esc [ I == PageUp on FreeBSD console. */
1046
			return KEY_PPAGE;
1047
		    case 'L': /* Esc [ L == Insert on ANSI/FreeBSD console. */
1048
			return KEY_IC;
1049
		    case 'M': /* Esc [ M == F1 on FreeBSD console. */
1050
			return KEY_F(1);
1051
		    case 'N': /* Esc [ N == F2 on FreeBSD console. */
1052
			return KEY_F(2);
1053
		    case 'O':
1054
			if (seq_len > 2) {
1055
			    switch (seq[2]) {
1056
				case 'P': /* Esc [ O P == F1 on xterm. */
1057
				    return KEY_F(1);
1058
				case 'Q': /* Esc [ O Q == F2 on xterm. */
1059
				    return KEY_F(2);
1060
				case 'R': /* Esc [ O R == F3 on xterm. */
1061
				    return KEY_F(3);
1062
				case 'S': /* Esc [ O S == F4 on xterm. */
1063
				    return KEY_F(4);
1064
			    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1065
			} else
1066
			    /* Esc [ O == F3 on FreeBSD console. */
1067
			    return KEY_F(3);
1068
1069
			break;
		    case 'P': /* Esc [ P == F4 on FreeBSD console. */
1070
			return KEY_F(4);
1071
		    case 'Q': /* Esc [ Q == F5 on FreeBSD console. */
1072
			return KEY_F(5);
1073
		    case 'R': /* Esc [ R == F6 on FreeBSD console. */
1074
			return KEY_F(6);
1075
		    case 'S': /* Esc [ S == F7 on FreeBSD console. */
1076
			return KEY_F(7);
1077
		    case 'T': /* Esc [ T == F8 on FreeBSD console. */
1078
			return KEY_F(8);
1079
		    case 'U': /* Esc [ U == PageDown on Mach console. */
1080
			return KEY_NPAGE;
1081
		    case 'V': /* Esc [ V == PageUp on Mach console. */
1082
			return KEY_PPAGE;
1083
		    case 'W': /* Esc [ W == F11 on FreeBSD console. */
1084
			return KEY_F(11);
1085
		    case 'X': /* Esc [ X == F12 on FreeBSD console. */
1086
			return KEY_F(12);
1087
		    case 'Y': /* Esc [ Y == End on Mach console. */
1088
			return KEY_END;
1089
		    case 'Z': /* Esc [ Z == F14 on FreeBSD console. */
1090
			return KEY_F(14);
1091
		    case 'a': /* Esc [ a == Shift-Up on rxvt/Eterm. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1092
		    case 'b': /* Esc [ b == Shift-Down on rxvt/Eterm. */
1093
		    case 'c': /* Esc [ c == Shift-Right on rxvt/Eterm. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1094
		    case 'd': /* Esc [ d == Shift-Left on rxvt/Eterm. */
1095
			shift_held = TRUE;
1096
			return arrow_from_abcd(seq[1]);
1097
		    case '[':
1098
			if (seq_len > 2 ) {
1099
			    switch (seq[2]) {
1100
1101
				case 'A': /* Esc [ [ A == F1 on Linux
					   * console. */
1102
				    return KEY_F(1);
1103
1104
				case 'B': /* Esc [ [ B == F2 on Linux
					   * console. */
1105
				    return KEY_F(2);
1106
1107
				case 'C': /* Esc [ [ C == F3 on Linux
					   * console. */
1108
				    return KEY_F(3);
1109
1110
				case 'D': /* Esc [ [ D == F4 on Linux
					   * console. */
1111
				    return KEY_F(4);
1112
1113
				case 'E': /* Esc [ [ E == F5 on Linux
					   * console. */
1114
				    return KEY_F(5);
1115
1116
			    }
			}
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1117
1118
1119
1120
			break;
		}
		break;
	}
1121
1122
    }

1123
    return ERR;
1124
1125
}

1126
1127
/* Return the equivalent arrow-key value for the first four letters
 * in the alphabet, common to many escape sequences. */
1128
int arrow_from_abcd(int kbinput)
1129
1130
1131
{
    switch (tolower(kbinput)) {
	case 'a':
1132
	    return KEY_UP;
1133
	case 'b':
1134
	    return KEY_DOWN;
1135
	case 'c':
1136
	    return KEY_RIGHT;
1137
	case 'd':
1138
	    return KEY_LEFT;
1139
1140
1141
1142
1143
	default:
	    return ERR;
    }
}

1144
/* Interpret the escape sequence in the keystroke buffer, the first
1145
1146
 * character of which is kbinput.  Assume that the keystroke buffer
 * isn't empty, and that the initial escape has already been read in. */
1147
int parse_escape_sequence(WINDOW *win, int kbinput)
1148
1149
1150
1151
1152
1153
1154
1155
{
    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);
1156
    seq_len = key_buffer_len;
1157
    seq = get_input(NULL, seq_len);
1158
    retval = convert_sequence(seq, seq_len);
1159
1160
1161

    free(seq);

1162
    /* If we got an unrecognized escape sequence, notify the user. */
1163
    if (retval == ERR) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1164
	if (win == edit) {
1165
1166
	    /* TRANSLATORS: This refers to a sequence of escape codes
	     * (from the keyboard) that nano does not know about. */
1167
	    statusline(ALERT, _("Unknown sequence"));
1168
	    suppress_cursorpos = FALSE;
1169
	    lastmessage = HUSH;
1170
1171
1172
1173
	    if (currmenu == MMAIN) {
		reset_cursor();
		curs_set(1);
	    }
1174
1175
1176
	}
    }

1177
#ifdef DEBUG
1178
1179
    fprintf(stderr, "parse_escape_sequence(): kbinput = %d, seq_len = %lu, retval = %d\n",
		kbinput, (unsigned long)seq_len, retval);
1180
1181
1182
1183
1184
#endif

    return retval;
}

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

1192
1193
    /* Increment the byte digit counter. */
    byte_digits++;
1194

1195
    switch (byte_digits) {
1196
	case 1:
1197
1198
	    /* First digit: This must be from zero to two.  Put it in
	     * the 100's position of the byte sequence holder. */
1199
	    if ('0' <= kbinput && kbinput <= '2')
1200
		byte = (kbinput - '0') * 100;
1201
	    else
1202
1203
		/* This isn't the start of a byte sequence.  Return this
		 * character as the result. */
1204
1205
1206
		retval = kbinput;
	    break;
	case 2:
1207
1208
1209
1210
	    /* 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. */
1211
1212
1213
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 200 &&
		'6' <= kbinput && kbinput <= '9'))
		byte += (kbinput - '0') * 10;
1214
	    else
1215
1216
		/* This isn't the second digit of a byte sequence.
		 * Return this character as the result. */
1217
1218
1219
		retval = kbinput;
	    break;
	case 3:
1220
	    /* Third digit: This must be from zero to five if the first
1221
1222
1223
	     * 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. */
1224
1225
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 250 &&
		'6' <= kbinput && kbinput <= '9')) {
1226
		byte += kbinput - '0';
1227
		/* The byte sequence is complete. */
1228
		retval = byte;
1229
	    } else
1230
1231
		/* This isn't the third digit of a byte sequence.
		 * Return this character as the result. */
1232
1233
		retval = kbinput;
	    break;
1234
	default:
1235
1236
1237
	    /* If there are more than three digits, return this
	     * character as the result.  (Maybe we should produce an
	     * error instead?) */
1238
1239
1240
1241
1242
1243
1244
1245
	    retval = kbinput;
	    break;
    }

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

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

    return retval;
}

1256
#ifdef ENABLE_UTF8
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1257
/* If the character in kbinput is a valid hexadecimal digit, multiply it
1258
 * by factor and add the result to uni, and return ERR to signify okay. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1259
1260
1261
1262
1263
1264
1265
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
1266
1267
	/* The character isn't hexadecimal; give it as the result. */
	return (long)kbinput;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1268

1269
    return ERR;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1270
1271
}

1272
/* Translate a Unicode sequence: turn a six-digit hexadecimal number
1273
 * (from 000000 to 10FFFF, case-insensitive) into its corresponding
1274
 * multibyte value. */
1275
long get_unicode_kbinput(WINDOW *win, int kbinput)
1276
{
1277
1278
1279
    static int uni_digits = 0;
    static long uni = 0;
    long retval = ERR;
1280

1281
    /* Increment the Unicode digit counter. */
1282
    uni_digits++;
1283

1284
    switch (uni_digits) {
1285
	case 1:
1286
1287
1288
1289
	    /* The first digit must be zero or one.  Put it in the
	     * 0x100000's position of the Unicode sequence holder.
	     * Otherwise, return the character itself as the result. */
	    if (kbinput == '0' || kbinput == '1')
1290
		uni = (kbinput - '0') * 0x100000;
1291
1292
1293
1294
	    else
		retval = kbinput;
	    break;
	case 2:
1295
1296
1297
	    /* The second digit must be zero if the first was one, but
	     * may be any hexadecimal value if the first was zero. */
	    if (kbinput == '0' || uni == 0)
1298
		retval = add_unicode_digit(kbinput, 0x10000, &uni);
1299
1300
1301
1302
	    else
		retval = kbinput;
	    break;
	case 3:
1303
	    /* Later digits may be any hexadecimal value. */
1304
	    retval = add_unicode_digit(kbinput, 0x1000, &uni);
1305
	    break;
1306
	case 4:
1307
	    retval = add_unicode_digit(kbinput, 0x100, &uni);
1308
	    break;
1309
	case 5:
1310
	    retval = add_unicode_digit(kbinput, 0x10, &uni);
1311
	    break;
1312
	case 6:
1313
	    retval = add_unicode_digit(kbinput, 0x1, &uni);
1314
1315
	    /* If also the sixth digit was a valid hexadecimal value, then
	     * the Unicode sequence is complete, so return it. */
1316
	    if (retval == ERR)
1317
		retval = uni;
1318
1319
	    break;
    }
1320

1321
    /* Show feedback only when editing, not when at a prompt. */
1322
    if (retval == ERR && win == edit) {
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
	char partial[7] = "......";

	/* Construct the partial result, right-padding it with dots. */
	snprintf(partial, uni_digits + 1, "%06lX", uni);
	partial[uni_digits] = '.';

	/* TRANSLATORS: This is shown while a six-digit hexadecimal
	 * Unicode character code (%s) is being typed in. */
	statusline(HUSH, _("Unicode Input: %s"), partial);
    }
1333

1334
#ifdef DEBUG
1335
1336
    fprintf(stderr, "get_unicode_kbinput(): kbinput = %d, uni_digits = %d, uni = %ld, retval = %ld\n",
						kbinput, uni_digits, uni, retval);
1337
1338
#endif

1339
1340
1341
1342
    /* If we have an end result, reset the Unicode digit counter. */
    if (retval != ERR)
	uni_digits = 0;

1343
1344
    return retval;
}
1345
#endif /* ENABLE_UTF8 */
1346

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

1353
    /* Ctrl-Space (Ctrl-2, Ctrl-@, Ctrl-`) */
1354
    if (kbinput == ' ' || kbinput == '2')
1355
	retval = 0;
1356
1357
    /* Ctrl-/ (Ctrl-7, Ctrl-_) */
    else if (kbinput == '/')
1358
	retval = 31;
1359
    /* Ctrl-3 (Ctrl-[, Esc) to Ctrl-7 (Ctrl-/, Ctrl-_) */
1360
1361
1362
    else if ('3' <= kbinput && kbinput <= '7')
	retval = kbinput - 24;
    /* Ctrl-8 (Ctrl-?) */
1363
    else if (kbinput == '8' || kbinput == '?')
1364
	retval = DEL_CODE;
1365
1366
    /* Ctrl-@ (Ctrl-Space, Ctrl-2, Ctrl-`) to Ctrl-_ (Ctrl-/, Ctrl-7) */
    else if ('@' <= kbinput && kbinput <= '_')
1367
	retval = kbinput - '@';
1368
1369
    /* Ctrl-` (Ctrl-2, Ctrl-Space, Ctrl-@) to Ctrl-~ (Ctrl-6, Ctrl-^) */
    else if ('`' <= kbinput && kbinput <= '~')
1370
	retval = kbinput - '`';
1371
1372
1373
    else
	retval = kbinput;

1374
#ifdef DEBUG
1375
    fprintf(stderr, "get_control_kbinput(): kbinput = %d, retval = %d\n", kbinput, retval);
1376
1377
#endif

1378
1379
    return retval;
}
1380

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1381
1382
/* Put the output-formatted characters in output back into the keystroke
 * buffer, so that they can be parsed and displayed as output again. */
1383
void unparse_kbinput(char *output, size_t output_len)
1384
{
1385
1386
    int *input;
    size_t i;
1387

1388
1389
1390
1391
    if (output_len == 0)
	return;

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

1393
1394
    for (i = 0; i < output_len; i++)
	input[i] = (int)output[i];
1395

1396
    unget_input(input, output_len);
1397

1398
    free(input);
1399
1400
}

1401
/* Read in a stream of characters verbatim, and return the length of the
1402
1403
1404
1405
 * string in kbinput_len.  Assume nodelay(win) is FALSE. */
int *get_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
{
    int *retval;
1406

1407
    /* Turn off flow control characters if necessary so that we can type
1408
1409
     * them in verbatim, and turn the keypad off if necessary so that we
     * don't get extended keypad values. */
1410
1411
    if (ISSET(PRESERVE))
	disable_flow_control();
1412
1413
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, FALSE);
1414
1415
1416

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

    /* Turn flow control characters back on if necessary and turn the
1419
     * keypad back on if necessary now that we're done. */
1420
1421
    if (ISSET(PRESERVE))
	enable_flow_control();
1422
1423
1424
1425
1426
1427
    /* Use the global window pointers, because a resize may have freed
     * the data that the win parameter points to. */
    if (!ISSET(REBIND_KEYPAD)) {
	keypad(edit, TRUE);
	keypad(bottomwin, TRUE);
    }
1428

1429
    return retval;
1430
1431
}

1432
1433
1434
1435
1436
/* Read in one control character (or an iTerm double Escape), or convert a
 * series of six digits into a Unicode codepoint.  Return in count either 1
 * (for a control character or the first byte of a multibyte sequence), or 2
 * (for an iTerm double Escape). */
int *parse_verbatim_kbinput(WINDOW *win, size_t *count)
1437
{
1438
    int *kbinput;
1439

1440
    /* Read in the first code. */
1441
1442
    while ((kbinput = get_input(win, 1)) == NULL)
	;
1443

1444
#ifndef NANO_TINY
1445
1446
1447
    /* When the window was resized, abort and return nothing. */
    if (*kbinput == KEY_WINCH) {
	free(kbinput);
1448
	*count = 0;
1449
1450
	return NULL;
    }
1451
#endif
1452

1453
#ifdef ENABLE_UTF8
1454
    if (using_utf8()) {
1455
	/* Check whether the first code is a valid starter digit: 0 or 1. */
1456
	long uni = get_unicode_kbinput(win, *kbinput);
1457

1458
	/* If the first code isn't the digit 0 nor 1, put it back. */
1459
1460
	if (uni != ERR)
	    unget_input(kbinput, 1);
1461
1462
	/* Otherwise, continue reading in digits until we have a complete
	 * Unicode value, and put back the corresponding byte(s). */
1463
1464
1465
1466
1467
	else {
	    char *uni_mb;
	    int uni_mb_len, *seq, i;

	    while (uni == ERR) {
1468
		free(kbinput);
1469
1470
		while ((kbinput = get_input(win, 1)) == NULL)
		    ;
1471
		uni = get_unicode_kbinput(win, *kbinput);
1472
	    }
1473

1474
	    /* Convert the Unicode value to a multibyte sequence. */
1475
	    uni_mb = make_mbchar(uni, &uni_mb_len);
1476

1477
	    seq = (int *)nmalloc(uni_mb_len * sizeof(int));
1478

1479
1480
	    for (i = 0; i < uni_mb_len; i++)
		seq[i] = (unsigned char)uni_mb[i];
1481

1482
	    /* Insert the multibyte sequence into the input buffer. */
1483
	    unget_input(seq, uni_mb_len);
1484

1485
1486
	    free(seq);
	    free(uni_mb);
1487
	}
1488
    } else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1489
#endif /* ENABLE_UTF8 */
1490
	/* Put back the first code. */
1491
	unget_input(kbinput, 1);
1492

1493
1494
    free(kbinput);

1495
    *count = 1;
1496

1497
1498
1499
1500
1501
1502
    /* If this is an iTerm double escape, take both Escapes. */
    if (key_buffer_len > 3 && *key_buffer == ESC_CODE &&
		key_buffer[1] == ESC_CODE && key_buffer[2] == '[')
	*count = 2;

    return get_input(NULL, *count);
1503
1504
}

1505
#ifndef DISABLE_MOUSE
1506
/* Handle any mouse event that may have occurred.  We currently handle
1507
1508
1509
1510
1511
1512
1513
 * 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
1514
1515
1516
1517
1518
1519
 * 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. */
1520
int get_mouseinput(int *mouse_x, int *mouse_y, bool allow_shortcuts)
1521
1522
{
    MEVENT mevent;
1523
    bool in_bottomwin;
1524
    subnfunc *f;
1525
1526
1527
1528
1529
1530

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

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

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

1537
1538
    in_bottomwin = wenclose(bottomwin, *mouse_y, *mouse_x);

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1539
    /* Handle releases/clicks of the first mouse button. */
1540
    if (mevent.bstate & (BUTTON1_RELEASED | BUTTON1_CLICKED)) {
1541
1542
	/* If we're allowing shortcuts, the current shortcut list is
	 * being displayed on the last two lines of the screen, and the
1543
1544
1545
	 * 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. */
1546
	if (allow_shortcuts && !ISSET(NO_HELP) && in_bottomwin) {
1547
1548
1549
1550
	    int i;
		/* The width of all the shortcuts, except for the last
		 * two, in the shortcut list in bottomwin. */
	    int j;
1551
		/* The calculated index number of the clicked item. */
1552
1553
	    size_t number;
		/* The number of available shortcuts in the current menu. */
1554

1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
	    /* 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;
	    }
1569

1570
	    /* Determine how many shortcuts are being shown. */
1571
	    number = length_of_list(currmenu);
1572

1573
1574
	    if (number > MAIN_VISIBLE)
		number = MAIN_VISIBLE;
1575

1576
1577
1578
	    /* 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. */
1579
	    if (number < 2)
1580
1581
		i = COLS / (MAIN_VISIBLE / 2);
	    else
1582
		i = COLS / ((number / 2) + (number % 2));
1583

1584
1585
	    /* Calculate the one-based index in the shortcut list. */
	    j = (*mouse_x / i) * 2 + *mouse_y;
1586

1587
	    /* Adjust the index if we hit the last two wider ones. */
1588
	    if ((j > number) && (*mouse_x % i < COLS % i))
1589
		j -= 2;
1590
1591
1592
#ifdef DEBUG
	    fprintf(stderr, "Calculated %i as index in shortcut list, currmenu = %x.\n", j, currmenu);
#endif
1593
1594
	    /* Ignore releases/clicks of the first mouse button beyond
	     * the last shortcut. */
1595
	    if (j > number)
1596
		return 2;
1597

1598
1599
	    /* Go through the list of functions to determine which
	     * shortcut in the current menu we released/clicked on. */
1600
	    for (f = allfuncs; f != NULL; f = f->next) {
1601
		if ((f->menus & currmenu) == 0)
1602
1603
		    continue;
		if (first_sc_for(currmenu, f->scfunc) == NULL)
1604
		    continue;
1605
1606
		/* Tick off an actually shown shortcut. */
		j -= 1;
1607
1608
		if (j == 0)
		    break;
1609
	    }
1610
#ifdef DEBUG
1611
	    fprintf(stderr, "Stopped on func %ld present in menus %x\n", (long)f->scfunc, f->menus);
1612
#endif
1613

1614
	    /* And put the corresponding key into the keyboard buffer. */
1615
	    if (f != NULL) {
1616
		const sc *s = first_sc_for(currmenu, f->scfunc);
1617
		unget_kbinput(s->keycode, s->meta);
1618
	    }
1619
	    return 1;
1620
	} else
1621
1622
	    /* Handle releases/clicks of the first mouse button that
	     * aren't on the current shortcut list elsewhere. */
1623
	    return 0;
1624
    }
1625
1626
#if NCURSES_MOUSE_VERSION >= 2
    /* Handle presses of the fourth mouse button (upward rolls of the
1627
1628
1629
     * 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
1630
	bool in_edit = wenclose(edit, *mouse_y, *mouse_x);
1631

1632
1633
1634
1635
	if (in_bottomwin)
	    /* Translate the mouse event coordinates so that they're
	     * relative to bottomwin. */
	    wmouse_trafo(bottomwin, mouse_y, mouse_x, FALSE);
1636

1637
	if (in_edit || (in_bottomwin && *mouse_y == 0)) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1638
1639
	    int i;

1640
1641
1642
1643
1644
	    /* 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) ?
1645
				KEY_PPAGE : KEY_NPAGE, FALSE);
1646
1647
1648
1649
1650
1651
1652

	    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;
1653
1654
    }
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1655
1656
1657

    /* Ignore all other mouse events. */
    return 2;
1658
}
1659
1660
#endif /* !DISABLE_MOUSE */

1661
1662
1663
1664
/* 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. */
1665
const sc *get_shortcut(int *kbinput)
1666
{
1667
    sc *s;
1668

1669
#ifdef DEBUG
1670
1671
    fprintf(stderr, "get_shortcut(): kbinput = %d, meta_key = %s -- ",
				*kbinput, meta_key ? "TRUE" : "FALSE");
1672
1673
#endif

1674
    for (s = sclist; s != NULL; s = s->next) {
1675
	if ((s->menus & currmenu) && *kbinput == s->keycode &&
1676
					meta_key == s->meta) {
1677
#ifdef DEBUG
1678
1679
	    fprintf (stderr, "matched seq '%s'  (menu is %x from %x)\n",
				s->keystr, currmenu, s->menus);
1680
#endif
1681
	    return s;
1682
1683
	}
    }
1684
#ifdef DEBUG
1685
    fprintf (stderr, "matched nothing\n");
1686
#endif
1687
1688
1689
1690

    return NULL;
}

1691
1692
1693
1694
1695
/* 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
1696

1697
1698
1699
1700
    for (; n > 0; n--)
	waddch(win, ' ');
}

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

1707
/* Blank all the lines of the middle portion of the window, i.e. the
1708
 * edit window. */
Chris Allegretta's avatar
Chris Allegretta committed
1709
1710
void blank_edit(void)
{
1711
    int i;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1712

1713
    for (i = 0; i < editwinrows; i++)
1714
	blank_line(edit, i, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1715
1716
}

1717
/* Blank the first line of the bottom portion of the window. */
Chris Allegretta's avatar
Chris Allegretta committed
1718
1719
void blank_statusbar(void)
{
1720
    blank_line(bottomwin, 0, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1721
1722
}

1723
1724
/* If the NO_HELP flag isn't set, blank the last two lines of the bottom
 * portion of the window. */
1725
1726
void blank_bottombars(void)
{
1727
    if (!ISSET(NO_HELP) && LINES > 4) {
1728
1729
	blank_line(bottomwin, 1, 0, COLS);
	blank_line(bottomwin, 2, 0, COLS);
1730
1731
1732
    }
}

1733
1734
/* Check if the number of keystrokes needed to blank the statusbar has
 * been pressed.  If so, blank the statusbar, unless constant cursor
1735
 * position display is on and we are in the editing screen. */
1736
void check_statusblank(void)
Chris Allegretta's avatar
Chris Allegretta committed
1737
{
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
    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
1752
    }
1753
1754
1755
1756

    /* If the subwindows overlap, make sure to show the edit window now. */
    if (LINES == 1)
	edit_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
1757
1758
}

1759
1760
/* Convert buf into a string that can be displayed on screen.  The
 * caller wants to display buf starting with column start_col, and
1761
1762
 * extending for at most span columns.  start_col is zero-based.  span
 * is one-based, so span == 0 means you get "" returned.  The returned
1763
1764
1765
 * 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. */
1766
1767
char *display_string(const char *buf, size_t start_col, size_t span,
	bool dollars)
1768
1769
{
    size_t start_index;
1770
	/* Index in buf of the first character shown. */
1771
    size_t column;
1772
	/* Screen column that start_index corresponds to. */
1773
1774
1775
1776
    char *converted;
	/* The string we return. */
    size_t index;
	/* Current position in converted. */
1777

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

1783
    if (span == 0)
1784
1785
1786
1787
	return mallocstrcpy(NULL, "");

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

1789
    assert(column <= start_col);
1790

1791
1792
    /* Allocate enough space to hold the entire converted buffer. */
    converted = charalloc(strlen(buf) * (mb_cur_max() + tabsize) + 1);
1793

1794
    index = 0;
1795
#ifdef USING_OLD_NCURSES
1796
    seen_wide = FALSE;
1797
#endif
1798
    buf += start_index;
1799

1800
    if (*buf != '\0' && *buf != '\t' &&
1801
	(column < start_col || (dollars && column > 0))) {
1802
	/* We don't display the complete first character as it starts to
1803
	 * the left of the screen. */
1804
	if (is_cntrl_mbchar(buf)) {
1805
	    if (column < start_col) {
1806
		converted[index++] = control_mbrep(buf);
1807
		start_col++;
1808
		buf += parse_mbchar(buf, NULL, NULL);
1809
	    }
1810
	}
1811
#ifdef ENABLE_UTF8
1812
	else if (using_utf8() && mbwidth(buf) == 2) {
1813
1814
1815
1816
1817
	    if (column >= start_col) {
		converted[index++] = ' ';
		start_col++;
	    }

1818
	    converted[index++] = ' ';
1819
	    start_col++;
1820

1821
	    buf += parse_mbchar(buf, NULL, NULL);
1822
	}
1823
#endif
1824
1825
    }

1826
    while (*buf != '\0') {
1827
	int charlength, charwidth = 1;
1828

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

1849
1850
		while (i < whitespace_len[0])
		    converted[index++] = whitespace[i++];
1851
	    } else
1852
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1853
		converted[index++] = ' ';
1854
	    start_col++;
1855
	    /* Fill the tab up with the required number of spaces. */
1856
	    while (start_col % tabsize != 0) {
1857
		converted[index++] = ' ';
1858
1859
		start_col++;
	    }
1860
1861
1862
1863
	    buf++;
	    continue;
	}

1864
	charlength = length_of_char(buf, &charwidth);
1865

1866
	/* If buf contains a control character, represent it. */
1867
	if (is_cntrl_mbchar(buf)) {
1868
	    converted[index++] = '^';
1869
	    converted[index++] = control_mbrep(buf);
1870
	    start_col += 2;
1871
1872
1873
	    buf += charlength;
	    continue;
	}
1874

1875
1876
1877
1878
	/* If buf contains a valid non-control character, simply copy it. */
	if (charlength > 0) {
	    for (; charlength > 0; charlength--)
		converted[index++] = *(buf++);
1879

1880
	    start_col += charwidth;
1881
#ifdef USING_OLD_NCURSES
1882
	    if (charwidth > 1)
1883
		seen_wide = TRUE;
1884
#endif
1885
	    continue;
1886
1887
	}

1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
	/* Represent an invalid sequence with the Replacement Character. */
	converted[index++] = '\xEF';
	converted[index++] = '\xBF';
	converted[index++] = '\xBD';

	start_col += 1;
	buf++;

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1901
    /* Null-terminate converted. */
1902
    converted[index] = '\0';
1903

1904
1905
    /* Make sure converted takes up no more than span columns. */
    index = actual_x(converted, span);
1906
    null_at(&converted, index);
1907

1908
    return converted;
1909
1910
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1911
1912
1913
1914
1915
1916
/* 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. */
1917
void titlebar(const char *path)
Chris Allegretta's avatar
Chris Allegretta committed
1918
{
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
    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. */
1931

1932
1933
1934
1935
    /* If the screen is too small, there is no titlebar. */
    if (topwin == NULL)
	return;

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

1938
    wattron(topwin, interface_color_pair[TITLE_BAR]);
1939

1940
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
1941

1942
1943
1944
    /* 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
1945

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

1960
1961
1962
1963
	if (openfile->modified)
	    state = _("Modified");
	else if (ISSET(VIEW_MODE))
	    state = _("View");
1964

1965
1966
	pluglen = strlenpt(_("Modified")) + 1;
    }
1967

1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
    /* 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;
1978
1979
    }

1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
    /* 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;
1992
1993
1994
	}
    }

1995
1996
1997
1998
    /* If we have side spaces left, center the path name. */
    if (verlen > 0)
	offset = verlen + (COLS - (verlen + pluglen + statelen) -
					(prefixlen + pathlen)) / 2;
1999

2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
    /* 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);
2017
    }
2018

2019
2020
2021
2022
2023
2024
    /* 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));

2025
    wattroff(topwin, interface_color_pair[TITLE_BAR]);
2026

2027
    wnoutrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
2028
    reset_cursor();
2029
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2030
2031
}

2032
2033
2034
2035
2036
2037
/* Display a normal message on the statusbar, quietly. */
void statusbar(const char *msg)
{
    statusline(HUSH, msg);
}

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

    UNSET(WHITESPACE_DISPLAY);
2051
#endif
2052
2053
2054
2055
2056

    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(). */
2057
    if (isendwin()) {
2058
2059
2060
2061
2062
	vfprintf(stderr, msg, ap);
	va_end(ap);
	return;
    }

2063
2064
2065
2066
2067
2068
2069
    /* 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)
2070
2071
	napms(1200);

2072
    if (importance == ALERT)
2073
	beep();
2074
2075

    lastmessage = importance;
2076

2077
2078
2079
    /* Turn the cursor off while fiddling in the statusbar. */
    curs_set(0);

2080
2081
    blank_statusbar();

2082
2083
2084
    /* Construct the message out of all the arguments. */
    compound = charalloc(mb_cur_max() * (COLS + 1));
    vsnprintf(compound, mb_cur_max() * (COLS + 1), msg, ap);
2085
    va_end(ap);
2086
2087
    message = display_string(compound, 0, COLS, FALSE);
    free(compound);
2088

2089
    start_x = (COLS - strlenpt(message)) / 2;
2090
    bracketed = (start_x > 1);
2091

2092
    wmove(bottomwin, 0, (bracketed ? start_x - 2 : start_x));
2093
    wattron(bottomwin, interface_color_pair[STATUS_BAR]);
2094
2095
    if (bracketed)
	waddstr(bottomwin, "[ ");
2096
2097
    waddstr(bottomwin, message);
    free(message);
2098
2099
    if (bracketed)
	waddstr(bottomwin, " ]");
2100
    wattroff(bottomwin, interface_color_pair[STATUS_BAR]);
2101

2102
    /* Push the message to the screen straightaway. */
2103
    wnoutrefresh(bottomwin);
2104
    doupdate();
2105

2106
    suppress_cursorpos = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2107

2108
#ifndef NANO_TINY
2109
2110
2111
2112
2113
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);

    /* If doing quick blanking, blank the statusbar after just one keystroke.
     * Otherwise, blank it after twenty-six keystrokes, as Pico does. */
2114
2115
2116
    if (ISSET(QUICK_BLANK))
	statusblank = 1;
    else
2117
#endif
2118
	statusblank = 26;
2119
2120
}

2121
2122
/* Display the shortcut list corresponding to menu on the last two rows
 * of the bottom portion of the window. */
2123
void bottombars(int menu)
Chris Allegretta's avatar
Chris Allegretta committed
2124
{
2125
    size_t number, itemwidth, i;
2126
2127
    subnfunc *f;
    const sc *s;
2128

2129
2130
2131
    /* Set the global variable to the given menu. */
    currmenu = menu;

2132
    if (ISSET(NO_HELP) || LINES < 5)
Chris Allegretta's avatar
Chris Allegretta committed
2133
2134
	return;

2135
    /* Determine how many shortcuts there are to show. */
2136
    number = length_of_list(menu);
2137

2138
2139
    if (number > MAIN_VISIBLE)
	number = MAIN_VISIBLE;
2140

2141
    /* Compute the width of each keyname-plus-explanation pair. */
2142
    itemwidth = COLS / ((number / 2) + (number % 2));
Chris Allegretta's avatar
Chris Allegretta committed
2143

2144
    /* If there is no room, don't print anything. */
2145
    if (itemwidth == 0)
2146
2147
	return;

2148
    blank_bottombars();
2149

2150
#ifdef DEBUG
2151
    fprintf(stderr, "In bottombars, number of items == \"%d\"\n", (int) number);
2152
#endif
2153

2154
    for (f = allfuncs, i = 0; i < number && f != NULL; f = f->next) {
2155
#ifdef DEBUG
2156
	fprintf(stderr, "Checking menu items....");
2157
#endif
2158
	if ((f->menus & menu) == 0)
2159
	    continue;
2160

2161
#ifdef DEBUG
2162
	fprintf(stderr, "found one! f->menus = %x, desc = \"%s\"\n", f->menus, f->desc);
2163
#endif
2164
2165
	s = first_sc_for(menu, f->scfunc);
	if (s == NULL) {
2166
2167
2168
#ifdef DEBUG
	    fprintf(stderr, "Whoops, guess not, no shortcut key found for func!\n");
#endif
2169
2170
	    continue;
	}
2171
2172

	wmove(bottomwin, 1 + i % 2, (i / 2) * itemwidth);
2173
#ifdef DEBUG
2174
	fprintf(stderr, "Calling onekey with keystr \"%s\" and desc \"%s\"\n", s->keystr, f->desc);
2175
#endif
2176
	onekey(s->keystr, _(f->desc), itemwidth + (COLS % itemwidth));
2177
	i++;
Chris Allegretta's avatar
Chris Allegretta committed
2178
    }
2179

2180
2181
    wnoutrefresh(bottomwin);
    reset_cursor();
2182
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2183
2184
}

2185
2186
/* 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
2187
 * to write at most length characters, even if length is very small and
2188
2189
 * keystroke and desc are long.  Note that waddnstr(,,(size_t)-1) adds
 * the whole string!  We do not bother padding the entry with blanks. */
2190
void onekey(const char *keystroke, const char *desc, int length)
Chris Allegretta's avatar
Chris Allegretta committed
2191
{
2192
2193
    assert(keystroke != NULL && desc != NULL);

2194
    wattron(bottomwin, interface_color_pair[KEY_COMBO]);
2195
    waddnstr(bottomwin, keystroke, actual_x(keystroke, length));
2196
    wattroff(bottomwin, interface_color_pair[KEY_COMBO]);
2197

2198
    length -= strlenpt(keystroke) + 1;
2199

2200
    if (length > 0) {
2201
	waddch(bottomwin, ' ');
2202
	wattron(bottomwin, interface_color_pair[FUNCTION_TAG]);
2203
	waddnstr(bottomwin, desc, actual_x(desc, length));
2204
	wattroff(bottomwin, interface_color_pair[FUNCTION_TAG]);
Chris Allegretta's avatar
Chris Allegretta committed
2205
2206
2207
    }
}

2208
2209
/* 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
2210
2211
void reset_cursor(void)
{
2212
    size_t xpt = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2213

2214
#ifndef NANO_TINY
2215
    if (ISSET(SOFTWRAP)) {
2216
	filestruct *line = openfile->edittop;
2217
2218
	openfile->current_y = 0;

2219
2220
2221
2222
	while (line != NULL && line != openfile->current) {
	    openfile->current_y += strlenpt(line->data) / COLS + 1;
	    line = line->next;
	}
2223
	openfile->current_y += xpt / COLS;
2224

2225
	if (openfile->current_y < editwinrows)
2226
	    wmove(edit, openfile->current_y, xpt % COLS);
2227
2228
2229
    } else
#endif
    {
2230
	openfile->current_y = openfile->current->lineno -
2231
				openfile->edittop->lineno;
2232
2233
2234
2235

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

2238
2239
2240
2241
2242
2243
2244
2245
/* 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. */
2246
void edit_draw(filestruct *fileptr, const char *converted, int
2247
	line, size_t start)
Chris Allegretta's avatar
Chris Allegretta committed
2248
{
2249
#if !defined(NANO_TINY) || !defined(DISABLE_COLOR)
2250
2251
2252
2253
2254
2255
2256
2257
2258
    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. */
2259
2260
#endif

2261
    assert(openfile != NULL && fileptr != NULL && converted != NULL);
2262
    assert(strlenpt(converted) <= COLS);
2263

2264
2265
2266
    /* 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);
2267

2268
#ifdef USING_OLD_NCURSES
2269
2270
2271
    /* 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. */
2272
2273
    if (seen_wide)
	wredrawln(edit, line, 1);
2274
#endif
2275

2276
#ifndef DISABLE_COLOR
2277
2278
2279
    /* If color syntaxes are available and turned on, we need to display
     * them. */
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX)) {
2280
	const colortype *varnish = openfile->colorstrings;
2281

2282
2283
2284
2285
	/* If there are multiline regexes, make sure there is a cache. */
	if (openfile->syntax->nmultis > 0)
	    alloc_multidata_if_needed(fileptr);

2286
	for (; varnish != NULL; varnish = varnish->next) {
2287
2288
	    int x_start;
		/* Starting column for mvwaddnstr.  Zero-based. */
2289
	    int paintlen = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2290
2291
		/* Number of chars to paint on this line.  There are
		 * COLS characters on a whole line. */
2292
	    size_t index;
2293
		/* Index in converted where we paint. */
2294
2295
2296
2297
	    regmatch_t startmatch;
		/* Match position for start_regex. */
	    regmatch_t endmatch;
		/* Match position for end_regex. */
2298

2299
	    wattron(edit, varnish->attributes);
2300
2301
2302
	    /* 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. */
2303

2304
2305
	    /* First case: varnish is a single-line expression. */
	    if (varnish->end == NULL) {
2306
2307
2308
		size_t k = 0;

		/* We increment k by rm_eo, to move past the end of the
2309
		 * last match.  Even though two matches may overlap, we
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2310
2311
		 * want to ignore them, so that we can highlight e.g. C
		 * strings correctly. */
2312
2313
2314
		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
2315
2316
2317
		     * unless k is zero.  If regexec() returns
		     * REG_NOMATCH, there are no more matches in the
		     * line. */
2318
		    if (regexec(varnish->start, &fileptr->data[k], 1,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2319
2320
			&startmatch, (k == 0) ? 0 : REG_NOTBOL) ==
			REG_NOMATCH)
2321
			break;
2322
2323
		    /* Translate the match to the beginning of the
		     * line. */
2324
2325
		    startmatch.rm_so += k;
		    startmatch.rm_eo += k;
2326
2327
2328

		    /* Skip over a zero-length regex match. */
		    if (startmatch.rm_so == startmatch.rm_eo)
2329
			startmatch.rm_eo++;
2330
		    else if (startmatch.rm_so < endpos &&
2331
			startmatch.rm_eo > startpos) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2332
2333
			x_start = (startmatch.rm_so <= startpos) ? 0 :
				strnlenpt(fileptr->data,
2334
				startmatch.rm_so) - start;
2335

2336
2337
2338
			index = actual_x(converted, x_start);

			paintlen = actual_x(converted + index,
2339
2340
				strnlenpt(fileptr->data,
				startmatch.rm_eo) - start - x_start);
2341
2342
2343

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

2344
			mvwaddnstr(edit, line, x_start, converted +
2345
				index, paintlen);
2346
		    }
2347
		    k = startmatch.rm_eo;
Chris Allegretta's avatar
Chris Allegretta committed
2348
		}
2349
	    } else {	/* Second case: varnish is a multiline expression. */
2350
		const filestruct *start_line = fileptr->prev;
2351
		    /* The first line before fileptr that matches 'start'. */
2352
		size_t start_col;
2353
		    /* Where the match starts in that line. */
2354
		const filestruct *end_line;
2355
		    /* The line that matches 'end'. */
2356

2357
		/* First see if the multidata was maybe already calculated. */
2358
		if (fileptr->multidata[varnish->id] == CNONE)
2359
		    goto tail_of_loop;
2360
		else if (fileptr->multidata[varnish->id] == CWHOLELINE) {
2361
		    mvwaddnstr(edit, line, 0, converted, -1);
2362
		    goto tail_of_loop;
2363
2364
		} else if (fileptr->multidata[varnish->id] == CBEGINBEFORE) {
		    regexec(varnish->end, fileptr->data, 1, &endmatch, 0);
2365
2366
		    /* If the coloured part is scrolled off, skip it. */
		    if (endmatch.rm_eo <= startpos)
2367
			goto tail_of_loop;
2368
2369
2370
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
			endmatch.rm_eo) - start);
		    mvwaddnstr(edit, line, 0, converted, paintlen);
2371
		    goto tail_of_loop;
2372
		} if (fileptr->multidata[varnish->id] == -1)
2373
		    /* Assume this until proven otherwise below. */
2374
		    fileptr->multidata[varnish->id] = CNONE;
2375

2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
		/* 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. */

2386
		while (start_line != NULL && regexec(varnish->start,
2387
2388
2389
			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. */
2390
		    if (regexec(varnish->end, start_line->data, 0, NULL, 0) == 0)
2391
2392
2393
			goto step_two;
		    start_line = start_line->prev;
		}
2394

2395
2396
2397
2398
		/* If no start was found, skip to the next step. */
		if (start_line == NULL)
		    goto step_two;

2399
		/* If a found start has been qualified as an end earlier,
2400
		 * believe it and skip to the next step. */
2401
		if (start_line->multidata != NULL &&
2402
2403
			(start_line->multidata[varnish->id] == CBEGINBEFORE ||
			start_line->multidata[varnish->id] == CSTARTENDHERE))
2404
2405
		    goto step_two;

2406
		/* Skip over a zero-length regex match. */
2407
		if (startmatch.rm_so == startmatch.rm_eo)
2408
2409
		    goto tail_of_loop;

2410
2411
2412
2413
2414
2415
2416
		/* 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;
2417
		    if (regexec(varnish->end, start_line->data +
2418
2419
2420
				start_col + startmatch.rm_eo, 0, NULL,
				(start_col + startmatch.rm_eo == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH)
2421
2422
2423
			/* No end found after this start. */
			break;
		    start_col++;
2424
2425
		    if (regexec(varnish->start, start_line->data + start_col,
				1, &startmatch, REG_NOTBOL) == REG_NOMATCH)
2426
2427
2428
2429
2430
2431
2432
2433
2434
			/* 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;
2435
		while (end_line != NULL && regexec(varnish->end,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2436
			end_line->data, 1, &endmatch, 0) == REG_NOMATCH)
2437
		    end_line = end_line->next;
2438

2439
2440
2441
2442
		/* 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) {
2443
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2444
2445
		    goto step_two;
		}
2446

2447
2448
2449
2450
2451
2452
2453
		/* 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;
2454
		    fileptr->multidata[varnish->id] = CWHOLELINE;
2455
#ifdef DEBUG
2456
    fprintf(stderr, "  Marking for id %i  line %i as CWHOLELINE\n", varnish->id, line);
2457
#endif
2458
2459
2460
		} else {
		    paintlen = actual_x(converted, strnlenpt(fileptr->data,
						endmatch.rm_eo) - start);
2461
		    fileptr->multidata[varnish->id] = CBEGINBEFORE;
2462
#ifdef DEBUG
2463
    fprintf(stderr, "  Marking for id %i  line %i as CBEGINBEFORE\n", varnish->id, line);
2464
#endif
2465
2466
2467
2468
2469
2470
		}
		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;
2471
  step_two:
2472
2473
2474
2475
2476
		/* 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) {
2477
		    if (regexec(varnish->start, fileptr->data + start_col,
2478
2479
				1, &startmatch, (start_col == 0) ?
				0 : REG_NOTBOL) == REG_NOMATCH ||
2480
				start_col + startmatch.rm_so >= endpos)
2481
2482
			/* No more starts on this line. */
			break;
2483

2484
2485
2486
2487
2488
2489
2490
		    /* 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,
2491
				startmatch.rm_so) - start;
2492

2493
		    index = actual_x(converted, x_start);
2494

2495
		    if (regexec(varnish->end, fileptr->data +
2496
				startmatch.rm_eo, 1, &endmatch,
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
				(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 &&
2507
				endmatch.rm_eo > startmatch.rm_so) {
2508
			    paintlen = actual_x(converted + index,
2509
					strnlenpt(fileptr->data,
2510
					endmatch.rm_eo) - start - x_start);
2511

2512
			    assert(0 <= x_start && x_start < COLS);
2513

2514
			    mvwaddnstr(edit, line, x_start,
2515
					converted + index, paintlen);
2516
			    if (paintlen > 0) {
2517
				fileptr->multidata[varnish->id] = CSTARTENDHERE;
2518
#ifdef DEBUG
2519
    fprintf(stderr, "  Marking for id %i  line %i as CSTARTENDHERE\n", varnish->id, line);
2520
#endif
2521
			    }
2522
2523
			}
			start_col = endmatch.rm_eo;
2524
2525
2526
			/* Skip over a zero-length match. */
			if (endmatch.rm_so == endmatch.rm_eo)
			    start_col += 1;
2527
2528
2529
2530
		    } else {
			/* There is no end on this line.  But we haven't yet
			 * looked for one on later lines. */
			end_line = fileptr->next;
2531

2532
			while (end_line != NULL &&
2533
				regexec(varnish->end, end_line->data,
2534
				0, NULL, 0) == REG_NOMATCH)
2535
			    end_line = end_line->next;
2536

2537
2538
2539
			/* If there is no end, we're done on this line. */
			if (end_line == NULL)
			    break;
2540

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

			/* Paint the rest of the line. */
			mvwaddnstr(edit, line, x_start, converted + index, -1);
2545
			fileptr->multidata[varnish->id] = CENDAFTER;
2546
#ifdef DEBUG
2547
    fprintf(stderr, "  Marking for id %i  line %i as CENDAFTER\n", varnish->id, line);
2548
#endif
2549
2550
2551
			/* We've painted to the end of the line, so don't
			 * bother checking for any more starts. */
			break;
2552
		    }
2553
2554
		}
	    }
2555
  tail_of_loop:
2556
	    wattroff(edit, varnish->attributes);
2557
	}
2558
    }
2559
#endif /* !DISABLE_COLOR */
2560

2561
#ifndef NANO_TINY
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
    /* 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. */
2573
	int x_start;
2574
	    /* The starting column for mvwaddnstr().  Zero-based. */
2575
	int paintlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2576
2577
	    /* Number of characters to paint on this line.  There are
	     * COLS characters on a whole line. */
2578
	size_t index;
2579
	    /* Index in converted where we paint. */
2580

2581
	mark_order(&top, &top_x, &bot, &bot_x, NULL);
2582
2583
2584
2585
2586

	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
2587

2588
	/* Only paint if the marked bit of fileptr is on this page. */
2589
2590
	if (top_x < endpos && bot_x > startpos) {
	    assert(startpos <= top_x);
2591
2592
2593
2594

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

2596
2597
2598
2599
2600
	    /* 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. */
2601
2602
2603
	    if (bot_x >= endpos)
		paintlen = -1;
	    else
2604
		paintlen = strnlenpt(fileptr->data, bot_x) - (x_start + start);
2605
2606
2607
2608
2609
2610
2611
2612

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

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

2616
	    index = actual_x(converted, x_start);
2617

2618
2619
2620
	    if (paintlen > 0)
		paintlen = actual_x(converted + index, paintlen);

2621
	    wattron(edit, hilite_attribute);
2622
	    mvwaddnstr(edit, line, x_start, converted + index, paintlen);
2623
	    wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
2624
	}
2625
    }
2626
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
2627
2628
}

2629
/* Just update one line in the edit buffer.  This is basically a wrapper
2630
 * for edit_draw().  The line will be displayed starting with
2631
 * fileptr->data[index].  Likely arguments are current_x or zero.
2632
 * Returns: Number of additional lines consumed (needed for SOFTWRAP). */
2633
int update_line(filestruct *fileptr, size_t index)
Chris Allegretta's avatar
Chris Allegretta committed
2634
{
2635
    int line = 0;
2636
	/* The line in the edit window that we want to update. */
2637
    int extralinesused = 0;
2638
2639
2640
2641
    char *converted;
	/* fileptr->data converted to have tabs and control characters
	 * expanded. */
    size_t page_start;
Chris Allegretta's avatar
Chris Allegretta committed
2642

2643
    assert(fileptr != NULL);
2644

2645
#ifndef NANO_TINY
2646
    if (ISSET(SOFTWRAP)) {
2647
2648
	filestruct *tmp;

2649
2650
	for (tmp = openfile->edittop; tmp && tmp != fileptr; tmp = tmp->next)
	    line += (strlenpt(tmp->data) / COLS) + 1;
2651
    } else
2652
#endif
2653
2654
	line = fileptr->lineno - openfile->edittop->lineno;

2655
    if (line < 0 || line >= editwinrows)
Chris Allegretta's avatar
Chris Allegretta committed
2656
	return 1;
2657

2658
    /* First, blank out the line. */
2659
    blank_line(edit, line, 0, COLS);
2660

2661
2662
    /* Next, convert variables that index the line to their equivalent
     * positions in the expanded line. */
2663
#ifndef NANO_TINY
2664
2665
2666
    if (ISSET(SOFTWRAP))
	index = 0;
    else
2667
#endif
2668
	index = strnlenpt(fileptr->data, index);
2669
    page_start = get_page_start(index);
2670

2671
2672
    /* Expand the line, replacing tabs with spaces, and control
     * characters with their displayed forms. */
2673
2674
2675
#ifdef NANO_TINY
    converted = display_string(fileptr->data, page_start, COLS, TRUE);
#else
2676
2677
2678
    converted = display_string(fileptr->data, page_start, COLS, !ISSET(SOFTWRAP));
#ifdef DEBUG
    if (ISSET(SOFTWRAP) && strlen(converted) >= COLS - 2)
2679
	fprintf(stderr, "update_line(): converted(1) line = %s\n", converted);
2680
#endif
2681
#endif /* !NANO_TINY */
2682

2683
    /* Paint the line. */
2684
    edit_draw(fileptr, converted, line, page_start);
2685
    free(converted);
Chris Allegretta's avatar
Chris Allegretta committed
2686

2687
#ifndef NANO_TINY
2688
    if (!ISSET(SOFTWRAP)) {
2689
#endif
2690
2691
2692
2693
	if (page_start > 0)
	    mvwaddch(edit, line, 0, '$');
	if (strlenpt(fileptr->data) > page_start + COLS)
	    mvwaddch(edit, line, COLS - 1, '$');
2694
#ifndef NANO_TINY
2695
    } else {
2696
	size_t full_length = strlenpt(fileptr->data);
2697
	for (index += COLS; index <= full_length && line < editwinrows - 1; index += COLS) {
2698
2699
	    line++;
#ifdef DEBUG
2700
	    fprintf(stderr, "update_line(): softwrap code, moving to %d index %lu\n", line, (unsigned long)index);
2701
#endif
2702
	    blank_line(edit, line, 0, COLS);
2703
2704

	    /* Expand the line, replacing tabs with spaces, and control
2705
	     * characters with their displayed forms. */
2706
2707
2708
2709
2710
	    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
2711
2712
2713

	    /* Paint the line. */
	    edit_draw(fileptr, converted, line, index);
2714
	    free(converted);
2715
2716
2717
	    extralinesused++;
	}
    }
2718
#endif /* !NANO_TINY */
2719
    return extralinesused;
Chris Allegretta's avatar
Chris Allegretta committed
2720
2721
}

2722
2723
2724
/* Check whether old_column and new_column are on different "pages" (or that
 * the mark is on), which means that the relevant line needs to be redrawn. */
bool need_horizontal_scroll(const size_t old_column, const size_t new_column)
2725
{
2726
#ifndef NANO_TINY
2727
2728
2729
    if (openfile->mark_set)
	return TRUE;
    else
2730
#endif
2731
	return (get_page_start(old_column) != get_page_start(new_column));
2732
2733
}

2734
/* When edittop changes, try and figure out how many lines
2735
 * we really have to work with (i.e. set maxrows). */
2736
2737
2738
2739
2740
void compute_maxrows(void)
{
    int n;
    filestruct *foo = openfile->edittop;

2741
2742
2743
2744
2745
    if (!ISSET(SOFTWRAP)) {
	maxrows = editwinrows;
	return;
    }

2746
2747
    maxrows = 0;
    for (n = 0; n < editwinrows && foo; n++) {
2748
	maxrows++;
2749
	n += strlenpt(foo->data) / COLS;
2750
2751
2752
	foo = foo->next;
    }

2753
2754
2755
    if (n < editwinrows)
	maxrows += editwinrows - n;

2756
#ifdef DEBUG
2757
    fprintf(stderr, "compute_maxrows(): maxrows = %d\n", maxrows);
2758
2759
2760
#endif
}

2761
2762
/* 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
2763
2764
 * scrolling.  direction is the direction to scroll, either UPWARD or
 * DOWNWARD, and nlines is the number of lines to scroll.  We change
2765
2766
 * edittop, and assume that current and current_x are up to date.  We
 * also assume that scrollok(edit) is FALSE. */
2767
void edit_scroll(scroll_dir direction, ssize_t nlines)
2768
{
2769
    ssize_t i;
2770
    filestruct *foo;
2771

2772
    assert(nlines > 0);
2773

2774
2775
2776
    /* Part 1: nlines is the number of lines we're going to scroll the
     * text of the edit window. */

2777
    /* Move the top line of the edit window up or down (depending on the
2778
2779
     * value of direction) nlines lines, or as many lines as we can if
     * there are fewer than nlines lines available. */
2780
    for (i = nlines; i > 0; i--) {
2781
	if (direction == UPWARD) {
2782
	    if (openfile->edittop == openfile->fileage)
2783
		break;
2784
	    openfile->edittop = openfile->edittop->prev;
2785
	} else {
2786
	    if (openfile->edittop == openfile->filebot)
2787
		break;
2788
	    openfile->edittop = openfile->edittop->next;
2789
	}
2790
2791

#ifndef NANO_TINY
2792
	/* Don't over-scroll on long lines. */
2793
	if (ISSET(SOFTWRAP) && direction == UPWARD) {
2794
	    ssize_t len = strlenpt(openfile->edittop->data) / COLS;
2795
	    i -= len;
2796
	    if (len > 0)
2797
		refresh_needed = TRUE;
2798
	}
2799
#endif
2800
2801
    }

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

2805
2806
2807
2808
    /* Don't bother scrolling zero lines, nor more than the window can hold. */
    if (nlines == 0)
	return;
    if (nlines >= editwinrows)
2809
	refresh_needed = TRUE;
2810

2811
    if (refresh_needed == TRUE)
2812
	return;
2813
2814
2815

    /* Scroll the text of the edit window up or down nlines lines,
     * depending on the value of direction. */
2816
    scrollok(edit, TRUE);
2817
    wscrl(edit, (direction == UPWARD) ? -nlines : nlines);
2818
2819
    scrollok(edit, FALSE);

2820
2821
2822
    /* Part 2: nlines is the number of lines in the scrolled region of
     * the edit window that we need to draw. */

2823
2824
2825
2826
2827
2828
    /* 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
2829

2830
2831
    if (nlines > editwinrows)
	nlines = editwinrows;
2832
2833
2834

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

2837
2838
    /* If we scrolled down, move down to the line before the scrolled
     * region. */
2839
    if (direction == DOWNWARD) {
2840
	for (i = editwinrows - nlines; i > 0 && foo != NULL; i--)
2841
2842
2843
	    foo = foo->next;
    }

2844
2845
2846
2847
2848
2849
    /* 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--) {
2850
2851
	if ((i == nlines && direction == DOWNWARD) || (i == 1 &&
		direction == UPWARD)) {
2852
	    if (need_horizontal_scroll(openfile->placewewant, 0))
2853
2854
2855
2856
		update_line(foo, (foo == openfile->current) ?
			openfile->current_x : 0);
	} else
	    update_line(foo, (foo == openfile->current) ?
2857
		openfile->current_x : 0);
2858
	foo = foo->next;
2859
    }
2860
    compute_maxrows();
2861
2862
2863
}

/* Update any lines between old_current and current that need to be
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2864
 * updated.  Use this if we've moved without changing any text. */
2865
void edit_redraw(filestruct *old_current)
2866
{
2867
2868
2869
2870
    size_t was_pww = openfile->placewewant;

    openfile->placewewant = xplustabs();

2871
2872
    /* If the current line is offscreen, scroll until it's onscreen. */
    if (openfile->current->lineno >= openfile->edittop->lineno + maxrows ||
2873
		openfile->current->lineno < openfile->edittop->lineno) {
2874
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : FLOWING);
2875
	refresh_needed = TRUE;
2876
    }
2877

2878
#ifndef NANO_TINY
2879
2880
2881
    /* If the mark is on, update all lines between old_current and current. */
    if (openfile->mark_set) {
	filestruct *foo = old_current;
2882

2883
	while (foo != openfile->current) {
2884
	    update_line(foo, 0);
2885

2886
2887
2888
	    foo = (foo->lineno > openfile->current->lineno) ?
			foo->prev : foo->next;
	}
2889
2890
2891
2892
2893
2894
    } 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);
2895
2896
2897

    /* Update current if we've changed page, or if it differs from
     * old_current and needs to be horizontally scrolled. */
2898
    if (need_horizontal_scroll(was_pww, openfile->placewewant) ||
2899
			(old_current != openfile->current &&
2900
			get_page_start(openfile->placewewant) > 0))
2901
	update_line(openfile->current, openfile->current_x);
2902
2903
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2904
2905
/* 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
2906
2907
void edit_refresh(void)
{
2908
    filestruct *foo;
2909
    int nlines;
2910

2911
    /* Figure out what maxrows should really be. */
2912
    compute_maxrows();
2913

2914
2915
    if (openfile->current->lineno < openfile->edittop->lineno ||
	openfile->current->lineno >= openfile->edittop->lineno +
2916
2917
	maxrows) {
#ifdef DEBUG
2918
2919
	fprintf(stderr, "edit_refresh(): line = %ld, edittop %ld + maxrows %d\n",
		(long)openfile->current->lineno, (long)openfile->edittop->lineno, maxrows);
2920
2921
#endif

2922
	/* Make sure the current line is on the screen. */
2923
	edit_update((focusing || !ISSET(SMOOTH_SCROLL)) ? CENTERING : STATIONARY);
2924
    }
Chris Allegretta's avatar
Chris Allegretta committed
2925

2926
2927
    foo = openfile->edittop;

2928
#ifdef DEBUG
2929
    fprintf(stderr, "edit_refresh(): edittop->lineno = %ld\n", (long)openfile->edittop->lineno);
2930
#endif
2931

2932
    for (nlines = 0; nlines < editwinrows && foo != NULL; nlines++) {
2933
	nlines += update_line(foo, (foo == openfile->current) ?
2934
		openfile->current_x : 0);
2935
2936
2937
	foo = foo->next;
    }

2938
    for (; nlines < editwinrows; nlines++)
2939
2940
2941
	blank_line(edit, nlines, 0, COLS);

    reset_cursor();
2942
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2943
2944
}

2945
2946
2947
2948
2949
2950
/* 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
2951
{
2952
    int goal = 0;
2953

2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
    /* 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)
2964
	goal = editwinrows / 2;
2965
    else if (manner == FLOWING) {
2966
	if (openfile->current->lineno >= openfile->edittop->lineno)
2967
2968
	    goal = editwinrows - 1;
    } else {
2969
	goal = openfile->current_y;
2970

2971
	/* Limit goal to (editwinrows - 1) lines maximum. */
2972
2973
	if (goal > editwinrows - 1)
	    goal = editwinrows - 1;
Chris Allegretta's avatar
Chris Allegretta committed
2974
    }
2975

2976
2977
2978
2979
2980
    openfile->edittop = openfile->current;

    while (goal > 0 && openfile->edittop->prev != NULL) {
	openfile->edittop = openfile->edittop->prev;
	goal --;
2981
#ifndef NANO_TINY
2982
2983
	if (ISSET(SOFTWRAP))
	    goal -= strlenpt(openfile->edittop->data) / COLS;
2984
#endif
2985
    }
2986
#ifdef DEBUG
2987
    fprintf(stderr, "edit_update(): setting edittop to lineno %ld\n", (long)openfile->edittop->lineno);
2988
#endif
2989
    compute_maxrows();
Chris Allegretta's avatar
Chris Allegretta committed
2990
2991
}

2992
/* Unconditionally redraw the entire screen. */
2993
void total_redraw(void)
2994
{
2995
2996
2997
2998
2999
3000
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 4: Slang doesn't define
     * curscr. */
    SLsmg_touch_screen();
    SLsmg_refresh();
#else
3001
    wrefresh(curscr);
3002
#endif
3003
3004
}

3005
3006
/* Unconditionally redraw the entire screen, and then refresh it using
 * the current file. */
3007
3008
void total_refresh(void)
{
3009
    total_redraw();
3010
    titlebar(NULL);
3011
    edit_refresh();
3012
    bottombars(currmenu);
3013
3014
}

3015
3016
/* Display the main shortcut list on the last two rows of the bottom
 * portion of the window. */
3017
3018
void display_main_list(void)
{
3019
#ifndef DISABLE_COLOR
3020
3021
    if (openfile->syntax &&
		(openfile->syntax->formatter || openfile->syntax->linter))
3022
	set_lint_or_format_shortcuts();
3023
3024
3025
3026
    else
	set_spell_shortcuts();
#endif

3027
    bottombars(MMAIN);
3028
3029
}

3030
/* If constant is TRUE, we display the current cursor position only if
3031
3032
 * suppress_cursorpos is FALSE.  If constant is FALSE, we display the
 * position always.  In any case we reset suppress_cursorpos to FALSE. */
3033
void do_cursorpos(bool constant)
Chris Allegretta's avatar
Chris Allegretta committed
3034
{
3035
    filestruct *f;
3036
    char c;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3037
    size_t i, cur_xpt = xplustabs() + 1;
3038
    size_t cur_lenpt = strlenpt(openfile->current->data) + 1;
3039
    int linepct, colpct, charpct;
Chris Allegretta's avatar
Chris Allegretta committed
3040

3041
    assert(openfile->fileage != NULL && openfile->current != NULL);
3042

3043
    /* Determine the size of the file up to the cursor. */
3044
    f = openfile->current->next;
3045
    c = openfile->current->data[openfile->current_x];
3046
3047

    openfile->current->next = NULL;
3048
    openfile->current->data[openfile->current_x] = '\0';
3049
3050
3051

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

3052
    openfile->current->data[openfile->current_x] = c;
3053
    openfile->current->next = f;
3054

3055
    /* If the position needs to be suppressed, don't suppress it next time. */
3056
    if (suppress_cursorpos && constant) {
3057
	suppress_cursorpos = FALSE;
3058
	return;
3059
    }
Chris Allegretta's avatar
Chris Allegretta committed
3060

3061
    /* Display the current cursor position on the statusbar. */
3062
    linepct = 100 * openfile->current->lineno / openfile->filebot->lineno;
3063
    colpct = 100 * cur_xpt / cur_lenpt;
3064
    charpct = (openfile->totsize == 0) ? 0 : 100 * i / openfile->totsize;
3065

3066
    statusline(HUSH,
3067
	_("line %ld/%ld (%d%%), col %lu/%lu (%d%%), char %lu/%lu (%d%%)"),
3068
	(long)openfile->current->lineno,
3069
	(long)openfile->filebot->lineno, linepct,
3070
	(unsigned long)cur_xpt, (unsigned long)cur_lenpt, colpct,
3071
	(unsigned long)i, (unsigned long)openfile->totsize, charpct);
3072
3073
3074

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

3077
/* Unconditionally display the current cursor position. */
3078
void do_cursorpos_void(void)
3079
{
3080
    do_cursorpos(FALSE);
3081
3082
}

3083
3084
void enable_nodelay(void)
{
3085
3086
    nodelay_mode = TRUE;
    nodelay(edit, TRUE);
3087
3088
3089
3090
}

void disable_nodelay(void)
{
3091
3092
    nodelay_mode = FALSE;
    nodelay(edit, FALSE);
3093
3094
}

3095
3096
/* Highlight the current word being replaced or spell checked.  We
 * expect word to have tabs and control characters expanded. */
3097
void spotlight(bool active, const char *word)
Chris Allegretta's avatar
Chris Allegretta committed
3098
{
3099
    size_t word_len = strlenpt(word), room;
Chris Allegretta's avatar
Chris Allegretta committed
3100

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

3104
    assert(room > 0);
3105

3106
3107
    if (word_len > room)
	room--;
3108

Chris Allegretta's avatar
Chris Allegretta committed
3109
    reset_cursor();
3110
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
3111

3112
    if (active)
3113
	wattron(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3114

3115
    /* This is so we can show zero-length matches. */
3116
    if (word_len == 0)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3117
	waddch(edit, ' ');
3118
    else
3119
	waddnstr(edit, word, actual_x(word, room));
3120

3121
    if (word_len > room)
3122
	waddch(edit, '$');
Chris Allegretta's avatar
Chris Allegretta committed
3123

3124
    if (active)
3125
	wattroff(edit, hilite_attribute);
Chris Allegretta's avatar
Chris Allegretta committed
3126
3127
}

3128
#ifndef DISABLE_EXTRA
3129
3130
#define CREDIT_LEN 54
#define XLCREDIT_LEN 9
3131

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3132
3133
/* Easter egg: Display credits.  Assume nodelay(edit) and scrollok(edit)
 * are FALSE. */
3134
3135
void do_credits(void)
{
3136
3137
    bool old_more_space = ISSET(MORE_SPACE);
    bool old_no_help = ISSET(NO_HELP);
3138
    int kbinput = ERR, crpos = 0, xlpos = 0;
3139
3140
3141
    const char *credits[CREDIT_LEN] = {
	NULL,				/* "The nano text editor" */
	NULL,				/* "version" */
Chris Allegretta's avatar
Chris Allegretta committed
3142
3143
	VERSION,
	"",
3144
	NULL,				/* "Brought to you by:" */
Chris Allegretta's avatar
Chris Allegretta committed
3145
3146
3147
3148
3149
	"Chris Allegretta",
	"Jordi Mallach",
	"Adam Rogoyski",
	"Rob Siemborski",
	"Rocco Corsi",
3150
	"David Lawrence Ramsey",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3151
	"David Benbennick",
Benno Schulenberg's avatar
Benno Schulenberg committed
3152
	"Mark Majeres",
3153
	"Mike Frysinger",
3154
	"Benno Schulenberg",
Chris Allegretta's avatar
Chris Allegretta committed
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
	"Ken Tyler",
	"Sven Guckes",
	"Bill Soudan",
	"Christian Weisgerber",
	"Erik Andersen",
	"Big Gaute",
	"Joshua Jensen",
	"Ryan Krebs",
	"Albert Chin",
	"",
3165
	NULL,				/* "Special thanks to:" */
3166
	"Monique, Brielle & Joseph",
Chris Allegretta's avatar
Chris Allegretta committed
3167
3168
3169
3170
3171
3172
	"Plattsburgh State University",
	"Benet Laboratories",
	"Amy Allegretta",
	"Linda Young",
	"Jeremy Robichaud",
	"Richard Kolb II",
3173
	NULL,				/* "The Free Software Foundation" */
Chris Allegretta's avatar
Chris Allegretta committed
3174
	"Linus Torvalds",
3175
	NULL,				/* "the many translators and the TP" */
3176
	NULL,				/* "For ncurses:" */
3177
3178
3179
3180
	"Thomas Dickey",
	"Pavel Curtis",
	"Zeyd Ben-Halim",
	"Eric S. Raymond",
3181
3182
3183
3184
3185
3186
	NULL,				/* "and anyone else we forgot..." */
	NULL,				/* "Thank you for using nano!" */
	"",
	"",
	"",
	"",
3187
	"(C) 1999 - 2016",
3188
	"Free Software Foundation, Inc.",
3189
3190
3191
3192
	"",
	"",
	"",
	"",
3193
	"https://nano-editor.org/"
3194
3195
    };

3196
    const char *xlcredits[XLCREDIT_LEN] = {
3197
3198
3199
3200
3201
	N_("The nano text editor"),
	N_("version"),
	N_("Brought to you by:"),
	N_("Special thanks to:"),
	N_("The Free Software Foundation"),
3202
	N_("the many translators and the TP"),
3203
3204
3205
	N_("For ncurses:"),
	N_("and anyone else we forgot..."),
	N_("Thank you for using nano!")
3206
    };
3207

3208
3209
3210
3211
3212
3213
    if (!old_more_space || !old_no_help) {
	SET(MORE_SPACE);
	SET(NO_HELP);
	window_init();
    }

3214
3215
    curs_set(0);
    nodelay(edit, TRUE);
3216

3217
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
3218
    blank_edit();
3219
    blank_statusbar();
3220

3221
    wrefresh(topwin);
Chris Allegretta's avatar
Chris Allegretta committed
3222
    wrefresh(edit);
3223
    wrefresh(bottomwin);
3224
    napms(700);
3225

3226
    for (crpos = 0; crpos < CREDIT_LEN + editwinrows / 2; crpos++) {
3227
	if ((kbinput = wgetch(edit)) != ERR)
3228
	    break;
3229

3230
	if (crpos < CREDIT_LEN) {
3231
	    const char *what;
3232
3233
	    size_t start_x;

3234
	    if (credits[crpos] == NULL) {
3235
		assert(0 <= xlpos && xlpos < XLCREDIT_LEN);
3236

3237
		what = _(xlcredits[xlpos]);
3238
		xlpos++;
3239
	    } else
3240
		what = credits[crpos];
3241

3242
	    start_x = COLS / 2 - strlenpt(what) / 2 - 1;
3243
3244
	    mvwaddstr(edit, editwinrows - 1 - (editwinrows % 2),
		start_x, what);
3245
	}
3246

3247
3248
3249
3250
	wrefresh(edit);

	if ((kbinput = wgetch(edit)) != ERR)
	    break;
3251
	napms(700);
3252

3253
	scrollok(edit, TRUE);
3254
	wscrl(edit, 1);
3255
	scrollok(edit, FALSE);
3256
	wrefresh(edit);
3257

3258
	if ((kbinput = wgetch(edit)) != ERR)
3259
	    break;
3260
	napms(700);
3261

3262
	scrollok(edit, TRUE);
3263
	wscrl(edit, 1);
3264
	scrollok(edit, FALSE);
3265
	wrefresh(edit);
3266
3267
    }

3268
3269
3270
    if (kbinput != ERR)
	ungetch(kbinput);

3271
    if (!old_more_space)
3272
	UNSET(MORE_SPACE);
3273
    if (!old_no_help)
3274
	UNSET(NO_HELP);
3275
    window_init();
3276

3277
    nodelay(edit, FALSE);
3278

3279
    total_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
3280
}
3281
#endif /* !DISABLE_EXTRA */