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

23
24
25
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
26

Chris Allegretta's avatar
Chris Allegretta committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdarg.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <errno.h>
#include <ctype.h>
#include <locale.h>
#include "proto.h"

#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

48
49
50
51
#ifndef NANO_SMALL
#include <setjmp.h>
#endif

Chris Allegretta's avatar
Chris Allegretta committed
52
static struct termios oldterm;	/* The user's original term settings */
53
static struct sigaction act;	/* For all our fun signal handlers */
Chris Allegretta's avatar
Chris Allegretta committed
54

55
#ifndef NANO_SMALL
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
56
57
static sigjmp_buf jmpbuf;	/* Used to return to main() after a
				   SIGWINCH. */
58
59
#endif

60
61
62
/* Create a new filestruct node.  Note that we specifically do not set
 * prevnode->next equal to the new line. */
filestruct *make_new_node(filestruct *prevnode)
63
{
64
65
66
67
68
69
70
71
    filestruct *newnode = (filestruct *)nmalloc(sizeof(filestruct));

    newnode->data = NULL;
    newnode->prev = prevnode;
    newnode->next = NULL;
    newnode->lineno = (prevnode != NULL) ? prevnode->lineno + 1 : 1;

    return newnode;
72
73
}

74
75
/* Make a copy of a filestruct node. */
filestruct *copy_node(const filestruct *src)
Chris Allegretta's avatar
Chris Allegretta committed
76
{
77
    filestruct *dst;
Chris Allegretta's avatar
Chris Allegretta committed
78

79
    assert(src != NULL);
Chris Allegretta's avatar
Chris Allegretta committed
80

81
    dst = (filestruct *)nmalloc(sizeof(filestruct));
82

83
84
85
86
    dst->data = mallocstrcpy(NULL, src->data);
    dst->next = src->next;
    dst->prev = src->prev;
    dst->lineno = src->lineno;
87

88
    return dst;
Chris Allegretta's avatar
Chris Allegretta committed
89
90
}

91
92
93
/* Splice a node into an existing filestruct. */
void splice_node(filestruct *begin, filestruct *newnode, filestruct
	*end)
Chris Allegretta's avatar
Chris Allegretta committed
94
{
95
    assert(newnode != NULL && begin != NULL);
96

97
98
99
100
101
102
    newnode->next = end;
    newnode->prev = begin;
    begin->next = newnode;
    if (end != NULL)
	end->prev = newnode;
}
103

104
105
106
107
/* Unlink a node from the rest of the filestruct. */
void unlink_node(const filestruct *fileptr)
{
    assert(fileptr != NULL);
108

109
110
111
112
113
    if (fileptr->prev != NULL)
	fileptr->prev->next = fileptr->next;
    if (fileptr->next != NULL)
	fileptr->next->prev = fileptr->prev;
}
114

115
116
117
118
/* Delete a node from the filestruct. */
void delete_node(filestruct *fileptr)
{
    assert(fileptr != NULL && fileptr->data != NULL);
119

120
121
    if (fileptr->data != NULL)
	free(fileptr->data);
122

123
    free(fileptr);
124
125
}

126
127
/* Duplicate a whole filestruct. */
filestruct *copy_filestruct(const filestruct *src)
128
{
129
    filestruct *head, *copy;
130

131
    assert(src != NULL);
132

133
134
135
136
    copy = copy_node(src);
    copy->prev = NULL;
    head = copy;
    src = src->next;
137

138
139
140
141
    while (src != NULL) {
	copy->next = copy_node(src);
	copy->next->prev = copy;
	copy = copy->next;
Chris Allegretta's avatar
Chris Allegretta committed
142

143
144
	src = src->next;
    }
145

146
    copy->next = NULL;
147

148
    return head;
Chris Allegretta's avatar
Chris Allegretta committed
149
150
}

151
/* Free a filestruct. */
152
void free_filestruct(filestruct *src)
153
{
154
155
156
157
158
159
    assert(src != NULL);

    while (src->next != NULL) {
	src = src->next;
	delete_node(src->prev);
    }
160

161
    delete_node(src);
162
163
}

164
/* Renumber all entries in a filestruct, starting with fileptr. */
165
void renumber(filestruct *fileptr)
Chris Allegretta's avatar
Chris Allegretta committed
166
{
167
    ssize_t line;
168

169
    assert(fileptr != NULL && fileptr->prev != NULL);
Chris Allegretta's avatar
Chris Allegretta committed
170

171
    line = (fileptr->prev == NULL) ? 0 : fileptr->prev->lineno;
172

173
    assert(fileptr != fileptr->next);
174

175
    for (; fileptr != NULL; fileptr = fileptr->next)
176
	fileptr->lineno = ++line;
Chris Allegretta's avatar
Chris Allegretta committed
177
178
}

179
180
181
182
/* Partition a filestruct so it begins at (top, top_x) and ends at (bot,
 * bot_x). */
partition *partition_filestruct(filestruct *top, size_t top_x,
	filestruct *bot, size_t bot_x)
183
{
184
    partition *p;
185

186
    assert(top != NULL && bot != NULL && openfile->fileage != NULL && openfile->filebot != NULL);
187

188
189
    /* Initialize the partition. */
    p = (partition *)nmalloc(sizeof(partition));
190

191
192
193
    /* If the top and bottom of the partition are different from the top
     * and bottom of the filestruct, save the latter and then set them
     * to top and bot. */
194
195
196
    if (top != openfile->fileage) {
	p->fileage = openfile->fileage;
	openfile->fileage = top;
197
    } else
198
	p->fileage = NULL;
199
200
201
    if (bot != openfile->filebot) {
	p->filebot = openfile->filebot;
	openfile->filebot = bot;
202
203
    } else
	p->filebot = NULL;
204

205
206
207
208
209
210
211
    /* Save the line above the top of the partition, detach the top of
     * the partition from it, and save the text before top_x in
     * top_data. */
    p->top_prev = top->prev;
    top->prev = NULL;
    p->top_data = mallocstrncpy(NULL, top->data, top_x + 1);
    p->top_data[top_x] = '\0';
212

213
214
215
216
217
218
    /* Save the line below the bottom of the partition, detach the
     * bottom of the partition from it, and save the text after bot_x in
     * bot_data. */
    p->bot_next = bot->next;
    bot->next = NULL;
    p->bot_data = mallocstrcpy(NULL, bot->data + bot_x);
219

220
221
    /* Remove all text after bot_x at the bottom of the partition. */
    null_at(&bot->data, bot_x);
222

223
    /* Remove all text before top_x at the top of the partition. */
224
225
    charmove(top->data, top->data + top_x, strlen(top->data) - top_x +
	1);
226
    align(&top->data);
227

228
229
230
    /* Return the partition. */
    return p;
}
231

232
233
234
235
236
/* Unpartition a filestruct so it begins at (fileage, 0) and ends at
 * (filebot, strlen(filebot)) again. */
void unpartition_filestruct(partition **p)
{
    char *tmp;
237

238
    assert(p != NULL && openfile->fileage != NULL && openfile->filebot != NULL);
239

240
241
242
    /* Reattach the line above the top of the partition, and restore the
     * text before top_x from top_data.  Free top_data when we're done
     * with it. */
243
244
245
246
247
248
249
    tmp = mallocstrcpy(NULL, openfile->fileage->data);
    openfile->fileage->prev = (*p)->top_prev;
    if (openfile->fileage->prev != NULL)
	openfile->fileage->prev->next = openfile->fileage;
    openfile->fileage->data = charealloc(openfile->fileage->data,
	strlen((*p)->top_data) + strlen(openfile->fileage->data) + 1);
    strcpy(openfile->fileage->data, (*p)->top_data);
250
    free((*p)->top_data);
251
    strcat(openfile->fileage->data, tmp);
252
    free(tmp);
253

254
255
256
    /* Reattach the line below the bottom of the partition, and restore
     * the text after bot_x from bot_data.  Free bot_data when we're
     * done with it. */
257
258
259
260
261
262
    openfile->filebot->next = (*p)->bot_next;
    if (openfile->filebot->next != NULL)
	openfile->filebot->next->prev = openfile->filebot;
    openfile->filebot->data = charealloc(openfile->filebot->data,
	strlen(openfile->filebot->data) + strlen((*p)->bot_data) + 1);
    strcat(openfile->filebot->data, (*p)->bot_data);
263
    free((*p)->bot_data);
264

265
266
267
    /* Restore the top and bottom of the filestruct, if they were
     * different from the top and bottom of the partition. */
    if ((*p)->fileage != NULL)
268
	openfile->fileage = (*p)->fileage;
269
    if ((*p)->filebot != NULL)
270
	openfile->filebot = (*p)->filebot;
271

272
273
274
275
    /* Uninitialize the partition. */
    free(*p);
    *p = NULL;
}
276

277
278
279
280
281
282
283
284
285
286
287
288
/* Move all the text between (top, top_x) and (bot, bot_x) in the
 * current filestruct to a filestruct beginning with file_top and ending
 * with file_bot.  If no text is between (top, top_x) and (bot, bot_x),
 * don't do anything. */
void move_to_filestruct(filestruct **file_top, filestruct **file_bot,
	filestruct *top, size_t top_x, filestruct *bot, size_t bot_x)
{
    filestruct *top_save;
    bool at_edittop;
#ifndef NANO_SMALL
    bool mark_inside = FALSE;
#endif
289

290
    assert(file_top != NULL && file_bot != NULL && top != NULL && bot != NULL);
291

292
293
294
    /* If (top, top_x)-(bot, bot_x) doesn't cover any text, get out. */
    if (top == bot && top_x == bot_x)
	return;
295

296
297
298
299
300
    /* Partition the filestruct so that it contains only the text from
     * (top, top_x) to (bot, bot_x), keep track of whether the top of
     * the partition is the top of the edit window, and keep track of
     * whether the mark begins inside the partition. */
    filepart = partition_filestruct(top, top_x, bot, bot_x);
301
    at_edittop = (openfile->fileage == openfile->edittop);
302
#ifndef NANO_SMALL
303
    if (openfile->mark_set)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
304
	mark_inside = (openfile->mark_begin->lineno >=
305
		openfile->fileage->lineno &&
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
306
		openfile->mark_begin->lineno <=
307
		openfile->filebot->lineno &&
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
308
309
310
311
		(openfile->mark_begin != openfile->fileage ||
		openfile->mark_begin_x >= top_x) &&
		(openfile->mark_begin != openfile->filebot ||
		openfile->mark_begin_x <= bot_x));
312
#endif
313

314
315
    /* Get the number of characters in the text, and subtract it from
     * totsize. */
316
    openfile->totsize -= get_totsize(top, bot);
317

318
319
320
321
    if (*file_top == NULL) {
	/* If file_top is empty, just move all the text directly into
	 * it.  This is equivalent to tacking the text in top onto the
	 * (lack of) text at the end of file_top. */
322
323
	*file_top = openfile->fileage;
	*file_bot = openfile->filebot;
324
325
326

	/* Renumber starting with file_top. */
	renumber(*file_top);
327
    } else {
328
329
	filestruct *file_bot_save = *file_bot;

330
331
332
	/* Otherwise, tack the text in top onto the text at the end of
	 * file_bot. */
	(*file_bot)->data = charealloc((*file_bot)->data,
333
334
335
		strlen((*file_bot)->data) +
		strlen(openfile->fileage->data) + 1);
	strcat((*file_bot)->data, openfile->fileage->data);
336

337
338
339
	/* Attach the line after top to the line after file_bot.  Then,
	 * if there's more than one line after top, move file_bot down
	 * to bot. */
340
	(*file_bot)->next = openfile->fileage->next;
341
342
	if ((*file_bot)->next != NULL) {
	    (*file_bot)->next->prev = *file_bot;
343
	    *file_bot = openfile->filebot;
344
	}
345
346
347
348
349

	/* Renumber starting with the line after the original
	 * file_bot. */
	if (file_bot_save->next != NULL)
	    renumber(file_bot_save->next);
350
    }
351

352
353
354
355
356
    /* Since the text has now been saved, remove it from the filestruct.
     * If the top of the partition was the top of the edit window, set
     * edittop to where the text used to start.  If the mark began
     * inside the partition, set the beginning of the mark to where the
     * text used to start. */
357
358
359
    openfile->fileage = (filestruct *)nmalloc(sizeof(filestruct));
    openfile->fileage->data = mallocstrcpy(NULL, "");
    openfile->filebot = openfile->fileage;
360
    if (at_edittop)
361
	openfile->edittop = openfile->fileage;
362
363
#ifndef NANO_SMALL
    if (mark_inside) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
364
365
	openfile->mark_begin = openfile->fileage;
	openfile->mark_begin_x = top_x;
366
367
    }
