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

24
#include "proto.h"
25

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

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

47
48
49
50
51
52
53
54
55
56
57
58
/* Control character compatibility:
 *
 * - NANO_BACKSPACE_KEY is Ctrl-H, which is Backspace under ASCII, ANSI,
 *   VT100, and VT220.
 * - NANO_TAB_KEY is Ctrl-I, which is Tab under ASCII, ANSI, VT100,
 *   VT220, and VT320.
 * - NANO_ENTER_KEY is Ctrl-M, which is Enter under ASCII, ANSI, VT100,
 *   VT220, and VT320.
 * - NANO_XON_KEY is Ctrl-Q, which is XON under ASCII, ANSI, VT100,
 *   VT220, and VT320.
 * - NANO_XOFF_KEY is Ctrl-S, which is XOFF under ASCII, ANSI, VT100,
 *   VT220, and VT320.
59
 * - NANO_CONTROL_8 is Ctrl-8 (Ctrl-?), which is Delete under ASCII,
60
61
 *   ANSI, VT100, and VT220, and which is Backspace under VT320.
 *
62
 * Note: VT220 and VT320 also generate Esc [ 3 ~ for Delete.  By
63
64
 * default, xterm assumes it's running on a VT320 and generates Ctrl-8
 * (Ctrl-?) for Backspace and Esc [ 3 ~ for Delete.  This causes
65
 * problems for VT100-derived terminals such as the FreeBSD console,
66
 * which expect Ctrl-H for Backspace and Ctrl-8 (Ctrl-?) for Delete, and
67
68
69
70
71
72
73
74
75
 * 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
76
 * console, the FreeBSD console, the Mach console (a.k.a. the Hurd
77
78
79
80
81
82
83
84
 * console), xterm, rxvt, and Eterm.  Among these, there are several
 * conflicts and omissions, outlined as follows:
 *
 * - 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
85
 *   keypad key, because the latter has no value when NumLock is off.)
86
87
88
89
 * - 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.)
90
 * - F9 on FreeBSD console == PageDown on Mach console; the former is
91
92
93
 *   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.)
94
 * - F10 on FreeBSD console == PageUp on Mach console; the former is
95
 *   omitted.  (Same as above.)
96
 * - F13 on FreeBSD console == End on Mach console; the former is
97
 *   omitted.  (Same as above.)
98
99
100
101
102
103
104
 * - F15 on FreeBSD console == Shift-Up on rxvt/Eterm; the former is
 *   omitted.  (The arrow keys, with or without modifiers, are more
 *   important to have working than the function keys, because the
 *   functions of the former are not arbitrary and the functions of the
 *   latter are.)
 * - F16 on FreeBSD console == Shift-Down on rxvt/Eterm; the former is
 *   omitted.  (Same as above.)
105
106
107
 *
 * Note that Center (5) on the numeric keypad with NumLock off can also
 * be the Begin key. */
108

109
#ifndef NANO_TINY
110
111
112
/* Reset all the input routines that rely on character sequences. */
void reset_kbinput(void)
{
113
    parse_kbinput(NULL, NULL, NULL, TRUE);
114
    get_byte_kbinput(0, TRUE);
115
    get_unicode_kbinput(0, TRUE);
116
117
118
}
#endif

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

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

    /* Read in the first character using blocking input. */
132
#ifndef NANO_TINY
133
134
    allow_pending_sigwinch(TRUE);
#endif
135

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

140
    errcount = 0;
141
    while ((input = wgetch(win)) == ERR) {
142
143
	errcount++;

144
145
	/* If we've failed to get a character MAX_BUF_SIZE times in a
	 * row, assume that the input source we were using is gone and
146
147
148
	 * die gracefully.  We could check if errno is set to EIO
	 * ("Input/output error") and die gracefully in that case, but
	 * it's not always set properly.  Argh. */
149
	if (errcount == MAX_BUF_SIZE)
150
151
	    handle_hupterm(0);
    }
152

153
#ifndef NANO_TINY
154
155
    allow_pending_sigwinch(FALSE);
#endif
156

157
158
    /* Increment the length of the keystroke buffer, save the value of
     * the keystroke in key, and set key_code to TRUE if the keystroke
159
     * is an extended keypad value or FALSE if it isn't. */
160
    key_buffer_len++;
161
162
    key_buffer = (int *)nmalloc(sizeof(int));
    key_buffer[0] = input;
163

164
165
166
167
    /* Read in the remaining characters using non-blocking input. */
    nodelay(win, TRUE);

    while (TRUE) {
168
#ifndef NANO_TINY
169
	allow_pending_sigwinch(TRUE);
170
#endif
171

172
	input = wgetch(win);
173

174
	/* If there aren't any more characters, stop reading. */
175
	if (input == ERR)
176
177
178
179
	    break;

	/* Otherwise, increment the length of the keystroke buffer, save
	 * the value of the keystroke in key, and set key_code to TRUE
180
181
	 * if the keystroke is an extended keypad value or FALSE if it
	 * isn't. */
182
	key_buffer_len++;
183
184
185
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
	key_buffer[key_buffer_len - 1] = input;
186

187
#ifndef NANO_TINY
188
189
	allow_pending_sigwinch(FALSE);
#endif
190
191
192
193
    }

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

#ifdef DEBUG
196
    fprintf(stderr, "get_key_buffer(): key_buffer_len = %lu\n", (unsigned long)key_buffer_len);
197
#endif
198
}
199

200
/* Return the length of the default keystroke buffer. */
201
size_t get_key_buffer_len(void)
202
203
204
205
206
207
{
    return key_buffer_len;
}

/* Add the contents of the keystroke buffer input to the default
 * keystroke buffer. */
208
void unget_input(int *input, size_t input_len)
209
{
210
#ifndef NANO_TINY
211
212
    allow_pending_sigwinch(TRUE);
    allow_pending_sigwinch(FALSE);
213
#endif
214

215
    /* If input is empty, get out. */
216
    if (input_len == 0)
217
218
219
220
221
	return;

    /* If adding input would put the default keystroke buffer beyond
     * maximum capacity, only add enough of input to put it at maximum
     * capacity. */
222
223
    if (key_buffer_len + input_len < key_buffer_len)
	input_len = (size_t)-1 - key_buffer_len;
224
225
226
227

    /* Add the length of input to the length of the default keystroke
     * buffer, and reallocate the default keystroke buffer so that it
     * has enough room for input. */
228
229
230
    key_buffer_len += input_len;
    key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
	sizeof(int));
231
232
233
234

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

    /* Copy input to the beginning of the default keystroke buffer. */
240
    memcpy(key_buffer, input, input_len * sizeof(int));
241
242
}

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

252
    unget_input(&kbinput, 1);
253
254

    if (meta_key) {
255
256
	kbinput = NANO_CONTROL_3;
	unget_input(&kbinput, 1);
257
258
259
260
261
262
263
264
    }
}

/* Try to read input_len characters from the default keystroke buffer.
 * If the default keystroke buffer is empty and win isn't NULL, try to
 * read in more characters from win and add them to the default
 * keystroke buffer before doing anything else.  If the default
 * keystroke buffer is empty and win is NULL, return NULL. */
265
int *get_input(WINDOW *win, size_t input_len)
266
{
267
    int *input;
268

269
#ifndef NANO_TINY
270
    allow_pending_sigwinch(TRUE);
271
272
273
    allow_pending_sigwinch(FALSE);
#endif

274
275
    if (key_buffer_len == 0) {
	if (win != NULL)
276
	    get_key_buffer(win);
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

	if (key_buffer_len == 0)
	    return NULL;
    }

    /* If input_len is greater than the length of the default keystroke
     * buffer, only read the number of characters in the default
     * keystroke buffer. */
    if (input_len > key_buffer_len)
	input_len = key_buffer_len;

    /* Subtract input_len from the length of the default keystroke
     * buffer, and allocate the keystroke buffer input so that it
     * has enough room for input_len keystrokes. */
    key_buffer_len -= input_len;
292
    input = (int *)nmalloc(input_len * sizeof(int));
293
294
295

    /* Copy input_len characters from the beginning of the default
     * keystroke buffer into input. */
296
    memcpy(input, key_buffer, input_len * sizeof(int));
297
298
299
300
301
302

    /* If the default keystroke buffer is empty, mark it as such. */
    if (key_buffer_len == 0) {
	free(key_buffer);
	key_buffer = NULL;
    /* If the default keystroke buffer isn't empty, move its
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
303
304
     * beginning forward far enough so that the keystrokes in input are
     * no longer at its beginning. */
305
306
    } else {
	memmove(key_buffer, key_buffer + input_len, key_buffer_len *
307
308
309
		sizeof(int));
	key_buffer = (int *)nrealloc(key_buffer, key_buffer_len *
		sizeof(int));
310
311
312
    }

    return input;
313
314
}

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/* Read in a single character.  If it's ignored, swallow it and go on.
 * Otherwise, try to translate it from ASCII, meta key sequences, escape
 * sequences, and/or extended keypad values.  Set meta_key to TRUE when
 * we get a meta key sequence, and set func_key to TRUE when we get an
 * extended keypad value.  Supported extended keypad values consist of
 * [arrow key], Ctrl-[arrow key], Shift-[arrow key], Enter, Backspace,
 * the editing keypad (Insert, Delete, Home, End, PageUp, and PageDown),
 * the function keypad (F1-F16), and the numeric keypad with NumLock
 * off.  Assume nodelay(win) is FALSE. */
int get_kbinput(WINDOW *win, bool *meta_key, bool *func_key)
{
    int kbinput;

    /* Read in a character and interpret it.  Continue doing this until
     * we get a recognized value or sequence. */
    while ((kbinput = parse_kbinput(win, meta_key, func_key
331
#ifndef NANO_TINY
332
333
334
335
336
337
338
339
340
341
342
343
		, FALSE
#endif
		)) == ERR);

    return kbinput;
}

/* Translate ASCII characters, extended keypad values, and escape
 * sequences into their corresponding key values.  Set meta_key to TRUE
 * when we get a meta key sequence, and set func_key to TRUE when we get
 * a function key.  Assume nodelay(win) is FALSE. */
int parse_kbinput(WINDOW *win, bool *meta_key, bool *func_key
344
#ifndef NANO_TINY
345
	, bool reset
346
347
#endif
	)
348

