files.c 37.4 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
/* $Id$ */
Chris Allegretta's avatar
Chris Allegretta committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**************************************************************************
 *   files.c                                                              *
 *                                                                        *
 *   Copyright (C) 1999 Chris Allegretta                                  *
 *   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 *
 *   the Free Software Foundation; either version 1, or (at your option)  *
 *   any later version.                                                   *
 *                                                                        *
 *   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.                         *
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program; if not, write to the Free Software          *
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.            *
 *                                                                        *
 **************************************************************************/

22
23
#include "config.h"

Chris Allegretta's avatar
Chris Allegretta committed
24
25
26
27
28
29
30
31
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
Chris Allegretta's avatar
Chris Allegretta committed
32
33
#include <ctype.h>
#include <dirent.h>
34
#include <pwd.h>
Chris Allegretta's avatar
Chris Allegretta committed
35
36
37

#include "proto.h"
#include "nano.h"
Chris Allegretta's avatar
Chris Allegretta committed
38

Chris Allegretta's avatar
Chris Allegretta committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#ifndef NANO_SMALL
#include <libintl.h>
#define _(string) gettext(string)
#else
#define _(string) (string)
#endif

/* Load file into edit buffer - takes data from file struct */
void load_file(void)
{
    current = fileage;
    wmove(edit, current_y, current_x);
}

/* What happens when there is no file to open? aiee! */
void new_file(void)
{
    fileage = nmalloc(sizeof(filestruct));
57
    fileage->data = charalloc(1);
Chris Allegretta's avatar
Chris Allegretta committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    strcpy(fileage->data, "");
    fileage->prev = NULL;
    fileage->next = NULL;
    fileage->lineno = 1;
    filebot = fileage;
    edittop = fileage;
    editbot = fileage;
    current = fileage;
    totlines = 1;
    UNSET(VIEW_MODE);
}


int read_byte(int fd, char *filename, char *input)
{
    static char buf[BUFSIZ];
    static int index = 0;
    static int size = 0;

    if (index == size) {
	index = 0;
	size = read(fd, buf, BUFSIZ);
	if (size == -1) {
	    clear();
	    refresh();
	    resetty();
	    endwin();
	    perror(filename);
	}
	if (!size)
	    return 0;
    }
    *input = buf[index++];
    return 1;
}

filestruct *read_line(char *buf, filestruct * prev, int *line1ins)
{
    filestruct *fileptr;

    fileptr = nmalloc(sizeof(filestruct));
99
    fileptr->data = charalloc(strlen(buf) + 2);
Chris Allegretta's avatar
Chris Allegretta committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    strcpy(fileptr->data, buf);

    if (*line1ins) {
	/* Special case, insert with cursor on 1st line. */
	fileptr->prev = NULL;
	fileptr->next = fileage;
	fileptr->lineno = 1;
	*line1ins = 0;
	/* If we're inserting into the first line of the file, then
	   we want to make sure that our edit buffer stays on the
	   first line (and that fileage stays up to date!) */
	fileage = fileptr;
	edittop = fileptr;
    } else if (fileage == NULL) {
	fileage = fileptr;
	fileage->lineno = 1;
	fileage->next = fileage->prev = NULL;
	fileptr = filebot = fileage;
    } else if (prev) {
	fileptr->prev = prev;
	fileptr->next = NULL;
	fileptr->lineno = prev->lineno + 1;
	prev->next = fileptr;
    } else {
	die(_("read_line: not on first line and prev is NULL"));
    }

    return fileptr;
}


int read_file(int fd, char *filename)
{
133
    long size, num_lines = 0, linetemp = 0;
Chris Allegretta's avatar
Chris Allegretta committed
134
135
136
137
138
139
    char input[2];		/* buffer */
    char *buf;
    long i = 0, bufx = 128;
    filestruct *fileptr = current, *tmp = NULL;
    int line1ins = 0;

140
    buf = charalloc(bufx);
141
    buf[0] = '\0';
Chris Allegretta's avatar
Chris Allegretta committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

    if (fileptr != NULL && fileptr->prev != NULL) {
	fileptr = fileptr->prev;
	tmp = fileptr;
    } else if (fileptr != NULL && fileptr->prev == NULL) {
	tmp = fileage;
	current = fileage;
	line1ins = 1;
    }
    input[1] = 0;
    /* Read the entire file into file struct */
    while ((size = read_byte(fd, filename, input)) > 0) {
	linetemp = 0;
	if (input[0] == '\n') {
	    fileptr = read_line(buf, fileptr, &line1ins);
157
	    num_lines++;
Chris Allegretta's avatar
Chris Allegretta committed
158
159
160
161
162
163
	    buf[0] = 0;
	    i = 0;
	} else {
	    /* Now we allocate a bigger buffer 128 characters at a time.
	       If we allocate a lot of space for one line, we may indeed 
	       have to use a buffer this big later on, so we don't
164
	       decrease it at all.  We do free it at the end, though. */
Chris Allegretta's avatar
Chris Allegretta committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

	    if (i >= bufx - 1) {
		buf = nrealloc(buf, bufx + 128);
		bufx += 128;
	    }
	    buf[i] = input[0];
	    buf[i + 1] = 0;
	    i++;
	}
	totsize += size;
    }

    /* Did we not get a newline but still have stuff to do? */
    if (buf[0]) {
	fileptr = read_line(buf, fileptr, &line1ins);
180
	num_lines++;
Chris Allegretta's avatar
Chris Allegretta committed
181
182
183
	buf[0] = 0;
    }
    /* Did we even GET a file? */
184
    if (totsize == 0 || fileptr == NULL) {
Chris Allegretta's avatar
Chris Allegretta committed
185
	new_file();
186
	statusbar(_("Read %d lines"), num_lines);
Chris Allegretta's avatar
Chris Allegretta committed
187
188
	return 1;
    }
Robert Siemborski's avatar
Robert Siemborski committed
189

Chris Allegretta's avatar
Chris Allegretta committed
190
191
192
193
194
195
196
197
    if (current != NULL) {
	fileptr->next = current;
	current->prev = fileptr;
	renumber(current);
	current_x = 0;
	placewewant = 0;
    } else if (fileptr->next == NULL) {
	filebot = fileptr;
Robert Siemborski's avatar
Robert Siemborski committed
198
	new_magicline();
Chris Allegretta's avatar
Chris Allegretta committed
199
	totsize--;
Robert Siemborski's avatar
Robert Siemborski committed
200
201

	/* Update the edit buffer */
Chris Allegretta's avatar
Chris Allegretta committed
202
203
	load_file();
    }
204
205
    statusbar(_("Read %d lines"), num_lines);
    totlines += num_lines;
Chris Allegretta's avatar
Chris Allegretta committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

    free(buf);
    close(fd);

    return 1;
}

/* Open the file (and decide if it exists) */
int open_file(char *filename, int insert, int quiet)
{
    int fd;
    struct stat fileinfo;

    if (!strcmp(filename, "") || stat(filename, &fileinfo) == -1) {
	if (insert) {
	    if (!quiet)
		statusbar(_("\"%s\" not found"), filename);
	    return -1;
	} else {
	    /* We have a new file */
	    statusbar(_("New File"));
	    new_file();
	}
    } else if ((fd = open(filename, O_RDONLY)) == -1) {
	if (!quiet)
	    statusbar("%s: %s", strerror(errno), filename);
232
233
	if (!insert)
	    new_file();
Chris Allegretta's avatar
Chris Allegretta committed
234
235
	return -1;
    } else {			/* File is A-OK */
236
237
238
239
240
241
242
243
	if (S_ISDIR(fileinfo.st_mode) || S_ISCHR(fileinfo.st_mode) || 
		S_ISBLK(fileinfo.st_mode)) {
	    if (S_ISDIR(fileinfo.st_mode))
		statusbar(_("File \"%s\" is a directory"), filename);
	    else
		/* Don't open character or block files.  Sorry, /dev/sndstat! */
		statusbar(_("File \"%s\" is a device file"), filename);

Chris Allegretta's avatar
Chris Allegretta committed
244
245
	    if (!insert)
		new_file();
Chris Allegretta's avatar
Chris Allegretta committed
246
247
248
249
250
251
252
253
254
255
256
257
258
	    return -1;
	}
	if (!quiet)
	    statusbar(_("Reading File"));
	read_file(fd, filename);
    }

    return 1;
}