#endif
368

369
    /* Restore the current line and cursor position. */
370
371
    openfile->current = openfile->fileage;
    openfile->current_x = top_x;
372

373
    top_save = openfile->fileage;
374

375
376
377
    /* Unpartition the filestruct so that it contains all the text
     * again, minus the saved text. */
    unpartition_filestruct(&filepart);
378

379
380
381
    /* Renumber starting with the beginning line of the old
     * partition. */
    renumber(top_save);
382

383
    if (openfile->filebot->data[0] != '\0')
384
	new_magicline();
385

386
    /* Set totlines to the new number of lines in the file. */
387
    openfile->totlines = openfile->filebot->lineno;
388
}
389

390
391
392
393
394
395
396
/* Copy all the text from the filestruct beginning with file_top and
 * ending with file_bot to the current filestruct at the current cursor
 * position. */
void copy_from_filestruct(filestruct *file_top, filestruct *file_bot)
{
    filestruct *top_save;
    bool at_edittop;
397

398
    assert(file_top != NULL && file_bot != NULL);
399

400
401
402
    /* Partition the filestruct so that it contains no text, and keep
     * track of whether the top of the partition is the top of the edit
     * window. */
403
404
405
    filepart = partition_filestruct(openfile->current,
	openfile->current_x, openfile->current, openfile->current_x);
    at_edittop = (openfile->fileage == openfile->edittop);
406

407
408
    /* Put the top and bottom of the filestruct at copies of file_top
     * and file_bot. */
409
410
411
412
    openfile->fileage = copy_filestruct(file_top);
    openfile->filebot = openfile->fileage;
    while (openfile->filebot->next != NULL)
	openfile->filebot = openfile->filebot->next;
413

414
    /* Restore the current line and cursor position. */
415
416
417
418
    openfile->current = openfile->filebot;
    openfile->current_x = strlen(openfile->filebot->data);
    if (openfile->fileage == openfile->filebot)
	openfile->current_x += strlen(filepart->top_data);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
419

420
421
422
423
    /* Get the number of characters in the text, and add it to
     * totsize. */
    openfile->totsize += get_totsize(openfile->fileage,
	openfile->filebot);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
424

425
426
427
428
429
430
    /* If the top of the partition was the top of the edit window, set
     * edittop to where the saved text now starts, and update the
     * current y-coordinate to account for the number of lines it
     * has, less one since the first line will be tacked onto the
     * current line. */
    if (at_edittop)
431
	openfile->edittop = openfile->fileage;
432
    openfile->current_y += openfile->filebot->lineno - 1;
433

434
    top_save = openfile->fileage;
435

436
437
438
    /* Unpartition the filestruct so that it contains all the text
     * again, minus the saved text. */
    unpartition_filestruct(&filepart);
439

440
441
442
    /* Renumber starting with the beginning line of the old
     * partition. */
    renumber(top_save);
443

444
    if (openfile->filebot->data[0] != '\0')
445
	new_magicline();
446

447
    /* Set totlines to the new number of lines in the file. */
448
    openfile->totlines = openfile->filebot->lineno;
Chris Allegretta's avatar
Chris Allegretta committed
449
450
}

451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/* Create a new openfilestruct node. */
openfilestruct *make_new_opennode(void)
{
    openfilestruct *newnode =
	(openfilestruct *)nmalloc(sizeof(openfilestruct));

    newnode->filename = NULL;
    newnode->fileage = NULL;
    newnode->filebot = NULL;
    newnode->edittop = NULL;
    newnode->current = NULL;

    return newnode;
}

/* Splice a node into an existing openfilestruct. */
void splice_opennode(openfilestruct *begin, openfilestruct *newnode,
	openfilestruct *end)
{
    assert(newnode != NULL && begin != NULL);

    newnode->next = end;
    newnode->prev = begin;
    begin->next = newnode;

    if (end != NULL)
	end->prev = newnode;
}

/* Unlink a node from the rest of the openfilestruct, and delete it. */
void unlink_opennode(openfilestruct *fileptr)
{
    assert(fileptr != NULL && fileptr->prev != NULL && fileptr->next != NULL && fileptr != fileptr->prev && fileptr != fileptr->next);

    fileptr->prev->next = fileptr->next;
    fileptr->next->prev = fileptr->prev;

    delete_opennode(fileptr);
}

/* Delete a node from the openfilestruct. */
void delete_opennode(openfilestruct *fileptr)
{
    assert(fileptr != NULL && fileptr->filename != NULL && fileptr->fileage != NULL);

    free(fileptr->filename);
    free_filestruct(fileptr->fileage);
#ifndef NANO_SMALL
    if (fileptr->current_stat != NULL)
	free(fileptr->current_stat);
#endif

    free(fileptr);
}

#ifdef DEBUG
/* Deallocate all memory associated with this and later files, including
 * the lines of text. */
void free_openfilestruct(openfilestruct *src)
{
    assert(src != NULL);

    while (src != src->next) {
	src = src->next;
	delete_opennode(src->prev);
    }

    delete_opennode(src);
}
#endif

522
void print_view_warning(void)
523
{
524
    statusbar(_("Key illegal in VIEW mode"));
525
526
}

527
528
/* What we do when we're all set to exit. */
void finish(void)
Chris Allegretta's avatar
Chris Allegretta committed
529
{
530
531
532
533
    if (!ISSET(NO_HELP))
	blank_bottombars();
    else
	blank_statusbar();
534

535
536
    wrefresh(bottomwin);
    endwin();
537

538
539
    /* Restore the old terminal settings. */
    tcsetattr(0, TCSANOW, &oldterm);
540

541
542
543
544
545
546
547
548
549
550
#if !defined(NANO_SMALL) && defined(ENABLE_NANORC)
    if (!ISSET(NO_RCFILE) && ISSET(HISTORYLOG))
	save_history();
#endif

#ifdef DEBUG
    thanks_for_all_the_fish();
#endif

    exit(0);
551
552
}

553
554
/* Die (gracefully?). */
void die(const char *msg, ...)
Chris Allegretta's avatar
Chris Allegretta committed
555
{
556
    va_list ap;
Chris Allegretta's avatar
Chris Allegretta committed
557

558
559
    endwin();
    curses_ended = TRUE;
Chris Allegretta's avatar
Chris Allegretta committed
560

561
562
    /* Restore the old terminal settings. */
    tcsetattr(0, TCSANOW, &oldterm);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
563

564
565
566
    va_start(ap, msg);
    vfprintf(stderr, msg, ap);
    va_end(ap);
Chris Allegretta's avatar
Chris Allegretta committed
567

568
    /* Save the current file buffer if it's been modified. */
569
    if (openfile->modified) {
570
571
572
573
	/* If we've partitioned the filestruct, unpartition it now. */
	if (filepart != NULL)
	    unpartition_filestruct(&filepart);

574
	die_save_file(openfile->filename);
Chris Allegretta's avatar
Chris Allegretta committed
575
576
    }

577
578
#ifdef ENABLE_MULTIBUFFER
    /* Save all of the other modified file buffers, if any. */
579
580
    if (openfile != NULL) {
	openfilestruct *tmp = openfile;
Chris Allegretta's avatar
Chris Allegretta committed
581

582
583
	while (tmp != openfile->next) {
	    openfile = openfile->next;
584

585
	    /* Save the current file buffer if it's been modified. */
586
	    if (openfile->modified)
587
		die_save_file(openfile->filename);
588
	}
589
    }
590
591
592
593
#endif

    /* Get out. */
    exit(1);
594
595
}

596
void die_save_file(const char *die_filename)
597
{
598
599
    char *retval;
    bool failed = TRUE;
600

601
602
603
604
605
    /* If we're using restricted mode, don't write any emergency backup
     * files, since that would allow reading from or writing to files
     * not specified on the command line. */
    if (ISSET(RESTRICTED))
	return;
606

607
608
609
610
    /* If we can't save, we have REAL bad problems, but we might as well
     * TRY. */
    if (die_filename[0] == '\0')
	die_filename = "nano";
611

612
613
614
    retval = get_next_filename(die_filename, ".save");
    if (retval[0] != '\0')
	failed = (write_file(retval, NULL, TRUE, FALSE, TRUE) == -1);
615

616
617
618
619
620
621
622
623
    if (!failed)
	fprintf(stderr, _("\nBuffer written to %s\n"), retval);
    else if (retval[0] != '\0')
	fprintf(stderr, _("\nBuffer not written to %s: %s\n"), retval,
		strerror(errno));
    else
	fprintf(stderr, _("\nBuffer not written: %s\n"),
		_("Too many backup files?"));
624

625
626
    free(retval);
}
627

628
629
630
631
632
633
634
635
/* Die with an error message that the screen was too small if, well, the
 * screen is too small. */
void check_die_too_small(void)
{
    editwinrows = LINES - 5 + no_more_space() + no_help();
    if (editwinrows < MIN_EDITOR_ROWS)
	die(_("Window size is too small for nano...\n"));
}
636

637
638
639
/* Make sure the window size isn't too small, and reinitialize the fill
 * variable, since it depends on the window size. */
void window_size_init(void)
640
{
641
642
    check_die_too_small();

643
644
645
646
647
648
649
650
#ifndef DISABLE_WRAPJUSTIFY
    fill = wrap_at;
    if (fill <= 0)
	fill += COLS;
    if (fill < 0)
	fill = 0;
#endif
}
651

652
653
654
void window_init(void)
{
    check_die_too_small();
655

656
657
658
659
660
661
    if (topwin != NULL)
	delwin(topwin);
    if (edit != NULL)
	delwin(edit);
    if (bottomwin != NULL)
	delwin(bottomwin);
662

663
664
665
    /* Set up the windows. */
    topwin = newwin(2 - no_more_space(), COLS, 0, 0);
    edit = newwin(editwinrows, COLS, 2 - no_more_space(), 0);
666
667
    bottomwin = newwin(3 - no_help(), COLS, editwinrows + (2 -
	no_more_space()), 0);
668

669
670
671
    /* Turn the keypad back on. */
    keypad(edit, TRUE);
    keypad(bottomwin, TRUE);
672
673
}

674
675
#ifndef DISABLE_MOUSE
void mouse_init(void)
676
{
677
678
679
680
681
682
    if (ISSET(USE_MOUSE)) {
	mousemask(BUTTON1_RELEASED, NULL);
	mouseinterval(50);
    } else
	mousemask(0, NULL);
}
683
684
#endif

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#ifndef DISABLE_HELP
/* This function allocates help_text, and stores the help string in it. 
 * help_text should be NULL initially. */
