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

24
#include "proto.h"
25

Chris Allegretta's avatar
Chris Allegretta committed
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdarg.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <locale.h>
35
#ifdef ENABLE_UTF8
36
#include <langinfo.h>
37
#endif
38
#include <termios.h>
Chris Allegretta's avatar
Chris Allegretta committed
39
40
41
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
42
43
44
45
#ifndef NANO_TINY
#include <sys/ioctl.h>
#endif

46
47
48
49
#ifndef DISABLE_MOUSE
static int oldinterval = -1;
	/* Used to store the user's original mouse click interval. */
#endif
50
51
52
53
#ifdef ENABLE_NANORC
static bool no_rcfiles = FALSE;
	/* Should we ignore all rcfiles? */
#endif
54
55
56
static struct termios oldterm;
	/* The user's original terminal settings. */
static struct sigaction act;
57
	/* Used to set up all our fun signal handlers. */
Chris Allegretta's avatar
Chris Allegretta committed
58

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
59
60
/* Create a new filestruct node.  Note that we do not set prevnode->next
 * to the new line. */
61
filestruct *make_new_node(filestruct *prevnode)
62
{
63
64
65
66
67
68
69
70
    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;
71
72
}

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

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

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

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

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

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

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

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

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

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

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

122
    free(fileptr);
123
124
}

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

130
    assert(src != NULL);
131

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

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

142
143
	src = src->next;
    }
144

145
    copy->next = NULL;
146

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

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

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

160
    delete_node(src);
161
162
}

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

168
    assert(fileptr != NULL);
Chris Allegretta's avatar
Chris Allegretta committed
169

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

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

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

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

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

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

190
191
192
    /* 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. */
193
194
195
    if (top != openfile->fileage) {
	p->fileage = openfile->fileage;
	openfile->fileage = top;
196
    } else
197
	p->fileage = NULL;
198
199
200
    if (bot != openfile->filebot) {
	p->filebot = openfile->filebot;
	openfile->filebot = bot;
201
202
    } else
	p->filebot = NULL;
203

204
205
206
207
208
209
210
    /* 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';
211

212
213
214
215
216
217
    /* 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);
218

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

222
    /* Remove all text before top_x at the top of the partition. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
223
224
    charmove(top->data, top->data + top_x, strlen(top->data) -
	top_x + 1);
225
    align(&top->data);
226

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

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

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

239
240
241
    /* 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. */
242
243
244
245
246
247
248
    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);
249
    free((*p)->top_data);
250
    strcat(openfile->fileage->data, tmp);
251
    free(tmp);
252

253
254
255
    /* 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. */
256
257
258
259
260
261
    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);
262
    free((*p)->bot_data);
263

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

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

276
277
278
279
280
281
282
283
/* 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;
284
    bool edittop_inside;
285
#ifndef NANO_TINY
286
287
    bool mark_inside = FALSE;
#endif
288

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

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

295
296
    /* 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
297
     * the edit window is inside the partition, and keep track of
298
299
     * whether the mark begins inside the partition. */
    filepart = partition_filestruct(top, top_x, bot, bot_x);
300
301
302
    edittop_inside = (openfile->edittop->lineno >=
	openfile->fileage->lineno && openfile->edittop->lineno <=
	openfile->filebot->lineno);
303
#ifndef NANO_TINY
304
    if (openfile->mark_set)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
305
	mark_inside = (openfile->mark_begin->lineno >=
306
		openfile->fileage->lineno &&
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
307
		openfile->mark_begin->lineno <=
308
		openfile->filebot->lineno &&
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
309
310
311
312
		(openfile->mark_begin != openfile->fileage ||
		openfile->mark_begin_x >= top_x) &&
		(openfile->mark_begin != openfile->filebot ||
		openfile->mark_begin_x <= bot_x));
313
#endif
314

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

319
320
321
322
    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. */
323
324
	*file_top = openfile->fileage;
	*file_bot = openfile->filebot;
325
326
327

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

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

338
339
340
	/* 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. */
341
	(*file_bot)->next = openfile->fileage->next;
342
343
	if ((*file_bot)->next != NULL) {
	    (*file_bot)->next->prev = *file_bot;
344
	    *file_bot = openfile->filebot;
345
	}
346
347
348
349
350

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
353
354
    /* Since the text has now been saved, remove it from the
     * filestruct. */
355
356
357
    openfile->fileage = (filestruct *)nmalloc(sizeof(filestruct));
    openfile->fileage->data = mallocstrcpy(NULL, "");
    openfile->filebot = openfile->fileage;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
358
359
360
361
362
363

    /* Restore the current line and cursor position.  If the mark begins
     * inside the partition, set the beginning of the mark to where the
     * saved text used to start. */
    openfile->current = openfile->fileage;
    openfile->current_x = top_x;
364
#ifndef NANO_TINY
365
    if (mark_inside) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
366
367
	openfile->mark_begin = openfile->current;
	openfile->mark_begin_x = openfile->current_x;
368
369
    }
#endif
370

371
    top_save = openfile->fileage;
372

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

377
378
379
380
    /* If the top of the edit window was inside the old partition, put
     * it in range of current. */
    if (edittop_inside)
	edit_update(
381
#ifndef NANO_TINY
382
383
384
385
		ISSET(SMOOTH_SCROLL) ? NONE :
#endif
		CENTER);

386
387
388
    /* Renumber starting with the beginning line of the old
     * partition. */
    renumber(top_save);
389

390
391
392
    /* If the NO_NEWLINES flag isn't set, and the text doesn't end with
     * a magicline, add a new magicline. */
    if (!ISSET(NO_NEWLINES) && openfile->filebot->data[0] != '\0')
393
394
	new_magicline();
}
395

396
397
398
399
400
401
/* 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;
402
    size_t current_x_save = openfile->current_x;
403
    bool edittop_inside;
404
#ifndef NANO_TINY
405
    bool right_side_up = FALSE, single_line = FALSE;
406
#endif
407

408
    assert(file_top != NULL && file_bot != NULL);
409

410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#ifndef NANO_TINY
    /* Keep track of whether the mark begins inside the partition and
     * will need adjustment. */
    if (openfile->mark_set) {
	filestruct *top, *bot;
	size_t top_x, bot_x;

	mark_order((const filestruct **)&top, &top_x,
		(const filestruct **)&bot, &bot_x, &right_side_up);

	single_line = (top == bot);
    }
#endif

    /* Partition the filestruct so that it contains no text, and keep
     * track of whether the top of the edit window is inside the
     * partition. */
427
428
429
    filepart = partition_filestruct(openfile->current,
	openfile->current_x, openfile->current, openfile->current_x);
    edittop_inside = (openfile->edittop == openfile->fileage);
430

431
432
    /* Put the top and bottom of the filestruct at copies of file_top
     * and file_bot. */
433
434
435
436
    openfile->fileage = copy_filestruct(file_top);
    openfile->filebot = openfile->fileage;
    while (openfile->filebot->next != NULL)
	openfile->filebot = openfile->filebot->next;
437

438
439
440
    /* Restore the current line and cursor position.  If the mark begins
     * inside the partition, adjust the mark coordinates to compensate
     * for the change in the current line. */
441
442
    openfile->current = openfile->filebot;
    openfile->current_x = strlen(openfile->filebot->data);
443
444
445
446
    if (openfile->fileage == openfile->filebot) {
#ifndef NANO_TINY
	if (openfile->mark_set) {
	    openfile->mark_begin = openfile->current;
447
	    if (!right_side_up)
448
449
450
		openfile->mark_begin_x += openfile->current_x;
	}
#endif
451
	openfile->current_x += current_x_save;
452
    }
453
#ifndef NANO_TINY
454
455
456
457
458
459
460
461
462
    else if (openfile->mark_set) {
	if (!right_side_up) {
	    if (single_line) {
		openfile->mark_begin = openfile->current;
		openfile->mark_begin_x -= current_x_save;
	    } else
		openfile->mark_begin_x -= openfile->current_x;
	}
    }
463
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
464

465
    /* Get the number of characters in the copied text, and add it to
466
467
468
     * totsize. */
    openfile->totsize += get_totsize(openfile->fileage,
	openfile->filebot);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
469

470
471
472
    /* Update the current y-coordinate to account for the number of
     * lines the copied text has, less one since the first line will be
     * tacked onto the current line. */
473
    openfile->current_y += openfile->filebot->lineno - 1;
474

475
    top_save = openfile->fileage;
476

477
478
479
480
481
    /* If the top of the edit window is inside the partition, set it to
     * where the copied text now starts. */
    if (edittop_inside)
	openfile->edittop = openfile->fileage;

482
    /* Unpartition the filestruct so that it contains all the text
483
     * again, plus the copied text. */
484
    unpartition_filestruct(&filepart);
485

486
487
488
    /* Renumber starting with the beginning line of the old
     * partition. */
    renumber(top_save);
489

490
491
492
    /* If the NO_NEWLINES flag isn't set, and the text doesn't end with
     * a magicline, add a new magicline. */
    if (!ISSET(NO_NEWLINES) && openfile->filebot->data[0] != '\0')