int do_insertfile(void)
{
    int i;
259
    char *realname = NULL;
Chris Allegretta's avatar
Chris Allegretta committed
260
261

    wrap_reset();
262
263

#ifndef DISABLE_MOUSE
264
265
    currshortcut = insertfile_list;
    currslen = INSERTFILE_LIST_LEN;
266
267
#endif

268
    i = statusq(1, insertfile_list, INSERTFILE_LIST_LEN, "",
Chris Allegretta's avatar
Chris Allegretta committed
269
270
271
272
273
274
275
		_("File to insert [from ./] "));
    if (i != -1) {

#ifdef DEBUG
	fprintf(stderr, "filename is %s", answer);
#endif

276
#ifndef DISABLE_TABCOMP
277
	realname = real_dir_from_tilde(answer);
278
#else
279
	realname = mallocstrcpy(realname, answer);
280
#endif
281

282
#ifndef DISABLE_BROWSER
Chris Allegretta's avatar
Chris Allegretta committed
283
	if (i == NANO_TOFILES_KEY) {
284
285
	    
	    char *tmp = do_browse_from(realname);
286
#ifndef DISABLE_MOUSE
287
288
	    currshortcut = insertfile_list;
	    currslen = INSERTFILE_LIST_LEN;
289
#endif
Chris Allegretta's avatar
Chris Allegretta committed
290

291
#ifdef DISABLE_TABCOMP
292
	    realname = NULL;
293
294
#endif
	    if 	(tmp != NULL)
295
		realname = mallocstrcpy(realname, tmp);
296
	    else
297
		return do_insertfile();
Chris Allegretta's avatar
Chris Allegretta committed
298
299
300
	}
#endif

301
302
	i = open_file(realname, 1, 0);
	free(realname);
Chris Allegretta's avatar
Chris Allegretta committed
303
304
305
306
307

	dump_buffer(fileage);
	set_modified();

	/* Here we want to rebuild the edit window */
Robert Siemborski's avatar
Robert Siemborski committed
308
	fix_editbot();
Chris Allegretta's avatar
Chris Allegretta committed
309

310
	/* If we've gone off the bottom, recenter; otherwise, just redraw */
Chris Allegretta's avatar
Chris Allegretta committed
311
	if (current->lineno > editbot->lineno)
312
	    edit_update(current, CENTER);
Chris Allegretta's avatar
Chris Allegretta committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
	else
	    edit_refresh();

	UNSET(KEEP_CUTBUFFER);
	display_main_list();
	return i;
    } else {
	statusbar(_("Cancelled"));
	UNSET(KEEP_CUTBUFFER);
	display_main_list();
	return 0;
    }
}

/*
 * Write a file out.  If tmp is nonzero, we set the umask to 0600,
329
 * we don't set the global variable filename to its name, and don't
Chris Allegretta's avatar
Chris Allegretta committed
330
331
 * print out how many lines we wrote on the statusbar.
 * 
332
 * tmp means we are writing a tmp file in a secure fashion.  We use
333
 * it when spell checking or dumping the file on an error.
334
335
336
 *
 * append means, not surprisingly, whether we are appending instead
 * of overwriting.
337
338
339
 *
 * nonamechange means don't change the current filename, it is ignored
 * if tmp == 1.
Chris Allegretta's avatar
Chris Allegretta committed
340
 */