349
{
350
    static int escapes = 0, byte_digits = 0;
351
    int *kbinput, retval = ERR;
352

353
#ifndef NANO_TINY
354
355
    if (reset) {
	escapes = 0;
356
	byte_digits = 0;
357
	return ERR;
358
    }
359
#endif
360

361
362
    *meta_key = FALSE;
    *func_key = FALSE;
363

364
365
366
    /* Read in a character. */
    while ((kbinput = get_input(win, 1)) == NULL);

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    switch (*kbinput) {
	case ERR:
	    break;
	case NANO_CONTROL_3:
	    /* Increment the escape counter. */
	    escapes++;
	    switch (escapes) {
		case 1:
		    /* One escape: wait for more input. */
		case 2:
		    /* Two escapes: wait for more input. */
		    break;
		default:
		    /* More than two escapes: reset the escape counter
		     * and wait for more input. */
		    escapes = 0;
	    }
	    break;
385
#if !defined(NANO_TINY) && defined(KEY_RESIZE)
386
	/* Since we don't change the default SIGWINCH handler when
387
	 * NANO_TINY is defined, KEY_RESIZE is never generated.  Also,
388
389
390
	 * Slang and SunOS 5.7-5.9 don't support KEY_RESIZE. */
	case KEY_RESIZE:
	    break;
391
392
#endif
#ifdef PDCURSES
393
394
395
396
397
398
399
	case KEY_SHIFT_L:
	case KEY_SHIFT_R:
	case KEY_CONTROL_L:
	case KEY_CONTROL_R:
	case KEY_ALT_L:
	case KEY_ALT_R:
	    break;
400
#endif
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
	default:
	    switch (escapes) {
		case 0:
		    switch (*kbinput) {
			case NANO_CONTROL_8:
			    retval = ISSET(REBIND_DELETE) ?
				NANO_DELETE_KEY : NANO_BACKSPACE_KEY;
			    break;
			case KEY_DOWN:
			    retval = NANO_NEXTLINE_KEY;
			    break;
			case KEY_UP:
			    retval = NANO_PREVLINE_KEY;
			    break;
			case KEY_LEFT:
			    retval = NANO_BACK_KEY;
			    break;
			case KEY_RIGHT:
			    retval = NANO_FORWARD_KEY;
			    break;
421
#ifdef KEY_HOME
422
423
424
425
			/* HP-UX 10 and 11 don't support KEY_HOME. */
			case KEY_HOME:
			    retval = NANO_HOME_KEY;
			    break;
426
#endif
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
			case KEY_BACKSPACE:
			    retval = NANO_BACKSPACE_KEY;
			    break;
			case KEY_DC:
			    retval = ISSET(REBIND_DELETE) ?
				NANO_BACKSPACE_KEY : NANO_DELETE_KEY;
			    break;
			case KEY_IC:
			    retval = NANO_INSERTFILE_KEY;
			    break;
			case KEY_NPAGE:
			    retval = NANO_NEXTPAGE_KEY;
			    break;
			case KEY_PPAGE:
			    retval = NANO_PREVPAGE_KEY;
			    break;
			case KEY_ENTER:
			    retval = NANO_ENTER_KEY;
			    break;
			case KEY_A1:	/* Home (7) on numeric keypad
					 * with NumLock off. */
			    retval = NANO_HOME_KEY;
			    break;
			case KEY_A3:	/* PageUp (9) on numeric keypad
					 * with NumLock off. */
			    retval = NANO_PREVPAGE_KEY;
			    break;
			case KEY_B2:	/* Center (5) on numeric keypad
					 * with NumLock off. */
			    break;
			case KEY_C1:	/* End (1) on numeric keypad
					 * with NumLock off. */
			    retval = NANO_END_KEY;
			    break;
			case KEY_C3:	/* PageDown (4) on numeric
					 * keypad with NumLock off. */
			    retval = NANO_NEXTPAGE_KEY;
			    break;
465
#ifdef KEY_BEG
466
467
468
469
			/* Slang doesn't support KEY_BEG. */
			case KEY_BEG:	/* Center (5) on numeric keypad
					 * with NumLock off. */
			    break;
470
#endif
471
#ifdef KEY_END
472
473
474
475
			/* HP-UX 10 and 11 don't support KEY_END. */
			case KEY_END:
			    retval = NANO_END_KEY;
			    break;
476
#endif
477
478
479
480
481
482
483
484
485
#ifdef KEY_SBEG
			/* Slang doesn't support KEY_SBEG. */
			case KEY_SBEG:	/* Center (5) on numeric keypad
					 * with NumLock off. */
			    break;
#endif
#ifdef KEY_SDC
			/* Slang doesn't support KEY_SDC. */
			case KEY_SDC:
486
487
			    retval = ISSET(REBIND_DELETE) ?
				NANO_BACKSPACE_KEY : NANO_DELETE_KEY;
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
			    break;
#endif
#ifdef KEY_SEND
			/* HP-UX 10 and 11 don't support KEY_SEND. */
			case KEY_SEND:
			    retval = NANO_END_KEY;
			    break;
#endif
#ifdef KEY_SHOME
			/* HP-UX 10 and 11 and Slang don't support
			 * KEY_SHOME. */
			case KEY_SHOME:
			    retval = NANO_HOME_KEY;
			    break;
#endif
#ifdef KEY_SIC
			/* Slang doesn't support KEY_SIC. */
			case KEY_SIC:
			    retval = NANO_INSERTFILE_KEY;
507
			    break;
508
509
#endif
#ifdef KEY_SLEFT
510
511
512
513
			/* Slang doesn't support KEY_SLEFT. */
			case KEY_SLEFT:
			    retval = NANO_BACK_KEY;
			    break;
514
515
#endif
#ifdef KEY_SRIGHT
516
517
518
519
			/* Slang doesn't support KEY_SRIGHT. */
			case KEY_SRIGHT:
			    retval = NANO_FORWARD_KEY;
			    break;
520
521
522
523
524
525
526
527
528
529
530
531
#endif
#ifdef KEY_SSUSPEND
			/* Slang doesn't support KEY_SSUSPEND. */
			case KEY_SSUSPEND:
			    retval = NANO_SUSPEND_KEY;
			    break;
#endif
#ifdef KEY_SUSPEND
			/* Slang doesn't support KEY_SUSPEND. */
			case KEY_SUSPEND:
			    retval = NANO_SUSPEND_KEY;
			    break;
532
#endif
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
			default:
			    retval = *kbinput;
			    break;
		    }
		    break;
		case 1:
		    /* One escape followed by a non-escape: escape
		     * sequence mode.  Reset the escape counter.  If
		     * there aren't any other keys waiting, we have a
		     * meta key sequence, so set meta_key to TRUE and
		     * save the lowercase version of the non-escape
		     * character as the result.  If there are other keys
		     * waiting, we have a true escape sequence, so
		     * interpret it. */
		    escapes = 0;
548
		    if (get_key_buffer_len() == 0) {
549
550
551
552
553
554
555
556
557
558
559
560
			*meta_key = TRUE;
			retval = tolower(*kbinput);
		    } else {
			int *seq;
			size_t seq_len;
			bool ignore_seq;

			/* Put back the non-escape character, get the
			 * complete escape sequence, translate the
			 * sequence into its corresponding key value,
			 * and save that as the result. */
			unget_input(kbinput, 1);
561
			seq_len = get_key_buffer_len();
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
			seq = get_input(NULL, seq_len);
			retval = get_escape_seq_kbinput(seq, seq_len,
				&ignore_seq);

			/* If the escape sequence is unrecognized and
			 * not ignored, put back all of its characters
			 * except for the initial escape. */
			if (retval == ERR && !ignore_seq)
			    unget_input(seq, seq_len);

			free(seq);
		    }
		    break;
		case 2:
		    /* Two escapes followed by one or more decimal
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
577
		     * digits: byte sequence mode.  If the byte
578
579
580
581
582
583
584
585
586
587
588
589
590
591
		     * sequence's range is limited to 2XX (the first
		     * digit is in the '0' to '2' range and it's the
		     * first digit, or it's in the '0' to '9' range and
		     * it's not the first digit), increment the byte
		     * sequence counter and interpret the digit.  If the
		     * byte sequence's range is not limited to 2XX, fall
		     * through. */
		    if (('0' <= *kbinput && *kbinput <= '6' &&
			byte_digits == 0) || ('0' <= *kbinput &&
			*kbinput <= '9' && byte_digits > 0)) {
			int byte;

			byte_digits++;
			byte = get_byte_kbinput(*kbinput
592
#ifndef NANO_TINY
593
				, FALSE
594
#endif
595
596
				);

597
			if (byte != ERR) {
598
599
600
			    char *byte_mb;
			    int byte_mb_len, *seq, i;

601
602
603
604
605
			    /* If we've read in a complete byte
			     * sequence, reset the byte sequence counter
			     * and the escape counter, and put back the
			     * corresponding byte value. */
			    byte_digits = 0;
606
			    escapes = 0;
607

608
609
			    /* Put back the multibyte equivalent of the
			     * byte value. */
610
611
			    byte_mb = make_mbchar((long)byte,
				&byte_mb_len);
612
613
614
615
616
617
618
619
620
621
622

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

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

			    unget_input(seq, byte_mb_len);

			    free(byte_mb);
			    free(seq);
623
			}
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
		    } else {
			/* Reset the escape counter. */
			escapes = 0;
			if (byte_digits == 0)
			    /* Two escapes followed by a non-decimal
			     * digit or a decimal digit that would
			     * create a byte sequence greater than 2XX,
			     * and we're not in the middle of a byte
			     * sequence: control character sequence
			     * mode.  Interpret the control sequence and
			     * save the corresponding control character
			     * as the result. */
			    retval = get_control_kbinput(*kbinput);
			else {
			    /* If we're in the middle of a byte
			     * sequence, reset the byte sequence counter
			     * and save the character we got as the
			     * result. */
			    byte_digits = 0;
			    retval = *kbinput;
			}
		    }
		    break;
	    }
    }
649

650
651
652
653
    /* If we have a result and it's an extended keypad value (i.e, a
     * value outside of byte range), set func_key to TRUE. */
    if (retval != ERR)
	*func_key = !is_byte(retval);
654
655

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

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

663
/* Translate escape sequences, most of which correspond to extended
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
664
 * keypad values, into their corresponding key values.  These sequences
665
666
667
668
669
 * are generated when the keypad doesn't support the needed keys.  If
 * the escape sequence is recognized but we want to ignore it, return
 * ERR and set ignore_seq to TRUE; if it's unrecognized, return ERR and
 * set ignore_seq to FALSE.  Assume that Escape has already been read
 * in. */
670
int get_escape_seq_kbinput(const int *seq, size_t seq_len, bool
671
	*ignore_seq)
672
{
673
    int retval = ERR;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
674

675
676
    *ignore_seq = FALSE;

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

1164
#ifdef DEBUG
1165
    fprintf(stderr, "get_escape_seq_kbinput(): retval = %d, ignore_seq = %d\n", retval, (int)*ignore_seq);
1166
#endif
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1167

1168
    return retval;
1169
1170
}

1171
/* Return the equivalent arrow key value for the case-insensitive
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1172
 * letters A (up), B (down), C (right), and D (left).  These are common
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
 * to many escape sequences. */
int get_escape_seq_abcd(int kbinput)
{
    switch (tolower(kbinput)) {
	case 'a':
	    return NANO_PREVLINE_KEY;
	case 'b':
	    return NANO_NEXTLINE_KEY;
	case 'c':
	    return NANO_FORWARD_KEY;
	case 'd':
	    return NANO_BACK_KEY;
	default:
	    return ERR;
    }
}

1190
1191
1192
/* Translate a byte sequence: turn a three-digit decimal number from
 * 000 to 255 into its corresponding byte value. */
int get_byte_kbinput(int kbinput
1193
#ifndef NANO_TINY
1194
1195
1196
	, bool reset
#endif
	)
1197
{
1198
    static int byte_digits = 0, byte = 0;
1199
    int retval = ERR;
1200

1201
#ifndef NANO_TINY
1202
    if (reset) {
1203
	byte_digits = 0;
1204
	byte = 0;
1205
1206
	return ERR;
    }
1207
1208
#endif

1209
1210
    /* Increment the byte digit counter. */
    byte_digits++;
1211

1212
    switch (byte_digits) {
1213
	case 1:
1214
1215
	    /* One digit: reset the byte sequence holder and add the
	     * digit we got to the 100's position of the byte sequence
1216
	     * holder. */
1217
	    byte = 0;
1218
	    if ('0' <= kbinput && kbinput <= '2')
1219
		byte += (kbinput - '0') * 100;
1220
1221
	    else
		/* If the character we got isn't a decimal digit, or if
1222
		 * it is and it would put the byte sequence out of byte
1223
1224
1225
1226
		 * range, save it as the result. */
		retval = kbinput;
	    break;
	case 2:
1227
1228
	    /* Two digits: add the digit we got to the 10's position of
	     * the byte sequence holder. */
1229
1230
1231
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 200 &&
		'6' <= kbinput && kbinput <= '9'))
		byte += (kbinput - '0') * 10;
1232
1233
	    else
		/* If the character we got isn't a decimal digit, or if
1234
		 * it is and it would put the byte sequence out of byte
1235
1236
1237
1238
		 * range, save it as the result. */
		retval = kbinput;
	    break;
	case 3:
1239
1240
1241
	    /* Three digits: add the digit we got to the 1's position of
	     * the byte sequence holder, and save the corresponding word
	     * value as the result. */
1242
1243
1244
1245
	    if (('0' <= kbinput && kbinput <= '5') || (byte < 250 &&
		'6' <= kbinput && kbinput <= '9')) {
		byte += (kbinput - '0');
		retval = byte;
1246
	    } else
1247
		/* If the character we got isn't a decimal digit, or if
1248
		 * it is and it would put the byte sequence out of word
1249
1250
1251
		 * range, save it as the result. */
		retval = kbinput;
	    break;
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
	default:
	    /* More than three digits: save the character we got as the
	     * result. */
	    retval = kbinput;
	    break;
    }

    /* If we have a result, reset the byte digit counter and the byte
     * sequence holder. */
    if (retval != ERR) {
	byte_digits = 0;
1263
	byte = 0;
1264
1265
1266
    }