493
	new_magicline();
Chris Allegretta's avatar
Chris Allegretta committed
494
495
}

496
497
498
499
500
501
502
503
504
505
506
/* 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;
507
#ifndef NANO_TINY
508
    newnode->last_action = OTHER;
509
#endif
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

    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);
546
#ifndef NANO_TINY
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    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

570
/* Display a warning about a key disabled in view mode. */
571
void print_view_warning(void)
572
{
573
    statusbar(_("Key invalid in view mode"));
574
575
}

576
/* Make nano exit gracefully. */
577
void finish(void)
Chris Allegretta's avatar
Chris Allegretta committed
578
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
579
580
    /* Blank the statusbar (and shortcut list, if applicable), and move
     * the cursor to the last line of the screen. */
581
582
583
584
    if (!ISSET(NO_HELP))
	blank_bottombars();
    else
	blank_statusbar();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
585
    wrefresh(bottomwin);
586
    endwin();
587

588
589
    /* Restore the old terminal settings. */
    tcsetattr(0, TCSANOW, &oldterm);
590

591
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
592
    if (!no_rcfiles && ISSET(HISTORYLOG))
593
594
595
596
597
598
599
	save_history();
#endif

#ifdef DEBUG
    thanks_for_all_the_fish();
#endif

600
    /* Get out. */
601
    exit(0);
602
603
}

604
/* Make nano die gracefully. */
605
void die(const char *msg, ...)
Chris Allegretta's avatar
Chris Allegretta committed
606
{
607
    va_list ap;
Chris Allegretta's avatar
Chris Allegretta committed
608

609
    endwin();
Chris Allegretta's avatar
Chris Allegretta committed
610

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

614
615
616
    va_start(ap, msg);
    vfprintf(stderr, msg, ap);
    va_end(ap);
Chris Allegretta's avatar
Chris Allegretta committed
617

618
    /* Save the current file buffer if it's been modified. */
619
    if (openfile && openfile->modified) {
620
621
622
623
	/* If we've partitioned the filestruct, unpartition it now. */
	if (filepart != NULL)
	    unpartition_filestruct(&filepart);

624
	die_save_file(openfile->filename);
Chris Allegretta's avatar
Chris Allegretta committed
625
626
    }

627
628
#ifdef ENABLE_MULTIBUFFER
    /* Save all of the other modified file buffers, if any. */
629
630
    if (openfile != NULL) {
	openfilestruct *tmp = openfile;
Chris Allegretta's avatar
Chris Allegretta committed
631

632
633
	while (tmp != openfile->next) {
	    openfile = openfile->next;
634

635
	    /* Save the current file buffer if it's been modified. */
636
	    if (openfile->modified)
637
		die_save_file(openfile->filename);
638
	}
639
    }
640
641
642
643
#endif

    /* Get out. */
    exit(1);
644
645
}

646
647
/* Save the current file under the name spacified in die_filename, which
 * is modified to be unique if necessary. */
648
void die_save_file(const char *die_filename)
649
{
650
651
    char *retval;
    bool failed = TRUE;
652

653
654
655
656
657
    /* 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;
658

659
660
    /* If we can't save, we have really bad problems, but we might as
     * well try. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
661
    if (*die_filename == '\0')
662
	die_filename = "nano";
663

664
665
    retval = get_next_filename(die_filename, ".save");
    if (retval[0] != '\0')
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
666
	failed = !write_file(retval, NULL, TRUE, OVERWRITE, TRUE);
667

668
669
670
671
672
673
674
675
    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?"));
676

677
678
    free(retval);
}
679

680
/* Initialize the three window portions nano uses. */
681
void window_init(void)
682
{
683
    /* If the screen height is too small, get out. */
684
    editwinrows = LINES - 5 + no_more_space() + no_help();
685
    if (COLS < MIN_EDITOR_COLS || editwinrows < MIN_EDITOR_ROWS)
686
	die(_("Window size is too small for nano...\n"));
687

688
#ifndef DISABLE_WRAPJUSTIFY
689
    /* Set up fill, based on the screen width. */
690
691
692
693
694
695
    fill = wrap_at;
    if (fill <= 0)
	fill += COLS;
    if (fill < 0)
	fill = 0;
#endif
696

697
698
699
700
701
702
    if (topwin != NULL)
	delwin(topwin);
    if (edit != NULL)
	delwin(edit);
    if (bottomwin != NULL)
	delwin(bottomwin);
703

704
705
706
    /* Set up the windows. */
    topwin = newwin(2 - no_more_space(), COLS, 0, 0);
    edit = newwin(editwinrows, COLS, 2 - no_more_space(), 0);
707
708
    bottomwin = newwin(3 - no_help(), COLS, editwinrows + (2 -
	no_more_space()), 0);
709

710
    /* Turn the keypad on for the windows, if necessary. */
711
    if (!ISSET(REBIND_KEYPAD)) {
712
	keypad(topwin, TRUE);
713
714
715
	keypad(edit, TRUE);
	keypad(bottomwin, TRUE);
    }
716
717
}

718
#ifndef DISABLE_MOUSE
719
720
721
722
/* Disable mouse support. */
void disable_mouse_support(void)
{
    mousemask(0, NULL);
723
    mouseinterval(oldinterval);
724
725
726
727
728
}

/* Enable mouse support. */
void enable_mouse_support(void)
{
729
    mousemask(ALL_MOUSE_EVENTS, NULL);
730
    oldinterval = mouseinterval(50);
731
732
733
734
}

/* Initialize mouse support.  Enable it if the USE_MOUSE flag is set,
 * and disable it otherwise. */
735
void mouse_init(void)
736
{
737
738
739
740
    if (ISSET(USE_MOUSE))
	enable_mouse_support();
    else
	disable_mouse_support();
741
}
742
#endif /* !DISABLE_MOUSE */
743

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
744
#ifdef HAVE_GETOPT_LONG
745
#define print_opt(shortflag, longflag, desc) print_opt_full(shortflag, longflag, desc)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
746
#else
747
#define print_opt(shortflag, longflag, desc) print_opt_full(shortflag, desc)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
748
749
#endif

750
/* Print one usage string to the screen.  This cuts down on duplicate
751
 * strings to translate, and leaves out the parts that shouldn't be
752
 * translatable (i.e. the flag names). */
753
void print_opt_full(const char *shortflag
754
755
756
757
#ifdef HAVE_GETOPT_LONG
	, const char *longflag
#endif
	, const char *desc)
758
759
{
    printf(" %s\t", shortflag);
760
    if (strlenpt(shortflag) < 8)
761
762
763
764
	printf("\t");

#ifdef HAVE_GETOPT_LONG
    printf("%s\t", longflag);
765
    if (strlenpt(longflag) < 8)
766
	printf("\t\t");
767
    else if (strlenpt(longflag) < 16)
768
769
770
	printf("\t");
#endif

771
772
773
    if (desc != NULL)
	printf("%s", _(desc));
    printf("\n");
774
775
}

776
/* Explain how to properly use nano and its command line options. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
777
void usage(void)
Chris Allegretta's avatar
Chris Allegretta committed
778
{
779
    printf(_("Usage: nano [OPTIONS] [[+LINE,COLUMN] FILE]...\n\n"));
780
    printf(
781
782
#ifdef HAVE_GETOPT_LONG
	_("Option\t\tGNU long option\t\tMeaning\n")
Chris Allegretta's avatar
Chris Allegretta committed
783
#else
784
	_("Option\t\tMeaning\n")
785
#endif
786
	);
787
    print_opt("-h, -?", "--help", N_("Show this message"));
788
    print_opt(_("+LINE,COLUMN"), "",
789
	N_("Start at line LINE, column COLUMN"));
790
#ifndef NANO_TINY
791
792
    print_opt("-A", "--smarthome", N_("Enable smart home key"));
    print_opt("-B", "--backup", N_("Save backups of existing files"));
793
    print_opt(_("-C <dir>"), _("--backupdir=<dir>"),
794
	N_("Directory for saving unique backup files"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
795
#endif
796
    print_opt("-D", "--boldtext",
797
	N_("Use bold instead of reverse video text"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
798
#ifndef NANO_TINY
799
    print_opt("-E", "--tabstospaces",
800
	N_("Convert typed tabs to spaces"));
801
#endif
802
#ifdef ENABLE_MULTIBUFFER
803
    print_opt("-F", "--multibuffer", N_("Enable multiple file buffers"));
Chris Allegretta's avatar
Chris Allegretta committed
804
805
#endif
#ifdef ENABLE_NANORC
806
#ifndef NANO_TINY
807
    print_opt("-H", "--historylog",
808
	N_("Log & read search/replace string history"));
809
#endif
810
    print_opt("-I", "--ignorercfiles",
811
	N_("Don't look at nanorc files"));
Chris Allegretta's avatar
Chris Allegretta committed
812
#endif
813
    print_opt("-K", "--rebindkeypad",
814
	N_("Fix numeric keypad key confusion problem"));
815
    print_opt("-L", "--nonewlines",
816
	N_("Don't add newlines to the ends of files"));
817
#ifndef NANO_TINY
818
    print_opt("-N", "--noconvert",
819
	N_("Don't convert files from DOS/Mac format"));
820
#endif
821
    print_opt("-O", "--morespace", N_("Use one more line for editing"));
822
#ifndef DISABLE_JUSTIFY
823
    print_opt(_("-Q <str>"), _("--quotestr=<str>"),
824
	N_("Quoting string"));
825
#endif
826
    print_opt("-R", "--restricted", N_("Restricted mode"));
827
#ifndef NANO_TINY
828
829
    print_opt("-S", "--smooth",
	N_("Scroll by line instead of half-screen"));
830
#endif
831
    print_opt(_("-T <#cols>"), _("--tabsize=<#cols>"),
832
	N_("Set width of a tab to #cols columns"));
833
#ifndef NANO_TINY
834
    print_opt("-U", "--quickblank", N_("Do quick statusbar blanking"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
835
#endif
836
    print_opt("-V", "--version",
837
	N_("Print version information and exit"));
838
#ifndef NANO_TINY
839
    print_opt("-W", "--wordbounds",
840
841
	N_("Detect word boundaries more accurately"));
#endif
842
#ifdef ENABLE_COLOR
843
    print_opt(_("-Y <str>"), _("--syntax=<str>"),
844
	N_("Syntax definition to use for coloring"));
845
#endif
846
847
    print_opt("-c", "--const", N_("Constantly show cursor position"));
    print_opt("-d", "--rebinddelete",
848
	N_("Fix Backspace/Delete confusion problem"));
849
#ifndef NANO_TINY
850
    print_opt("-i", "--autoindent",
851
	N_("Automatically indent new lines"));
852
    print_opt("-k", "--cut", N_("Cut from cursor to end of line"));
853
#endif
854
    print_opt("-l", "--nofollow",
855
	N_("Don't follow symbolic links, overwrite"));
856
#ifndef DISABLE_MOUSE
857
    print_opt("-m", "--mouse", N_("Enable the use of the mouse"));
Chris Allegretta's avatar
Chris Allegretta committed
858
#endif
859
#ifndef DISABLE_OPERATINGDIR
860
    print_opt(_("-o <dir>"), _("--operatingdir=<dir>"),
861
	N_("Set operating directory"));
Chris Allegretta's avatar
Chris Allegretta committed
862
#endif
863
    print_opt("-p", "--preserve",
864
	N_("Preserve XON (^Q) and XOFF (^S) keys"));
865
#ifndef DISABLE_WRAPJUSTIFY
866
    print_opt(_("-r <#cols>"), _("--fill=<#cols>"),
867
	N_("Set wrapping point at column #cols"));
868
#endif
869
#ifndef DISABLE_SPELLER
870
    print_opt(_("-s <prog>"), _("--speller=<prog>"),
871
	N_("Enable alternate speller"));
872
#endif
873
    print_opt("-t", "--tempfile",
874
	N_("Auto save on exit, don't prompt"));
875
    print_opt("-v", "--view", N_("View mode (read-only)"));
876
#ifndef DISABLE_WRAPPING
877
    print_opt("-w", "--nowrap", N_("Don't wrap long lines"));
Chris Allegretta's avatar
Chris Allegretta committed
878
#endif
879
880
    print_opt("-x", "--nohelp", N_("Don't show the two help lines"));
    print_opt("-z", "--suspend", N_("Enable suspension"));
Chris Allegretta's avatar
Chris Allegretta committed
881

882
    /* This is a special case. */
883
884
    print_opt("-a, -b, -e,", "", NULL);
    print_opt("-f, -g, -j", "", N_("(ignored, for Pico compatibility)"));
885

Chris Allegretta's avatar
Chris Allegretta committed
886
887
888
    exit(0);
}