void help_init(void)
{
    size_t allocsize = 0;	/* Space needed for help_text. */
    const char *htx[3];		/* Untranslated help message.  We break
				 * it up into three chunks in case the
				 * full string is too long for the
				 * compiler to handle. */
    char *ptr;
    const shortcut *s;
#ifndef NANO_SMALL
    const toggle *t;
#ifdef ENABLE_NANORC
    bool old_whitespace = ISSET(WHITESPACE_DISPLAY);
701

702
703
704
    UNSET(WHITESPACE_DISPLAY);
#endif
#endif
705

706
    /* First, set up the initial help text for the current function. */
707
708
    if (currshortcut == whereis_list || currshortcut == replace_list ||
	currshortcut == replace_list_2) {
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
	htx[0] = N_("Search Command Help Text\n\n "
		"Enter the words or characters you would like to "
		"search for, and then press Enter.  If there is a "
		"match for the text you entered, the screen will be "
		"updated to the location of the nearest match for the "
		"search string.\n\n The previous search string will be "
		"shown in brackets after the search prompt.  Hitting "
		"Enter without entering any text will perform the "
		"previous search.  ");
	htx[1] = N_("If you have selected text with the mark and then "
		"search to replace, only matches in the selected text "
		"will be replaced.\n\n The following function keys are "
		"available in Search mode:\n\n");
	htx[2] = NULL;
    } else if (currshortcut == gotoline_list) {
	htx[0] = N_("Go To Line Help Text\n\n "
		"Enter the line number that you wish to go to and hit "
		"Enter.  If there are fewer lines of text than the "
		"number you entered, you will be brought to the last "
		"line of the file.\n\n The following function keys are "
		"available in Go To Line mode:\n\n");
	htx[1] = NULL;
	htx[2] = NULL;
    } else if (currshortcut == insertfile_list) {
	htx[0] = N_("Insert File Help Text\n\n "
		"Type in the name of a file to be inserted into the "
		"current file buffer at the current cursor "
		"location.\n\n If you have compiled nano with multiple "
		"file buffer support, and enable multiple file buffers "
		"with the -F or --multibuffer command line flags, the "
		"Meta-F toggle, or a nanorc file, inserting a file "
		"will cause it to be loaded into a separate buffer "
		"(use Meta-< and > to switch between file buffers).  ");
	htx[1] = N_("If you need another blank buffer, do not enter "
		"any filename, or type in a nonexistent filename at "
		"the prompt and press Enter.\n\n The following "
		"function keys are available in Insert File mode:\n\n");
	htx[2] = NULL;
    } else if (currshortcut == writefile_list) {
	htx[0] = N_("Write File Help Text\n\n "
		"Type the name that you wish to save the current file "
		"as and press Enter to save the file.\n\n If you have "
		"selected text with the mark, you will be prompted to "
		"save only the selected portion to a separate file.  To "
		"reduce the chance of overwriting the current file with "
		"just a portion of it, the current filename is not the "
		"default in this mode.\n\n The following function keys "
		"are available in Write File mode:\n\n");
	htx[1] = NULL;
	htx[2] = NULL;
    }
#ifndef DISABLE_BROWSER
    else if (currshortcut == browser_list) {
	htx[0] = N_("File Browser Help Text\n\n "
		"The file browser is used to visually browse the "
		"directory structure to select a file for reading "
		"or writing.  You may use the arrow keys or Page Up/"
		"Down to browse through the files, and S or Enter to "
		"choose the selected file or enter the selected "
		"directory.  To move up one level, select the "
		"directory called \"..\" at the top of the file "
		"list.\n\n The following function keys are available "
		"in the file browser:\n\n");
	htx[1] = NULL;
	htx[2] = NULL;
    } else if (currshortcut == gotodir_list) {
	htx[0] = N_("Browser Go To Directory Help Text\n\n "
		"Enter the name of the directory you would like to "
		"browse to.\n\n If tab completion has not been "
		"disabled, you can use the Tab key to (attempt to) "
		"automatically complete the directory name.\n\n The "
		"following function keys are available in Browser Go "
		"To Directory mode:\n\n");
	htx[1] = NULL;
	htx[2] = NULL;
    }
#endif
#ifndef DISABLE_SPELLER
    else if (currshortcut == spell_list) {
	htx[0] = N_("Spell Check Help Text\n\n "
		"The spell checker checks the spelling of all text in "
		"the current file.  When an unknown word is "
		"encountered, it is highlighted and a replacement can "
		"be edited.  It will then prompt to replace every "
		"instance of the given misspelled word in the current "
		"file, or, if you have selected text with the mark, in "
		"the selected text.\n\n The following other functions "
		"are available in Spell Check mode:\n\n");
	htx[1] = NULL;
	htx[2] = NULL;
    }
#endif
801
#ifndef NANO_SMALL
802
803
804
805
806
807
808
809
810
811
812
    else if (currshortcut == extcmd_list) {
	htx[0] = N_("Execute Command Help Text\n\n "
		"This menu allows you to insert the output of a "
		"command run by the shell into the current buffer (or "
		"a new buffer in multiple file buffer mode). If you "
		"need another blank buffer, do not enter any "
		"command.\n\n The following keys are available in "
		"Execute Command mode:\n\n");
	htx[1] = NULL;
	htx[2] = NULL;
    }
813
#endif
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
    else {
	/* Default to the main help list. */
	htx[0] = N_(" nano help text\n\n "
		"The nano editor is designed to emulate the "
		"functionality and ease-of-use of the UW Pico text "
		"editor.  There are four main sections of the editor.  "
		"The top line shows the program version, the current "
		"filename being edited, and whether or not the file "
		"has been modified.  Next is the main editor window "
		"showing the file being edited.  The status line is "
		"the third line from the bottom and shows important "
		"messages.  The bottom two lines show the most "
		"commonly used shortcuts in the editor.\n\n ");
	htx[1] = N_("The notation for shortcuts is as follows: "
		"Control-key sequences are notated with a caret (^) "
		"symbol and can be entered either by using the Control "
		"(Ctrl) key or pressing the Escape (Esc) key twice.  "
		"Escape-key sequences are notated with the Meta (M) "
		"symbol and can be entered using either the Esc, Alt, "
		"or Meta key depending on your keyboard setup.  ");
	htx[2] = N_("Also, pressing Esc twice and then typing a "
		"three-digit decimal number from 000 to 255 will enter "
		"the character with the corresponding value.  The "
		"following keystrokes are available in the main editor "
		"window.  Alternative keys are shown in "
		"parentheses:\n\n");
    }
841

842
843
844
845
846
    htx[0] = _(htx[0]);
    if (htx[1] != NULL)
	htx[1] = _(htx[1]);
    if (htx[2] != NULL)
	htx[2] = _(htx[2]);
847

848
849
850
851
852
    allocsize += strlen(htx[0]);
    if (htx[1] != NULL)
	allocsize += strlen(htx[1]);
    if (htx[2] != NULL)
	allocsize += strlen(htx[2]);
853

854
855
856
857
    /* The space needed for the shortcut lists, at most COLS characters,
     * plus '\n'. */
    allocsize += (COLS < 24 ? (24 * mb_cur_max()) :
	((COLS + 1) * mb_cur_max())) * length_of_list(currshortcut);
858
859

#ifndef NANO_SMALL
860
861
862
863
864
865
866
867
    /* If we're on the main list, we also count the toggle help text.
     * Each line has "M-%c\t\t\t", which fills 24 columns, plus a space,
     * plus translated text, plus '\n'. */
    if (currshortcut == main_list) {
	size_t endis_len = strlen(_("enable/disable"));

	for (t = toggles; t != NULL; t = t->next)
	    allocsize += 8 + strlen(t->desc) + endis_len;
868
869
870
    }
#endif

871
872
873
    /* help_text has been freed and set to NULL unless the user resized
     * while in the help screen. */
    free(help_text);
874

875
876
    /* Allocate space for the help text. */
    help_text = charalloc(allocsize + 1);
877

878
879
880
881
882
883
    /* Now add the text we want. */
    strcpy(help_text, htx[0]);
    if (htx[1] != NULL)
	strcat(help_text, htx[1]);
    if (htx[2] != NULL)
	strcat(help_text, htx[2]);
884

885
    ptr = help_text + strlen(help_text);
886

887
888
889
890
891
892
893
    /* Now add our shortcut info.  Assume that each shortcut has, at the
     * very least, an equivalent control key, an equivalent primary meta
     * key sequence, or both.  Also assume that the meta key values are
     * not control characters.  We can display a maximum of 3 shortcut
     * entries. */
    for (s = currshortcut; s != NULL; s = s->next) {
	int entries = 0;
894

895
896
897
898
899
900
901
902
	/* Control key. */
	if (s->ctrlval != NANO_NO_KEY) {
	    entries++;
	    /* Yucky sentinel values that we can't handle a better
	     * way. */
	    if (s->ctrlval == NANO_CONTROL_SPACE) {
		char *space_ptr = display_string(_("Space"), 0, 6,
			FALSE);
903

904
		ptr += sprintf(ptr, "^%s", space_ptr);
905

906
907
908
909
910
911
912
913
		free(space_ptr);
	    } else if (s->ctrlval == NANO_CONTROL_8)
		ptr += sprintf(ptr, "^?");
	    /* Normal values. */
	    else
		ptr += sprintf(ptr, "^%c", s->ctrlval + 64);
	    *(ptr++) = '\t';
	}
914

915
916
917
918
919
920
921
922
923
924
925
	/* Function key. */
	if (s->funcval != NANO_NO_KEY) {
	    entries++;
	    /* If this is the first entry, put it in the middle. */
	    if (entries == 1) {
		entries++;
		*(ptr++) = '\t';
	    }
	    ptr += sprintf(ptr, "(F%d)", s->funcval - KEY_F0);
	    *(ptr++) = '\t';
	}
926

927
928
929
930
931
932
933
934
935
936
937
938
939
940
	/* Primary meta key sequence.  If it's the first entry, don't
	 * put parentheses around it. */
	if (s->metaval != NANO_NO_KEY) {
	    entries++;
	    /* If this is the last entry, put it at the end. */
	    if (entries == 2 && s->miscval == NANO_NO_KEY) {
		entries++;
		*(ptr++) = '\t';
	    }
	    /* Yucky sentinel values that we can't handle a better
	     * way. */
	    if (s->metaval == NANO_ALT_SPACE && entries == 1) {
		char *space_ptr = display_string(_("Space"), 0, 5,
			FALSE);
941

942
		ptr += sprintf(ptr, "M-%s", space_ptr);
943

944
945
946
947
948
949
950
		free(space_ptr);
	    } else
		/* Normal values. */
		ptr += sprintf(ptr, (entries == 1) ? "M-%c" : "(M-%c)",
			toupper(s->metaval));
	    *(ptr++) = '\t';
	}
951

952
953
954
955
956
957
958
959
960
961
962
	/* Miscellaneous meta key sequence. */
	if (entries < 3 && s->miscval != NANO_NO_KEY) {
	    entries++;
	    /* If this is the last entry, put it at the end. */
	    if (entries == 2) {
		entries++;
		*(ptr++) = '\t';
	    }
	    ptr += sprintf(ptr, "(M-%c)", toupper(s->miscval));
	    *(ptr++) = '\t';
	}
963

964
965
966
967
968
	/* Make sure all the help text starts at the same place. */
	while (entries < 3) {
	    entries++;
	    *(ptr++) = '\t';
	}
969

970
	assert(s->help != NULL);
971

972
973
974
	if (COLS > 24) {
	    char *help_ptr = display_string(s->help, 0, COLS - 24,
		FALSE);
975

976
	    ptr += sprintf(ptr, help_ptr);
977

978
979
	    free(help_ptr);
	}
980

981
982
	ptr += sprintf(ptr, "\n");
    }
Chris Allegretta's avatar
Chris Allegretta committed
983

984
985
986
987
#ifndef NANO_SMALL
    /* And the toggles... */
    if (currshortcut == main_list) {
	for (t = toggles; t != NULL; t = t->next) {
988

989
	    assert(t->desc != NULL);
Chris Allegretta's avatar
Chris Allegretta committed
990

991
992
993
994
	    ptr += sprintf(ptr, "M-%c\t\t\t%s %s\n", toupper(t->val),
		t->desc, _("enable/disable"));
	}
    }
995

996
997
998
999
1000
#ifdef ENABLE_NANORC
    if (old_whitespace)
	SET(WHITESPACE_DISPLAY);
#endif
#endif
1001

1002
1003
1004
    /* If all went well, we didn't overwrite the allocated space for
     * help_text. */
    assert(strlen(help_text) <= allocsize + 1);
Chris Allegretta's avatar
Chris Allegretta committed
1005
}
1006
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1007

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1008
1009
1010
1011
1012
1013
#ifdef HAVE_GETOPT_LONG
#define print1opt(shortflag, longflag, desc) print1opt_full(shortflag, longflag, desc)
#else
#define print1opt(shortflag, longflag, desc) print1opt_full(shortflag, desc)
#endif

1014
/* Print one usage string to the screen.  This cuts down on duplicate
1015
 * strings to translate, and leaves out the parts that shouldn't be
Chris Allegretta's avatar
Chris Allegretta committed
1016
 * translatable (the flag names). */