#ifdef DEBUG
1267
    fprintf(stderr, "get_byte_kbinput(): kbinput = %d, byte_digits = %d, byte = %d, retval = %d\n", kbinput, byte_digits, byte, retval);
1268
1269
1270
1271
1272
#endif

    return retval;
}

1273
1274
1275
/* Translate a Unicode sequence: turn a six-digit hexadecimal number
 * from 000000 to 10FFFF (case-insensitive) into its corresponding
 * multibyte value. */
1276
long get_unicode_kbinput(int kbinput
1277
#ifndef NANO_TINY
1278
1279
1280
1281
	, bool reset
#endif
	)
{
1282
1283
1284
    static int uni_digits = 0;
    static long uni = 0;
    long retval = ERR;
1285

1286
#ifndef NANO_TINY
1287
    if (reset) {
1288
1289
	uni_digits = 0;
	uni = 0;
1290
1291
1292
1293
	return ERR;
    }
#endif

1294
    /* Increment the Unicode digit counter. */
1295
    uni_digits++;
1296

1297
    switch (uni_digits) {
1298
	case 1:
1299
	    /* One digit: reset the Unicode sequence holder and add the
1300
	     * digit we got to the 0x100000's position of the Unicode
1301
1302
	     * sequence holder. */
	    uni = 0;
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
	    if ('0' <= kbinput && kbinput <= '1')
		uni += (kbinput - '0') * 0x100000;
	    else
		/* If the character we got isn't a hexadecimal digit, or
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
		retval = kbinput;
	    break;
	case 2:
	    /* Two digits: add the digit we got to the 0x10000's
	     * position of the Unicode sequence holder. */
	    if ('0' == kbinput || (uni < 0x100000 && '1' <= kbinput &&
		kbinput <= '9'))
		uni += (kbinput - '0') * 0x10000;
	    else if (uni < 0x100000 && 'a' <= tolower(kbinput) &&
		tolower(kbinput) <= 'f')
		uni += (tolower(kbinput) + 10 - 'a') * 0x10000;
	    else
		/* If the character we got isn't a hexadecimal digit, or
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
		retval = kbinput;
	    break;
	case 3:
	    /* Three digits: add the digit we got to the 0x1000's
	     * position of the Unicode sequence holder. */
1329
	    if ('0' <= kbinput && kbinput <= '9')
1330
		uni += (kbinput - '0') * 0x1000;
1331
	    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
1332
		uni += (tolower(kbinput) + 10 - 'a') * 0x1000;
1333
1334
	    else
		/* If the character we got isn't a hexadecimal digit, or
1335
1336
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1337
1338
		retval = kbinput;
	    break;
1339
1340
	case 4:
	    /* Four digits: add the digit we got to the 0x100's position
1341
	     * of the Unicode sequence holder. */
1342
	    if ('0' <= kbinput && kbinput <= '9')
1343
		uni += (kbinput - '0') * 0x100;
1344
	    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
1345
		uni += (tolower(kbinput) + 10 - 'a') * 0x100;
1346
	    else
1347
		/* If the character we got isn't a hexadecimal digit, or
1348
1349
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1350
1351
		retval = kbinput;
	    break;
1352
1353
	case 5:
	    /* Five digits: add the digit we got to the 0x10's position
1354
	     * of the Unicode sequence holder. */
1355
	    if ('0' <= kbinput && kbinput <= '9')
1356
		uni += (kbinput - '0') * 0x10;
1357
	    else if ('a' <= tolower(kbinput) && tolower(kbinput) <= 'f')
1358
		uni += (tolower(kbinput) + 10 - 'a') * 0x10;
1359
1360
	    else
		/* If the character we got isn't a hexadecimal digit, or
1361
1362
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1363
1364
		retval = kbinput;
	    break;
1365
1366
	case 6:
	    /* Six digits: add the digit we got to the 1's position of
1367
1368
	     * the Unicode sequence holder, and save the corresponding
	     * Unicode value as the result. */
1369
	    if ('0' <= kbinput && kbinput <= '9') {
1370
1371
		uni += (kbinput - '0');
		retval = uni;
1372
1373
	    } else if ('a' <= tolower(kbinput) && tolower(kbinput) <=
		'f') {
1374
1375
		uni += (tolower(kbinput) + 10 - 'a');
		retval = uni;
1376
	    } else
1377
		/* If the character we got isn't a hexadecimal digit, or
1378
1379
		 * if it is and it would put the Unicode sequence out of
		 * valid range, save it as the result. */
1380
1381
1382
		retval = kbinput;
	    break;
	default:
1383
	    /* More than six digits: save the character we got as the
1384
1385
1386
1387
	     * result. */
	    retval = kbinput;
	    break;
    }
1388

1389
1390
    /* If we have a result, reset the Unicode digit counter and the
     * Unicode sequence holder. */
1391
    if (retval != ERR) {
1392
1393
	uni_digits = 0;
	uni = 0;
1394
    }
1395

1396
#ifdef DEBUG
1397
    fprintf(stderr, "get_unicode_kbinput(): kbinput = %d, uni_digits = %d, uni = %ld, retval = %ld\n", kbinput, uni_digits, uni, retval);
1398
1399
#endif

1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
    return retval;
}

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

     /* Ctrl-2 (Ctrl-Space, Ctrl-@, Ctrl-`) */
    if (kbinput == '2' || kbinput == ' ' || kbinput == '@' ||
	kbinput == '`')
	retval = NANO_CONTROL_SPACE;
    /* Ctrl-3 (Ctrl-[, Esc) to Ctrl-7 (Ctrl-_) */
    else if ('3' <= kbinput && kbinput <= '7')
	retval = kbinput - 24;
    /* Ctrl-8 (Ctrl-?) */
    else if (kbinput == '8' || kbinput == '?')
	retval = NANO_CONTROL_8;
    /* Ctrl-A to Ctrl-_ */
    else if ('A' <= kbinput && kbinput <= '_')
	retval = kbinput - 64;
    /* Ctrl-a to Ctrl-~ */
    else if ('a' <= kbinput && kbinput <= '~')
	retval = kbinput - 96;
    else
	retval = kbinput;

1428
#ifdef DEBUG
1429
    fprintf(stderr, "get_control_kbinput(): kbinput = %d, retval = %d\n", kbinput, retval);
1430
1431
#endif

1432
1433
    return retval;
}
1434

1435
1436
1437
1438
/* Put the output-formatted characters in output back into the default
 * keystroke buffer, so that they can be parsed and displayed as output
 * again. */
void unparse_kbinput(char *output, size_t output_len)
1439
{
1440
1441
    int *input;
    size_t i;
1442

1443
1444
1445
1446
1447
1448
1449
1450
    if (output_len == 0)
	return;

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

1453
/* Read in a stream of characters verbatim, and return the length of the
1454
1455
1456
1457
 * string in kbinput_len.  Assume nodelay(win) is FALSE. */
int *get_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
{
    int *retval;
1458

1459
    /* Turn off flow control characters if necessary so that we can type
1460
1461
     * them in verbatim, and turn the keypad off if necessary so that we
     * don't get extended keypad values. */
1462
1463
    if (ISSET(PRESERVE))
	disable_flow_control();
1464
1465
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, FALSE);
1466
1467
1468

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

    /* Turn flow control characters back on if necessary and turn the
1471
     * keypad back on if necessary now that we're done. */
1472
1473
    if (ISSET(PRESERVE))
	enable_flow_control();
1474
1475
    if (!ISSET(REBIND_KEYPAD))
	keypad(win, TRUE);
1476

1477
    return retval;
1478
1479
}

1480
1481
/* Read in a stream of all available characters, and return the length
 * of the string in kbinput_len.  Translate the first few characters of
1482
1483
 * the input into the corresponding multibyte value if possible.  After
 * that, leave the input as-is. */ 