889
890
891
/* Display the current version of nano, the date and time it was
 * compiled, contact information for it, and the configuration options
 * it was compiled with. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
892
void version(void)
Chris Allegretta's avatar
Chris Allegretta committed
893
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
894
895
    printf(_(" GNU nano version %s (compiled %s, %s)\n"), VERSION,
	__TIME__, __DATE__);
896
897
    printf(" (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007\n");
    printf(" Free Software Foundation, Inc.\n");
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
898
899
    printf(
	_(" Email: nano@nano-editor.org	Web: http://www.nano-editor.org/"));
900
    printf(_("\n Compiled options:"));
901

902
#ifdef DISABLE_BROWSER
903
    printf(" --disable-browser");
904
#endif
905
906
#ifdef DISABLE_HELP
    printf(" --disable-help");
907
908
#endif
#ifdef DISABLE_JUSTIFY
909
    printf(" --disable-justify");
910
#endif
911
#ifdef DISABLE_MOUSE
912
    printf(" --disable-mouse");
913
#endif
914
915
916
#ifndef ENABLE_NLS
    printf(" --disable-nls");
#endif
917
918
919
#ifdef DISABLE_OPERATINGDIR
    printf(" --disable-operatingdir");
#endif
920
921
922
923
924
925
926
927
928
#ifdef DISABLE_SPELLER
    printf(" --disable-speller");
#endif
#ifdef DISABLE_TABCOMP
    printf(" --disable-tabcomp");
#endif
#ifdef DISABLE_WRAPPING
    printf(" --disable-wrapping");
#endif
929
#ifdef DISABLE_ROOTWRAPPING
930
931
    printf(" --disable-wrapping-as-root");
#endif
932
933
934
#ifdef ENABLE_COLOR
    printf(" --enable-color");
#endif
935
936
937
938
939
940
#ifdef DEBUG
    printf(" --enable-debug");
#endif
#ifdef NANO_EXTRA
    printf(" --enable-extra");
#endif
941
942
943
944
945
946
#ifdef ENABLE_MULTIBUFFER
    printf(" --enable-multibuffer");
#endif
#ifdef ENABLE_NANORC
    printf(" --enable-nanorc");
#endif
947
#ifdef NANO_TINY
948
949
    printf(" --enable-tiny");
#endif
950
#ifdef ENABLE_UTF8
951
    printf(" --enable-utf8");
952
953
954
#endif
#ifdef USE_SLANG
    printf(" --with-slang");
955
956
#endif
    printf("\n");
Chris Allegretta's avatar
Chris Allegretta committed
957
958
}

959
960
961
/* Return 1 if the MORE_SPACE flag is set, and 0 otherwise.  This is
 * used to calculate the relative screen position while taking this flag
 * into account, since it adds one line to the edit window. */
962
963
964
965
966
int no_more_space(void)
{
    return ISSET(MORE_SPACE) ? 1 : 0;
}

967
968
969
/* Return 2 if the NO_HELP flag is set, and 0 otherwise.  This is used
 * to calculate the relative screen position while taking this flag into
 * account, since it removes two lines from the edit window. */
Chris Allegretta's avatar
Chris Allegretta committed
970
971
int no_help(void)
{
Chris Allegretta's avatar
Chris Allegretta committed
972
    return ISSET(NO_HELP) ? 2 : 0;
Chris Allegretta's avatar
Chris Allegretta committed
973
974
}

975
/* Indicate a disabled function on the statusbar. */
976
void nano_disabled_msg(void)
977
{
Chris Allegretta's avatar
Chris Allegretta committed
978
    statusbar(_("Sorry, support for this function has been disabled"));
979
980
}

981
982
983
984
985
/* If the current file buffer has been modified, and the TEMP_FILE flag
 * isn't set, ask whether or not to save the file buffer.  If the
 * TEMP_FILE flag is set, save it unconditionally.  Then, if more than
 * one file buffer is open, close the current file buffer and switch to
 * the next one.  If only one file buffer is open, exit from nano. */
986
void do_exit(void)
Chris Allegretta's avatar
Chris Allegretta committed
987
{
988
989
    int i;

990
991
    /* If the file hasn't been modified, pretend the user chose not to
     * save. */
992
    if (!openfile->modified)
993
	i = 0;
994
    /* If the TEMP_FILE flag is set, pretend the user chose to save. */
995
    else if (ISSET(TEMP_FILE))
996
	i = 1;
997
    /* Otherwise, ask the user whether or not to save. */
David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
998
    else
999
	i = do_yesno_prompt(FALSE,
1000
1001
		_("Save modified buffer (ANSWERING \"No\" WILL DESTROY CHANGES) ? "));

1002
#ifdef DEBUG
1003
    dump_filestruct(openfile->fileage);
1004
#endif
1005

1006
1007
    /* If the user chose not to save, or if the user chose to save and
     * the save succeeded, we're ready to exit. */
1008
    if (i == 0 || (i == 1 && do_writeout(TRUE))) {
1009
#ifdef ENABLE_MULTIBUFFER
1010
	/* Exit only if there are no more open file buffers. */
1011
	if (!close_buffer())
1012
#endif
1013
	    finish();
1014
    /* If the user canceled, we go on. */
1015
    } else if (i != 1)
1016
1017
	statusbar(_("Cancelled"));

1018
    shortcut_init(FALSE);
1019
1020
1021
    display_main_list();
}