341
int write_file(char *name, int tmp, int append, int nonamechange)
Chris Allegretta's avatar
Chris Allegretta committed
342
343
{
    long size, lineswritten = 0;
Chris Allegretta's avatar
Chris Allegretta committed
344
    static char *buf = NULL;
Chris Allegretta's avatar
Chris Allegretta committed
345
    filestruct *fileptr;
346
    int fd, mask = 0, realexists, anyexists;
347
    struct stat st, lst;
348
    static char *realname = NULL;
Chris Allegretta's avatar
Chris Allegretta committed
349
350
351
352
353

    if (!strcmp(name, "")) {
	statusbar(_("Cancelled"));
	return -1;
    }
Chris Allegretta's avatar
Chris Allegretta committed
354
    titlebar(NULL);
Chris Allegretta's avatar
Chris Allegretta committed
355
    fileptr = fileage;
356
357
358
359

    if (realname != NULL)
	free(realname);

Chris Allegretta's avatar
Chris Allegretta committed
360
361
362
    if (buf != NULL)
	free(buf);

363
#ifndef DISABLE_TABCOMP
364
365
366
367
    realname = real_dir_from_tilde(name);
#else
    realname = mallocstrcpy(realname, name);
#endif
Chris Allegretta's avatar
Chris Allegretta committed
368

369
    /* Save the state of file at the end of the symlink (if there is one) */
370
371
    realexists = stat(realname, &st);

372
373
    /* Stat the link itself for the check... */
    anyexists = lstat(realname, &lst);
374

375
376
    /* New case: if the file exists, just give up */
    if (tmp && anyexists != -1)
377
	return -1;
378
    /* NOTE: If you change this statement, you MUST CHANGE the if 
379
380
381
       statement below (that says:
		if (realexists == -1 || tmp || (!ISSET(FOLLOW_SYMLINKS) &&
		S_ISLNK(lst.st_mode))) {
382
383
       to reflect whether or not to link/unlink/rename the file */
    else if (ISSET(FOLLOW_SYMLINKS) || !S_ISLNK(lst.st_mode) || tmp) {
Chris Allegretta's avatar
Chris Allegretta committed
384
	/* Use O_EXCL if tmp == 1.  This is now copied from joe, because
385
	   wiggy says so *shrug*. */
386
387
388
	if (append)
	    fd = open(realname, O_WRONLY | O_APPEND, (S_IRUSR|S_IWUSR));
	else if (tmp)
389
390
391
	    fd = open(realname, O_WRONLY | O_CREAT | O_EXCL, (S_IRUSR|S_IWUSR));
	else
	    fd = open(realname, O_WRONLY | O_CREAT | O_TRUNC, (S_IRUSR|S_IWUSR));
392
393

	/* First, just give up if we couldn't even open the file */
394
	if (fd == -1) {
395
	    if (!tmp && ISSET(TEMP_OPT)) {
Chris Allegretta's avatar
Chris Allegretta committed
396
		UNSET(TEMP_OPT);
397
		return do_writeout(filename, 1, 0);
Chris Allegretta's avatar
Chris Allegretta committed
398
	    }
Chris Allegretta's avatar
Chris Allegretta committed
399
400
401
402
	    statusbar(_("Could not open file for writing: %s"),
		      strerror(errno));
	    return -1;
	}
403

Chris Allegretta's avatar
Chris Allegretta committed
404
405
406
    }
    /* Don't follow symlink.  Create new file. */
    else {
407
	buf = charalloc(strlen(realname) + 8);
Chris Allegretta's avatar
Chris Allegretta committed
408
	strncpy(buf, realname, strlen(realname)+1);
Chris Allegretta's avatar
Chris Allegretta committed
409
410
	strcat(buf, ".XXXXXX");
	if ((fd = mkstemp(buf)) == -1) {
Chris Allegretta's avatar
Chris Allegretta committed
411
412
	    if (ISSET(TEMP_OPT)) {
		UNSET(TEMP_OPT);
413
		return do_writeout(filename, 1, 0);
414
	    }
Chris Allegretta's avatar
Chris Allegretta committed
415
416
417
418
419
420
421
422
	    statusbar(_("Could not open file for writing: %s"),
		      strerror(errno));
	    return -1;
	}
    }

    dump_buffer(fileage);
    while (fileptr != NULL && fileptr->next != NULL) {
Robert Siemborski's avatar
Robert Siemborski committed
423
	/* Next line is so we discount the "magic line" */
424
425
	if (filebot == fileptr && fileptr->data[0] == '\0')
	    break;
Robert Siemborski's avatar
Robert Siemborski committed
426

Chris Allegretta's avatar
Chris Allegretta committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
	size = write(fd, fileptr->data, strlen(fileptr->data));
	if (size == -1) {
	    statusbar(_("Could not open file for writing: %s"),
		      strerror(errno));
	    return -1;
	} else {
#ifdef DEBUG
	    fprintf(stderr, _("Wrote >%s\n"), fileptr->data);
#endif
	}
	write(fd, "\n", 1);

	fileptr = fileptr->next;
	lineswritten++;
    }

    if (fileptr != NULL) {
	size = write(fd, fileptr->data, strlen(fileptr->data));
	if (size == -1) {
	    statusbar(_("Could not open file for writing: %s"),
		      strerror(errno));
	    return -1;
	} else if (size > 0) {
	    size = write(fd, "\n", 1);
	    if (size == -1) {
		statusbar(_("Could not open file for writing: %s"),
			  strerror(errno));
		return -1;
	    }
	}
    }


    if (close(fd) == -1) {
461
	statusbar(_("Could not close %s: %s"), realname, strerror(errno));
Chris Allegretta's avatar
Chris Allegretta committed
462
463
464
465
	unlink(buf);
	return -1;
    }

466
467
    if (realexists == -1 || tmp ||
	(!ISSET(FOLLOW_SYMLINKS) && S_ISLNK(lst.st_mode))) {
Chris Allegretta's avatar
Chris Allegretta committed
468

469
	/* Use default umask as file permissions if file is a new file. */
470
471
	mask = umask(0);
	umask(mask);
Chris Allegretta's avatar
Chris Allegretta committed
472

473
474
475
476
477
	if (tmp)		/* We don't want anyone reading our temporary file! */
	    mask = 0600;
	else
	    mask = 0666 & ~mask;
    } else
Chris Allegretta's avatar
Chris Allegretta committed
478
	/* Use permissions from file we are overwriting. */
479
480
481
482
483
	mask = st.st_mode;

    if (!tmp && (!ISSET(FOLLOW_SYMLINKS) && S_ISLNK(lst.st_mode))) {
	if (unlink(realname) == -1) {
	    if (errno != ENOENT) {
484
		statusbar(_("Could not open %s for writing: %s"),
485
			  realname, strerror(errno));
486
487
488
		unlink(buf);
		return -1;
	    }
Chris Allegretta's avatar
Chris Allegretta committed
489
	}
490
491
492
493
494
495
496
497
498
499
500
501
502
	if (link(buf, realname) != -1)
	    unlink(buf);
	else if (errno != EPERM) {
	    statusbar(_("Could not open %s for writing: %s"),
		      name, strerror(errno));
	    unlink(buf);
	    return -1;
	} else if (rename(buf, realname) == -1) {	/* Try a rename?? */
	    statusbar(_("Could not open %s for writing: %s"),
		      realname, strerror(errno));
	    unlink(buf);
	    return -1;
	}
Chris Allegretta's avatar
Chris Allegretta committed
503
    }
504
505
506
507
    if (chmod(realname, mask) == -1)
	statusbar(_("Could not set permissions %o on %s: %s"),
		  mask, realname, strerror(errno));

Chris Allegretta's avatar
Chris Allegretta committed
508
    if (!tmp) {
509
510
511
	if (nonamechange)
	    filename = mallocstrcpy(filename, realname);

Chris Allegretta's avatar
Chris Allegretta committed
512
	statusbar(_("Wrote %d lines"), lineswritten);
513
	UNSET(MODIFIED);
Chris Allegretta's avatar
Chris Allegretta committed
514
	titlebar(NULL);
Chris Allegretta's avatar
Chris Allegretta committed
515
516
517
518
    }
    return 1;
}

519
int do_writeout(char *path, int exiting, int append)
Chris Allegretta's avatar
Chris Allegretta committed
520
521
{
    int i = 0;
Chris Allegretta's avatar
Chris Allegretta committed
522

523
524
525
#ifdef NANO_EXTRA
    static int did_cred = 0;
#endif
Chris Allegretta's avatar
Chris Allegretta committed
526

527
#ifndef DISABLE_MOUSE
528
529
    currshortcut = writefile_list;
    currslen = WRITEFILE_LIST_LEN;
530
531
#endif

532
    answer = mallocstrcpy(answer, path);
Chris Allegretta's avatar
Chris Allegretta committed
533

534
    if ((exiting) && (ISSET(TEMP_OPT))) {
535
	if (filename[0]) {
536
	    i = write_file(answer, 0, 0, 0);
537
538
	    display_main_list();
	    return i;
539
	} else {
Chris Allegretta's avatar
Chris Allegretta committed
540
541
542
543
544
	    UNSET(TEMP_OPT);
	    do_exit();

	    /* They cancelled, abort quit */
	    return -1;
545
	}
Chris Allegretta's avatar
Chris Allegretta committed
546
547
548
    }

    while (1) {
549
	if (ISSET(MARK_ISSET) && !exiting)
550
	    i = statusq(1, writefile_list, WRITEFILE_LIST_LEN, "",
551
552
553
554
		    _("%s Selection to File"), append ? _("Append") : _("Write"));
	else
	    i = statusq(1, writefile_list, WRITEFILE_LIST_LEN, answer,
		    _("File Name to %s"), append ? _("Append") : _("Write"));
Chris Allegretta's avatar
Chris Allegretta committed
555

Chris Allegretta's avatar
Chris Allegretta committed
556
	if (i != -1) {
Chris Allegretta's avatar
Chris Allegretta committed
557

558
#ifndef DISABLE_BROWSER
Chris Allegretta's avatar
Chris Allegretta committed
559
	if (i == NANO_TOFILES_KEY) {
560
561

	    char *tmp = do_browse_from(answer);
562
563

#ifndef DISABLE_MOUSE
564
565
	    currshortcut = writefile_list;
	    currslen = WRITEFILE_LIST_LEN;
566
#endif
Chris Allegretta's avatar
Chris Allegretta committed
567

568
	    if (tmp != NULL) {
569
		answer = mallocstrcpy(answer, tmp);
570
571
572
	    } else
		return do_writeout(answer, exiting, append);
	} else
Chris Allegretta's avatar
Chris Allegretta committed
573
#endif
574
575
	if (i == NANO_APPEND_KEY)
	    return(do_writeout(answer, exiting, 1 - append));
Chris Allegretta's avatar
Chris Allegretta committed
576

Chris Allegretta's avatar
Chris Allegretta committed
577
578
579
#ifdef DEBUG
	    fprintf(stderr, _("filename is %s"), answer);
#endif
580
581

#ifdef NANO_EXTRA
582
583
	    if (exiting && !ISSET(TEMP_OPT) && !strcasecmp(answer, "zzy")
		&& !did_cred) {
584
585
		do_credits();
		did_cred = 1;
586
		return -1;
587
588
	    }
#endif
589
	    if (!append && strcmp(answer, filename)) {
Chris Allegretta's avatar
Chris Allegretta committed
590
591
592
593
594
595
		struct stat st;
		if (!stat(answer, &st)) {
		    i = do_yesno(0, 0, _("File exists, OVERWRITE ?"));

		    if (!i || (i == -1))
			continue;
Chris Allegretta's avatar
Chris Allegretta committed
596
597
		}
	    }
598
#ifndef NANO_SMALL
Chris Allegretta's avatar
Chris Allegretta committed
599

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
	/* Here's where we allow the selected text to be written to 
	   a separate file. */
	if (ISSET(MARK_ISSET) && !exiting) {
	    filestruct *fileagebak = fileage;	
	    filestruct *filebotbak = filebot;
	    filestruct *cutback = cutbuffer;
	    int oldmod = 0;

	    /* Okay, since write_file changes the filename, back it up */
	    if (ISSET(MODIFIED))
		oldmod = 1;

	    /* Now, non-destructively add the marked text to the
	       cutbuffer, and write the file out using the cutbuffer ;) */
	    if (current->lineno < mark_beginbuf->lineno)
		cut_marked_segment(current, current_x, mark_beginbuf,
				mark_beginx, 0);
	    else
		cut_marked_segment(mark_beginbuf, mark_beginx, current,
				current_x, 0);

	    fileage = cutbuffer;
	    for (filebot = cutbuffer; filebot->next != NULL; 
			filebot = filebot->next)
		;
625
	    i = write_file(answer, 0, append, 1);
626
627
628
629
630
631
632
633
634

	    /* Now restore everything */
	    fileage = fileagebak;
	    filebot = filebotbak;
	    cutbuffer = cutback;
	    if (oldmod)
		set_modified();
	} else
#endif
635
	    i = write_file(answer, 0, append, 0);
636
	
Chris Allegretta's avatar
Chris Allegretta committed
637
638
	    display_main_list();
	    return i;
Chris Allegretta's avatar
Chris Allegretta committed
639
	} else {
Chris Allegretta's avatar
Chris Allegretta committed
640
641
642
	    statusbar(_("Cancelled"));
	    display_main_list();
	    return 0;
Chris Allegretta's avatar
Chris Allegretta committed
643
	}
Chris Allegretta's avatar
Chris Allegretta committed
644
645
646
647
648
    }
}