1484
int *parse_verbatim_kbinput(WINDOW *win, size_t *kbinput_len)
1485
{
1486
1487
    int *kbinput, *retval;
    long uni;
1488

1489
1490
1491
    /* Read in the first keystroke. */
    while ((kbinput = get_input(win, 1)) == NULL);

1492
    /* Check whether the first keystroke is a hexadecimal digit. */
1493
    uni = get_unicode_kbinput(*kbinput
1494
#ifndef NANO_TINY
1495
	, FALSE
1496
#endif
1497
1498
	);

1499
1500
    /* If the first keystroke isn't a hexadecimal digit, put back the
     * first keystroke. */
1501
    if (uni != ERR)
1502
1503
1504
1505
	unget_input(kbinput, 1);
    /* Otherwise, read in keystrokes until we have a complete word
     * sequence, and put back the corresponding word value. */
    else {
1506
1507
	char *uni_mb;
	int uni_mb_len, *seq, i;
1508

1509
	while (uni == ERR) {
1510
	    while ((kbinput = get_input(win, 1)) == NULL);
1511

1512
	    uni = get_unicode_kbinput(*kbinput
1513
#ifndef NANO_TINY
1514
		, FALSE
1515
#endif
1516
1517
		);
	}
1518

1519
1520
	/* Put back the multibyte equivalent of the Unicode value. */
	uni_mb = make_mbchar(uni, &uni_mb_len);
1521

1522
	seq = (int *)nmalloc(uni_mb_len * sizeof(int));
1523

1524
1525
	for (i = 0; i < uni_mb_len; i++)
	    seq[i] = (unsigned char)uni_mb[i];
1526

1527
	unget_input(seq, uni_mb_len);
1528
1529

	free(seq);
1530
	free(uni_mb);
1531
1532
    }

1533
    /* Get the complete sequence, and save the characters in it as the
1534
     * result. */
1535
    *kbinput_len = get_key_buffer_len();
1536
    retval = get_input(NULL, *kbinput_len);
1537
1538
1539
1540

    return retval;
}

1541
#ifndef DISABLE_MOUSE
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1542
1543
/* Check for a mouse event, and if one's taken place, save the
 * coordinates where it took place in mouse_x and mouse_y.  After that,
1544
1545
 * assuming allow_shortcuts is FALSE, if the shortcut list on the
 * bottom two lines of the screen is visible and the mouse event took
1546
1547
1548
 * place on it, figure out which shortcut was clicked and put back the
 * equivalent keystroke(s).  Return FALSE if no keystrokes were
 * put back, or TRUE if at least one was.  Assume that KEY_MOUSE has
1549
 * already been read in. */
1550
bool get_mouseinput(int *mouse_x, int *mouse_y, bool allow_shortcuts)
1551
1552
1553
1554
1555
1556
1557
1558
{
    MEVENT mevent;

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

    /* First, get the actual mouse event. */
    if (getmouse(&mevent) == ERR)
1559
	return FALSE;
1560
1561
1562
1563
1564

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

1565
1566
1567
    /* If we're allowing shortcuts, the current shortcut list is being
     * displayed on the last two lines of the screen, and the mouse
     * event took place inside it, we need to figure out which shortcut
1568
     * was clicked and put back the equivalent keystroke(s) for it. */
1569
1570
    if (allow_shortcuts && !ISSET(NO_HELP) && wenclose(bottomwin,
	*mouse_y, *mouse_x)) {
1571
	int i, j;
1572
	size_t currslen;
1573
1574
1575
1576
1577
1578
1579
1580
	    /* The number of shortcuts in the current shortcut list. */
	const shortcut *s = currshortcut;
	    /* The actual shortcut we clicked on, starting at the first
	     * one in the current shortcut list. */

	/* Get the shortcut lists' length. */
	if (currshortcut == main_list)
	    currslen = MAIN_VISIBLE;
1581
	else {
1582
1583
	    currslen = length_of_list(currshortcut);

1584
1585
1586
1587
1588
1589
	    /* We don't show any more shortcuts than the main list
	     * does. */
	    if (currslen > MAIN_VISIBLE)
		currslen = MAIN_VISIBLE;
	}

1590
1591
1592
	/* 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. */
1593
	if (currslen < 2)
1594
	    i = COLS / (MAIN_VISIBLE / 2);
1595
1596
1597
	else
	    i = COLS / ((currslen / 2) + (currslen % 2));

1598
	/* Calculate the y-coordinate relative to the beginning of
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1599
1600
	 * the shortcut list in bottomwin, i.e, with the sizes of
	 * topwin, edit, and the first line of bottomwin subtracted
1601
	 * out, and set j to it. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1602
	j = *mouse_y - (2 - no_more_space()) - editwinrows - 1;
1603

1604
1605
	/* If we're on the statusbar, don't do anything. */
	if (j < 0)
1606
	    return FALSE;
1607
1608
1609
1610

	/* Calculate the x-coordinate relative to the beginning of the
	 * shortcut list in bottomwin, and add it to j.  j should now be
	 * the index in the shortcut list of the shortcut we clicked. */
1611
	j = (*mouse_x / i) * 2 + j;
1612
1613
1614
1615
1616
1617

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

	/* If we're beyond the last shortcut, don't do anything. */
1618
	if (j >= currslen)
1619
	    return FALSE;
1620
1621
1622
1623
1624
1625

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

1626
1627
1628
	/* And put back the equivalent key.  Assume that each shortcut
	 * has, at the very least, an equivalent control key, an
	 * equivalent primary meta key sequence, or both. */
1629
	if (s->ctrlval != NANO_NO_KEY) {
1630
	    unget_kbinput(s->ctrlval, FALSE, FALSE);
1631
1632
	    return TRUE;
	} else if (s->metaval != NANO_NO_KEY) {
1633
	    unget_kbinput(s->metaval, TRUE, FALSE);
1634
1635
	    return TRUE;
	}
1636
    }
1637
    return FALSE;
1638
}
1639
1640
#endif /* !DISABLE_MOUSE */

1641
1642
1643
1644
1645
1646
1647
1648
/* Return the shortcut corresponding to the values of kbinput (the key
 * itself), meta_key (whether the key is a meta sequence), and func_key
 * (whether the key is a function key), if any.  The shortcut will be
 * the first one in the list (control key, meta key sequence, function
 * key, other meta key sequence) for the corresponding function.  For
 * example, passing in a meta key sequence that corresponds to a
 * function with a control key, a function key, and a meta key sequence
 * will return the control key corresponding to that function. */
1649
const shortcut *get_shortcut(const shortcut *s_list, int *kbinput, bool
1650
	*meta_key, bool *func_key)
1651
1652
1653
1654
{
    const shortcut *s = s_list;
    size_t slen = length_of_list(s_list);

1655
#ifdef DEBUG
1656
    fprintf(stderr, "get_shortcut(): kbinput = %d, meta_key = %d, func_key = %d\n", *kbinput, (int)*meta_key, (int)*func_key);
1657
1658
#endif

1659
1660
1661
1662
1663
1664
    /* Check for shortcuts. */
    for (; slen > 0; slen--) {
	/* We've found a shortcut if:
	 *
	 * 1. The key exists.
	 * 2. The key is a control key in the shortcut list.
1665
1666
1667
1668
1669
	 * 3. meta_key is TRUE and the key is the primary or
	 *    miscellaneous meta sequence in the shortcut list.
	 * 4. func_key is TRUE and the key is a function key in the
	 *    shortcut list. */

1670
1671
1672
1673
	if (*kbinput != NANO_NO_KEY && (*kbinput == s->ctrlval ||
		(*meta_key == TRUE && (*kbinput == s->metaval ||
		*kbinput == s->miscval)) || (*func_key == TRUE &&
		*kbinput == s->funcval))) {
1674
1675
1676
1677
1678
1679
1680
1681
	    break;
	}

	s = s->next;
    }

    /* Translate the shortcut to either its control key or its meta key
     * equivalent.  Assume that the shortcut has an equivalent control
1682
     * key, an equivalent primary meta key sequence, or both. */
1683
1684
1685
    if (slen > 0) {
	if (s->ctrlval != NANO_NO_KEY) {
	    *meta_key = FALSE;
1686
	    *func_key = FALSE;
1687
	    *kbinput = s->ctrlval;
1688
	    return s;
1689
1690
	} else if (s->metaval != NANO_NO_KEY) {
	    *meta_key = TRUE;
1691
	    *func_key = FALSE;
1692
	    *kbinput = s->metaval;
1693
	    return s;
1694
1695
1696
1697
1698
1699
	}
    }

    return NULL;
}

1700
#ifndef NANO_TINY
1701
1702
1703
/* Return the global toggle corresponding to the values of kbinput (the
 * key itself) and meta_key (whether the key is a meta sequence), if
 * any. */