1022
/* Initialize the signal handlers. */
1023
1024
void signal_init(void)
{
1025
1026
    /* Trap SIGINT and SIGQUIT because we want them to do useful
     * things. */
1027
1028
1029
    memset(&act, 0, sizeof(struct sigaction));
    act.sa_handler = SIG_IGN;
    sigaction(SIGINT, &act, NULL);
1030
    sigaction(SIGQUIT, &act, NULL);
1031

1032
    /* Trap SIGHUP and SIGTERM because we want to write the file out. */
1033
    act.sa_handler = handle_hupterm;
1034
    sigaction(SIGHUP, &act, NULL);
1035
    sigaction(SIGTERM, &act, NULL);
1036

1037
#ifndef NANO_TINY
1038
    /* Trap SIGWINCH because we want to handle window resizes. */
1039
1040
    act.sa_handler = handle_sigwinch;
    sigaction(SIGWINCH, &act, NULL);
1041
    allow_pending_sigwinch(FALSE);
1042
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1043

1044
    /* Trap normal suspend (^Z) so we can handle it ourselves. */
1045
1046
1047
1048
    if (!ISSET(SUSPEND)) {
	act.sa_handler = SIG_IGN;
	sigaction(SIGTSTP, &act, NULL);
    } else {
1049
1050
	/* Block all other signals in the suspend and continue handlers.
	 * If we don't do this, other stuff interrupts them! */
1051
	sigfillset(&act.sa_mask);
Chris Allegretta's avatar
Chris Allegretta committed
1052

1053
1054
	act.sa_handler = do_suspend;
	sigaction(SIGTSTP, &act, NULL);
1055

1056
	act.sa_handler = do_continue;
1057
1058
1059
	sigaction(SIGCONT, &act, NULL);
    }
}
1060

1061
/* Handler for SIGHUP (hangup) and SIGTERM (terminate). */
1062
RETSIGTYPE handle_hupterm(int signal)
1063
{
1064
    die(_("Received SIGHUP or SIGTERM\n"));
1065
}
1066

1067
/* Handler for SIGTSTP (suspend). */
1068
RETSIGTYPE do_suspend(int signal)
1069
{
1070
1071
1072
1073
1074
#ifndef DISABLE_MOUSE
    /* Turn mouse support off. */
    disable_mouse_support();
#endif

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1075
1076
    /* Blank the screen, and move the cursor to the last line of the
     * screen. */
1077
1078
1079
    erase();
    move(LINES - 1, 0);
    refresh();
1080

1081
1082
    /* Display our helpful message. */
    printf(_("Use \"fg\" to return to nano.\n"));
1083
    fflush(stdout);
1084

1085
    /* Restore the old terminal settings. */
1086
    tcsetattr(0, TCSANOW, &oldterm);
1087

1088
    /* Trap SIGHUP and SIGTERM so we can properly deal with them while
1089
     * suspended. */
1090
1091
1092
1093
    act.sa_handler = handle_hupterm;
    sigaction(SIGHUP, &act, NULL);
    sigaction(SIGTERM, &act, NULL);

1094
    /* Do what mutt does: send ourselves a SIGSTOP. */
1095
1096
    kill(0, SIGSTOP);
}
1097

1098
1099
1100
1101
1102
1103
1104
/* the subnfunc version */
void do_suspend_void(void) 
{
    if (ISSET(SUSPEND))
	do_suspend(0);
}

1105
/* Handler for SIGCONT (continue after suspend). */
1106
RETSIGTYPE do_continue(int signal)
1107
{
1108
1109
1110
1111
1112
1113
#ifndef DISABLE_MOUSE
    /* Turn mouse support back on if it was on before. */
    if (ISSET(USE_MOUSE))
	enable_mouse_support();
#endif

1114
#ifndef NANO_TINY
1115
    /* Perhaps the user resized the window while we slept.  Handle it,
1116
1117
     * and restore the terminal to its previous state and update the
     * screen in the process. */
1118
    handle_sigwinch(0);
1119
#else
1120
1121
1122
    /* Restore the terminal to its previous state. */
    terminal_init();

1123
1124
1125
1126
1127
    /* Turn the cursor back on for sure. */
    curs_set(1);

    /* Redraw the contents of the windows that need it. */
    blank_statusbar();
1128
    wnoutrefresh(bottomwin);
1129
    total_refresh();
1130
1131
1132
#endif
}

1133
#ifndef NANO_TINY
1134
/* Handler for SIGWINCH (window size change). */
1135
RETSIGTYPE handle_sigwinch(int signal)
1136
1137
{
    const char *tty = ttyname(0);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1138
    int fd, result = 0;
1139
1140
    struct winsize win;

1141
    if (tty == NULL)
1142
1143
1144
1145
1146
1147
1148
1149
1150
	return;
    fd = open(tty, O_RDWR);
    if (fd == -1)
	return;
    result = ioctl(fd, TIOCGWINSZ, &win);
    close(fd);
    if (result == -1)
	return;

1151
1152
1153
1154
    /* We could check whether the COLS or LINES changed, and return
     * otherwise.  However, COLS and LINES are curses global variables,
     * and in some cases curses has already updated them.  But not in
     * all cases.  Argh. */
1155
1156
1157
    COLS = win.ws_col;
    LINES = win.ws_row;

1158
1159
    /* If we've partitioned the filestruct, unpartition it now. */
    if (filepart != NULL)
1160
	unpartition_filestruct(&filepart);
1161

1162
1163
1164
1165
1166
1167
1168
1169
#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
1170
1171
1172
    /* Do the equivalent of what Minimum Profit does: Leave and
     * immediately reenter curses mode. */
    endwin();
1173
    doupdate();
1174
#endif
1175

1176
1177
1178
    /* Restore the terminal to its previous state. */
    terminal_init();

1179
1180
1181
    /* Turn the cursor back on for sure. */
    curs_set(1);

1182
1183
1184
1185
1186
    /* Do the equivalent of what both mutt and Minimum Profit do:
     * Reinitialize all the windows based on the new screen
     * dimensions. */
    window_init();

1187
    /* Redraw the contents of the windows that need it. */
1188
    blank_statusbar();
1189
    wnoutrefresh(bottomwin);
1190
    currmenu = MMAIN;
1191
1192
    total_refresh();

1193
1194
1195
    /* Jump back to either main() or the unjustify routine in
     * do_justify(). */
    siglongjmp(jump_buf, 1);
1196
}
1197

1198
1199
1200
/* If allow is TRUE, block any SIGWINCH signals that we get, so that we
 * can deal with them later.  If allow is FALSE, unblock any SIGWINCH
 * signals that we have, so that we can deal with them now. */
1201
void allow_pending_sigwinch(bool allow)
1202
1203
1204
1205
{
    sigset_t winch;
    sigemptyset(&winch);
    sigaddset(&winch, SIGWINCH);
1206
    sigprocmask(allow ? SIG_UNBLOCK : SIG_BLOCK, &winch, NULL);
1207
}
1208
#endif /* !NANO_TINY */
1209

1210
#ifndef NANO_TINY
1211
/* Handle the global toggle specified in which. */
1212
void do_toggle(int flag)
1213
{
1214
    bool enabled;
1215
    char *desc;
1216

1217
    TOGGLE(flag);
Chris Allegretta's avatar
Chris Allegretta committed
1218

1219
    switch (flag) {
1220
#ifndef DISABLE_MOUSE
1221
	case USE_MOUSE:
1222
1223
	    mouse_init();
	    break;
1224
#endif
1225
1226
	case MORE_SPACE:
	case NO_HELP:
1227
	    window_init();
1228
	    total_refresh();
1229
	    break;
1230
	case SUSPEND:
1231
	    signal_init();
1232
	    break;
1233
#ifdef ENABLE_NANORC
1234
	case WHITESPACE_DISPLAY:
1235
	    titlebar(NULL);
1236
1237
	    edit_refresh();
	    break;
1238
1239
#endif
#ifdef ENABLE_COLOR
1240
	case NO_COLOR_SYNTAX:
1241
1242
	    edit_refresh();
	    break;
1243
#endif
1244
    }
Chris Allegretta's avatar
Chris Allegretta committed
1245

1246
    enabled = ISSET(flag);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1247

1248
    if (flag ==  NO_HELP
1249
#ifndef DISABLE_WRAPPING
1250
	|| flag == NO_WRAP
1251
1252
#endif
#ifdef ENABLE_COLOR
1253
	|| flag == NO_COLOR_SYNTAX
1254
1255
#endif
	)
Chris Allegretta's avatar
Chris Allegretta committed
1256
	enabled = !enabled;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1257

1258
    desc = _(flagtostr(flag));
1259
    statusbar("%s %s", desc, enabled ? _("enabled") :
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1260
	_("disabled"));
Chris Allegretta's avatar
Chris Allegretta committed
1261
}
1262
#endif /* !NANO_TINY */
Chris Allegretta's avatar
Chris Allegretta committed
1263

1264
1265
/* Disable extended input and output processing in our terminal
 * settings. */