int do_writeout_void(void)
{
649
    return do_writeout(filename, 0, 0);
Chris Allegretta's avatar
Chris Allegretta committed
650
}
Chris Allegretta's avatar
Chris Allegretta committed
651

652
#ifndef DISABLE_TABCOMP
653
654
655
656

/* Return a malloc()ed string containing the actual directory, used
 * to convert ~user and ~/ notation...
 */
657
char *real_dir_from_tilde(char *buf)
658
{
659
660
    char *dirtmp = NULL, *find_user = NULL;
    int i = 1;
661
    struct passwd *userdata;
662

663
664
665
    /* set a default value for dirtmp, in the case user home dir not found */
    dirtmp = mallocstrcpy(dirtmp, buf);

666
    if (buf[0] == '~') {
667
	if (buf[1] == 0 || buf[1] == '/') {
668
	    if (getenv("HOME") != NULL) {
669
670

		free(dirtmp);
671
		dirtmp = charalloc(strlen(buf) + 2 + strlen(getenv("HOME")));
672

673
		sprintf(dirtmp, "%s%s", getenv("HOME"), &buf[1]);
674

675
	    }
676
677
	}
	else {
678

679
	    /* Figure how how much of the str we need to compare */
680
681
682
683
684
	    for (i = 1; buf[i] != '/' && buf[i] != 0; i++)
		;

	    find_user = mallocstrcpy(find_user, &buf[1]);
	    find_user[i - 1] = 0;
685

686
	    for (userdata = getpwent(); userdata != NULL && 
687
		  strcmp(userdata->pw_name, find_user); 
688
		  userdata = getpwent());
689

690
691
692
	    free(find_user);

	    if (userdata != NULL) {  /* User found */
693

694
	        free(dirtmp);
695
		dirtmp = charalloc(strlen(buf) + 2 + strlen(userdata->pw_dir));
696
697
698
		sprintf(dirtmp, "%s%s", userdata->pw_dir, &buf[i]);

	    }
699

700
	    endpwent();
701
	}
702
    }
703
704

    return dirtmp;
705
706
707
}

/* Tack a slash onto the string we're completing if it's a directory */
708
int append_slash_if_dir(char *buf, int *lastWasTab, int *place)
709
710
711
{
    char *dirptr;
    struct stat fileinfo;
712
    int ret = 0;
713
714
715
716

    dirptr = real_dir_from_tilde(buf);

    if (stat(dirptr, &fileinfo) == -1)
717
	ret = 0;
718
719
720
721
722
    else if (S_ISDIR(fileinfo.st_mode)) {
	strncat(buf, "/", 1);
	*place += 1;
	/* now we start over again with # of tabs so far */
	*lastWasTab = 0;
723
	ret = 1;
724
725
726
    }

    if (dirptr != buf)
727
	free(dirptr);
728
729

    return ret;
730
}
Chris Allegretta's avatar
Chris Allegretta committed
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752

/*
 * These functions (username_tab_completion, cwd_tab_completion, and
 * input_tab were taken from busybox 0.46 (cmdedit.c).  Here is the notice
 * from that file:
 *
 * Termios command line History and Editting, originally
 * intended for NetBSD sh (ash)
 * Copyright (c) 1999
 *      Main code:            Adam Rogoyski <rogoyski@cs.utexas.edu>
 *      Etc:                  Dave Cinege <dcinege@psychosis.com>
 *  Majorly adjusted/re-written for busybox:
 *                            Erik Andersen <andersee@debian.org>
 *
 * You may use this code as you wish, so long as the original author(s)
 * are attributed in any redistributions of the source code.
 * This code is 'as is' with no warranty.
 * This code may safely be consumed by a BSD or GPL license.
 */

char **username_tab_completion(char *buf, int *num_matches)
{
753
    char **matches = (char **) NULL;
754
    char *matchline = NULL;
755
    struct passwd *userdata;
756

757
    *num_matches = 0;
758
    matches = nmalloc(BUFSIZ * sizeof(char *));
759

760
    strcat(buf, "*");
761

762
    while ((userdata = getpwent()) != NULL) {
763

764
	if (check_wildcard_match(userdata->pw_name, &buf[1]) == TRUE) {
765
766
767
768

	    /* Cool, found a match.  Add it to the list
	     * This makes a lot more sense to me (Chris) this way...
	     */
769

770
	    matchline = charalloc(strlen(userdata->pw_name) + 2);
771
772
773
	    sprintf(matchline, "~%s", userdata->pw_name);
	    matches[*num_matches] = matchline;
	    ++*num_matches;
774

775
776
777
	    /* If there's no more room, bail out */
	    if (*num_matches == BUFSIZ)
		break;
778
	}
779
780
    }
    endpwent();
781

Chris Allegretta's avatar
Chris Allegretta committed
782
783
784
785
786
787
788
789
    return (matches);
}

/* This was originally called exe_n_cwd_tab_completion, but we're not
   worried about executables, only filenames :> */