1704
1705
1706
1707
const toggle *get_toggle(int kbinput, bool meta_key)
{
    const toggle *t = toggles;

1708
1709
1710
1711
#ifdef DEBUG
    fprintf(stderr, "get_toggle(): kbinput = %d, meta_key = %d\n", kbinput, (int)meta_key);
#endif

1712
1713
    /* Check for toggles. */
    for (; t != NULL; t = t->next) {
1714
1715
	/* We've found a toggle if the key exists, meta_key is TRUE, and
	 * the key is in the meta key toggle list. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1716
1717
1718
1719
1720
	if (
#ifndef DISABLE_HELP
		t->val != TOGGLE_NO_KEY &&
#endif
		meta_key && kbinput == t->val)
1721
1722
1723
1724
1725
	    break;
    }

    return t;
}
1726
#endif /* !NANO_TINY */
1727

1728
1729
1730
1731
1732
1733
1734
1735
1736
/* Move to (x, y) in win, and display a line of n spaces with the
 * current attributes. */
void blank_line(WINDOW *win, int y, int x, int n)
{
    wmove(win, y, x);
    for (; n > 0; n--)
	waddch(win, ' ');
}

1737
/* Blank the first line of the top portion of the window. */
1738
void blank_titlebar(void)
Chris Allegretta's avatar
Chris Allegretta committed
1739
{
1740
    blank_line(topwin, 0, 0, COLS);
1741
1742
}

1743
1744
/* If the MORE_SPACE flag isn't set, blank the second line of the top
 * portion of the window. */
1745
1746
1747
void blank_topbar(void)
{
    if (!ISSET(MORE_SPACE))
1748
	blank_line(topwin, 1, 0, COLS);
1749
1750
}

1751
1752
/* Blank all the lines of the middle portion of the window, i.e, the
 * edit window. */
Chris Allegretta's avatar
Chris Allegretta committed
1753
1754
void blank_edit(void)
{
1755
    int i;
1756
    for (i = 0; i < editwinrows; i++)
1757
	blank_line(edit, i, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1758
1759
}

1760
/* Blank the first line of the bottom portion of the window. */
Chris Allegretta's avatar
Chris Allegretta committed
1761
1762
void blank_statusbar(void)
{
1763
    blank_line(bottomwin, 0, 0, COLS);
Chris Allegretta's avatar
Chris Allegretta committed
1764
1765
}

1766
1767
/* If the NO_HELP flag isn't set, blank the last two lines of the bottom
 * portion of the window. */
1768
1769
1770
void blank_bottombars(void)
{
    if (!ISSET(NO_HELP)) {
1771
1772
	blank_line(bottomwin, 1, 0, COLS);
	blank_line(bottomwin, 2, 0, COLS);
1773
1774
1775
    }
}

1776
1777
1778
/* Check if the number of keystrokes needed to blank the statusbar has
 * been pressed.  If so, blank the statusbar, unless constant cursor
 * position display is on. */
1779
void check_statusblank(void)
Chris Allegretta's avatar
Chris Allegretta committed
1780
{
1781
    if (statusblank > 0)
1782
	statusblank--;
1783
1784

    if (statusblank == 0 && !ISSET(CONST_UPDATE)) {
1785
1786
1787
	blank_statusbar();
	wnoutrefresh(bottomwin);
	reset_cursor();
1788
	wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
1789
1790
1791
    }
}

1792
1793
1794
1795
/* Convert buf into a string that can be displayed on screen.  The
 * caller wants to display buf starting with column start_col, and
 * extending for at most len columns.  start_col is zero-based.  len is
 * one-based, so len == 0 means you get "" returned.  The returned
1796
1797
1798
1799
1800
 * string is dynamically allocated, and should be freed.  If dollars is
 * TRUE, the caller might put "$" at the beginning or end of the line if
 * it's too long. */
char *display_string(const char *buf, size_t start_col, size_t len, bool
	dollars)
1801
1802
{
    size_t start_index;
1803
	/* Index in buf of the first character shown. */
1804
    size_t column;
1805
	/* Screen column that start_index corresponds to. */
1806
1807
1808
1809
1810
1811
    size_t alloc_len;
	/* The length of memory allocated for converted. */
    char *converted;
	/* The string we return. */
    size_t index;
	/* Current position in converted. */
1812
    char *buf_mb;
1813
1814
    int buf_mb_len;

1815
1816
1817
1818
1819
    /* If dollars is TRUE, make room for the "$" at the end of the
     * line. */
    if (dollars && len > 0 && strlenpt(buf) > start_col + len)
	len--;

1820
1821
1822
    if (len == 0)
	return mallocstrcpy(NULL, "");

1823
1824
    buf_mb = charalloc(mb_cur_max());

1825
1826
    start_index = actual_x(buf, start_col);
    column = strnlenpt(buf, start_index);
1827

1828
    assert(column <= start_col);
1829

1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
    /* Make sure there's enough room for the initial character, whether
     * it's a multibyte control character, a non-control multibyte
     * character, a tab character, or a null terminator.  Rationale:
     *
     * multibyte control character followed by a null terminator:
     *     1 byte ('^') + mb_cur_max() bytes + 1 byte ('\0')
     * multibyte non-control character followed by a null terminator:
     *     mb_cur_max() bytes + 1 byte ('\0')
     * tab character followed by a null terminator:
     *     mb_cur_max() bytes + (tabsize - 1) bytes + 1 byte ('\0')
     *
     * Since tabsize has a minimum value of 1, it can substitute for 1
     * byte above. */
    alloc_len = (mb_cur_max() + tabsize + 1) * MAX_BUF_SIZE;
    converted = charalloc(alloc_len);
1845

1846
1847
    index = 0;

1848
1849
    if (buf[start_index] != '\t' && (column < start_col || (dollars &&
	column > 0))) {
1850
1851
	/* We don't display all of buf[start_index] since it starts to
	 * the left of the screen. */
1852
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1853

1854
	if (is_cntrl_mbchar(buf_mb)) {
1855
	    if (column < start_col) {
1856
1857
		char *ctrl_buf_mb = charalloc(mb_cur_max());
		int ctrl_buf_mb_len, i;
1858

1859
1860
		ctrl_buf_mb = control_mbrep(buf_mb, ctrl_buf_mb,
			&ctrl_buf_mb_len);
1861

1862
1863
		for (i = 0; i < ctrl_buf_mb_len; i++)
		    converted[index++] = ctrl_buf_mb[i];
1864

1865
		start_col += mbwidth(ctrl_buf_mb);
1866

1867
		free(ctrl_buf_mb);
1868

1869
		start_index += buf_mb_len;
1870
	    }
1871
	}
1872
#ifdef ENABLE_UTF8
1873
	else if (using_utf8() && mbwidth(buf_mb) > 1) {
1874
	    converted[index++] = ' ';
1875
	    start_col++;
1876
1877

	    start_index += buf_mb_len;
1878
	}
1879
#endif
1880
1881
    }

1882
    while (buf[start_index] != '\0') {
1883
	buf_mb_len = parse_mbchar(buf + start_index, buf_mb, NULL);
1884

1885
1886
1887
1888
1889
1890
1891
1892
	/* Make sure there's enough room for the next character, whether
	 * it's a multibyte control character, a non-control multibyte
	 * character, a tab character, or a null terminator. */
	if (index + mb_cur_max() + tabsize + 1 >= alloc_len - 1) {
	    alloc_len += (mb_cur_max() + tabsize + 1) * MAX_BUF_SIZE;
	    converted = charealloc(converted, alloc_len);
	}

1893
	/* If buf contains a tab character, interpret it. */
1894
	if (*buf_mb == '\t') {
1895
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
1896
1897
1898
1899
1900
1901
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i;

		for (i = 0; i < whitespace_len[0]; i++)
		    converted[index++] = whitespace[i];
	    } else
1902
#endif
1903
		converted[index++] = ' '; 
1904
	    start_col++;
1905
	    while (start_col % tabsize != 0) {
1906
		converted[index++] = ' ';
1907
1908
		start_col++;
	    }
1909
	/* If buf contains a control character, interpret it.  If buf
1910
1911
	 * contains an invalid multibyte control character, display it
	 * as such.*/
1912
	} else if (is_cntrl_mbchar(buf_mb)) {
1913
1914
	    char *ctrl_buf_mb = charalloc(mb_cur_max());
	    int ctrl_buf_mb_len, i;
1915

1916
	    converted[index++] = '^';
1917
1918
	    start_col++;

1919
1920
	    ctrl_buf_mb = control_mbrep(buf_mb, ctrl_buf_mb,
		&ctrl_buf_mb_len);
1921

1922
1923
	    for (i = 0; i < ctrl_buf_mb_len; i++)
		converted[index++] = ctrl_buf_mb[i];
1924

1925
	    start_col += mbwidth(ctrl_buf_mb);
1926

1927
	    free(ctrl_buf_mb);
1928
	/* If buf contains a space character, interpret it. */
1929
	} else if (*buf_mb == ' ') {
1930
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
1931
1932
1933
1934
1935
1936
1937
	    if (ISSET(WHITESPACE_DISPLAY)) {
		int i;

		for (i = whitespace_len[0]; i < whitespace_len[0] +
			whitespace_len[1]; i++)
		    converted[index++] = whitespace[i];
	    } else
1938
#endif
1939
		converted[index++] = ' '; 
1940
	    start_col++;
1941
1942
1943
	/* If buf contains a non-control character, interpret it.  If
	 * buf contains an invalid multibyte non-control character,
	 * display it as such. */
1944
	} else {
1945
1946
	    char *nctrl_buf_mb = charalloc(mb_cur_max());
	    int nctrl_buf_mb_len, i;
1947

1948
1949
	    nctrl_buf_mb = mbrep(buf_mb, nctrl_buf_mb,
		&nctrl_buf_mb_len);
1950

1951
1952
1953
1954
1955
1956
	    for (i = 0; i < nctrl_buf_mb_len; i++)
		converted[index++] = nctrl_buf_mb[i];

	    start_col += mbwidth(nctrl_buf_mb);

	    free(nctrl_buf_mb);
1957
1958
	}

1959
	start_index += buf_mb_len;
1960
1961
    }

1962
1963
    free(buf_mb);

1964
1965
1966
1967
    assert(alloc_len >= index + 1);

    /* Null terminate converted. */
    converted[index] = '\0';
1968
1969
1970

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

1973
    return converted;
1974
1975
}

1976
1977
1978
1979
1980
1981
/* Display the path specified in path on the titlebar, along with the
 * current version of nano and whether the current file has been
 * modified.  If path is NULL, assume we're in normal editing mode and
 * display the current filename instead.  Otherwise, assume we're in the
 * file browser, and don't display whether the current file has been
 * modified. */
1982
void titlebar(const char *path)
Chris Allegretta's avatar
Chris Allegretta committed
1983
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1984
    int space = COLS;
1985
	/* The space we have available for display. */
1986
    size_t verlen = strlenpt(PACKAGE_STRING) + 1;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1987
1988
	/* The length of the version message in columns, plus one for
	 * padding. */
1989
    const char *prefix;
1990
	/* "DIR:", "File:", or "New Buffer".  Goes before filename. */
1991
    size_t prefixlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1992
	/* The length of the prefix in columns, plus one for padding. */
1993
    const char *state;
1994
1995
	/* "Modified", "View", or "".  Shows the state of this
	 * buffer. */
1996
    size_t statelen = 0;
1997
	/* The length of the state in columns, or the length of
1998
	 * "Modified" if the state is blank. */
1999
2000
    char *exppath = NULL;
	/* The file name, expanded for display. */
2001
    bool newfie = FALSE;
2002
	/* Do we say "New Buffer"? */
2003
    bool dots = FALSE;
2004
2005
	/* Do we put an ellipsis before the path? */

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

2008
    wattron(topwin, reverse_attr);
2009
    blank_titlebar();
Chris Allegretta's avatar
Chris Allegretta committed
2010

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2011
2012
2013
2014
    /* space has to be at least 4: two spaces before the version message,
     * at least one character of the version message, and one space
     * after the version message. */
    if (space < 4)
2015
2016
	space = 0;
    else {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2017
2018
2019
2020
	/* Limit verlen to 1/3 the length of the screen in columns,
	 * minus three columns for spaces. */
	if (verlen > (COLS / 3) - 3)
	    verlen = (COLS / 3) - 3;
2021
    }
Chris Allegretta's avatar
Chris Allegretta committed
2022

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2023
    if (space >= 4) {
2024
2025
	/* Add a space after the version message, and account for both
	 * it and the two spaces before it. */
2026
2027
	mvwaddnstr(topwin, 0, 2, PACKAGE_STRING,
		actual_x(PACKAGE_STRING, verlen));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2028
2029
2030
2031
	verlen += 3;

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

2034
2035
2036
2037
2038
2039
2040
2041
2042
#ifndef DISABLE_BROWSER
    /* Don't display the state if we're in the file browser. */
    if (path != NULL)
	state = "";
    else
#endif
	state = openfile->modified ? _("Modified") : ISSET(VIEW_MODE) ?
		_("View") : "";

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2045
2046
    /* If possible, add a space before state. */
    if (space > 0 && statelen < space)
2047
	statelen++;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2048
    else
2049
2050
2051
	goto the_end;

#ifndef DISABLE_BROWSER
2052
    /* path should be a directory if we're in the file browser. */
2053
2054
2055
2056
    if (path != NULL)
	prefix = _("DIR:");
    else
#endif
2057
    if (openfile->filename[0] == '\0') {
2058
	prefix = _("New Buffer");
2059
	newfie = TRUE;
2060
2061
    } else
	prefix = _("File:");
2062

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2065
    /* If newfie is FALSE, add a space after prefix. */
2066
    if (!newfie && prefixlen + statelen < space)
2067
2068
	prefixlen++;

2069
2070
    /* If we're not in the file browser, path should be the current
     * filename. */
2071
    if (path == NULL)
2072
	path = openfile->filename;
2073

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2074
    /* Account for the full lengths of the prefix and the state. */
2075
2076
2077
2078
    if (space >= prefixlen + statelen)
	space -= prefixlen + statelen;
    else
	space = 0;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2079
	/* space is now the room we have for the filename. */
2080

2081
    if (!newfie) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2082
	size_t lenpt = strlenpt(path), start_col;
2083

2084
	dots = (lenpt >= space);
2085
2086
2087
2088
2089
2090
2091
2092

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

	exppath = display_string(path, start_col, space, FALSE);
2093
2094
2095
    }

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

2099
	/* There is room for the whole filename, so we center it. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2100
2101
	mvwaddnstr(topwin, 0, verlen + ((space - exppathlen) / 3),
		prefix, actual_x(prefix, prefixlen));
2102
	if (!newfie) {
2103
2104
2105
2106
2107
	    waddch(topwin, ' ');
	    waddstr(topwin, exppath);
	}
    } else {
	/* We will say something like "File: ...ename". */
2108
2109
	mvwaddnstr(topwin, 0, verlen - 1, prefix, actual_x(prefix,
		prefixlen));
2110
	if (space <= -3 || newfie)
2111
2112
	    goto the_end;
	waddch(topwin, ' ');
2113
2114
	waddnstr(topwin, "...", space + 3);
	if (space <= 0)
2115
	    goto the_end;
2116
	waddstr(topwin, exppath);
2117
2118
2119
2120
2121
    }

  the_end:
    free(exppath);

2122
    if (state[0] != '\0') {
2123
	if (statelen >= COLS - 1)
2124
2125
	    mvwaddnstr(topwin, 0, 0, state, actual_x(state, COLS));
	else {
2126
	    assert(COLS - statelen - 1 >= 0);
2127

2128
	    mvwaddnstr(topwin, 0, COLS - statelen - 1, state,
2129
		actual_x(state, statelen));
2130
	}
2131
    }
2132

2133
    wattroff(topwin, reverse_attr);
2134

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

2140
2141
/* Mark the current file as modified if it isn't already, and then
 * update the titlebar to display the file's new status. */
2142
2143
void set_modified(void)
{
2144
2145
    if (!openfile->modified) {
	openfile->modified = TRUE;
2146
2147
2148
2149
	titlebar(NULL);
    }
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2150
2151
2152
/* Display a message on the statusbar, and set disable_cursorpos to
 * TRUE, so that the message won't be immediately overwritten if
 * constant cursor position display is on. */
2153
2154
2155
void statusbar(const char *msg, ...)
{
    va_list ap;
2156
2157
    char *bar, *foo;
    size_t start_x, foo_len;
2158
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2159
2160
    bool old_whitespace;
#endif
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174

    va_start(ap, msg);

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

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

2175
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2176
2177
    old_whitespace = ISSET(WHITESPACE_DISPLAY);
    UNSET(WHITESPACE_DISPLAY);
2178
#endif
2179
2180
2181
2182
    bar = charalloc(mb_cur_max() * (COLS - 3));
    vsnprintf(bar, mb_cur_max() * (COLS - 3), msg, ap);
    va_end(ap);
    foo = display_string(bar, 0, COLS - 4, FALSE);
2183
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2184
2185
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);
2186
#endif
2187
2188
2189
    free(bar);
    foo_len = strlenpt(foo);
    start_x = (COLS - foo_len - 4) / 2;
2190

2191
    wmove(bottomwin, 0, start_x);
2192
    wattron(bottomwin, reverse_attr);
2193
2194
2195
2196
    waddstr(bottomwin, "[ ");
    waddstr(bottomwin, foo);
    free(foo);
    waddstr(bottomwin, " ]");
2197
    wattroff(bottomwin, reverse_attr);
2198
2199
2200
2201
2202
    wnoutrefresh(bottomwin);
    reset_cursor();
    wnoutrefresh(edit);
	/* Leave the cursor at its position in the edit window, not in
	 * the statusbar. */
2203

2204
    disable_cursorpos = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2205
2206
2207
2208
2209

    /* If we're doing quick statusbar blanking, and constant cursor
     * position display is off, blank the statusbar after only one
     * keystroke.  Otherwise, blank it after twenty-five keystrokes,
     * as Pico does. */
2210
    statusblank =
2211
#ifndef NANO_TINY
2212
	ISSET(QUICK_BLANK) && !ISSET(CONST_UPDATE) ? 1 :
2213
2214
#endif
	25;
2215
2216
}

2217
2218
/* Display the shortcut list in s on the last two rows of the bottom
 * portion of the window. */
2219
void bottombars(const shortcut *s)
Chris Allegretta's avatar
Chris Allegretta committed
2220
{
2221
    size_t i, colwidth, slen;
2222

Chris Allegretta's avatar
Chris Allegretta committed
2223
2224
2225
    if (ISSET(NO_HELP))
	return;

2226
2227
    if (s == main_list) {
	slen = MAIN_VISIBLE;
2228

2229
	assert(slen <= length_of_list(s));
2230
    } else {
2231
2232
	slen = length_of_list(s);

2233
	/* Don't show any more shortcuts than the main list does. */
2234
2235
2236
2237
	if (slen > MAIN_VISIBLE)
	    slen = MAIN_VISIBLE;
    }

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

2244
    blank_bottombars();
2245

2246
    for (i = 0; i < slen; i++, s = s->next) {
2247
	const char *keystr;
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
	char foo[4] = "";

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

	keystr = foo;
2263
2264

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

2268
2269
    wnoutrefresh(bottomwin);
    reset_cursor();
2270
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2271
2272
}

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

2282
2283
    assert(keystroke != NULL && desc != NULL);

2284
    wattron(bottomwin, reverse_attr);
2285
    waddnstr(bottomwin, keystroke, actual_x(keystroke, len));
2286
    wattroff(bottomwin, reverse_attr);
2287
2288
2289
2290
2291
2292

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

2293
2294
    if (len > 0) {
	waddch(bottomwin, ' ');
2295
	waddnstr(bottomwin, desc, actual_x(desc, len));
Chris Allegretta's avatar
Chris Allegretta committed
2296
2297
2298
    }
}

2299
2300
/* Reset current_y, based on the position of current, and put the cursor
 * in the edit window at (current_y, current_x). */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2301
2302
void reset_cursor(void)
{
2303
2304
    /* If we haven't opened any files yet, put the cursor in the top
     * left corner of the edit window and get out. */
2305
    if (openfile == NULL) {
2306
	wmove(edit, 0, 0);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2307
	return;
2308
    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2309

2310
2311
2312
    openfile->current_y = openfile->current->lineno -
	openfile->edittop->lineno;
    if (openfile->current_y < editwinrows) {
2313
2314
	size_t xpt = xplustabs();
	wmove(edit, openfile->current_y, xpt - get_page_start(xpt));
2315
     }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2316
}
Chris Allegretta's avatar
Chris Allegretta committed
2317

2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
/* edit_draw() takes care of the job of actually painting a line into
 * the edit window.  fileptr is the line to be painted, at row line of
 * the window.  converted is the actual string to be written to the
 * window, with tabs and control characters replaced by strings of
 * regular characters.  start is the column number of the first
 * character of this page.  That is, the first character of converted
 * corresponds to character number actual_x(fileptr->data, start) of the
 * line. */
void edit_draw(const filestruct *fileptr, const char *converted, int
	line, size_t start)
Chris Allegretta's avatar
Chris Allegretta committed
2328
{
2329
#if !defined(NANO_TINY) || defined(ENABLE_COLOR)
2330
2331
2332
2333
2334
2335
2336
2337
2338
    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. */
2339
2340
#endif

2341
    assert(openfile != NULL && fileptr != NULL && converted != NULL);
2342
    assert(strlenpt(converted) <= COLS);
2343

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

Chris Allegretta's avatar
Chris Allegretta committed
2348
#ifdef ENABLE_COLOR
2349
2350
2351
2352
    /* If color syntaxes are available and turned on, we need to display
     * them. */
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX)) {
	const colortype *tmpcolor = openfile->colorstrings;
2353
2354
2355
2356
2357

	for (; tmpcolor != NULL; tmpcolor = tmpcolor->next) {
	    int x_start;
		/* Starting column for mvwaddnstr.  Zero-based. */
	    int paintlen;
2358
		/* Number of chars to paint on this line.  There are COLS
2359
		 * characters on a whole line. */
2360
	    size_t index;
2361
		/* Index in converted where we paint. */
2362
2363
2364
2365
	    regmatch_t startmatch;
		/* Match position for start_regex. */
	    regmatch_t endmatch;
		/* Match position for end_regex. */
2366
2367
2368
2369

	    if (tmpcolor->bright)
		wattron(edit, A_BOLD);
	    wattron(edit, COLOR_PAIR(tmpcolor->pairnum));
2370
2371
2372
	    /* 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. */
2373
2374

	    /* First case, tmpcolor is a single-line expression. */
2375
	    if (tmpcolor->end == NULL) {
2376
2377
2378
		size_t k = 0;

		/* We increment k by rm_eo, to move past the end of the
2379
2380
2381
2382
2383
2384
2385
2386
		 * last match.  Even though two matches may overlap, we
		 * want to ignore them, so that we can highlight
		 * C-strings correctly. */
		while (k < endpos) {
		    /* Note the fifth parameter to regexec().  It says
		     * not to match the beginning-of-line character
		     * unless k is 0.  If regexec() returns REG_NOMATCH,
		     * there are no more matches in the line. */
2387
		    if (regexec(tmpcolor->start, &fileptr->data[k], 1,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2388
2389
			&startmatch, (k == 0) ? 0 : REG_NOTBOL) ==
			REG_NOMATCH)
2390
			break;
2391
2392
		    /* Translate the match to the beginning of the
		     * line. */
2393
2394
		    startmatch.rm_so += k;
		    startmatch.rm_eo += k;
2395
2396
		    if (startmatch.rm_so == startmatch.rm_eo) {
			startmatch.rm_eo++;
2397
2398
			statusbar(
				_("Refusing zero-length regex match"));
2399
		    } else if (startmatch.rm_so < endpos &&
2400
			startmatch.rm_eo > startpos) {
2401
			if (startmatch.rm_so <= startpos)
2402
			    x_start = 0;
2403
			else
2404
2405
			    x_start = strnlenpt(fileptr->data,
				startmatch.rm_so) - start;
2406

2407
2408
2409
			index = actual_x(converted, x_start);

			paintlen = actual_x(converted + index,
2410
2411
				strnlenpt(fileptr->data,
				startmatch.rm_eo) - start - x_start);
2412
2413
2414

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

2415
2416
			mvwaddnstr(edit, line, x_start, converted +
				index, paintlen);
2417
		    }
2418
		    k = startmatch.rm_eo;
Chris Allegretta's avatar
Chris Allegretta committed
2419
		}
2420
	    } else {
2421
		/* This is a multi-line regex.  There are two steps.
2422
2423
2424
2425
2426
2427
		 * First, we have to see if the beginning of the line is
		 * colored by a start on an earlier line, and an end on
		 * this line or later.
		 *
		 * We find the first line before fileptr matching the
		 * start.  If every match on that line is followed by an
2428
2429
2430
2431
		 * end, then go to step two.  Otherwise, find the next
		 * line after start_line matching the end.  If that line
		 * is not before fileptr, then paint the beginning of
		 * this line. */
2432
		const filestruct *start_line = fileptr->prev;
2433
		    /* The first line before fileptr matching start. */
2434
		regoff_t start_col;
2435
		    /* Where it starts in that line. */
2436
2437
		const filestruct *end_line;

2438
		while (start_line != NULL && regexec(tmpcolor->start,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2439
2440
			start_line->data, 1, &startmatch, 0) ==
			REG_NOMATCH) {
2441
2442
		    /* If there is an end on this line, there is no need
		     * to look for starts on earlier lines. */
2443
2444
		    if (regexec(tmpcolor->end, start_line->data, 0,
			NULL, 0) == 0)
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
			goto step_two;
		    start_line = start_line->prev;
		}
		/* No start found, so skip to the next step. */
		if (start_line == NULL)
		    goto step_two;
		/* Now start_line is the first line before fileptr
		 * containing a start match.  Is there a start on this
		 * line not followed by an end on this line? */
		start_col = 0;
2455
		while (TRUE) {
2456
2457
		    start_col += startmatch.rm_so;
		    startmatch.rm_eo -= startmatch.rm_so;
2458
2459
 		    if (regexec(tmpcolor->end, start_line->data +
			start_col + startmatch.rm_eo, 0, NULL,
2460
			(start_col + startmatch.rm_eo == 0) ? 0 :
2461
2462
			REG_NOTBOL) == REG_NOMATCH)
			/* No end found after this start. */
2463
			break;
2464
		    start_col++;
2465
		    if (regexec(tmpcolor->start, start_line->data +
2466
2467
			start_col, 1, &startmatch,
			REG_NOTBOL) == REG_NOMATCH)
2468
2469
			/* No later start on this line. */
			goto step_two;
2470
		}
2471
2472
		/* Indeed, there is a start not followed on this line by
		 * an end. */
2473
2474
2475

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

		/* No end found, or it is too early. */
2484
2485
		if (end_line == NULL || (end_line == fileptr &&
			endmatch.rm_eo <= startpos))
2486
2487
2488
		    goto step_two;

		/* Now paint the start of fileptr. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
		if (end_line != fileptr)
		    /* If the start of fileptr is on a different line
		     * from the end, paintlen is -1, meaning that
		     * everything on the line gets painted. */
		    paintlen = -1;
		else
		    /* Otherwise, paintlen is the expanded location of
		     * the end of the match minus the expanded location
		     * of the beginning of the page. */
		    paintlen = actual_x(converted,
			strnlenpt(fileptr->data, endmatch.rm_eo) -
			start);
2501

2502
		mvwaddnstr(edit, line, 0, converted, paintlen);
2503

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2504
2505
  step_two:
		/* Second step, we look for starts on this line. */
2506
		start_col = 0;
2507

2508
		while (start_col < endpos) {
2509
2510
2511
2512
		    if (regexec(tmpcolor->start, fileptr->data +
			start_col, 1, &startmatch, (start_col == 0) ?
			0 : REG_NOTBOL) == REG_NOMATCH || start_col +
			startmatch.rm_so >= endpos)
2513
2514
2515
2516
2517
2518
2519
			/* No more starts on this line. */
			break;
		    /* Translate the match to be relative to the
		     * beginning of the line. */
		    startmatch.rm_so += start_col;
		    startmatch.rm_eo += start_col;

2520
		    if (startmatch.rm_so <= startpos)
2521
			x_start = 0;
2522
		    else
2523
2524
			x_start = strnlenpt(fileptr->data,
				startmatch.rm_so) - start;
2525

2526
		    index = actual_x(converted, x_start);
2527

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2528
2529
2530
2531
		    if (regexec(tmpcolor->end, fileptr->data +
			startmatch.rm_eo, 1, &endmatch,
			(startmatch.rm_eo == 0) ? 0 : REG_NOTBOL) ==
			0) {
2532
			/* Translate the end match to be relative to the
2533
			 * beginning of the line. */
2534
2535
2536
			endmatch.rm_so += startmatch.rm_eo;
			endmatch.rm_eo += startmatch.rm_eo;
			/* There is an end on this line.  But does it
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2537
2538
			 * appear on this page, and is the match more
			 * than zero characters long? */
2539
			if (endmatch.rm_eo > startpos &&
2540
				endmatch.rm_eo > startmatch.rm_so) {
2541
			    paintlen = actual_x(converted + index,
2542
2543
				strnlenpt(fileptr->data,
				endmatch.rm_eo) - start - x_start);
2544
2545

			    assert(0 <= x_start && x_start < COLS);
2546

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

2555
			while (end_line != NULL &&
2556
2557
				regexec(tmpcolor->end, end_line->data,
				0, NULL, 0) == REG_NOMATCH)
2558
			    end_line = end_line->next;
2559

2560
			if (end_line != NULL) {
2561
			    assert(0 <= x_start && x_start < COLS);
2562

2563
2564
			    mvwaddnstr(edit, line, x_start, converted +
				index, -1);
2565
2566
2567
			    /* We painted to the end of the line, so
			     * don't bother checking any more starts. */
			    break;
2568
2569
			}
		    }
2570
		    start_col = startmatch.rm_so + 1;
2571
2572
		}
	    }
2573

2574
2575
	    wattroff(edit, A_BOLD);
	    wattroff(edit, COLOR_PAIR(tmpcolor->pairnum));
2576
	}
2577
    }
2578
#endif /* ENABLE_COLOR */
2579

2580
#ifndef NANO_TINY
2581
    /* If the mark is on, we need to display it. */
2582
    if (openfile->mark_set && (fileptr->lineno <=
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2583
	openfile->mark_begin->lineno || fileptr->lineno <=
2584
	openfile->current->lineno) && (fileptr->lineno >=
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2585
	openfile->mark_begin->lineno || fileptr->lineno >=
2586
	openfile->current->lineno)) {
2587
	/* fileptr is at least partially selected. */
2588
	const filestruct *top;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2589
	    /* Either current or mark_begin, whichever is first. */
2590
	size_t top_x;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2591
	    /* current_x or mark_begin_x, corresponding to top. */
2592
2593
	const filestruct *bot;
	size_t bot_x;
2594
	int x_start;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2595
	    /* Starting column for mvwaddnstr().  Zero-based. */
2596
	int paintlen;
2597
	    /* Number of chars to paint on this line.  There are COLS
2598
	     * characters on a whole line. */
2599
	size_t index;
2600
	    /* Index in converted where we paint. */
2601

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

	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
2608

2609
	/* The selected bit of fileptr is on this page. */
2610
2611
	if (top_x < endpos && bot_x > startpos) {
	    assert(startpos <= top_x);
2612
2613
2614
2615

	    /* 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;
2616
2617

	    if (bot_x >= endpos)
2618
2619
2620
2621
		/* If the end of the mark is off the page, paintlen is
		 * -1, meaning that everything on the line gets
		 * painted. */
		paintlen = -1;
2622
	    else
2623
2624
2625
		/* Otherwise, paintlen is the expanded location of the
		 * end of the mark minus the expanded location of the
		 * beginning of the mark. */
2626
2627
		paintlen = strnlenpt(fileptr->data, bot_x) -
			(x_start + start);
2628
2629
2630
2631
2632
2633
2634
2635

	    /* 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;
	    }
2636
2637
2638

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

2639
	    index = actual_x(converted, x_start);
2640

2641
2642
2643
	    if (paintlen > 0)
		paintlen = actual_x(converted + index, paintlen);

2644
	    wattron(edit, reverse_attr);
2645
	    mvwaddnstr(edit, line, x_start, converted + index,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2646
		paintlen);
2647
	    wattroff(edit, reverse_attr);
Chris Allegretta's avatar
Chris Allegretta committed
2648
	}
2649
    }
2650
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
2651
2652
}

2653
/* Just update one line in the edit buffer.  This is basically a wrapper
2654
2655
 * for edit_draw().  The line will be displayed starting with
 * fileptr->data[index].  Likely arguments are current_x or zero. */
2656
void update_line(const filestruct *fileptr, size_t index)
Chris Allegretta's avatar
Chris Allegretta committed
2657
{
2658
    int line;
2659
	/* The line in the edit window that we want to update. */
2660
2661
2662
2663
    char *converted;
	/* fileptr->data converted to have tabs and control characters
	 * expanded. */
    size_t page_start;
Chris Allegretta's avatar
Chris Allegretta committed
2664

2665
    assert(fileptr != NULL);
2666

2667
    line = fileptr->lineno - openfile->edittop->lineno;
Chris Allegretta's avatar
Chris Allegretta committed
2668

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

2672
2673
    if (line < 0 || line >= editwinrows)
	return;
2674

2675
    /* First, blank out the line. */
2676
    blank_line(edit, line, 0, COLS);
2677

2678
2679
    /* Next, convert variables that index the line to their equivalent
     * positions in the expanded line. */
2680
    index = strnlenpt(fileptr->data, index);
2681
    page_start = get_page_start(index);
2682

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

2687
    /* Paint the line. */
2688
    edit_draw(fileptr, converted, line, page_start);
2689
    free(converted);
Chris Allegretta's avatar
Chris Allegretta committed
2690

2691
    if (page_start > 0)
Chris Allegretta's avatar
Chris Allegretta committed
2692
	mvwaddch(edit, line, 0, '$');
2693
    if (strlenpt(fileptr->data) > page_start + COLS)
2694
	mvwaddch(edit, line, COLS - 1, '$');
Chris Allegretta's avatar
Chris Allegretta committed
2695
2696
}

2697
2698
/* Return TRUE if we need an update after moving horizontally, and FALSE
 * otherwise.  We need one if the mark is on or if old_pww and
2699
 * placewewant are on different pages. */
2700
bool need_horizontal_update(size_t old_pww)
2701
2702
{
    return
2703
#ifndef NANO_TINY
2704
	openfile->mark_set ||
2705
#endif
2706
2707
	get_page_start(old_pww) !=
	get_page_start(openfile->placewewant);
2708
2709
}

2710
2711
2712
2713
/* Return TRUE if we need an update after moving vertically, and FALSE
 * otherwise.  We need one if the mark is on or if old_pww and
 * placewewant are on different pages. */
bool need_vertical_update(size_t old_pww)
2714
2715
{
    return
2716
#ifndef NANO_TINY
2717
	openfile->mark_set ||
2718
#endif
2719
2720
	get_page_start(old_pww) !=
	get_page_start(openfile->placewewant);
2721
2722
2723
2724
2725
}

/* Scroll the edit window in the given direction and the given number
 * of lines, and draw new lines on the blank lines left after the
 * scrolling.  direction is the direction to scroll, either UP or DOWN,
2726
 * and nlines is the number of lines to scroll.  We change edittop, and
2727
2728
 * assume that current and current_x are up to date.  We also assume
 * that scrollok(edit) is FALSE. */
2729
void edit_scroll(scroll_dir direction, ssize_t nlines)
2730
{
2731
    bool do_redraw = need_vertical_update(0);
2732
    const filestruct *foo;
2733
    ssize_t i;
2734

2735
2736
    /* Don't bother scrolling less than one line. */
    if (nlines < 1)
2737
2738
	return;

2739
2740
2741
    /* Part 1: nlines is the number of lines we're going to scroll the
     * text of the edit window. */

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

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2760
2761
2762
    /* Don't bother scrolling zero lines or more than the number of
     * lines in the edit window minus one; in both cases, get out, and
     * in the latter case, call edit_refresh() beforehand. */
2763
2764
2765
2766
2767
2768
2769
    if (nlines == 0)
	return;

    if (nlines >= editwinrows) {
	edit_refresh();
	return;
    }
2770
2771
2772

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

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

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

2787
2788
2789
2790
2791
2792
    /* 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
2793

2794
2795
    if (nlines > editwinrows)
	nlines = editwinrows;
2796
2797
2798

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

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

2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
    /* Draw new lines on any blank lines before or inside the scrolled
     * region.  If we scrolled down and we're on the top line, or if we
     * scrolled up and we're on the bottom line, the line won't be
     * blank, so we don't need to draw it unless the mark is on or we're
     * not on the first page. */
    for (i = nlines; i > 0 && foo != NULL; i--) {
	if ((i == nlines && direction == DOWN) || (i == 1 &&
		direction == UP)) {
	    if (do_redraw)
		update_line(foo, (foo == openfile->current) ?
			openfile->current_x : 0);
	} else
	    update_line(foo, (foo == openfile->current) ?
2821
		openfile->current_x : 0);
2822
	foo = foo->next;
2823
2824
2825
2826
    }
}

/* Update any lines between old_current and current that need to be
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2827
 * updated.  Use this if we've moved without changing any text. */
2828
void edit_redraw(const filestruct *old_current, size_t old_pww)
2829
{
2830
    bool do_redraw = need_vertical_update(0) ||
2831
	need_vertical_update(old_pww);
2832
2833
    const filestruct *foo;

2834
2835
    /* If either old_current or current is offscreen, scroll the edit
     * window until it's onscreen and get out. */
2836
2837
2838
2839
2840
    if (old_current->lineno < openfile->edittop->lineno ||
	old_current->lineno >= openfile->edittop->lineno +
	editwinrows || openfile->current->lineno <
	openfile->edittop->lineno || openfile->current->lineno >=
	openfile->edittop->lineno + editwinrows) {
2841
2842
2843
2844
2845
2846
2847
	filestruct *old_edittop = openfile->edittop;
	ssize_t nlines;

	/* Put edittop in range of current, get the difference in lines
	 * between the original edittop and the current edittop, and
	 * then restore the original edittop. */
	edit_update(
2848
#ifndef NANO_TINY
2849
2850
2851
2852
2853
2854
2855
2856
		ISSET(SMOOTH_SCROLL) ? NONE :
#endif
		CENTER);

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

	openfile->edittop = old_edittop;

2857
2858
2859
2860
2861
	/* Update old_current if we're not on the first page and/or
	 * we're not on the same page as before. */
	if (do_redraw)
	    update_line(old_current, 0);

2862
2863
	/* Scroll the edit window up or down until edittop is in range
	 * of current. */
2864
2865
2866
2867
2868
	if (nlines < 0)
	    edit_scroll(UP, -nlines);
	else
	    edit_scroll(DOWN, nlines);

2869
2870
2871
	return;
    }

2872
2873
2874
    /* Update old_current and current if we're not on the first page
     * and/or we're not on the same page as before.  If the mark is on,
     * update all the lines between old_current and current too. */
2875
    foo = old_current;
2876

2877
    while (foo != openfile->current) {
2878
	if (do_redraw)
2879
	    update_line(foo, 0);
2880

2881
#ifndef NANO_TINY
2882
	if (!openfile->mark_set)
2883
2884
#endif
	    break;
2885

2886
#ifndef NANO_TINY
2887
2888
	foo = (foo->lineno > openfile->current->lineno) ? foo->prev :
		foo->next;
2889
#endif
2890
    }
2891

2892
    if (do_redraw)
2893
	update_line(openfile->current, openfile->current_x);
2894
2895
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2896
2897
/* 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
2898
2899
void edit_refresh(void)
{
2900
2901
    const filestruct *foo;
    int nlines;
2902

2903
2904
2905
    if (openfile->current->lineno < openfile->edittop->lineno ||
	openfile->current->lineno >= openfile->edittop->lineno +
	editwinrows)
2906
2907
	/* Put the top line of the edit window in range of the current
	 * line. */
2908
	edit_update(
2909
#ifndef NANO_TINY
2910
		ISSET(SMOOTH_SCROLL) ? NONE :
2911
2912
#endif
		CENTER);
Chris Allegretta's avatar
Chris Allegretta committed
2913

2914
2915
    foo = openfile->edittop;

2916
#ifdef DEBUG
2917
    fprintf(stderr, "edit_refresh(): edittop->lineno = %ld\n", (long)openfile->edittop->lineno);
2918
#endif
2919

2920
    for (nlines = 0; nlines < editwinrows && foo != NULL; nlines++) {
2921
	update_line(foo, (foo == openfile->current) ?
2922
		openfile->current_x : 0);
2923
2924
2925
	foo = foo->next;
    }

2926
    for (; nlines < editwinrows; nlines++)
2927
2928
2929
	blank_line(edit, nlines, 0, COLS);

    reset_cursor();
2930
    wnoutrefresh(edit);
Chris Allegretta's avatar
Chris Allegretta committed
2931
2932
}

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

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

2955
2956
2957
	/* Limit goal to (editwinrows - 1) lines maximum. */
	if (goal > editwinrows - 1)
	    goal = editwinrows - 1;
Chris Allegretta's avatar
Chris Allegretta committed
2958
    }
2959

2960
    for (; goal > 0 && foo->prev != NULL; goal--)
2961
2962
	foo = foo->prev;

2963
    openfile->edittop = foo;
Chris Allegretta's avatar
Chris Allegretta committed
2964
2965
}

2966
/* Unconditionally redraw the entire screen. */
2967
void total_redraw(void)
2968
{
2969
2970
2971
2972
2973
2974
2975
2976
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 3: Slang doesn't define
     * curscr. */
    SLsmg_touch_screen();
    SLsmg_refresh();
#else
    wrefresh(curscr);
#endif
2977
2978
}

2979
2980
/* Unconditionally redraw the entire screen, and then refresh it using
 * the current file. */
2981
2982
void total_refresh(void)
{
2983
    total_redraw();
2984
    titlebar(NULL);
2985
    edit_refresh();
2986
    bottombars(currshortcut);
2987
2988
}

2989
2990
/* Display the main shortcut list on the last two rows of the bottom
 * portion of the window. */
2991
2992
2993
2994
2995
void display_main_list(void)
{
    bottombars(main_list);
}

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

3010
    assert(openfile->fileage != NULL && openfile->current != NULL);
3011

3012
    f = openfile->current->next;
3013
    c = openfile->current->data[openfile->current_x];
3014
3015

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

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

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

3023
3024
    if (constant && disable_cursorpos) {
	disable_cursorpos = FALSE;
3025
	return;
3026
    }
Chris Allegretta's avatar
Chris Allegretta committed
3027

3028
3029
    /* Display the current cursor position on the statusbar, and set 
     * disable_cursorpos to FALSE. */
3030
3031
    linepct = 100 * openfile->current->lineno /
	openfile->filebot->lineno;
3032
    colpct = 100 * cur_xpt / cur_lenpt;
3033
3034
    charpct = (openfile->totsize == 0) ? 0 : 100 * i /
	openfile->totsize;
3035
3036

    statusbar(
3037
	_("line %ld/%ld (%d%%), col %lu/%lu (%d%%), char %lu/%lu (%d%%)"),
3038
	(long)openfile->current->lineno,
3039
	(long)openfile->filebot->lineno, linepct,
3040
	(unsigned long)cur_xpt, (unsigned long)cur_lenpt, colpct,
3041
	(unsigned long)i, (unsigned long)openfile->totsize, charpct);
3042

3043
    disable_cursorpos = FALSE;
Chris Allegretta's avatar
Chris Allegretta committed
3044
3045
}

3046
/* Unconditionally display the current cursor position. */
3047
void do_cursorpos_void(void)
3048
{
3049
    do_cursorpos(FALSE);
3050
3051
}

3052
3053
/* Highlight the current word being replaced or spell checked.  We
 * expect word to have tabs and control characters expanded. */
3054
void do_replace_highlight(bool highlight, const char *word)
Chris Allegretta's avatar
Chris Allegretta committed
3055
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3056
    size_t y = xplustabs(), word_len = strlenpt(word);
Chris Allegretta's avatar
Chris Allegretta committed
3057

3058
    y = get_page_start(y) + COLS - y;
3059
	/* Now y is the number of columns that we can display on this
3060
	 * line. */
Chris Allegretta's avatar
Chris Allegretta committed
3061

3062
3063
3064
3065
3066
    assert(y > 0);

    if (word_len > y)
	y--;

Chris Allegretta's avatar
Chris Allegretta committed
3067
    reset_cursor();
Chris Allegretta's avatar
Chris Allegretta committed
3068

3069
    if (highlight)
3070
	wattron(edit, reverse_attr);
Chris Allegretta's avatar
Chris Allegretta committed
3071

3072
#ifdef HAVE_REGEX_H
3073
3074
    /* This is so we can show zero-length regexes. */
    if (word_len == 0)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3075
	waddch(edit, ' ');
3076
    else
3077
#endif
3078
	waddnstr(edit, word, actual_x(word, y));
3079
3080
3081

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

3083
    if (highlight)
3084
	wattroff(edit, reverse_attr);
Chris Allegretta's avatar
Chris Allegretta committed
3085
3086
}