1017
1018
1019
1020
1021
void print1opt_full(const char *shortflag
#ifdef HAVE_GETOPT_LONG
	, const char *longflag
#endif
	, const char *desc)
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
{
    printf(" %s\t", shortflag);
    if (strlen(shortflag) < 8)
	printf("\t");

#ifdef HAVE_GETOPT_LONG
    printf("%s\t", longflag);
    if (strlen(longflag) < 8)
	printf("\t\t");
    else if (strlen(longflag) < 16)
	printf("\t");
#endif

1035
1036
1037
    if (desc != NULL)
	printf("%s", _(desc));
    printf("\n");
1038
1039
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1040
void usage(void)
Chris Allegretta's avatar
Chris Allegretta committed
1041
1042
{
#ifdef HAVE_GETOPT_LONG
1043
1044
    printf(
	_("Usage: nano [+LINE,COLUMN] [GNU long option] [option] [file]\n\n"));
Chris Allegretta's avatar
Chris Allegretta committed
1045
    printf(_("Option\t\tLong option\t\tMeaning\n"));
Chris Allegretta's avatar
Chris Allegretta committed
1046
#else
1047
    printf(_("Usage: nano [+LINE,COLUMN] [option] [file]\n\n"));
Chris Allegretta's avatar
Chris Allegretta committed
1048
    printf(_("Option\t\tMeaning\n"));
1049
#endif
1050

1051
    print1opt("-h, -?", "--help", N_("Show this message"));
1052
1053
    print1opt(_("+LINE,COLUMN"), "",
	N_("Start at line LINE, column COLUMN"));
1054
#ifndef NANO_SMALL
1055
    print1opt("-A", "--smarthome", N_("Enable smart home key"));
1056
    print1opt("-B", "--backup", N_("Save backups of existing files"));
1057
    print1opt(_("-C [dir]"), _("--backupdir=[dir]"),
1058
	N_("Directory for saving unique backup files"));
1059
1060
    print1opt("-E", "--tabstospaces",
	N_("Convert typed tabs to spaces"));
1061
#endif
1062
#ifdef ENABLE_MULTIBUFFER
1063
    print1opt("-F", "--multibuffer", N_("Enable multiple file buffers"));
Chris Allegretta's avatar
Chris Allegretta committed
1064
1065
#endif
#ifdef ENABLE_NANORC
1066
#ifndef NANO_SMALL
1067
1068
    print1opt("-H", "--historylog",
	N_("Log & read search/replace string history"));
1069
#endif
1070
1071
    print1opt("-I", "--ignorercfiles",
	N_("Don't look at nanorc files"));
Chris Allegretta's avatar
Chris Allegretta committed
1072
1073
#endif
#ifndef NANO_SMALL
1074
1075
    print1opt("-N", "--noconvert",
	N_("Don't convert files from DOS/Mac format"));
1076
#endif
1077
    print1opt("-O", "--morespace", N_("Use more space for editing"));
1078
#ifndef DISABLE_JUSTIFY
1079
    print1opt(_("-Q [str]"), _("--quotestr=[str]"),
1080
	N_("Quoting string"));
1081
#endif
1082
    print1opt("-R", "--restricted", N_("Restricted mode"));
1083
#ifndef NANO_SMALL
1084
    print1opt("-S", "--smooth", N_("Smooth scrolling"));
1085
#endif
1086
1087
    print1opt(_("-T [#cols]"), _("--tabsize=[#cols]"),
	N_("Set width of a tab in cols to #cols"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1088
#ifndef NANO_SMALL
1089
1090
    print1opt("-U", _("--quickblank"),
	N_("Do quick statusbar blanking"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1091
#endif
1092
1093
    print1opt("-V", "--version",
	N_("Print version information and exit"));
1094
#ifdef ENABLE_COLOR
1095
1096
    print1opt(_("-Y [str]"), _("--syntax=[str]"),
	N_("Syntax definition to use"));
1097
#endif
1098
    print1opt("-c", "--const", N_("Constantly show cursor position"));
1099
1100
    print1opt("-d", "--rebinddelete",
	N_("Fix Backspace/Delete confusion problem"));
1101
#ifndef NANO_SMALL
1102
1103
    print1opt("-i", "--autoindent",
	N_("Automatically indent new lines"));
1104
    print1opt("-k", "--cut", N_("Cut from cursor to end of line"));
1105
#endif
1106
1107
    print1opt("-l", "--nofollow",
	N_("Don't follow symbolic links, overwrite"));
1108
#ifndef DISABLE_MOUSE
1109
    print1opt("-m", "--mouse", N_("Enable mouse"));
Chris Allegretta's avatar
Chris Allegretta committed
1110
#endif
1111
#ifndef DISABLE_OPERATINGDIR
1112
1113
    print1opt(_("-o [dir]"), _("--operatingdir=[dir]"),
	N_("Set operating directory"));
Chris Allegretta's avatar
Chris Allegretta committed
1114
#endif
1115
1116
    print1opt("-p", "--preserve",
	N_("Preserve XON (^Q) and XOFF (^S) keys"));
1117
#ifndef DISABLE_WRAPJUSTIFY
1118
1119
    print1opt(_("-r [#cols]"), _("--fill=[#cols]"),
	N_("Set fill cols to (wrap lines at) #cols"));
1120
#endif
1121
#ifndef DISABLE_SPELLER
1122
1123
    print1opt(_("-s [prog]"), _("--speller=[prog]"),
	N_("Enable alternate speller"));
1124
#endif
1125
1126
    print1opt("-t", "--tempfile",
	N_("Auto save on exit, don't prompt"));
1127
    print1opt("-v", "--view", N_("View (read only) mode"));
1128
#ifndef DISABLE_WRAPPING
1129
    print1opt("-w", "--nowrap", N_("Don't wrap long lines"));
Chris Allegretta's avatar
Chris Allegretta committed
1130
#endif
1131
1132
    print1opt("-x", "--nohelp", N_("Don't show help window"));
    print1opt("-z", "--suspend", N_("Enable suspend"));
Chris Allegretta's avatar
Chris Allegretta committed
1133

1134
    /* This is a special case. */
1135
    print1opt("-a, -b, -e,", "", NULL);
1136
    print1opt("-f, -g, -j", "", N_("(ignored, for Pico compatibility)"));
1137

Chris Allegretta's avatar
Chris Allegretta committed
1138
1139
1140
    exit(0);
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1141
void version(void)
Chris Allegretta's avatar
Chris Allegretta committed
1142
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1143
1144
1145
1146
    printf(_(" GNU nano version %s (compiled %s, %s)\n"), VERSION,
	__TIME__, __DATE__);
    printf(
	_(" Email: nano@nano-editor.org	Web: http://www.nano-editor.org/"));
1147
    printf(_("\n Compiled options:"));
1148

1149
#ifdef DISABLE_BROWSER
1150
    printf(" --disable-browser");
1151
#endif
1152
1153
#ifdef DISABLE_HELP
    printf(" --disable-help");
1154
1155
#endif
#ifdef DISABLE_JUSTIFY
1156
    printf(" --disable-justify");
1157
#endif
1158
#ifdef DISABLE_MOUSE
1159
    printf(" --disable-mouse");
1160
#endif
1161
1162
1163
#ifndef ENABLE_NLS
    printf(" --disable-nls");
#endif
1164
1165
1166
#ifdef DISABLE_OPERATINGDIR
    printf(" --disable-operatingdir");
#endif
1167
1168
1169
1170
1171
1172
1173
1174
1175
#ifdef DISABLE_SPELLER
    printf(" --disable-speller");
#endif
#ifdef DISABLE_TABCOMP
    printf(" --disable-tabcomp");
#endif
#ifdef DISABLE_WRAPPING
    printf(" --disable-wrapping");
#endif
1176
1177
1178
#ifdef DISABLE_ROOTWRAP
    printf(" --disable-wrapping-as-root");
#endif
1179
1180
1181
#ifdef ENABLE_COLOR
    printf(" --enable-color");
#endif
1182
1183
1184
1185
1186
1187
#ifdef DEBUG
    printf(" --enable-debug");
#endif
#ifdef NANO_EXTRA
    printf(" --enable-extra");
#endif
1188
1189
1190
1191
1192
1193
#ifdef ENABLE_MULTIBUFFER
    printf(" --enable-multibuffer");
#endif
#ifdef ENABLE_NANORC
    printf(" --enable-nanorc");
#endif
1194
1195
1196
#ifdef NANO_SMALL
    printf(" --enable-tiny");
#endif
1197
#ifdef ENABLE_UTF8
1198
1199
    printf(" --enable-utf8");
#endif
1200
1201
1202
1203
#ifdef USE_SLANG
    printf(" --with-slang");
#endif
    printf("\n");
Chris Allegretta's avatar
Chris Allegretta committed
1204
1205
}

1206
1207
1208
1209
1210
int no_more_space(void)
{
    return ISSET(MORE_SPACE) ? 1 : 0;
}

Chris Allegretta's avatar
Chris Allegretta committed
1211
1212
int no_help(void)
{
Chris Allegretta's avatar
Chris Allegretta committed
1213
    return ISSET(NO_HELP) ? 2 : 0;
Chris Allegretta's avatar
Chris Allegretta committed
1214
1215
}

1216
void nano_disabled_msg(void)
1217
{
Chris Allegretta's avatar
Chris Allegretta committed
1218
    statusbar(_("Sorry, support for this function has been disabled"));
1219
1220
}

1221
void do_verbatim_input(void)
1222
{
1223
1224
1225
    int *kbinput;
    size_t kbinput_len, i;
    char *output;
1226

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1227
    statusbar(_("Verbatim Input"));
1228

1229
1230
1231
1232
1233
    /* If constant cursor position display is on, make sure the current
     * cursor position will be properly displayed on the statusbar. */
    if (ISSET(CONST_UPDATE))
	do_cursorpos(TRUE);

1234
1235
    /* Read in all the verbatim characters. */
    kbinput = get_verbatim_kbinput(edit, &kbinput_len);
1236

1237
1238
    /* Display all the verbatim characters at once, not filtering out
     * control characters. */
1239
    output = charalloc(kbinput_len + 1);
1240

1241
1242
1243
1244
    for (i = 0; i < kbinput_len; i++)
	output[i] = (char)kbinput[i];
    output[i] = '\0';

1245
    do_output(output, kbinput_len, TRUE);
1246
1247

    free(output);
1248
1249
}

1250
void do_backspace(void)
Chris Allegretta's avatar
Chris Allegretta committed
1251
{
1252
1253
    if (openfile->current != openfile->fileage ||
	openfile->current_x > 0) {
1254
	do_left(FALSE);
1255
	do_delete();
Chris Allegretta's avatar
Chris Allegretta committed
1256
1257
1258
    }
}

1259
void do_delete(void)
Chris Allegretta's avatar
Chris Allegretta committed
1260
{
1261
    bool do_refresh = FALSE;
1262
1263
1264
	/* Do we have to call edit_refresh(), or can we get away with
	 * update_line()? */

1265
    assert(openfile->current != NULL && openfile->current->data != NULL && openfile->current_x <= strlen(openfile->current->data));
Chris Allegretta's avatar
Chris Allegretta committed
1266

1267
    openfile->placewewant = xplustabs();
1268

1269
1270
1271
1272
1273
    if (openfile->current->data[openfile->current_x] != '\0') {
	int char_buf_len = parse_mbchar(openfile->current->data +
		openfile->current_x, NULL, NULL, NULL);
	size_t line_len = strlen(openfile->current->data +
		openfile->current_x);
1274

1275
	assert(openfile->current_x < strlen(openfile->current->data));
Chris Allegretta's avatar
Chris Allegretta committed
1276

1277
	/* Let's get dangerous. */
1278
1279
1280
	charmove(&openfile->current->data[openfile->current_x],
		&openfile->current->data[openfile->current_x +
		char_buf_len], line_len - char_buf_len + 1);
Chris Allegretta's avatar
Chris Allegretta committed
1281

1282
1283
	null_at(&openfile->current->data, openfile->current_x +
		line_len - char_buf_len);
1284
#ifndef NANO_SMALL
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1285
1286
1287
1288
	if (openfile->mark_set && openfile->mark_begin ==
		openfile->current && openfile->current_x <
		openfile->mark_begin_x)
	    openfile->mark_begin_x -= char_buf_len;
1289
1290
1291
1292
1293
#endif
	openfile->totsize--;
    } else if (openfile->current != openfile->filebot &&
	(openfile->current->next != openfile->filebot ||
	openfile->current->data[0] == '\0')) {
1294
	/* We can delete the line before filebot only if it is blank: it
1295
	 * becomes the new magicline then. */
1296
	filestruct *foo = openfile->current->next;
Chris Allegretta's avatar
Chris Allegretta committed
1297

1298
	assert(openfile->current_x == strlen(openfile->current->data));
1299
1300
1301

	/* If we're deleting at the end of a line, we need to call
	 * edit_refresh(). */
1302
	if (openfile->current->data[openfile->current_x] == '\0')
1303
1304
	    do_refresh = TRUE;

1305
1306
1307
1308
	openfile->current->data = charealloc(openfile->current->data,
		openfile->current_x + strlen(foo->data) + 1);
	strcpy(openfile->current->data + openfile->current_x,
		foo->data);
1309
#ifndef NANO_SMALL
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1310
	if (openfile->mark_set && openfile->mark_begin ==
1311
		openfile->current->next) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1312
1313
	    openfile->mark_begin = openfile->current;
	    openfile->mark_begin_x += openfile->current_x;
1314
1315
	}
#endif
1316
1317
	if (openfile->filebot == foo)
	    openfile->filebot = openfile->current;
Chris Allegretta's avatar
Chris Allegretta committed
1318
1319
1320

	unlink_node(foo);
	delete_node(foo);
1321
1322
1323
	renumber(openfile->current);
	openfile->totlines--;
	openfile->totsize--;
1324
#ifndef DISABLE_WRAPPING
1325
	wrap_reset();
1326
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1327
    } else
1328
	return;
Chris Allegretta's avatar
Chris Allegretta committed
1329
1330

    set_modified();
1331
1332

#ifdef ENABLE_COLOR
1333
    /* If color syntaxes are available and turned on, we need to call
1334
     * edit_refresh(). */
1335
    if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX))
1336
1337
1338
1339
1340
1341
	do_refresh = TRUE;
#endif

    if (do_refresh)
	edit_refresh();
    else
1342
	update_line(openfile->current, openfile->current_x);
Chris Allegretta's avatar
Chris Allegretta committed
1343
1344
}

1345
void do_tab(void)
Chris Allegretta's avatar
Chris Allegretta committed
1346
{
1347
1348
1349
#ifndef NANO_SMALL
    if (ISSET(TABS_TO_SPACES)) {
	char *output;
1350
	size_t output_len = 0, new_pww = openfile->placewewant;
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362

	do {
	    new_pww++;
	    output_len++;
	} while (new_pww % tabsize != 0);

	output = charalloc(output_len + 1);

	charset(output, ' ', output_len);
	output[output_len] = '\0';

	do_output(output, output_len, TRUE);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1363
1364

	free(output);
1365
1366
1367
1368
1369
1370
    } else {
#endif
	do_output("\t", 1, TRUE);
#ifndef NANO_SMALL
    }
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1371
1372
}

1373
/* Someone hits Return *gasp!* */
1374
void do_enter(void)
Chris Allegretta's avatar
Chris Allegretta committed
1375
{
1376
    filestruct *newnode = make_new_node(openfile->current);
1377
    size_t extra = 0;
Chris Allegretta's avatar
Chris Allegretta committed
1378

1379
    assert(openfile->current != NULL && openfile->current->data != NULL);
1380

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1381
#ifndef NANO_SMALL
1382
1383
    /* Do auto-indenting, like the neolithic Turbo Pascal editor. */
    if (ISSET(AUTOINDENT)) {
1384
1385
1386
	/* If we are breaking the line in the indentation, the new
	 * indentation should have only current_x characters, and
	 * current_x should not change. */
1387
1388
1389
	extra = indent_length(openfile->current->data);
	if (extra > openfile->current_x)
	    extra = openfile->current_x;
1390
1391
    }
#endif
1392
1393
1394
1395
    newnode->data = charalloc(strlen(openfile->current->data +
	openfile->current_x) + extra + 1);
    strcpy(&newnode->data[extra], openfile->current->data +
	openfile->current_x);
1396
#ifndef NANO_SMALL
1397
    if (ISSET(AUTOINDENT)) {
1398
1399
	strncpy(newnode->data, openfile->current->data, extra);
	openfile->totsize += mbstrlen(newnode->data);
1400
    }
1401
#endif
1402
    null_at(&openfile->current->data, openfile->current_x);
1403
#ifndef NANO_SMALL
1404
    if (openfile->mark_set && openfile->current ==
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1405
1406
1407
1408
	openfile->mark_begin && openfile->current_x <
	openfile->mark_begin_x) {
	openfile->mark_begin = newnode;
	openfile->mark_begin_x += extra - openfile->current_x;
1409
    }
1410
#endif
1411
    openfile->current_x = extra;
Chris Allegretta's avatar
Chris Allegretta committed
1412

1413
1414
1415
1416
    if (openfile->current == openfile->filebot)
	openfile->filebot = newnode;
    splice_node(openfile->current, newnode,
	openfile->current->next);
1417

1418
1419
    renumber(openfile->current);
    openfile->current = newnode;
1420
1421

    edit_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
1422

1423
1424
    openfile->totlines++;
    openfile->totsize++;
1425
    set_modified();
1426
    openfile->placewewant = xplustabs();
Chris Allegretta's avatar
Chris Allegretta committed
1427
1428
}

1429
#ifndef NANO_SMALL
1430
void do_mark(void)
1431
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1432
    openfile->mark_set = !openfile->mark_set;
1433
    if (openfile->mark_set) {
1434
	statusbar(_("Mark Set"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1435
1436
	openfile->mark_begin = openfile->current;
	openfile->mark_begin_x = openfile->current_x;
1437
1438
    } else {
	statusbar(_("Mark UNset"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1439
1440
	openfile->mark_begin = NULL;
	openfile->mark_begin_x = 0;
1441
1442
1443
	edit_refresh();
    }
}
1444
#endif /* !NANO_SMALL */
Chris Allegretta's avatar
Chris Allegretta committed
1445

1446
void do_exit(void)
Chris Allegretta's avatar
Chris Allegretta committed
1447
{
1448
1449
    int i;

1450
    if (!openfile->modified)
1451
	i = 0;		/* Pretend the user chose not to save. */
1452
    else if (ISSET(TEMP_FILE))
1453
	i = 1;
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1454
    else
1455
1456
1457
	i = do_yesno(FALSE,
		_("Save modified buffer (ANSWERING \"No\" WILL DESTROY CHANGES) ? "));

1458
#ifdef DEBUG
1459
    dump_filestruct(openfile->fileage);
1460
#endif
1461

1462
    if (i == 0 || (i == 1 && do_writeout(TRUE) == 0)) {
1463
#ifdef ENABLE_MULTIBUFFER
1464
	/* Exit only if there are no more open file buffers. */
1465
	if (!close_buffer())
1466
#endif
1467
	    finish();
1468
    } else if (i != 1)
1469
1470
1471
1472
1473
1474
1475
	statusbar(_("Cancelled"));

    display_main_list();
}

void signal_init(void)
{
1476
1477
    /* Trap SIGINT and SIGQUIT because we want them to do useful
     * things. */
1478
1479
1480
    memset(&act, 0, sizeof(struct sigaction));
    act.sa_handler = SIG_IGN;
    sigaction(SIGINT, &act, NULL);
1481
    sigaction(SIGQUIT, &act, NULL);
1482

1483
    /* Trap SIGHUP and SIGTERM because we want to write the file out. */
1484
    act.sa_handler = handle_hupterm;
1485
    sigaction(SIGHUP, &act, NULL);
1486
    sigaction(SIGTERM, &act, NULL);
1487

1488
#ifndef NANO_SMALL
1489
    /* Trap SIGWINCH because we want to handle window resizes. */
1490
1491
    act.sa_handler = handle_sigwinch;
    sigaction(SIGWINCH, &act, NULL);
1492
    allow_pending_sigwinch(FALSE);
1493
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1494

1495
    /* Trap normal suspend (^Z) so we can handle it ourselves. */
1496
1497
1498
1499
    if (!ISSET(SUSPEND)) {
	act.sa_handler = SIG_IGN;
	sigaction(SIGTSTP, &act, NULL);
    } else {
1500
1501
	/* Block all other signals in the suspend and continue handlers.
	 * If we don't do this, other stuff interrupts them! */
1502
	sigfillset(&act.sa_mask);
Chris Allegretta's avatar
Chris Allegretta committed
1503

1504
1505
	act.sa_handler = do_suspend;
	sigaction(SIGTSTP, &act, NULL);
1506

1507
1508
1509
1510
	act.sa_handler = do_cont;
	sigaction(SIGCONT, &act, NULL);
    }
}
1511

1512
/* Handler for SIGHUP (hangup) and SIGTERM (terminate). */
1513
void handle_hupterm(int signal)
1514
{
1515
    die(_("Received SIGHUP or SIGTERM\n"));
1516
}
1517

1518
/* Handler for SIGTSTP (suspend). */
1519
void do_suspend(int signal)
1520
1521
{
    endwin();
1522
    printf("\n\n\n\n\n%s\n", _("Use \"fg\" to return to nano"));
1523
    fflush(stdout);
1524

1525
    /* Restore the old terminal settings. */
1526
    tcsetattr(0, TCSANOW, &oldterm);
1527

1528
    /* Trap SIGHUP and SIGTERM so we can properly deal with them while
1529
     * suspended. */
1530
1531
1532
1533
    act.sa_handler = handle_hupterm;
    sigaction(SIGHUP, &act, NULL);
    sigaction(SIGTERM, &act, NULL);

1534
    /* Do what mutt does: send ourselves a SIGSTOP. */
1535
1536
    kill(0, SIGSTOP);
}
1537

1538
/* Handler for SIGCONT (continue after suspend). */
1539
void do_cont(int signal)
1540
{
1541
#ifndef NANO_SMALL
1542
1543
    /* Perhaps the user resized the window while we slept.  Handle it
     * and update the screen in the process. */
1544
    handle_sigwinch(0);
1545
#else
1546
1547
    /* Just update the screen. */
    doupdate();
1548
1549
1550
1551
1552
1553
1554
#endif
}

#ifndef NANO_SMALL
void handle_sigwinch(int s)
{
    const char *tty = ttyname(0);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1555
    int fd, result = 0;
1556
1557
    struct winsize win;

1558
    if (tty == NULL)
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
	return;
    fd = open(tty, O_RDWR);
    if (fd == -1)
	return;
    result = ioctl(fd, TIOCGWINSZ, &win);
    close(fd);
    if (result == -1)
	return;

    /* Could check whether the COLS or LINES changed, and return
     * otherwise.  EXCEPT, that COLS and LINES are ncurses global
     * variables, and in some cases ncurses has already updated them. 
     * But not in all cases, argh. */
    COLS = win.ws_col;
    LINES = win.ws_row;

1575
1576
    /* Reinitialize the window size variables. */
    window_size_init();
1577

1578
1579
    /* If we've partitioned the filestruct, unpartition it now. */
    if (filepart != NULL)
1580
	unpartition_filestruct(&filepart);
1581

1582
#ifndef DISABLE_JUSTIFY
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1583
1584
    /* If the justify buffer isn't empty, blow away the text in it and
     * display the shortcut list with UnCut. */
1585
1586
1587
1588
1589
1590
1591
    if (jusbuffer != NULL) {
	free_filestruct(jusbuffer);
	jusbuffer = NULL;
	shortcut_init(FALSE);
    }
#endif

1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 1: If we just do what
     * curses does here, it'll only work properly if the resize made the
     * window smaller.  Do what mutt does: Leave and immediately reenter
     * Slang screen management mode. */
    SLsmg_reset_smg();
    SLsmg_init_smg();
#else
    /* Do the equivalent of what Minimum Profit does: Leave and
     * immediately reenter curses mode. */
    endwin();
    refresh();
#endif
1605

1606
1607
1608
    /* Restore the terminal to its previous state. */
    terminal_init();

1609
1610
1611
    /* Turn the cursor back on for sure. */
    curs_set(1);

1612
1613
1614
1615
1616
    /* Do the equivalent of what both mutt and Minimum Profit do:
     * Reinitialize all the windows based on the new screen
     * dimensions. */
    window_init();

1617
    /* Redraw the contents of the windows that need it. */
1618
    blank_statusbar();
1619
    currshortcut = main_list;
1620
1621
    total_refresh();

1622
1623
1624
    /* Reset all the input routines that rely on character sequences. */
    reset_kbinput();

1625
    /* Jump back to the main loop. */
1626
1627
    siglongjmp(jmpbuf, 1);
}
1628

1629
void allow_pending_sigwinch(bool allow)
1630
1631
1632
1633
{
    sigset_t winch;
    sigemptyset(&winch);
    sigaddset(&winch, SIGWINCH);
1634
    sigprocmask(allow ? SIG_UNBLOCK : SIG_BLOCK, &winch, NULL);
1635
}
1636
#endif /* !NANO_SMALL */
1637

1638
#ifndef NANO_SMALL
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1639
void do_toggle(const toggle *which)
1640
{
1641
    bool enabled;
1642

1643
    TOGGLE(which->flag);
Chris Allegretta's avatar
Chris Allegretta committed
1644

1645
    switch (which->val) {
1646
#ifndef DISABLE_MOUSE
1647
1648
1649
	case TOGGLE_MOUSE_KEY:
	    mouse_init();
	    break;
1650
#endif
1651
	case TOGGLE_MORESPACE_KEY:
1652
1653
	case TOGGLE_NOHELP_KEY:
	    window_init();
1654
	    total_refresh();
1655
	    break;
1656
1657
	case TOGGLE_SUSPEND_KEY:
	    signal_init();
1658
	    break;
1659
#ifdef ENABLE_NANORC
1660
	case TOGGLE_WHITESPACE_KEY:
1661
	    titlebar(NULL);
1662
1663
	    edit_refresh();
	    break;
1664
1665
1666
1667
1668
#endif
#ifdef ENABLE_COLOR
	case TOGGLE_SYNTAX_KEY:
	    edit_refresh();
	    break;
1669
#endif
1670
    }
Chris Allegretta's avatar
Chris Allegretta committed
1671

Chris Allegretta's avatar
Chris Allegretta committed
1672
    enabled = ISSET(which->flag);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1673

1674
1675
1676
1677
1678
1679
1680
1681
    if (which->val == TOGGLE_NOHELP_KEY
#ifndef DISABLE_WRAPPING
	|| which->val == TOGGLE_WRAP_KEY
#endif
#ifdef ENABLE_COLOR
	|| which->val == TOGGLE_SYNTAX_KEY
#endif
	)
Chris Allegretta's avatar
Chris Allegretta committed
1682
	enabled = !enabled;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1683
1684
1685

    statusbar("%s %s", which->desc, enabled ? _("enabled") :
	_("disabled"));
Chris Allegretta's avatar
Chris Allegretta committed
1686
}
1687
#endif /* !NANO_SMALL */
Chris Allegretta's avatar
Chris Allegretta committed
1688

1689
void disable_extended_io(void)
1690
1691
1692
1693
1694
{
    struct termios term;

    tcgetattr(0, &term);
    term.c_lflag &= ~IEXTEN;
1695
    term.c_oflag &= ~OPOST;
1696
1697
1698
    tcsetattr(0, TCSANOW, &term);
}

1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
void disable_signals(void)
{
    struct termios term;

    tcgetattr(0, &term);
    term.c_lflag &= ~ISIG;
    tcsetattr(0, TCSANOW, &term);
}

#ifndef NANO_SMALL
void enable_signals(void)
{
    struct termios term;

    tcgetattr(0, &term);
    term.c_lflag |= ISIG;
    tcsetattr(0, TCSANOW, &term);
}
#endif

void disable_flow_control(void)
{
    struct termios term;

    tcgetattr(0, &term);
1724
    term.c_iflag &= ~IXON;
1725
1726
1727
1728
1729
1730
1731
1732
    tcsetattr(0, TCSANOW, &term);
}

void enable_flow_control(void)
{
    struct termios term;

    tcgetattr(0, &term);
1733
    term.c_iflag |= IXON;
1734
1735
1736
    tcsetattr(0, TCSANOW, &term);
}

1737
1738
1739
1740
/* Set up the terminal state.  Put the terminal in cbreak mode (read one
 * character at a time and interpret the special control keys), disable
 * translation of carriage return (^M) into newline (^J) so that we can
 * tell the difference between the Enter key and Ctrl-J, and disable
1741
 * echoing of characters as they're typed.  Finally, disable extended
1742
1743
1744
 * input and output processing, disable interpretation of the special
 * control keys, and if we're not in preserve mode, disable
 * interpretation of the flow control characters too. */
1745
1746
1747
1748
1749
void terminal_init(void)
{
    cbreak();
    nonl();
    noecho();
1750
    disable_extended_io();
1751
1752
1753
1754
1755
    disable_signals();
    if (!ISSET(PRESERVE))
	disable_flow_control();
}

1756
int do_input(bool *meta_key, bool *func_key, bool *s_or_t, bool
1757
	*ran_func, bool *finished, bool allow_funcs)
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
{
    int input;
	/* The character we read in. */
    static int *kbinput = NULL;
	/* The input buffer. */
    static size_t kbinput_len = 0;
	/* The length of the input buffer. */
    const shortcut *s;
    bool have_shortcut;
#ifndef NANO_SMALL
    const toggle *t;
    bool have_toggle;
#endif

    *s_or_t = FALSE;
1773
    *ran_func = FALSE;
1774
    *finished = FALSE;
1775
1776
1777
1778
1779
1780
1781

    /* Read in a character. */
    input = get_kbinput(edit, meta_key, func_key);

#ifndef DISABLE_MOUSE
    /* If we got a mouse click and it was on a shortcut, read in the
     * shortcut character. */
1782
    if (allow_funcs && *func_key == TRUE && input == KEY_MOUSE) {
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
	if (do_mouse())
	    input = get_kbinput(edit, meta_key, func_key);
	else
	    input = ERR;
    }
#endif

    /* Check for a shortcut in the main list. */
    s = get_shortcut(main_list, &input, meta_key, func_key);

    /* If we got a shortcut from the main list, or a "universal"
     * edit window shortcut, set have_shortcut to TRUE. */
    have_shortcut = (s != NULL || input == NANO_XON_KEY ||
	input == NANO_XOFF_KEY || input == NANO_SUSPEND_KEY);

#ifndef NANO_SMALL
    /* Check for a toggle in the main list. */
    t = get_toggle(input, *meta_key);

    /* If we got a toggle from the main list, set have_toggle to
     * TRUE. */
    have_toggle = (t != NULL);
#endif

    /* Set s_or_t to TRUE if we got a shortcut or toggle. */
    *s_or_t = (have_shortcut
#ifndef NANO_SMALL
	|| have_toggle
#endif
	);

    if (allow_funcs) {
1815
1816
1817
1818
1819
	/* If we got a character, and it isn't a shortcut or toggle,
	 * it's a normal text character.  Display the warning if we're
	 * in view mode, or add the character to the input buffer if
	 * we're not. */
	if (input != ERR && *s_or_t == FALSE) {
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
	    if (ISSET(VIEW_MODE))
		print_view_warning();
	    else {
		kbinput_len++;
		kbinput = (int *)nrealloc(kbinput, kbinput_len *
			sizeof(int));
		kbinput[kbinput_len - 1] = input;
	    }
	}

	/* If we got a shortcut or toggle, or if there aren't any other
	 * characters waiting after the one we read in, we need to
	 * display all the characters in the input buffer if it isn't
	 * empty.  Note that it should be empty if we're in view
	 * mode. */
1835
	 if (*s_or_t == TRUE || get_key_buffer_len() == 0) {
1836
1837
	    if (kbinput != NULL) {
		/* Display all the characters in the input buffer at
1838
		 * once, filtering out control characters. */
1839
1840
1841
1842
1843
1844
1845
		char *output = charalloc(kbinput_len + 1);
		size_t i;

		for (i = 0; i < kbinput_len; i++)
		    output[i] = (char)kbinput[i];
		output[i] = '\0';

1846
		do_output(output, kbinput_len, FALSE);
1847
1848

		free(output);
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858

		/* Empty the input buffer. */
		kbinput_len = 0;
		free(kbinput);
		kbinput = NULL;
	    }
	}

	if (have_shortcut) {
	    switch (input) {
1859
		/* Handle the "universal" edit window shortcuts. */
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
		case NANO_XON_KEY:
		    statusbar(_("XON ignored, mumble mumble."));
		    break;
		case NANO_XOFF_KEY:
		    statusbar(_("XOFF ignored, mumble mumble."));
		    break;
#ifndef NANO_SMALL
		case NANO_SUSPEND_KEY:
		    if (ISSET(SUSPEND))
			do_suspend(0);
		    break;
#endif
1872
		/* Handle the normal edit window shortcuts, setting
1873
1874
1875
		 * ran_func to TRUE if we try to run their associated
		 * functions and setting finished to TRUE to indicate
		 * that we're done after trying to run their associated
1876
		 * functions. */
1877
1878
1879
1880
1881
1882
		default:
		    /* Blow away the text in the cutbuffer if we aren't
		     * cutting text. */
		    if (s->func != do_cut_text)
			cutbuffer_reset();

1883
		    if (s->func != NULL) {
1884
			*ran_func = TRUE;
1885
1886
1887
1888
			if (ISSET(VIEW_MODE) && !s->viewok)
			    print_view_warning();
			else
			    s->func();
1889
		    }
1890
		    *finished = TRUE;
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
		    break;
	    }
	}
#ifndef NANO_SMALL
	else if (have_toggle) {
	    /* Blow away the text in the cutbuffer, since we aren't
	     * cutting text. */
	    cutbuffer_reset();
	    /* Toggle the flag associated with this shortcut. */
	    if (allow_funcs)
		do_toggle(t);
	}
#endif
	else
	    /* Blow away the text in the cutbuffer, since we aren't
	     * cutting text. */
	    cutbuffer_reset();
    }

    return input;
}

#ifndef DISABLE_MOUSE
bool do_mouse(void)
{
    int mouse_x, mouse_y;
    bool retval;

    retval = get_mouseinput(&mouse_x, &mouse_y, TRUE);

    if (!retval) {
	/* We can click in the edit window to move the cursor. */
	if (wenclose(edit, mouse_y, mouse_x)) {
	    bool sameline;
		/* Did they click on the line with the cursor?  If they
		 * clicked on the cursor, we set the mark. */
	    size_t xcur;
		/* The character they clicked on. */

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1930
	    /* Subtract out the size of topwin. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1931
	    mouse_y -= 2 - no_more_space();
1932

1933
	    sameline = (mouse_y == openfile->current_y);
1934
1935

	    /* Move to where the click occurred. */
1936
1937
1938
1939
1940
1941
1942
1943
	    for (; openfile->current_y < mouse_y &&
		openfile->current->next != NULL; openfile->current_y++)
		openfile->current = openfile->current->next;
	    for (; openfile->current_y > mouse_y &&
		openfile->current->prev != NULL; openfile->current_y--)
		openfile->current = openfile->current->prev;

	    xcur = actual_x(openfile->current->data,
1944
		get_page_start(xplustabs()) + mouse_x);
1945
1946
1947
1948
1949

#ifndef NANO_SMALL
	    /* Clicking where the cursor is toggles the mark, as does
	     * clicking beyond the line length with the cursor at the
	     * end of the line. */
1950
	    if (sameline && xcur == openfile->current_x) {
1951
1952
1953
1954
1955
1956
1957
1958
		if (ISSET(VIEW_MODE)) {
		    print_view_warning();
		    return retval;
		}
		do_mark();
	    }
#endif

1959
1960
	    openfile->current_x = xcur;
	    openfile->placewewant = xplustabs();
1961
1962
1963
1964
1965
1966
1967
1968
	    edit_refresh();
	}
    }

    return retval;
}
#endif /* !DISABLE_MOUSE */

1969
1970
/* The user typed ouuput_len multibyte characters.  Add them to the edit
 * buffer, filtering out all control characters if allow_cntrls is
1971
1972
 * TRUE. */
void do_output(char *output, size_t output_len, bool allow_cntrls)
1973
{
1974
    size_t current_len, i = 0;
1975
    bool old_const_update = ISSET(CONST_UPDATE);
1976
1977
1978
1979
    bool do_refresh = FALSE;
	/* Do we have to call edit_refresh(), or can we get away with
	 * update_line()? */

1980
1981
    char *char_buf = charalloc(mb_cur_max());
    int char_buf_len;
1982

1983
    assert(openfile->current != NULL && openfile->current->data != NULL);
1984

1985
    current_len = strlen(openfile->current->data);
1986

1987
    /* Turn off constant cursor position display. */
1988
    UNSET(CONST_UPDATE);
1989

1990
    while (i < output_len) {
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
	/* If allow_cntrls is FALSE, filter out nulls and newlines,
	 * since they're control characters. */
	if (allow_cntrls) {
	    /* Null to newline, if needed. */
	    if (output[i] == '\0')
		output[i] = '\n';
	    /* Newline to Enter, if needed. */
	    else if (output[i] == '\n') {
		do_enter();
		i++;
		continue;
	    }
2003
2004
	}

2005
2006
2007
	/* Interpret the next multibyte character.  If it's an invalid
	 * multibyte character, interpret it as though it's a byte
	 * character. */
2008
	char_buf_len = parse_mbchar(output + i, char_buf, NULL, NULL);
2009
2010

	i += char_buf_len;
2011

2012
2013
2014
2015
	/* If allow_cntrls is FALSE, filter out a control character. */
	if (!allow_cntrls && is_cntrl_mbchar(output + i - char_buf_len))
	    continue;

2016
2017
	/* When a character is inserted on the current magicline, it
	 * means we need a new one! */
2018
	if (openfile->filebot == openfile->current)
2019
2020
2021
	    new_magicline();

	/* More dangerousness fun =) */
2022
	openfile->current->data = charealloc(openfile->current->data,
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2023
		current_len + (char_buf_len * 2));
2024

2025
	assert(openfile->current_x <= current_len);
2026

2027
2028
2029
2030
2031
2032
	charmove(&openfile->current->data[openfile->current_x +
		char_buf_len],
		&openfile->current->data[openfile->current_x],
		current_len - openfile->current_x + char_buf_len);
	strncpy(&openfile->current->data[openfile->current_x], char_buf,
		char_buf_len);
2033
	current_len += char_buf_len;
2034
	openfile->totsize++;
2035
2036
2037
2038
	set_modified();

#ifndef NANO_SMALL
	/* Note that current_x has not yet been incremented. */
2039
	if (openfile->mark_set && openfile->current ==
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2040
2041
2042
		openfile->mark_begin && openfile->current_x <
		openfile->mark_begin_x)
	    openfile->mark_begin_x += char_buf_len;
2043
2044
#endif

2045
	openfile->current_x += char_buf_len;
2046
2047

#ifndef DISABLE_WRAPPING
2048
2049
	/* If we're wrapping text, we need to call edit_refresh(). */
	if (!ISSET(NO_WRAP)) {
2050
2051
	    bool do_refresh_save = do_refresh;

2052
	    do_refresh = do_wrap(openfile->current);
2053
2054
2055
2056
2057
2058
2059
2060
2061

	    /* If we needed to call edit_refresh() before this, we'll
	     * still need to after this. */
	    if (do_refresh_save)
		do_refresh = TRUE;
	}
#endif

#ifdef ENABLE_COLOR
2062
2063
2064
	/* If color syntaxes are available and turned on, we need to
	 * call edit_refresh(). */
	if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX))
2065
2066
2067
2068
	    do_refresh = TRUE;
#endif
    }

2069
2070
    /* Turn constant cursor position display back on if it was on
     * before. */
2071
2072
    if (old_const_update)
	SET(CONST_UPDATE);
2073

2074
    free(char_buf);
2075

2076
2077
    openfile->placewewant = xplustabs();

2078
2079
2080
    if (do_refresh)
	edit_refresh();
    else
2081
	update_line(openfile->current, openfile->current_x);
2082
2083
}

2084
int main(int argc, char **argv)
Chris Allegretta's avatar
Chris Allegretta committed
2085
2086
{
    int optchr;
2087
    ssize_t startline = 1;
2088
	/* Line to try and start at. */
2089
2090
    ssize_t startcol = 1;
	/* Column to try and start at. */
2091
#ifndef DISABLE_WRAPJUSTIFY
2092
2093
    bool fill_flag_used = FALSE;
	/* Was the fill option used? */
2094
#endif
2095
2096
2097
2098
2099
#ifdef ENABLE_MULTIBUFFER
    bool old_multibuffer;
	/* The old value of the multibuffer option, restored after we
	 * load all files on the command line. */
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2100
#ifdef HAVE_GETOPT_LONG
2101
    const struct option long_options[] = {
2102
	{"help", 0, NULL, 'h'},
2103
#ifdef ENABLE_MULTIBUFFER
2104
	{"multibuffer", 0, NULL, 'F'},
Chris Allegretta's avatar
Chris Allegretta committed
2105
2106
#endif
#ifdef ENABLE_NANORC
2107
	{"ignorercfiles", 0, NULL, 'I'},
2108
#endif
2109
	{"morespace", 0, NULL, 'O'},
2110
#ifndef DISABLE_JUSTIFY
2111
	{"quotestr", 1, NULL, 'Q'},
2112
#endif
2113
	{"restricted", 0, NULL, 'R'},
2114
2115
	{"tabsize", 1, NULL, 'T'},
	{"version", 0, NULL, 'V'},
2116
#ifdef ENABLE_COLOR
2117
	{"syntax", 1, NULL, 'Y'},
2118
#endif
2119
2120
2121
	{"const", 0, NULL, 'c'},
	{"rebinddelete", 0, NULL, 'd'},
	{"nofollow", 0, NULL, 'l'},
2122
#ifndef DISABLE_MOUSE
2123
	{"mouse", 0, NULL, 'm'},
2124
#endif
2125
#ifndef DISABLE_OPERATINGDIR
2126
	{"operatingdir", 1, NULL, 'o'},
2127
#endif
2128
	{"preserve", 0, NULL, 'p'},
2129
#ifndef DISABLE_WRAPJUSTIFY
2130
	{"fill", 1, NULL, 'r'},
2131
2132
#endif
#ifndef DISABLE_SPELLER
2133
	{"speller", 1, NULL, 's'},
2134
#endif
2135
2136
	{"tempfile", 0, NULL, 't'},
	{"view", 0, NULL, 'v'},
2137
#ifndef DISABLE_WRAPPING
2138
	{"nowrap", 0, NULL, 'w'},
2139
#endif
2140
2141
	{"nohelp", 0, NULL, 'x'},
	{"suspend", 0, NULL, 'z'},
2142
#ifndef NANO_SMALL
2143
2144
	{"smarthome", 0, NULL, 'A'},
	{"backup", 0, NULL, 'B'},
2145
2146
	{"backupdir", 1, NULL, 'C'},
	{"tabstospaces", 0, NULL, 'E'},
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2147
	{"historylog", 0, NULL, 'H'},
2148
2149
	{"noconvert", 0, NULL, 'N'},
	{"smooth", 0, NULL, 'S'},
2150
	{"quickblank", 0, NULL, 'U'},
2151
2152
	{"autoindent", 0, NULL, 'i'},
	{"cut", 0, NULL, 'k'},
2153
#endif
2154
	{NULL, 0, NULL, 0}
Chris Allegretta's avatar
Chris Allegretta committed
2155
2156
2157
    };
#endif

2158
#ifdef ENABLE_UTF8
2159
    {
2160
2161
	/* If the locale set exists and includes the case-insensitive
	 * string "UTF8" or "UTF-8", we should use UTF-8. */
2162
2163
	char *locale = setlocale(LC_ALL, "");

2164
2165
2166
	if (locale != NULL && (strcasestr(locale, "UTF8") != NULL ||
		strcasestr(locale, "UTF-8") != NULL)) {
	    SET(USE_UTF8);
2167
#ifdef USE_SLANG
2168
	    SLutf8_enable(TRUE);
2169
#endif
2170
	}
2171
2172
    }
#else
Chris Allegretta's avatar
Chris Allegretta committed
2173
    setlocale(LC_ALL, "");
2174
2175
#endif

2176
#ifdef ENABLE_NLS
Chris Allegretta's avatar
Chris Allegretta committed
2177
2178
2179
2180
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);
#endif

Chris Allegretta's avatar
Chris Allegretta committed
2181
#if !defined(ENABLE_NANORC) && defined(DISABLE_ROOTWRAP) && !defined(DISABLE_WRAPPING)
2182
2183
    /* If we don't have rcfile support, we're root, and
     * --disable-wrapping-as-root is used, turn wrapping off. */
2184
    if (geteuid() == NANO_ROOT_UID)
2185
2186
	SET(NO_WRAP);
#endif
2187

2188
    while ((optchr =
Chris Allegretta's avatar
Chris Allegretta committed
2189
#ifdef HAVE_GETOPT_LONG
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2190
	getopt_long(argc, argv,
2191
		"h?ABC:EFHINOQ:RST:UVY:abcdefgijklmo:pr:s:tvwxz",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2192
		long_options, NULL)
Chris Allegretta's avatar
Chris Allegretta committed
2193
#else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2194
	getopt(argc, argv,
2195
		"h?ABC:EFHINOQ:RST:UVY:abcdefgijklmo:pr:s:tvwxz")
Chris Allegretta's avatar
Chris Allegretta committed
2196
#endif
2197
		) != -1) {
Chris Allegretta's avatar
Chris Allegretta committed
2198
	switch (optchr) {
2199
2200
2201
2202
2203
2204
2205
2206
	    case 'a':
	    case 'b':
	    case 'e':
	    case 'f':
	    case 'g':
	    case 'j':
		/* Pico compatibility flags. */
		break;
2207
#ifndef NANO_SMALL
2208
2209
2210
2211
2212
2213
	    case 'A':
		SET(SMART_HOME);
		break;
	    case 'B':
		SET(BACKUP_FILE);
		break;
2214
	    case 'C':
2215
2216
		backup_dir = mallocstrcpy(backup_dir, optarg);
		break;
2217
2218
2219
	    case 'E':
		SET(TABS_TO_SPACES);
		break;
2220
#endif
2221
#ifdef ENABLE_MULTIBUFFER
2222
2223
2224
	    case 'F':
		SET(MULTIBUFFER);
		break;
Chris Allegretta's avatar
Chris Allegretta committed
2225
2226
#endif
#ifdef ENABLE_NANORC
2227
#ifndef NANO_SMALL
2228
2229
2230
	    case 'H':
		SET(HISTORYLOG);
		break;
2231
#endif
2232
2233
2234
	    case 'I':
		SET(NO_RCFILE);
		break;
2235
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2236
#ifndef NANO_SMALL
2237
2238
2239
	    case 'N':
		SET(NO_CONVERT);
		break;
2240
#endif
2241
2242
2243
	    case 'O':
		SET(MORE_SPACE);
		break;
2244
#ifndef DISABLE_JUSTIFY
2245
2246
2247
	    case 'Q':
		quotestr = mallocstrcpy(quotestr, optarg);
		break;
2248
#endif
2249
2250
2251
	    case 'R':
		SET(RESTRICTED);
		break;
2252
#ifndef NANO_SMALL
2253
	    case 'S':
2254
		SET(SMOOTH_SCROLL);
2255
		break;
2256
#endif
2257
2258
	    case 'T':
		if (!parse_num(optarg, &tabsize) || tabsize <= 0) {
2259
2260
		    fprintf(stderr, _("Requested tab size %s invalid"), optarg);
		    fprintf(stderr, "\n");
2261
2262
2263
		    exit(1);
		}
		break;
2264
2265
2266
2267
2268
#ifndef NANO_SMALL
	    case 'U':
		SET(QUICK_BLANK);
		break;
#endif
2269
2270
2271
	    case 'V':
		version();
		exit(0);
2272
#ifdef ENABLE_COLOR
2273
2274
2275
	    case 'Y':
		syntaxstr = mallocstrcpy(syntaxstr, optarg);
		break;
2276
#endif
2277
	    case 'c':
2278
		SET(CONST_UPDATE);
2279
2280
2281
2282
		break;
	    case 'd':
		SET(REBIND_DELETE);
		break;
2283
#ifndef NANO_SMALL
2284
2285
2286
2287
2288
2289
	    case 'i':
		SET(AUTOINDENT);
		break;
	    case 'k':
		SET(CUT_TO_END);
		break;
2290
#endif
2291
2292
2293
	    case 'l':
		SET(NOFOLLOW_SYMLINKS);
		break;
2294
#ifndef DISABLE_MOUSE
2295
2296
2297
	    case 'm':
		SET(USE_MOUSE);
		break;
2298
#endif
2299
#ifndef DISABLE_OPERATINGDIR
2300
2301
2302
	    case 'o':
		operating_dir = mallocstrcpy(operating_dir, optarg);
		break;
2303
#endif
2304
2305
2306
	    case 'p':
		SET(PRESERVE);
		break;
2307
#ifndef DISABLE_WRAPJUSTIFY
2308
2309
	    case 'r':
		if (!parse_num(optarg, &wrap_at)) {
2310
2311
		    fprintf(stderr, _("Requested fill size %s invalid"), optarg);
		    fprintf(stderr, "\n");
2312
2313
2314
2315
		    exit(1);
		}
		fill_flag_used = TRUE;
		break;
2316
#endif
2317
#ifndef DISABLE_SPELLER
2318
2319
2320
	    case 's':
		alt_speller = mallocstrcpy(alt_speller, optarg);
		break;
2321
#endif
2322
2323
2324
2325
2326
2327
	    case 't':
		SET(TEMP_FILE);
		break;
	    case 'v':
		SET(VIEW_MODE);
		break;
2328
#ifndef DISABLE_WRAPPING
2329
2330
2331
	    case 'w':
		SET(NO_WRAP);
		break;
2332
#endif
2333
2334
2335
2336
2337
2338
2339
2340
	    case 'x':
		SET(NO_HELP);
		break;
	    case 'z':
		SET(SUSPEND);
		break;
	    default:
		usage();
Chris Allegretta's avatar
Chris Allegretta committed
2341
2342
2343
	}
    }

2344
2345
    /* If the executable filename starts with 'r', we use restricted
     * mode. */
2346
2347
2348
    if (*(tail(argv[0])) == 'r')
	SET(RESTRICTED);

2349
2350
2351
    /* If we're using restricted mode, disable suspending, backups, and
     * reading rcfiles, since they all would allow reading from or
     * writing to files not specified on the command line. */
2352
2353
2354
2355
2356
2357
    if (ISSET(RESTRICTED)) {
	UNSET(SUSPEND);
	UNSET(BACKUP_FILE);
	SET(NO_RCFILE);
    }

Chris Allegretta's avatar
Chris Allegretta committed
2358
/* We've read through the command line options.  Now back up the flags
2359
2360
 * and values that are set, and read the rcfile(s).  If the values
 * haven't changed afterward, restore the backed-up values. */
Chris Allegretta's avatar
Chris Allegretta committed
2361
2362
2363
2364
2365
#ifdef ENABLE_NANORC
    if (!ISSET(NO_RCFILE)) {
#ifndef DISABLE_OPERATINGDIR
	char *operating_dir_cpy = operating_dir;
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2366
#ifndef DISABLE_WRAPJUSTIFY
2367
	ssize_t wrap_at_cpy = wrap_at;
Chris Allegretta's avatar
Chris Allegretta committed
2368
#endif
2369
2370
2371
#ifndef NANO_SMALL
	char *backup_dir_cpy = backup_dir;
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2372
2373
2374
2375
2376
2377
#ifndef DISABLE_JUSTIFY
	char *quotestr_cpy = quotestr;
#endif
#ifndef DISABLE_SPELLER
	char *alt_speller_cpy = alt_speller;
#endif
2378
	ssize_t tabsize_cpy = tabsize;
2379
	long flags_cpy = flags;
Chris Allegretta's avatar
Chris Allegretta committed
2380

2381
#ifndef DISABLE_OPERATINGDIR
Chris Allegretta's avatar
Chris Allegretta committed
2382
	operating_dir = NULL;
2383
#endif
2384
2385
2386
#ifndef NANO_SMALL
	backup_dir = NULL;
#endif
2387
#ifndef DISABLE_JUSTIFY
Chris Allegretta's avatar
Chris Allegretta committed
2388
	quotestr = NULL;
2389
2390
#endif
#ifndef DISABLE_SPELLER
Chris Allegretta's avatar
Chris Allegretta committed
2391
	alt_speller = NULL;
2392
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2393
2394
2395
2396
2397
2398
2399
2400
2401

	do_rcfile();

#ifndef DISABLE_OPERATINGDIR
	if (operating_dir_cpy != NULL) {
	    free(operating_dir);
	    operating_dir = operating_dir_cpy;
	}
#endif
2402
#ifndef DISABLE_WRAPJUSTIFY
Chris Allegretta's avatar
Chris Allegretta committed
2403
2404
2405
	if (fill_flag_used)
	    wrap_at = wrap_at_cpy;
#endif
2406
2407
2408
2409
2410
2411
#ifndef NANO_SMALL
	if (backup_dir_cpy != NULL) {
	    free(backup_dir);
	    backup_dir = backup_dir_cpy;
	}
#endif	
Chris Allegretta's avatar
Chris Allegretta committed
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
#ifndef DISABLE_JUSTIFY
	if (quotestr_cpy != NULL) {
	    free(quotestr);
	    quotestr = quotestr_cpy;
	}
#endif
#ifndef DISABLE_SPELLER
	if (alt_speller_cpy != NULL) {
	    free(alt_speller);
	    alt_speller = alt_speller_cpy;
	}
#endif
2424
	if (tabsize_cpy != -1)
Chris Allegretta's avatar
Chris Allegretta committed
2425
2426
2427
2428
	    tabsize = tabsize_cpy;
	flags |= flags_cpy;
    }
#if defined(DISABLE_ROOTWRAP) && !defined(DISABLE_WRAPPING)
2429
    else if (geteuid() == NANO_ROOT_UID)
Chris Allegretta's avatar
Chris Allegretta committed
2430
2431
2432
2433
	SET(NO_WRAP);
#endif
#endif /* ENABLE_NANORC */

2434
2435
2436
2437
2438
2439
2440
2441
#ifndef NANO_SMALL
    history_init();
#ifdef ENABLE_NANORC
    if (!ISSET(NO_RCFILE) && ISSET(HISTORYLOG))
	load_history();
#endif
#endif

2442
#ifndef NANO_SMALL
2443
    /* Set up the backup directory (unless we're using restricted mode,
2444
2445
2446
2447
     * in which case backups are disabled, since they would allow
     * reading from or writing to files not specified on the command
     * line).  This entails making sure it exists and is a directory, so
     * that backup files will be saved there. */
2448
2449
    if (!ISSET(RESTRICTED))
	init_backup_dir();
2450
2451
#endif

2452
#ifndef DISABLE_OPERATINGDIR
Chris Allegretta's avatar
Chris Allegretta committed
2453
    /* Set up the operating directory.  This entails chdir()ing there,
2454
     * so that file reads and writes will be based there. */
2455
2456
2457
    init_operating_dir();
#endif

Chris Allegretta's avatar
Chris Allegretta committed
2458
#ifndef DISABLE_JUSTIFY
2459
    if (punct == NULL)
2460
	punct = mallocstrcpy(NULL, ".?!");
2461
2462

    if (brackets == NULL)
2463
	brackets = mallocstrcpy(NULL, "'\")}]>");
2464

Chris Allegretta's avatar
Chris Allegretta committed
2465
    if (quotestr == NULL)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2466
	quotestr = mallocstrcpy(NULL,
Chris Allegretta's avatar
Chris Allegretta committed
2467
#ifdef HAVE_REGEX_H
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2468
		"^([ \t]*[|>:}#])+"
Chris Allegretta's avatar
Chris Allegretta committed
2469
#else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2470
		"> "
Chris Allegretta's avatar
Chris Allegretta committed
2471
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2472
		);
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
#ifdef HAVE_REGEX_H
    quoterc = regcomp(&quotereg, quotestr, REG_EXTENDED);

    if (quoterc == 0) {
	/* We no longer need quotestr, just quotereg. */
	free(quotestr);
	quotestr = NULL;
    } else {
	size_t size = regerror(quoterc, &quotereg, NULL, 0);

	quoteerr = charalloc(size);
	regerror(quoterc, &quotereg, quoteerr, size);
    }
#else
    quotelen = strlen(quotestr);
#endif /* !HAVE_REGEX_H */
Chris Allegretta's avatar
Chris Allegretta committed
2489
#endif /* !DISABLE_JUSTIFY */
2490

2491
2492
#ifndef DISABLE_SPELLER
    /* If we don't have an alternative spell checker after reading the
2493
     * command line and/or rcfile(s), check $SPELL for one, as Pico
2494
     * does (unless we're using restricted mode, in which case spell
2495
2496
     * checking is disabled, since it would allow reading from or
     * writing to files not specified on the command line). */
2497
    if (!ISSET(RESTRICTED) && alt_speller == NULL) {
2498
2499
2500
2501
2502
2503
	char *spellenv = getenv("SPELL");
	if (spellenv != NULL)
	    alt_speller = mallocstrcpy(NULL, spellenv);
    }
#endif

2504
#if !defined(NANO_SMALL) && defined(ENABLE_NANORC)
2505
    /* If whitespace wasn't specified, set its default value. */
2506
    if (whitespace == NULL) {
2507
	whitespace = mallocstrcpy(NULL, "  ");
2508
2509
2510
	whitespace_len[0] = 1;
	whitespace_len[1] = 1;
    }
2511
2512
#endif

2513
    /* If tabsize wasn't specified, set its default value. */
Chris Allegretta's avatar
Chris Allegretta committed
2514
    if (tabsize == -1)
2515
	tabsize = WIDTH_OF_TAB;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2516

2517
    /* Back up the old terminal settings so that they can be restored. */
2518
    tcgetattr(0, &oldterm);
2519

2520
    /* Initialize curses mode. */
Chris Allegretta's avatar
Chris Allegretta committed
2521
    initscr();
2522
2523

    /* Set up the terminal state. */
2524
    terminal_init();
2525

2526
2527
2528
    /* Turn the cursor on for sure. */
    curs_set(1);

2529
2530
2531
2532
    /* Initialize the window size variables. */
    window_size_init();

    /* Set up the shortcuts. */
2533
    shortcut_init(FALSE);
2534
2535

    /* Set up the signal handlers. */
2536
    signal_init();
Chris Allegretta's avatar
Chris Allegretta committed
2537
2538

#ifdef DEBUG
2539
    fprintf(stderr, "Main: set up windows\n");
Chris Allegretta's avatar
Chris Allegretta committed
2540
2541
#endif

2542
    window_init();
2543
#ifndef DISABLE_MOUSE
2544
    mouse_init();
2545
#endif
2546

Chris Allegretta's avatar
Chris Allegretta committed
2547
#ifdef DEBUG
2548
    fprintf(stderr, "Main: open file\n");
Chris Allegretta's avatar
Chris Allegretta committed
2549
#endif
2550

2551
2552
2553
    /* If there's a +LINE or +LINE,COLUMN flag here, it is the first
     * non-option argument, and it is followed by at least one other
     * argument, the filename it applies to. */
2554
    if (0 < optind && optind < argc - 1 && argv[optind][0] == '+') {
2555
	parse_line_column(&argv[optind][1], &startline, &startcol);
2556
2557
2558
	optind++;
    }

Chris Allegretta's avatar
Chris Allegretta committed
2559
#ifdef ENABLE_MULTIBUFFER
2560
2561
2562
2563
2564
2565
    old_multibuffer = ISSET(MULTIBUFFER);
    SET(MULTIBUFFER);

    /* Read all the files after the first one on the command line into
     * new buffers. */
    {
2566
2567
	int i = optind + 1;
	ssize_t iline = 1, icol = 1;
2568

2569
	for (; i < argc; i++) {
2570
2571
2572
2573
	    /* If there's a +LINE or +LINE,COLUMN flag here, it is
	     * followed by at least one other argument, the filename it
	     * applies to. */
	    if (i < argc - 1 && argv[i][0] == '+' && iline == 1 &&
2574
		icol == 1)
2575
		parse_line_column(&argv[i][1], &iline, &icol);
2576
	    else {
2577
		open_buffer(argv[i]);
2578

2579
		if (iline > 1 || icol > 1) {
2580
2581
		    do_gotolinecolumn(iline, icol, FALSE, FALSE, FALSE,
			FALSE);
2582
2583
		    iline = 1;
		    icol = 1;
2584
2585
2586
		}
	    }
	}
2587
2588
2589
2590
2591
2592
2593
    }
#endif

    /* Read the first file on the command line into either the current
     * buffer or a new buffer, depending on whether multibuffer mode is
     * enabled. */
    if (optind < argc)
2594
	open_buffer(argv[optind]);
2595
2596
2597
2598
2599

    /* We didn't open any files if all the command line arguments were
     * invalid files like directories or if there were no command line
     * arguments given.  In this case, we have to load a blank buffer.
     * Also, we unset view mode to allow editing. */
2600
2601
    if (openfile == NULL) {
	open_buffer("");
2602
	UNSET(VIEW_MODE);
Chris Allegretta's avatar
Chris Allegretta committed
2603
    }
2604
2605
2606
2607

#ifdef ENABLE_MULTIBUFFER
    if (!old_multibuffer)
	UNSET(MULTIBUFFER);
Chris Allegretta's avatar
Chris Allegretta committed
2608
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2609

2610
2611
2612
2613
#ifdef DEBUG
    fprintf(stderr, "Main: top and bottom win\n");
#endif

2614
    if (startline > 1 || startcol > 1)
2615
2616
	do_gotolinecolumn(startline, startcol, FALSE, FALSE, FALSE,
		FALSE);
2617

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2618
2619
    display_main_list();

2620
2621
#ifndef NANO_SMALL
    /* Return here after a SIGWINCH. */
2622
    sigsetjmp(jmpbuf, 1);
2623
#endif
2624

2625
    display_buffer();    
Robert Siemborski's avatar
Robert Siemborski committed
2626

2627
    while (TRUE) {
2628
	bool meta_key, func_key, s_or_t, ran_func, finished;
2629
2630

	/* Make sure the cursor is in the edit window. */
2631
	reset_cursor();
2632

2633
2634
2635
	/* If constant cursor position display is on, display the
	 * current cursor position on the statusbar. */
	if (ISSET(CONST_UPDATE))
2636
	    do_cursorpos(TRUE);
2637

2638
2639
	currshortcut = main_list;

2640
	/* Read in and interpret characters. */
2641
2642
	do_input(&meta_key, &func_key, &s_or_t, &ran_func, &finished,
		TRUE);
Chris Allegretta's avatar
Chris Allegretta committed
2643
    }
2644

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2645
    assert(FALSE);
Chris Allegretta's avatar
Chris Allegretta committed
2646
}