char **cwd_tab_completion(char *buf, int *num_matches)
{
790
    char *dirName, *dirtmp = NULL, *tmp = NULL, *tmp2 = NULL;
Chris Allegretta's avatar
Chris Allegretta committed
791
792
793
794
    char **matches = (char **) NULL;
    DIR *dir;
    struct dirent *next;

795
    matches = nmalloc(BUFSIZ * sizeof(char *));
Chris Allegretta's avatar
Chris Allegretta committed
796
797
798
799

    /* Stick a wildcard onto the buf, for later use */
    strcat(buf, "*");

800
    /* Okie, if there's a / in the buffer, strip out the directory part */
Chris Allegretta's avatar
Chris Allegretta committed
801
    if (strcmp(buf, "") && strstr(buf, "/")) {
802
	dirName = charalloc(strlen(buf) + 1);
Chris Allegretta's avatar
Chris Allegretta committed
803
804
	tmp = buf + strlen(buf);
	while (*tmp != '/' && tmp != buf)
805
	    tmp--;
806

Chris Allegretta's avatar
Chris Allegretta committed
807
808
	tmp++;

809
810
811
	strncpy(dirName, buf, tmp - buf + 1);
	dirName[tmp - buf] = 0;

Chris Allegretta's avatar
Chris Allegretta committed
812
    } else {
813
814
815
816

#ifdef PATH_MAX
	if ((dirName = getcwd(NULL, PATH_MAX+1)) == NULL)
#else
817
	/* The better, but apparently segfault-causing way */
Chris Allegretta's avatar
Chris Allegretta committed
818
	if ((dirName = getcwd(NULL, 0)) == NULL)
819
#endif /* PATH_MAX */
Chris Allegretta's avatar
Chris Allegretta committed
820
821
822
823
824
825
826
827
828
829
	    return matches;
	else
	    tmp = buf;
    }

#ifdef DEBUG
    fprintf(stderr, "\nDir = %s\n", dirName);
    fprintf(stderr, "\nbuf = %s\n", buf);
    fprintf(stderr, "\ntmp = %s\n", tmp);
#endif
830

831
832
833
834
835
836
837
838
839
840
841
    dirtmp = real_dir_from_tilde(dirName);
    free(dirName);
    dirName = dirtmp;

#ifdef DEBUG
    fprintf(stderr, "\nDir = %s\n", dirName);
    fprintf(stderr, "\nbuf = %s\n", buf);
    fprintf(stderr, "\ntmp = %s\n", tmp);
#endif


Chris Allegretta's avatar
Chris Allegretta committed
842
843
844
845
846
847
848
849
850
851
    dir = opendir(dirName);
    if (!dir) {
	/* Don't print an error, just shut up and return */
	*num_matches = 0;
	beep();
	return (matches);
    }
    while ((next = readdir(dir)) != NULL) {

#ifdef DEBUG
852
	fprintf(stderr, "Comparing \'%s\'\n", next->d_name);
Chris Allegretta's avatar
Chris Allegretta committed
853
854
855
#endif
	/* See if this matches */
	if (check_wildcard_match(next->d_name, tmp) == TRUE) {
856
857
858
859
860

	    /* Cool, found a match.  Add it to the list
	     * This makes a lot more sense to me (Chris) this way...
	     */
	    tmp2 = NULL;
861
	    tmp2 = charalloc(strlen(next->d_name) + 1);
862
863
	    strcpy(tmp2, next->d_name);
	    matches[*num_matches] = tmp2;
Chris Allegretta's avatar
Chris Allegretta committed
864
	    ++*num_matches;
865
866
867
868

	    /* If there's no more room, bail out */
	    if (*num_matches == BUFSIZ)
		break;
Chris Allegretta's avatar
Chris Allegretta committed
869
870
871
872
873
874
	}
    }

    return (matches);
}

875
/* This function now has an arg which refers to how much the 
Chris Allegretta's avatar
Chris Allegretta committed
876
877
 * statusbar (place) should be advanced, i.e. the new cursor pos.
 */
878
char *input_tab(char *buf, int place, int *lastWasTab, int *newplace)
Chris Allegretta's avatar
Chris Allegretta committed
879
880
{
    /* Do TAB completion */
881
    static int num_matches = 0, match_matches = 0;
Chris Allegretta's avatar
Chris Allegretta committed
882
    static char **matches = (char **) NULL;
883
    int pos = place, i = 0, col = 0, editline = 0;
884
    int longestname = 0, is_dir = 0;
885
    char *foo;
Chris Allegretta's avatar
Chris Allegretta committed
886

887
    if (*lastWasTab == FALSE) {
888
	char *tmp, *copyto, *matchBuf;
Chris Allegretta's avatar
Chris Allegretta committed
889

890
891
	*lastWasTab = 1;

Chris Allegretta's avatar
Chris Allegretta committed
892
893
	/* Make a local copy of the string -- up to the position of the
	   cursor */
894
	matchBuf = (char *) nmalloc((strlen(buf) + 2) * sizeof(char));
895
	memset(matchBuf, '\0', (strlen(buf) + 2));
896

Chris Allegretta's avatar
Chris Allegretta committed
897
898
899
900
	strncpy(matchBuf, buf, place);
	tmp = matchBuf;

	/* skip any leading white space */
901
	while (*tmp && isspace((int) *tmp))
Chris Allegretta's avatar
Chris Allegretta committed
902
903
904
905
	    ++tmp;

	/* Free up any memory already allocated */
	if (matches != NULL) {
906
907
	    for (i = i; i < num_matches; i++)
		free(matches[i]);
Chris Allegretta's avatar
Chris Allegretta committed
908
909
	    free(matches);
	    matches = (char **) NULL;
910
	    num_matches = 0;
Chris Allegretta's avatar
Chris Allegretta committed
911
912
913
914
915
	}

	/* If the word starts with `~' and there is no slash in the word, 
	 * then try completing this word as a username. */

916
	/* FIXME -- this check is broken! */
917
918
	if (*tmp == '~' && !strchr(tmp, '/'))
	    matches = username_tab_completion(tmp, &num_matches);
Chris Allegretta's avatar
Chris Allegretta committed
919
920
921
922
923
924
925
926
927

	/* Try to match everything in the current working directory that
	 * matches.  */
	if (!matches)
	    matches = cwd_tab_completion(tmp, &num_matches);

	/* Don't leak memory */
	free(matchBuf);

928
929
930
#ifdef DEBUG
	fprintf(stderr, "%d matches found...\n", num_matches);
#endif
Chris Allegretta's avatar
Chris Allegretta committed
931
	/* Did we find exactly one match? */
932
	switch (num_matches) {
933
	case 0:
934
	    blank_edit();
935
	    wrefresh(edit);
936
937
	    break;
	case 1:
938
939
940
941

	    buf = nrealloc(buf, strlen(buf) + strlen(matches[0]) + 1);

	    if (strcmp(buf, "") && strstr(buf, "/")) {
942
943
		for (tmp = buf + strlen(buf); *tmp != '/' && tmp != buf;
		     tmp--);
944
		tmp++;
945
	    } else
946
947
		tmp = buf;

948
949
950
951
952
	    if (!strcmp(tmp, matches[0]))
		is_dir = append_slash_if_dir(buf, lastWasTab, newplace);

	    if (is_dir)
		break;
953
954

	    copyto = tmp;
955
956
	    for (pos = 0; *tmp == matches[0][pos] &&
		 pos <= strlen(matches[0]); pos++)
957
958
		tmp++;

959
	    /* write out the matched name */
960
	    strncpy(copyto, matches[0], strlen(matches[0]) + 1);
961
962
	    *newplace += strlen(matches[0]) - pos;

963
964
965
	    /* Is it a directory? */
	    append_slash_if_dir(buf, lastWasTab, newplace);

966
967
	    break;
	default:
968
	    /* Check to see if all matches share a beginning, and, if so,
969
	       tack it onto buf and then beep */
970

971
	    if (strcmp(buf, "") && strstr(buf, "/")) {
972
973
		for (tmp = buf + strlen(buf); *tmp != '/' && tmp != buf;
		     tmp--);
974
		tmp++;
975
	    } else
976
977
978
		tmp = buf;

	    for (pos = 0; *tmp == matches[0][pos] && *tmp != 0 &&
979
		 pos <= strlen(matches[0]); pos++)
980
981
		tmp++;

982
983
984
985
986
987
988
989
990
	    while (1) {
		match_matches = 0;

		for (i = 0; i < num_matches; i++) {
		    if (matches[i][pos] == 0)
			break;
		    else if (matches[i][pos] == matches[0][pos])
			match_matches++;
		}
991
992
		if (match_matches == num_matches &&
		    (i == num_matches || matches[i] != 0)) {
993
		    /* All the matches have the same character at pos+1,
994
		       so paste it into buf... */
995
		    buf = nrealloc(buf, strlen(buf) + 2);
996
		    strncat(buf, matches[0] + pos, 1);
997
		    *newplace += 1;
998
		    pos++;
999
		} else {
1000
1001
1002
1003
		    beep();
		    break;
		}
	    }
1004
	    break;
1005
	}
Chris Allegretta's avatar
Chris Allegretta committed
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
    } else {
	/* Ok -- the last char was a TAB.  Since they
	 * just hit TAB again, print a list of all the
	 * available choices... */
	if (matches && num_matches > 0) {

	    /* Blank the edit window, and print the matches out there */
	    blank_edit();
	    wmove(edit, 0, 0);

1016
	    editline = 0;
1017

1018
1019
1020
1021
1022
1023
1024
1025
	    /* Figure out the length of the longest filename */
	    for (i = 0; i < num_matches; i++)
		if (strlen(matches[i]) > longestname)
		    longestname = strlen(matches[i]);

	    if (longestname > COLS - 1)
		longestname = COLS - 1;

1026
	    foo = charalloc(longestname + 5);
1027

Chris Allegretta's avatar
Chris Allegretta committed
1028
1029
	    /* Print the list of matches */
	    for (i = 0, col = 0; i < num_matches; i++) {
1030

1031
		/* make each filename shown be the same length as the longest
1032
		   filename, with two spaces at the end */
1033
1034
1035
1036
1037
1038
		snprintf(foo, longestname + 1, matches[i]);
		while (strlen(foo) < longestname)
		    strcat(foo, " ");

		strcat(foo, "  ");

1039
1040
		/* Disable el cursor */
		curs_set(0);
1041
1042
1043
1044
1045
1046
		/* now, put the match on the screen */
		waddnstr(edit, foo, strlen(foo));
		col += strlen(foo);

		/* And if the next match isn't going to fit on the
		   line, move to the next one */
1047
		if (col > (COLS - longestname) && matches[i + 1] != NULL) {
1048
1049
		    editline++;
		    wmove(edit, editline, 0);
1050
1051
1052
1053
		    if (editline == editwinrows - 1) {
			waddstr(edit, _("(more)"));
			break;
		    }
Chris Allegretta's avatar
Chris Allegretta committed
1054
1055
1056
		    col = 0;
		}
	    }
1057
	    free(foo);
Chris Allegretta's avatar
Chris Allegretta committed
1058
	    wrefresh(edit);
1059
1060
	} else
	    beep();
Chris Allegretta's avatar
Chris Allegretta committed
1061
1062
1063
1064

    }

    edit_refresh();
1065
1066
    curs_set(1);
    return buf;
Chris Allegretta's avatar
Chris Allegretta committed
1067
}
1068
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1069