3087
#ifdef NANO_EXTRA
3088
#define CREDIT_LEN 55
3089
3090
#define XLCREDIT_LEN 8

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

3156
    const char *xlcredits[XLCREDIT_LEN] = {
3157
3158
3159
3160
3161
3162
3163
3164
	N_("The nano text editor"),
	N_("version"),
	N_("Brought to you by:"),
	N_("Special thanks to:"),
	N_("The Free Software Foundation"),
	N_("For ncurses:"),
	N_("and anyone else we forgot..."),
	N_("Thank you for using nano!")
3165
    };
3166

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

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

3182
3183
    curs_set(0);
    nodelay(edit, TRUE);
3184

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

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

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

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

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

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

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

3217
3218
3219
3220
	wrefresh(edit);

	if ((kbinput = wgetch(edit)) != ERR)
	    break;
3221
	napms(700);
3222

3223
	scrollok(edit, TRUE);
3224
	wscrl(edit, 1);
3225
	scrollok(edit, FALSE);
3226
	wrefresh(edit);
3227

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

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

3238
3239
3240
    if (kbinput != ERR)
	ungetch(kbinput);

3241
3242
3243
3244
3245
3246
    if (!old_more_space || !old_no_help) {
	UNSET(MORE_SPACE);
	UNSET(NO_HELP);
	window_init();
    }

3247
    curs_set(1);
3248
    nodelay(edit, FALSE);
3249

3250
    total_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
3251
}
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
3252
#endif /* NANO_EXTRA */