1266
void disable_extended_io(void)
1267
1268
1269
1270
1271
{
    struct termios term;

    tcgetattr(0, &term);
    term.c_lflag &= ~IEXTEN;
1272
    term.c_oflag &= ~OPOST;
1273
1274
1275
    tcsetattr(0, TCSANOW, &term);
}

1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
#ifdef USE_SLANG
/* Disable interpretation of the special control keys in our terminal
 * settings. */
void disable_signals(void)
{
    struct termios term;

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

1289
#ifndef NANO_TINY
1290
1291
/* Enable interpretation of the special control keys in our terminal
 * settings. */
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
void enable_signals(void)
{
    struct termios term;

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

1302
1303
/* Disable interpretation of the flow control characters in our terminal
 * settings. */
1304
1305
1306
1307
1308
void disable_flow_control(void)
{
    struct termios term;

    tcgetattr(0, &term);
1309
    term.c_iflag &= ~IXON;
1310
1311
1312
    tcsetattr(0, TCSANOW, &term);
}

1313
1314
/* Enable interpretation of the flow control characters in our terminal
 * settings. */
1315
1316
1317
1318
1319
void enable_flow_control(void)
{
    struct termios term;

    tcgetattr(0, &term);
1320
    term.c_iflag |= IXON;
1321
1322
1323
    tcsetattr(0, TCSANOW, &term);
}

1324
1325
1326
1327
1328
1329
1330
1331
/* Set up the terminal state.  Put the terminal in raw mode (read one
 * character at a time, disable the special control keys, and disable
 * the flow control characters), 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 echoing of characters as they're
 * typed.  Finally, disable extended input and output processing, and,
 * if we're not in preserve mode, reenable interpretation of the flow
 * control characters. */
1332
1333
void terminal_init(void)
{
1334
1335
1336
1337
#ifdef USE_SLANG
    /* Slang curses emulation brain damage, part 2: Slang doesn't
     * implement raw(), nonl(), or noecho() properly, so there's no way
     * to properly reinitialize the terminal using them.  We have to
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1338
1339
1340
     * disable the special control keys and interpretation of the flow
     * control characters using termios, save the terminal state after
     * the first call, and restore it on subsequent calls. */
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
    static struct termios newterm;
    static bool newterm_set = FALSE;

    if (!newterm_set) {
#endif

	raw();
	nonl();
	noecho();
	disable_extended_io();
	if (ISSET(PRESERVE))
	    enable_flow_control();

#ifdef USE_SLANG
	disable_signals();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1356
1357
	if (!ISSET(PRESERVE))
	    disable_flow_control();
1358
1359
1360
1361
1362
1363

	tcgetattr(0, &newterm);
	newterm_set = TRUE;
    } else
	tcsetattr(0, TCSANOW, &newterm);
#endif
1364
1365
}

1366
1367
1368
1369
1370
1371
1372
1373
1374
/* Read in a character, interpret it as a shortcut or toggle if
 * necessary, and return it.  Set meta_key to TRUE if the character is a
 * meta sequence, set func_key to TRUE if the character is a function
 * key, set s_or_t to TRUE if the character is a shortcut or toggle
 * key, set ran_func to TRUE if we ran a function associated with a
 * shortcut key, and set finished to TRUE if we're done after running
 * or trying to run a function associated with a shortcut key.  If
 * allow_funcs is FALSE, don't actually run any functions associated
 * with shortcut keys. */
1375
int do_input(bool *meta_key, bool *func_key, bool *s_or_t, bool
1376
	*ran_func, bool *finished, bool allow_funcs)
1377
1378
1379
1380
1381
1382
1383
{
    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. */
1384
1385
    bool cut_copy = FALSE;
	/* Are we cutting or copying text? */
1386
    const sc *s;
1387
1388
1389
    bool have_shortcut;

    *s_or_t = FALSE;
1390
    *ran_func = FALSE;
1391
    *finished = FALSE;
1392
1393
1394
1395
1396

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

#ifndef DISABLE_MOUSE
1397
    if (allow_funcs) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1398
1399
	/* If we got a mouse click and it was on a shortcut, read in the
	 * shortcut character. */
1400
	if (*func_key && input == KEY_MOUSE) {
1401
	    if (do_mouse() == 1)
1402
1403
1404
1405
1406
1407
1408
		input = get_kbinput(edit, meta_key, func_key);
	    else {
		*meta_key = FALSE;
		*func_key = FALSE;
		input = ERR;
	    }
	}
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1409
    }
1410
1411
1412
#endif

    /* Check for a shortcut in the main list. */
1413
    s = get_shortcut(MMAIN, &input, meta_key, func_key);
1414
1415
1416

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

1419
1420
    /* If we got a non-high-bit control key, a meta key sequence, or a
     * function key, and it's not a shortcut or toggle, throw it out. */
1421
    if (!have_shortcut) {
1422
	if (is_ascii_cntrl_char(input) || *meta_key || *func_key) {
1423
	    statusbar(_("Unknown Command"));
1424
	    beep();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1425
1426
	    *meta_key = FALSE;
	    *func_key = FALSE;
1427
	    input = ERR;
1428
1429
1430
	}
    }

1431
    if (allow_funcs) {
1432
1433
1434
1435
	/* 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. */
1436
	if (input != ERR && !have_shortcut) {
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
	    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
1449
	 * output all the characters in the input buffer if it isn't
1450
1451
	 * empty.  Note that it should be empty if we're in view
	 * mode. */
1452
	 if (have_shortcut || get_key_buffer_len() == 0) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1453
#ifndef DISABLE_WRAPPING
1454
1455
1456
	    /* If we got a shortcut or toggle, and it's not the shortcut
	     * for verbatim input, turn off prepending of wrapped
	     * text. */
1457
	    if (have_shortcut && (!have_shortcut || s == NULL || s->scfunc !=
1458
		do_verbatim_input))
1459
		wrap_reset();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1460
#endif
1461

1462
1463
	    if (kbinput != NULL) {
		/* Display all the characters in the input buffer at
1464
		 * once, filtering out control characters. */
1465
1466
1467
1468
1469
1470
1471
		char *output = charalloc(kbinput_len + 1);
		size_t i;

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

1472
		do_output(output, kbinput_len, FALSE);
1473
1474

		free(output);
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484

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

	if (have_shortcut) {
	    switch (input) {
1485
		/* Handle the normal edit window shortcuts, setting
1486
1487
		 * ran_func to TRUE if we try to run their associated
		 * functions and setting finished to TRUE to indicate
1488
1489
		 * that we're done after running or trying to run their
		 * associated functions. */
1490
		default:
1491
1492
		    /* If the function associated with this shortcut is
		     * cutting or copying text, indicate this. */
1493
		    if (s->scfunc == do_cut_text_void
1494
#ifndef NANO_TINY
1495
			|| s->scfunc == do_copy_text || s->scfunc ==
1496
			do_cut_till_end
1497
1498
#endif
			)
1499
			cut_copy = TRUE;
1500

1501
1502
		    if (s->scfunc != NULL) {
			const subnfunc *f = sctofunc((sc *) s);
1503
			*ran_func = TRUE;
1504
			if (ISSET(VIEW_MODE) && f && !f->viewok)
1505
1506
			    print_view_warning();
			else
1507
1508
1509
1510
1511
1512
#ifndef NANO_TINY
			    if (s->scfunc == (void *) do_toggle)
				do_toggle(s->toggle);
			    else
#endif
				s->scfunc();
1513
		    }
1514
		    *finished = TRUE;
1515
1516
1517
1518
1519
		    break;
	    }
	}
    }

1520
1521
1522
1523
1524
    /* If we aren't cutting or copying text, blow away the text in the
     * cutbuffer. */
    if (!cut_copy)
	cutbuffer_reset();

1525
1526
1527
    return input;
}

1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
void xon_complaint(void)
{
    statusbar(_("XON ignored, mumble mumble"));
}

void xoff_complaint(void)
{
    statusbar(_("XOFF ignored, mumble mumble"));
}


1539
#ifndef DISABLE_MOUSE
1540
/* Handle a mouse click on the edit window or the shortcut list. */
1541
int do_mouse(void)
1542
1543
{
    int mouse_x, mouse_y;
1544
    int retval = get_mouseinput(&mouse_x, &mouse_y, TRUE);
1545

1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
    /* We can click on the edit window to move the cursor. */
    if (retval == 0 && wmouse_trafo(edit, &mouse_y, &mouse_x, FALSE)) {
	bool sameline;
	    /* Did they click on the line with the cursor?  If they
	     * clicked on the cursor, we set the mark. */
	const filestruct *current_save = openfile->current;
	size_t current_x_save = openfile->current_x;
	size_t pww_save = openfile->placewewant;

	sameline = (mouse_y == openfile->current_y);

	/* Move to where the click occurred. */
	for (; openfile->current_y < mouse_y && openfile->current !=
		openfile->filebot; openfile->current_y++)
	    openfile->current = openfile->current->next;
	for (; openfile->current_y > mouse_y && openfile->current !=
		openfile->fileage; openfile->current_y--)
	    openfile->current = openfile->current->prev;

	openfile->current_x = actual_x(openfile->current->data,
1566
		get_page_start(xplustabs()) + mouse_x);
1567
	openfile->placewewant = xplustabs();
1568

1569
#ifndef NANO_TINY
1570
1571
1572
1573
1574
	/* Clicking where the cursor is toggles the mark, as does
	 * clicking beyond the line length with the cursor at the end of
	 * the line. */
	if (sameline && openfile->current_x == current_x_save)
	    do_mark();
1575
1576
#endif

1577
	edit_redraw(current_save, pww_save);
1578
1579
1580
1581
1582
1583
    }

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

1584
/* The user typed output_len multibyte characters.  Add them to the edit
1585
 * buffer, filtering out all ASCII control characters if allow_cntrls is
1586
1587
 * TRUE. */
void do_output(char *output, size_t output_len, bool allow_cntrls)
1588
{
1589
    size_t current_len, i = 0;
1590
1591
    bool do_refresh = FALSE;
	/* Do we have to call edit_refresh(), or can we get away with
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1592
	 * just update_line()? */
1593

1594
1595
    char *char_buf = charalloc(mb_cur_max());
    int char_buf_len;
1596

1597
    assert(openfile->current != NULL && openfile->current->data != NULL);
1598

1599
    current_len = strlen(openfile->current->data);
1600

1601
    while (i < output_len) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1602
1603
	/* If allow_cntrls is TRUE, convert nulls and newlines
	 * properly. */
1604
1605
1606
	if (allow_cntrls) {
	    /* Null to newline, if needed. */
	    if (output[i] == '\0')
1607
		output[i] = '\n';
1608
1609
	    /* Newline to Enter, if needed. */
	    else if (output[i] == '\n') {
1610
1611
1612
1613
		do_enter();
		i++;
		continue;
	    }
1614
1615
	}

1616
1617
	/* Interpret the next multibyte character. */
	char_buf_len = parse_mbchar(output + i, char_buf, NULL);
1618
1619

	i += char_buf_len;
1620

1621
1622
1623
1624
	/* If allow_cntrls is FALSE, filter out an ASCII control
	 * character. */
	if (!allow_cntrls && is_ascii_cntrl_char(*(output + i -
		char_buf_len)))
1625
1626
	    continue;

1627
	/* If the NO_NEWLINES flag isn't set, when a character is
1628
	 * added to the magicline, it means we need a new magicline. */
1629
1630
	if (!ISSET(NO_NEWLINES) && openfile->filebot ==
		openfile->current)
1631
1632
1633
	    new_magicline();

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

1637
	assert(openfile->current_x <= current_len);
1638

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1639
1640
1641
1642
1643
	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,
1644
		char_buf_len);
1645
	current_len += char_buf_len;
1646
	openfile->totsize++;
1647
1648
	set_modified();

1649
#ifndef NANO_TINY
1650
1651
1652
	update_undo(ADD, openfile);


1653
	/* Note that current_x has not yet been incremented. */
1654
	if (openfile->mark_set && openfile->current ==
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1655
1656
1657
		openfile->mark_begin && openfile->current_x <
		openfile->mark_begin_x)
	    openfile->mark_begin_x += char_buf_len;
1658
1659
#endif

1660
	openfile->current_x += char_buf_len;
1661
1662

#ifndef DISABLE_WRAPPING
1663
1664
	/* If we're wrapping text, we need to call edit_refresh(). */
	if (!ISSET(NO_WRAP)) {
1665
1666
	    bool do_refresh_save = do_refresh;

1667
	    do_refresh = do_wrap(openfile->current);
1668
1669
1670
1671
1672
1673
1674
1675
1676

	    /* 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
1677
1678
1679
	/* If color syntaxes are available and turned on, we need to
	 * call edit_refresh(). */
	if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX))
1680
1681
1682
1683
	    do_refresh = TRUE;
#endif
    }

1684
    free(char_buf);
1685

1686
1687
    openfile->placewewant = xplustabs();

1688
1689
1690
    if (do_refresh)
	edit_refresh();
    else
1691
	update_line(openfile->current, openfile->current_x);
1692
1693
}

1694
int main(int argc, char **argv)
Chris Allegretta's avatar
Chris Allegretta committed
1695
1696
{
    int optchr;
1697
    ssize_t startline = 1;
1698
	/* Line to try and start at. */
1699
1700
    ssize_t startcol = 1;
	/* Column to try and start at. */
1701
#ifndef DISABLE_WRAPJUSTIFY
1702
    bool fill_used = FALSE;
1703
	/* Was the fill option used? */
1704
#endif
1705
1706
1707
1708
1709
#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
1710
#ifdef HAVE_GETOPT_LONG
1711
    const struct option long_options[] = {
1712
	{"help", 0, NULL, 'h'},
1713
	{"boldtext", 0, NULL, 'D'},
1714
#ifdef ENABLE_MULTIBUFFER
1715
	{"multibuffer", 0, NULL, 'F'},
Chris Allegretta's avatar
Chris Allegretta committed
1716
1717
#endif
#ifdef ENABLE_NANORC
1718
	{"ignorercfiles", 0, NULL, 'I'},
1719
#endif
1720
	{"rebindkeypad", 0, NULL, 'K'},
1721
	{"nonewlines", 0, NULL, 'L'},
1722
	{"morespace", 0, NULL, 'O'},
1723
#ifndef DISABLE_JUSTIFY
1724
	{"quotestr", 1, NULL, 'Q'},
1725
#endif
1726
	{"restricted", 0, NULL, 'R'},
1727
1728
	{"tabsize", 1, NULL, 'T'},
	{"version", 0, NULL, 'V'},
1729
#ifdef ENABLE_COLOR
1730
	{"syntax", 1, NULL, 'Y'},
1731
#endif
1732
1733
1734
	{"const", 0, NULL, 'c'},
	{"rebinddelete", 0, NULL, 'd'},
	{"nofollow", 0, NULL, 'l'},
1735
#ifndef DISABLE_MOUSE
1736
	{"mouse", 0, NULL, 'm'},
1737
#endif
1738
#ifndef DISABLE_OPERATINGDIR
1739
	{"operatingdir", 1, NULL, 'o'},
1740
#endif
1741
	{"preserve", 0, NULL, 'p'},
1742
#ifndef DISABLE_WRAPJUSTIFY
1743
	{"fill", 1, NULL, 'r'},
1744
1745
#endif
#ifndef DISABLE_SPELLER
1746
	{"speller", 1, NULL, 's'},
1747
#endif
1748
1749
	{"tempfile", 0, NULL, 't'},
	{"view", 0, NULL, 'v'},
1750
#ifndef DISABLE_WRAPPING
1751
	{"nowrap", 0, NULL, 'w'},
1752
#endif
1753
1754
	{"nohelp", 0, NULL, 'x'},
	{"suspend", 0, NULL, 'z'},
1755
#ifndef NANO_TINY
1756
1757
	{"smarthome", 0, NULL, 'A'},
	{"backup", 0, NULL, 'B'},
1758
1759
	{"backupdir", 1, NULL, 'C'},
	{"tabstospaces", 0, NULL, 'E'},
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1760
	{"historylog", 0, NULL, 'H'},
1761
1762
	{"noconvert", 0, NULL, 'N'},
	{"smooth", 0, NULL, 'S'},
1763
	{"quickblank", 0, NULL, 'U'},
1764
	{"wordbounds", 0, NULL, 'W'},
1765
1766
	{"autoindent", 0, NULL, 'i'},
	{"cut", 0, NULL, 'k'},
1767
#endif
1768
	{NULL, 0, NULL, 0}
Chris Allegretta's avatar
Chris Allegretta committed
1769
1770
1771
    };
#endif

1772
#ifdef ENABLE_UTF8
1773
    {
1774
1775
	/* If the locale set exists and uses UTF-8, we should use
	 * UTF-8. */
1776
1777
	char *locale = setlocale(LC_ALL, "");

1778
1779
	if (locale != NULL && (strcmp(nl_langinfo(CODESET),
		"UTF-8") == 0)) {
1780
#ifdef USE_SLANG
1781
	    SLutf8_enable(1);
1782
#endif
1783
	    utf8_init();
1784
	}
1785
1786
    }
#else
Chris Allegretta's avatar
Chris Allegretta committed
1787
    setlocale(LC_ALL, "");
1788
1789
#endif

1790
#ifdef ENABLE_NLS
Chris Allegretta's avatar
Chris Allegretta committed
1791
1792
1793
1794
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);
#endif

1795
#if !defined(ENABLE_NANORC) && defined(DISABLE_ROOTWRAPPING)
1796
1797
    /* If we don't have rcfile support, --disable-wrapping-as-root is
     * used, and we're root, turn wrapping off. */
1798
    if (geteuid() == NANO_ROOT_UID)
1799
1800
	SET(NO_WRAP);
#endif
1801

1802
    while ((optchr =
Chris Allegretta's avatar
Chris Allegretta committed
1803
#ifdef HAVE_GETOPT_LONG
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1804
	getopt_long(argc, argv,
1805
		"h?ABC:DEFHIKLNOQ:RST:UVWY:abcdefgijklmo:pr:s:tvwxz",
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1806
		long_options, NULL)
Chris Allegretta's avatar
Chris Allegretta committed
1807
#else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1808
	getopt(argc, argv,
1809
		"h?ABC:DEFHIKLNOQ:RST:UVWY:abcdefgijklmo:pr:s:tvwxz")
Chris Allegretta's avatar
Chris Allegretta committed
1810
#endif
1811
		) != -1) {
Chris Allegretta's avatar
Chris Allegretta committed
1812
	switch (optchr) {
1813
1814
1815
1816
1817
1818
1819
1820
	    case 'a':
	    case 'b':
	    case 'e':
	    case 'f':
	    case 'g':
	    case 'j':
		/* Pico compatibility flags. */
		break;
1821
#ifndef NANO_TINY
1822
1823
1824
1825
1826
1827
	    case 'A':
		SET(SMART_HOME);
		break;
	    case 'B':
		SET(BACKUP_FILE);
		break;
1828
	    case 'C':
1829
1830
		backup_dir = mallocstrcpy(backup_dir, optarg);
		break;
1831
1832
1833
1834
1835
#endif
	    case 'D':
		SET(BOLD_TEXT);
		break;
#ifndef NANO_TINY
1836
1837
1838
	    case 'E':
		SET(TABS_TO_SPACES);
		break;
1839
#endif
1840
#ifdef ENABLE_MULTIBUFFER
1841
1842
1843
	    case 'F':
		SET(MULTIBUFFER);
		break;
Chris Allegretta's avatar
Chris Allegretta committed
1844
1845
#endif
#ifdef ENABLE_NANORC
1846
#ifndef NANO_TINY
1847
1848
1849
	    case 'H':
		SET(HISTORYLOG);
		break;
1850
#endif
1851
	    case 'I':
1852
		no_rcfiles = TRUE;
1853
		break;
1854
#endif
1855
1856
1857
	    case 'K':
		SET(REBIND_KEYPAD);
		break;
1858
1859
1860
	    case 'L':
		SET(NO_NEWLINES);
		break;
1861
#ifndef NANO_TINY
1862
1863
1864
	    case 'N':
		SET(NO_CONVERT);
		break;
1865
#endif
1866
1867
1868
	    case 'O':
		SET(MORE_SPACE);
		break;
1869
#ifndef DISABLE_JUSTIFY
1870
1871
1872
	    case 'Q':
		quotestr = mallocstrcpy(quotestr, optarg);
		break;
1873
#endif
1874
1875
1876
	    case 'R':
		SET(RESTRICTED);
		break;
1877
#ifndef NANO_TINY
1878
	    case 'S':
1879
		SET(SMOOTH_SCROLL);
1880
		break;
1881
#endif
1882
1883
	    case 'T':
		if (!parse_num(optarg, &tabsize) || tabsize <= 0) {
1884
		    fprintf(stderr, _("Requested tab size \"%s\" is invalid"), optarg);
1885
		    fprintf(stderr, "\n");
1886
1887
1888
		    exit(1);
		}
		break;
1889
#ifndef NANO_TINY
1890
1891
1892
1893
	    case 'U':
		SET(QUICK_BLANK);
		break;
#endif
1894
1895
1896
	    case 'V':
		version();
		exit(0);
1897
#ifndef NANO_TINY
1898
1899
1900
1901
	    case 'W':
		SET(WORD_BOUNDS);
		break;
#endif
1902
#ifdef ENABLE_COLOR
1903
1904
1905
	    case 'Y':
		syntaxstr = mallocstrcpy(syntaxstr, optarg);
		break;
1906
#endif
1907
	    case 'c':
1908
		SET(CONST_UPDATE);
1909
1910
1911
1912
		break;
	    case 'd':
		SET(REBIND_DELETE);
		break;
1913
#ifndef NANO_TINY
1914
1915
1916
1917
1918
1919
	    case 'i':
		SET(AUTOINDENT);
		break;
	    case 'k':
		SET(CUT_TO_END);
		break;
1920
#endif
1921
1922
1923
	    case 'l':
		SET(NOFOLLOW_SYMLINKS);
		break;
1924
#ifndef DISABLE_MOUSE
1925
1926
1927
	    case 'm':
		SET(USE_MOUSE);
		break;
1928
#endif
1929
#ifndef DISABLE_OPERATINGDIR
1930
1931
1932
	    case 'o':
		operating_dir = mallocstrcpy(operating_dir, optarg);
		break;
1933
#endif
1934
1935
1936
	    case 'p':
		SET(PRESERVE);
		break;
1937
#ifndef DISABLE_WRAPJUSTIFY
1938
1939
	    case 'r':
		if (!parse_num(optarg, &wrap_at)) {
1940
		    fprintf(stderr, _("Requested fill size \"%s\" is invalid"), optarg);
1941
		    fprintf(stderr, "\n");
1942
1943
		    exit(1);
		}
1944
		fill_used = TRUE;
1945
		break;
1946
#endif
1947
#ifndef DISABLE_SPELLER
1948
1949
1950
	    case 's':
		alt_speller = mallocstrcpy(alt_speller, optarg);
		break;
1951
#endif
1952
1953
1954
1955
1956
1957
	    case 't':
		SET(TEMP_FILE);
		break;
	    case 'v':
		SET(VIEW_MODE);
		break;
1958
#ifndef DISABLE_WRAPPING
1959
1960
1961
	    case 'w':
		SET(NO_WRAP);
		break;
1962
#endif
1963
1964
1965
1966
1967
1968
1969
1970
	    case 'x':
		SET(NO_HELP);
		break;
	    case 'z':
		SET(SUSPEND);
		break;
	    default:
		usage();
Chris Allegretta's avatar
Chris Allegretta committed
1971
1972
1973
	}
    }

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1974
    /* If the executable filename starts with 'r', enable restricted
1975
     * mode. */
1976
1977
1978
    if (*(tail(argv[0])) == 'r')
	SET(RESTRICTED);

1979
1980
1981
    /* 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. */
1982
1983
1984
    if (ISSET(RESTRICTED)) {
	UNSET(SUSPEND);
	UNSET(BACKUP_FILE);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1985
#ifdef ENABLE_NANORC
1986
	no_rcfiles = TRUE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1987
#endif
1988
1989
    }

1990
1991
1992
1993
1994

    /* Set up the shortcut lists.
       Need to do this before the rcfile */
    shortcut_init(FALSE);

Chris Allegretta's avatar
Chris Allegretta committed
1995
/* We've read through the command line options.  Now back up the flags
1996
1997
 * 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
1998
#ifdef ENABLE_NANORC
1999
    if (!no_rcfiles) {
Chris Allegretta's avatar
Chris Allegretta committed
2000
2001
2002
#ifndef DISABLE_OPERATINGDIR
	char *operating_dir_cpy = operating_dir;
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2003
#ifndef DISABLE_WRAPJUSTIFY
2004
	ssize_t wrap_at_cpy = wrap_at;
Chris Allegretta's avatar
Chris Allegretta committed
2005
#endif
2006
#ifndef NANO_TINY
2007
2008
	char *backup_dir_cpy = backup_dir;
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2009
2010
2011
2012
2013
2014
#ifndef DISABLE_JUSTIFY
	char *quotestr_cpy = quotestr;
#endif
#ifndef DISABLE_SPELLER
	char *alt_speller_cpy = alt_speller;
#endif
2015
	ssize_t tabsize_cpy = tabsize;
2016
	long flags_cpy = flags;
Chris Allegretta's avatar
Chris Allegretta committed
2017

2018
#ifndef DISABLE_OPERATINGDIR
Chris Allegretta's avatar
Chris Allegretta committed
2019
	operating_dir = NULL;
2020
#endif
2021
#ifndef NANO_TINY
2022
2023
	backup_dir = NULL;
#endif
2024
#ifndef DISABLE_JUSTIFY
Chris Allegretta's avatar
Chris Allegretta committed
2025
	quotestr = NULL;
2026
2027
#endif
#ifndef DISABLE_SPELLER
Chris Allegretta's avatar
Chris Allegretta committed
2028
	alt_speller = NULL;
2029
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2030
2031
2032

	do_rcfile();

2033
2034
2035
2036
2037
#ifdef DEBUG
        fprintf(stderr, "After rebinding keys...\n");
        print_sclist();
#endif

Chris Allegretta's avatar
Chris Allegretta committed
2038
2039
2040
2041
2042
2043
#ifndef DISABLE_OPERATINGDIR
	if (operating_dir_cpy != NULL) {
	    free(operating_dir);
	    operating_dir = operating_dir_cpy;
	}
#endif
2044
#ifndef DISABLE_WRAPJUSTIFY
2045
	if (fill_used)
Chris Allegretta's avatar
Chris Allegretta committed
2046
2047
	    wrap_at = wrap_at_cpy;
#endif
2048
#ifndef NANO_TINY
2049
2050
2051
2052
	if (backup_dir_cpy != NULL) {
	    free(backup_dir);
	    backup_dir = backup_dir_cpy;
	}
2053
#endif
Chris Allegretta's avatar
Chris Allegretta committed
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
#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
2066
	if (tabsize_cpy != -1)
Chris Allegretta's avatar
Chris Allegretta committed
2067
2068
2069
	    tabsize = tabsize_cpy;
	flags |= flags_cpy;
    }
2070
#ifdef DISABLE_ROOTWRAPPING
2071
2072
    /* If we don't have any rcfiles, --disable-wrapping-as-root is used,
     * and we're root, turn wrapping off. */
2073
    else if (geteuid() == NANO_ROOT_UID)
Chris Allegretta's avatar
Chris Allegretta committed
2074
2075
2076
2077
	SET(NO_WRAP);
#endif
#endif /* ENABLE_NANORC */

2078
2079
2080
2081
2082
    /* If we're using bold text instead of reverse video text, set it up
     * now. */
    if (ISSET(BOLD_TEXT))
	reverse_attr = A_BOLD;

2083
#ifndef NANO_TINY
2084
    /* Set up the search/replace history. */
2085
2086
    history_init();
#ifdef ENABLE_NANORC
2087
    if (!no_rcfiles && ISSET(HISTORYLOG))
2088
2089
2090
2091
	load_history();
#endif
#endif

2092
#ifndef NANO_TINY
2093
    /* Set up the backup directory (unless we're using restricted mode,
2094
2095
2096
2097
     * 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. */
2098
2099
    if (!ISSET(RESTRICTED))
	init_backup_dir();
2100
2101
#endif

2102
#ifndef DISABLE_OPERATINGDIR
Chris Allegretta's avatar
Chris Allegretta committed
2103
    /* Set up the operating directory.  This entails chdir()ing there,
2104
     * so that file reads and writes will be based there. */
2105
2106
2107
    init_operating_dir();
#endif

Chris Allegretta's avatar
Chris Allegretta committed
2108
#ifndef DISABLE_JUSTIFY
2109
    /* If punct wasn't specified, set its default value. */
2110
    if (punct == NULL)
2111
	punct = mallocstrcpy(NULL, "!.?");
2112

2113
    /* If brackets wasn't specified, set its default value. */
2114
    if (brackets == NULL)
2115
	brackets = mallocstrcpy(NULL, "\"')>]}");
2116

2117
    /* If quotestr wasn't specified, set its default value. */
Chris Allegretta's avatar
Chris Allegretta committed
2118
    if (quotestr == NULL)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2119
	quotestr = mallocstrcpy(NULL,
Chris Allegretta's avatar
Chris Allegretta committed
2120
#ifdef HAVE_REGEX_H
2121
		"^([ \t]*[#:>|}])+"
Chris Allegretta's avatar
Chris Allegretta committed
2122
#else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2123
		"> "
Chris Allegretta's avatar
Chris Allegretta committed
2124
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2125
		);
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
#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
2142
#endif /* !DISABLE_JUSTIFY */
2143

2144
2145
#ifndef DISABLE_SPELLER
    /* If we don't have an alternative spell checker after reading the
2146
     * command line and/or rcfile(s), check $SPELL for one, as Pico
2147
     * does (unless we're using restricted mode, in which case spell
2148
2149
     * checking is disabled, since it would allow reading from or
     * writing to files not specified on the command line). */
2150
    if (!ISSET(RESTRICTED) && alt_speller == NULL) {
2151
2152
2153
2154
2155
2156
	char *spellenv = getenv("SPELL");
	if (spellenv != NULL)
	    alt_speller = mallocstrcpy(NULL, spellenv);
    }
#endif

2157
2158
2159
2160
2161
2162
#ifndef NANO_TINY
    /* If matchbrackets wasn't specified, set its default value. */
    if (matchbrackets == NULL)
	matchbrackets = mallocstrcpy(NULL, "(<[{)>]}");
#endif

2163
#if !defined(NANO_TINY) && defined(ENABLE_NANORC)
2164
    /* If whitespace wasn't specified, set its default value. */
2165
    if (whitespace == NULL) {
2166
	whitespace = mallocstrcpy(NULL, "  ");
2167
2168
2169
	whitespace_len[0] = 1;
	whitespace_len[1] = 1;
    }
2170
2171
#endif

2172
    /* If tabsize wasn't specified, set its default value. */
Chris Allegretta's avatar
Chris Allegretta committed
2173
    if (tabsize == -1)
2174
	tabsize = WIDTH_OF_TAB;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2175

2176
    /* Back up the old terminal settings so that they can be restored. */
2177
    tcgetattr(0, &oldterm);
2178

2179
2180
2181
    /* Initialize curses mode.  If this fails, get out. */
    if (initscr() == NULL)
	exit(1);
2182
2183

    /* Set up the terminal state. */
2184
    terminal_init();
2185

2186
2187
2188
    /* Turn the cursor on for sure. */
    curs_set(1);

2189
2190
2191
#ifdef DEBUG
    fprintf(stderr, "Main: set up windows\n");
#endif
2192

2193
2194
2195
    /* Initialize all the windows based on the current screen
     * dimensions. */
    window_init();
2196
2197

    /* Set up the signal handlers. */
2198
    signal_init();
Chris Allegretta's avatar
Chris Allegretta committed
2199

2200
#ifndef DISABLE_MOUSE
2201
    /* Initialize mouse support. */
2202
    mouse_init();
2203
#endif
2204

Chris Allegretta's avatar
Chris Allegretta committed
2205
#ifdef DEBUG
2206
    fprintf(stderr, "Main: open file\n");
Chris Allegretta's avatar
Chris Allegretta committed
2207
#endif
2208

2209
2210
2211
    /* 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. */
2212
    if (0 < optind && optind < argc - 1 && argv[optind][0] == '+') {
2213
	parse_line_column(&argv[optind][1], &startline, &startcol);
2214
2215
2216
	optind++;
    }

Chris Allegretta's avatar
Chris Allegretta committed
2217
#ifdef ENABLE_MULTIBUFFER
2218
2219
2220
2221
2222
2223
    old_multibuffer = ISSET(MULTIBUFFER);
    SET(MULTIBUFFER);

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

2227
	for (; i < argc; i++) {
2228
2229
2230
2231
	    /* 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 &&
2232
		icol == 1)
2233
		parse_line_column(&argv[i][1], &iline, &icol);
2234
	    else {
2235
		open_buffer(argv[i]);
2236

2237
		if (iline > 1 || icol > 1) {
2238
2239
		    do_gotolinecolumn(iline, icol, FALSE, FALSE, FALSE,
			FALSE);
2240
2241
		    iline = 1;
		    icol = 1;
2242
2243
2244
		}
	    }
	}
2245
2246
2247
2248
2249
2250
2251
    }
#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)
2252
	open_buffer(argv[optind]);
2253
2254
2255
2256
2257

    /* 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. */
2258
2259
    if (openfile == NULL) {
	open_buffer("");
2260
	UNSET(VIEW_MODE);
Chris Allegretta's avatar
Chris Allegretta committed
2261
    }
2262
2263
2264
2265

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

2268
2269
2270
2271
#ifdef DEBUG
    fprintf(stderr, "Main: top and bottom win\n");
#endif

2272
    if (startline > 1 || startcol > 1)
2273
2274
	do_gotolinecolumn(startline, startcol, FALSE, FALSE, FALSE,
		FALSE);
2275

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2276
2277
    display_main_list();

2278
    display_buffer();
Robert Siemborski's avatar
Robert Siemborski committed
2279

2280
    while (TRUE) {
2281
	bool meta_key, func_key, s_or_t, ran_func, finished;
2282
2283

	/* Make sure the cursor is in the edit window. */
2284
	reset_cursor();
2285
	wnoutrefresh(edit);
2286

2287
#ifndef NANO_TINY
2288
2289
2290
2291
2292
2293
2294
2295
	if (!jump_buf_main) {
	    /* If we haven't already, we're going to set jump_buf so
	     * that we return here after a SIGWINCH.  Indicate this. */
	    jump_buf_main = TRUE;

	    /* Return here after a SIGWINCH. */
	    sigsetjmp(jump_buf, 1);
	}
2296
2297
#endif

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2298
2299
2300
2301
	/* Just in case we were at the statusbar prompt, make sure the
	 * statusbar cursor position is reset. */
	do_prompt_abort();

2302
2303
2304
2305
	/* If constant cursor position display is on, and there are no
	 * keys waiting in the input buffer, display the current cursor
	 * position on the statusbar. */
	if (ISSET(CONST_UPDATE) && get_key_buffer_len() == 0)
2306
	    do_cursorpos(TRUE);
2307

2308
        currmenu = MMAIN;
2309

2310
	/* Read in and interpret characters. */
2311
2312
	do_input(&meta_key, &func_key, &s_or_t, &ran_func, &finished,
		TRUE);
Chris Allegretta's avatar
Chris Allegretta committed
2313
    }
2314

2315
    /* We should never get here. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
2316
    assert(FALSE);
Chris Allegretta's avatar
Chris Allegretta committed
2317
}