1070
#ifndef DISABLE_BROWSER
Chris Allegretta's avatar
Chris Allegretta committed
1071
1072
1073
1074
1075

/* Return the stat of the file pointed to by path */
struct stat filestat(const char *path) {
    struct stat st;

1076
    stat(path, &st);
Chris Allegretta's avatar
Chris Allegretta committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
    return st;
}

/* Our sort routine for file listings - sort directories before
 * files, and then alphabetically
 */ 
int diralphasort(const void *va, const void *vb) {
    struct stat file1info, file2info;
    char *a = *(char **)va, *b = *(char **)vb;
1086
    int aisdir, bisdir;
Chris Allegretta's avatar
Chris Allegretta committed
1087

1088
1089
    aisdir = (stat(a, &file1info) != -1) && S_ISDIR(file1info.st_mode);
    bisdir = (stat(b, &file2info) != -1) && S_ISDIR(file2info.st_mode);
Chris Allegretta's avatar
Chris Allegretta committed
1090

1091
1092
1093
1094
1095
1096
1097
1098
    if (aisdir && !bisdir) return -1;
    if (!aisdir && bisdir) return 1;

#ifdef HAVE_STRCASECMP
    return(strcasecmp(a,b));
#else
    return(strcmp(a,b));
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1099
1100
1101

}

Chris Allegretta's avatar
Chris Allegretta committed
1102
1103

/* Initialize the browser code, including the list of files in *path */
Chris Allegretta's avatar
Chris Allegretta committed
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
char **browser_init(char *path, int *longest, int *numents)
{
    DIR *dir;
    struct dirent *next;
    char **filelist = (char **) NULL;
    int i = 0;

    dir = opendir(path);
    if (!dir) 
	return NULL;

    *numents = 0;
    while ((next = readdir(dir)) != NULL) {
	if (!strcmp(next->d_name, "."))
	   continue;
	(*numents)++;
	if (strlen(next->d_name) > *longest)
	    *longest = strlen(next->d_name);
    }
    rewinddir(dir);
    *longest += 10;

    filelist = nmalloc(*numents * sizeof (char *));

    while ((next = readdir(dir)) != NULL) {
	if (!strcmp(next->d_name, "."))
	   continue;
1131
	filelist[i] = charalloc(strlen(next->d_name) + strlen(path) + 2);
Chris Allegretta's avatar
Chris Allegretta committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147

	if (!strcmp(path, "/"))
	    snprintf(filelist[i], strlen(next->d_name) + strlen(path) + 1, 
			"%s%s", path, next->d_name);
	else
	    snprintf(filelist[i], strlen(next->d_name) + strlen(path) + 2, 
			"%s/%s", path, next->d_name);
	i++;
    }

    if (*longest > COLS - 1)
	*longest = COLS - 1;

    return filelist;
}

1148
/* Free our malloc()ed memory */
Chris Allegretta's avatar
Chris Allegretta committed
1149
1150
1151
1152
1153
1154
1155
1156
1157
void free_charptrarray(char **array, int len)
{
    int i;

    for (i = 0; i < len - 1; i++)
	free(array[i]);
    free(array);
}

1158
/* only print the last part of a path; isn't there a shell 
Chris Allegretta's avatar
Chris Allegretta committed
1159
   command for this? */
Chris Allegretta's avatar
Chris Allegretta committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
char *tail(char *foo)
{
    char *tmp = NULL;

    tmp = foo + strlen(foo);
    while (*tmp != '/' && tmp != foo)
	tmp--;

    tmp++;

    return tmp;
}

Chris Allegretta's avatar
Chris Allegretta committed
1173
/* Strip one dir from the end of a string */
Chris Allegretta's avatar
Chris Allegretta committed
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
void striponedir(char *foo)
{
    char *tmp = NULL;

    /* Don't strip the root dir */
    if (!strcmp(foo, "/"))
	return;

    tmp = foo + strlen(foo);
    if (*tmp == '/')
	tmp--;

    while (*tmp != '/' && tmp != foo)
	tmp--;

    if (tmp != foo)
	*tmp = 0;
    else
	*(tmp+1) = 0;

    return;
}

Chris Allegretta's avatar
Chris Allegretta committed
1197
/* Our browser function.  inpath is the path to start browsing from */
Chris Allegretta's avatar
Chris Allegretta committed
1198
1199
1200
1201
1202
1203
1204
char *do_browser(char *inpath)
{
    struct stat st;
    char *foo, *retval = NULL;
    static char *path = NULL;
    int numents = 0, i = 0, j = 0, kbinput = 0, longest = 0, abort = 0;
    int col = 0, selected = 0, editline = 0, width = 0, filecols = 0;
1205
    int lineno = 0, kb;
Chris Allegretta's avatar
Chris Allegretta committed
1206
    char **filelist = (char **) NULL;
1207
1208
1209
1210
1211
#ifndef DISABLE_MOUSE
#ifdef NCURSES_MOUSE_VERSION
    MEVENT mevent;
#endif
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1212

Chris Allegretta's avatar
Chris Allegretta committed
1213
1214
1215
    /* If path isn't the same as inpath, we are being passed a new
	dir as an arg.  We free it here so it will be copied from 
	inpath below */
Chris Allegretta's avatar
Chris Allegretta committed
1216
1217
1218
1219
1220
    if (path != NULL && strcmp(path, inpath)) {
	free(path);
	path = NULL;
    }

Chris Allegretta's avatar
Chris Allegretta committed
1221
    /* if path doesn't exist, make it so */
Chris Allegretta's avatar
Chris Allegretta committed
1222
1223
1224
1225
    if (path == NULL)
	path = mallocstrcpy(path, inpath);

    filelist = browser_init(path, &longest, &numents);
1226
    foo = charalloc(longest + 8);
Chris Allegretta's avatar
Chris Allegretta committed
1227

1228
    /* Sort the list by directory first, then alphabetically */
Chris Allegretta's avatar
Chris Allegretta committed
1229
1230
    qsort(filelist, numents, sizeof(char *), diralphasort);

1231
    kb = keypad_on(edit, 1);
Chris Allegretta's avatar
Chris Allegretta committed
1232
1233
1234
1235
1236
1237
1238
    titlebar(path);
    bottombars(browser_list, BROWSER_LIST_LEN);
    curs_set(0);
    wmove(edit, 0, 0);
    i = 0;
    width = 0;
    filecols = 0;
Chris Allegretta's avatar
Chris Allegretta committed
1239
1240

    /* Loop invariant: Microsoft sucks. */
Chris Allegretta's avatar
Chris Allegretta committed
1241
    do {
Rocco Corsi's avatar
   
Rocco Corsi committed
1242
1243
1244
1245
	DIR *test_dir;

	blank_statusbar_refresh();

1246
#ifndef DISABLE_MOUSE
1247
1248
	currshortcut = browser_list;
	currslen = BROWSER_LIST_LEN;
1249
1250
#endif

Chris Allegretta's avatar
Chris Allegretta committed
1251
1252
 	editline = 0;
	col = 0;
1253
	    
1254
	/* Compute line number we're on now, so we don't divide by zero later */
1255
1256
1257
1258
	if (width == 0)
	    lineno = selected;
	else
	    lineno = selected / width;
Chris Allegretta's avatar
Chris Allegretta committed
1259
1260

	switch (kbinput) {
1261

1262
#ifndef DISABLE_MOUSE
1263
1264
#ifdef NCURSES_MOUSE_VERSION
        case KEY_MOUSE:
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
	    if (getmouse(&mevent) == ERR)
	        return retval;
 
	    /* If they clicked in the edit window, they probably clicked
		on a file */
 	    if (wenclose(edit, mevent.y, mevent.x)) { 
		int selectedbackup = selected;

		mevent.y -= 2;

		/* If we're on line 0, don't toy with finding out what
			page we're on */
		if (lineno / editwinrows == 0)
		    selected = mevent.y * width + mevent.x / longest;
		else
		    selected = (lineno / editwinrows) * editwinrows * width 
			+ mevent.y * width + mevent.x / longest;

		/* If we're off the screen, reset to the last item.
		   If we clicked where we did last time, select this name! */
1285
		if (selected > numents - 1)
1286
1287
1288
1289
1290
1291
1292
1293
		    selected = numents - 1;
		else if (selectedbackup == selected) {
		    ungetch('s');	/* Unget the 'select' key */
		    break;
		}
	    } else	/* Must be clicking a shortcut */
		do_mouse();

1294
1295
1296
            break;
#endif
#endif
Chris Allegretta's avatar
Chris Allegretta committed
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
	case KEY_UP:
	case 'u':
	    if (selected - width >= 0)
		selected -= width;
	    break;
	case KEY_LEFT:
	case 'l':
	    if (selected > 0)
		selected--;
	    break;
	case KEY_DOWN:
	case 'd':
	    if (selected + width <= numents - 1)
		selected += width;
	    break;
	case KEY_RIGHT:
	case 'r':
	    if (selected < numents - 1)
		selected++;
	    break;
	case NANO_PREVPAGE_KEY:
1318
	case NANO_PREVPAGE_FKEY:
Chris Allegretta's avatar
Chris Allegretta committed
1319
	case KEY_PPAGE:
1320
	case '-':
1321
1322

	    if (lineno % editwinrows == 0) {
1323
1324
		if (selected - (editwinrows * width) >= 0)
		    selected -= editwinrows * width; 
Chris Allegretta's avatar
Chris Allegretta committed
1325
1326
1327
1328
		else
		    selected = 0;
	    }
	    else if (selected - (editwinrows + 
1329
1330
1331
		lineno % editwinrows) * width  >= 0)

		selected -= (editwinrows + lineno % editwinrows) * width; 
Chris Allegretta's avatar
Chris Allegretta committed
1332
1333
1334
1335
	    else
		selected = 0;
	    break;
	case NANO_NEXTPAGE_KEY:
1336
	case NANO_NEXTPAGE_FKEY:
Chris Allegretta's avatar
Chris Allegretta committed
1337
	case KEY_NPAGE:	
1338
	case ' ':
1339
	    if (lineno % editwinrows == 0) {
1340
1341
		if (selected + (editwinrows * width) <= numents - 1)
		    selected += editwinrows * width; 
Chris Allegretta's avatar
Chris Allegretta committed
1342
1343
1344
1345
		else
		    selected = numents - 1;
	    }
	    else if (selected + (editwinrows - 
1346
1347
			lineno %  editwinrows) * width <= numents - 1)
 		selected += (editwinrows - lineno % editwinrows) * width; 
Chris Allegretta's avatar
Chris Allegretta committed
1348
1349
1350
1351
1352
 	    else
		selected = numents - 1;
	    break;
	case KEY_ENTER:
	case NANO_CONTROL_M:
1353
1354
	case 's': /* More Pico compatibility */
	case 'S':
Chris Allegretta's avatar
Chris Allegretta committed
1355
1356

	    /* You can't cd up from / */
Rocco Corsi's avatar
   
Rocco Corsi committed
1357
	    if (!strcmp(filelist[selected], "/..") && !strcmp(path, "/")) {
Chris Allegretta's avatar
Chris Allegretta committed
1358
		statusbar(_("Can't move up a directory"));
Rocco Corsi's avatar
   
Rocco Corsi committed
1359
1360
1361
1362
		break;
	    }

	    path = mallocstrcpy(path, filelist[selected]);
Chris Allegretta's avatar
Chris Allegretta committed
1363
1364
1365

	    st = filestat(path);
	    if (S_ISDIR(st.st_mode)) {
Rocco Corsi's avatar
   
Rocco Corsi committed
1366
		if ((test_dir = opendir(path)) == NULL) {
Chris Allegretta's avatar
Chris Allegretta committed
1367
		    /* We can't open this dir for some reason.  Complain */
Chris Allegretta's avatar
Chris Allegretta committed
1368
		    statusbar(_("Can't open \"%s\": %s"), path, strerror(errno));
Rocco Corsi's avatar
   
Rocco Corsi committed
1369
		    striponedir(path);
Chris Allegretta's avatar
Chris Allegretta committed
1370
1371
		    align(&path);
		    break;
Chris Allegretta's avatar
Chris Allegretta committed
1372
		} 
Rocco Corsi's avatar
   
Rocco Corsi committed
1373
		closedir(test_dir);
Chris Allegretta's avatar
Chris Allegretta committed
1374
1375

		if (!strcmp("..", tail(path))) {
Chris Allegretta's avatar
Chris Allegretta committed
1376
1377
		    /* They want to go up a level, so strip off .. and the
			current dir */
Chris Allegretta's avatar
Chris Allegretta committed
1378
1379
1380
1381
		    striponedir(path);
		    striponedir(path);
		    align(&path);
		}
Chris Allegretta's avatar
Chris Allegretta committed
1382
1383

		/* Start over again with the new path value */
Chris Allegretta's avatar
Chris Allegretta committed
1384
1385
1386
1387
1388
1389
		return do_browser(path);
	    } else {
		retval = path;
		abort = 1;
	    }
	    break;
Rocco Corsi's avatar
   
Rocco Corsi committed
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
	/* Goto a specific directory */
	case 'g':	/* Pico compatibility */
	case 'G':
	case NANO_GOTO_KEY:

	    curs_set(1);
	    j = statusq(0, gotodir_list, GOTODIR_LIST_LEN, "", _("Goto Directory"));
	    bottombars(browser_list, BROWSER_LIST_LEN);
	    curs_set(0);

	    if (j < 0) {
		statusbar(_("Goto Cancelled"));
		break;
	    }

	    if (answer[0] != '/') {
		char *saveanswer = NULL;

		saveanswer = mallocstrcpy(saveanswer, answer);
		answer = realloc(answer, strlen(path) + strlen(saveanswer) + 2);
		sprintf(answer, "%s/%s", path, saveanswer);
		free(saveanswer);
	    }

	    if ((test_dir = opendir(answer)) == NULL) {
		/* We can't open this dir for some reason.  Complain */
		statusbar(_("Can't open \"%s\": %s"), answer, strerror(errno));
		break;
	    } 
	    closedir(test_dir);

	    /* Start over again with the new path value */
	    path = mallocstrcpy(path, answer);
	    return do_browser(path);

Chris Allegretta's avatar
Chris Allegretta committed
1425
	/* Stuff we want to abort the browser */
1426
	case NANO_CONTROL_C:
Chris Allegretta's avatar
Chris Allegretta committed
1427
1428
1429
1430
	case 'q':
	case 'Q':
	case 'e':	/* Pico compatibility, yeech */
	case 'E':
1431
	case NANO_EXIT_FKEY:
Chris Allegretta's avatar
Chris Allegretta committed
1432
1433
1434
1435
1436
1437
		abort = 1;
		break;
	}
	if (abort)
	    break;

Rocco Corsi's avatar
   
Rocco Corsi committed
1438
1439
	blank_edit();

Chris Allegretta's avatar
Chris Allegretta committed
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
	if (width)
	    i = width * editwinrows * ((selected / width) / editwinrows);
	else
	    i = 0;

	wmove(edit, 0, 0);
	for (j = i; j < numents && editline <= editwinrows - 1; j++) {
	    filecols++;

	    strncpy(foo, tail(filelist[j]), strlen(tail(filelist[j])) + 1);
	    while (strlen(foo) < longest)
		strcat(foo, " ");
	    col += strlen(foo);

	    /* Put file info in the string also */
1455
1456
	    /* We use lstat here to detect links; then, if we find a
		symlink, we examine it via stat() to see if it is a
1457
1458
		directory or just a file symlink */
	    lstat(filelist[j], &st);
Chris Allegretta's avatar
Chris Allegretta committed
1459
1460
1461
	    if (S_ISDIR(st.st_mode))
		strcpy(foo + longest - 5, "(dir)");
	    else {
1462
1463
1464
1465
1466
1467
1468
1469
		if (S_ISLNK(st.st_mode)) {
		     /* Aha!  It's a symlink!  Now, is it a dir?  If so,
			mark it as such */
		    st = filestat(filelist[j]);
		    if (S_ISDIR(st.st_mode))
			strcpy(foo + longest - 5, "(dir)");
		    else
			strcpy(foo + longest - 2, "--");
1470
1471
		} else if (st.st_size < (1 << 10)) /* less than 1 K */
		    sprintf(foo + longest - 7, "%4d  B", 
1472
			(int) st.st_size);
1473
1474
1475
1476
1477
1478
		else if (st.st_size >= (1 << 30)) /* at least 1 gig */
		    sprintf(foo + longest - 7, "%4d GB", 
			(int) st.st_size >> 30);
		else if (st.st_size >= (1 << 20)) /* at least 1 meg */
		    sprintf(foo + longest - 7, "%4d MB", 
			(int) st.st_size >>     20);
Chris Allegretta's avatar
Chris Allegretta committed
1479
		else /* Its more than 1 k and less than a meg */
1480
1481
		    sprintf(foo + longest - 7, "%4d KB", 
			(int) st.st_size >> 10);
Chris Allegretta's avatar
Chris Allegretta committed
1482
1483
	    }

Chris Allegretta's avatar
Chris Allegretta committed
1484
	    /* Hilight the currently selected file/dir */
1485
1486
1487
1488
	    if (j == selected) {
#ifdef ENABLE_COLOR
		color_on(edit, COLOR_STATUSBAR);
#else
Chris Allegretta's avatar
Chris Allegretta committed
1489
		wattron(edit, A_REVERSE);
1490
1491
1492

#endif
	    }
Chris Allegretta's avatar
Chris Allegretta committed
1493
	    waddnstr(edit, foo, strlen(foo));
1494
1495
1496
1497
	    if (j == selected) {
#ifdef ENABLE_COLOR
		color_off(edit, COLOR_STATUSBAR);
#else
Chris Allegretta's avatar
Chris Allegretta committed
1498
		wattroff(edit, A_REVERSE);
1499
1500
#endif
	    }
Chris Allegretta's avatar
Chris Allegretta committed
1501

Chris Allegretta's avatar
Chris Allegretta committed
1502
	    /* And add some space between the cols */
Chris Allegretta's avatar
Chris Allegretta committed
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
	    waddstr(edit, "  ");
	    col += 2;

	    /* And if the next entry isn't going to fit on the
		line, move to the next one */
	    if (col > (COLS - longest)) {
		editline++;
		wmove(edit, editline, 0);
		col = 0;
		if (width == 0)
		    width = filecols;
	    }
	}
 	wrefresh(edit);
    } while ((kbinput = wgetch(edit)) != NANO_EXIT_KEY);
    curs_set(1);
    blank_edit();
    titlebar(NULL); 
    edit_refresh();
1522
    kb = keypad_on(edit, kb);
Chris Allegretta's avatar
Chris Allegretta committed
1523

Chris Allegretta's avatar
Chris Allegretta committed
1524
    /* cleanup */
Chris Allegretta's avatar
Chris Allegretta committed
1525
1526
1527
1528
    free_charptrarray(filelist, numents);
    free(foo);
    return retval;
}
1529

1530
/* Browser front end, checks to see if inpath has a dir in it and, if so,
1531
1532
1533
1534
1535
1536
1537
1538
 starts do_browser from there, else from the current dir */
char *do_browse_from(char *inpath)
{
    struct stat st;
    char *tmp = NULL;

    tmp = mallocstrcpy(tmp, inpath);

1539

1540
    /* If there's no / in the string, we may as well start from . */
1541
1542
1543
1544
    if (tmp == NULL || *tmp == '\0' || !strstr(tmp, "/")) {
#ifdef PATH_MAX
	char *from = getcwd(NULL, PATH_MAX+1);
#else
1545
	char *from = getcwd(NULL, 0);
1546
1547
1548
#endif /* PATH_MAX */
	return do_browser(from ? from : "./");
    }
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564

    /* If the string is a directory, pass do_browser that */
    st = filestat(tmp);
    if (S_ISDIR(st.st_mode))
	return do_browser(tmp);

    /* Okay, there's a dir in there, but not at the end of the string... 
       try stripping it off */
    striponedir(tmp);
    align(&tmp);
    return do_browser(tmp);

}



Chris Allegretta's avatar
Chris Allegretta committed
1565
1566
#endif