utils.c 15.9 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
/**************************************************************************
2
 *   utils.c  --  This file is part of GNU nano.                          *
Chris Allegretta's avatar
Chris Allegretta committed
3
 *                                                                        *
4
 *   Copyright (C) 1999-2011, 2013-2017 Free Software Foundation, Inc.    *
5
6
 *   Copyright (C) 2016 Benno Schulenberg                                 *
 *                                                                        *
7
8
9
10
 *   GNU nano 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 3 of the License,    *
 *   or (at your option) any later version.                               *
Chris Allegretta's avatar
Chris Allegretta committed
11
 *                                                                        *
12
13
14
15
 *   GNU nano 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
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
18
 *   along with this program.  If not, see http://www.gnu.org/licenses/.  *
Chris Allegretta's avatar
Chris Allegretta committed
19
20
21
 *                                                                        *
 **************************************************************************/

22
#include "proto.h"
23

24
#include <errno.h>
25
#ifdef HAVE_PWD_H
26
#include <pwd.h>
27
#endif
28
29
#include <string.h>
#include <unistd.h>
Chris Allegretta's avatar
Chris Allegretta committed
30

31
/* Return the user's home directory.  We use $HOME, and if that fails,
32
 * we fall back on the home directory of the effective user ID. */
33
34
35
36
37
void get_homedir(void)
{
    if (homedir == NULL) {
	const char *homenv = getenv("HOME");

38
#ifdef HAVE_PWD_H
39
40
41
	/* When HOME isn't set, or when we're root, get the home directory
	 * from the password file instead. */
	if (homenv == NULL || geteuid() == 0) {
42
43
44
45
46
	    const struct passwd *userage = getpwuid(geteuid());

	    if (userage != NULL)
		homenv = userage->pw_dir;
	}
47
#endif
48
49
50
51
52

	/* Only set homedir if some home directory could be determined,
	 * otherwise keep homedir NULL. */
	if (homenv != NULL && strcmp(homenv, "") != 0)
	    homedir = mallocstrcpy(NULL, homenv);
53
54
55
    }
}

56
57
#ifdef ENABLE_LINENUMBERS
/* Return the number of digits that the given integer n takes up. */
58
int digits(ssize_t n)
59
60
{
    if (n < 100000) {
61
62
63
64
65
66
67
68
69
70
71
	if (n < 1000) {
	    if (n < 100)
		return 2;
	    else
		return 3;
	} else {
	    if (n < 10000)
		return 4;
	    else
		return 5;
	}
72
    } else {
73
74
75
76
77
78
79
80
81
82
83
	if (n < 10000000) {
	    if (n < 1000000)
		return 6;
	    else
		return 7;
	} else {
	    if (n < 100000000)
		return 8;
	    else
		return 9;
	}
84
85
86
87
    }
}
#endif

88
89
90
/* Read an integer from str.  If it parses okay, store it in *result
 * and return TRUE; otherwise, return FALSE. */
bool parse_num(const char *str, ssize_t *result)
91
92
{
    char *first_error;
93
    ssize_t value;
94

95
    /* The manual page for strtol() says this is required. */
96
97
    errno = 0;

98
    value = (ssize_t)strtol(str, &first_error, 10);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
99

100
    if (errno == ERANGE || *str == '\0' || *first_error != '\0')
101
	return FALSE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
102

103
    *result = value;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
104

105
    return TRUE;
106
107
}

108
109
/* Read two numbers, separated by a comma, from str, and store them in
 * *line and *column.  Return FALSE on error, and TRUE otherwise. */
110
bool parse_line_column(const char *str, ssize_t *line, ssize_t *column)
111
{
112
113
    bool retval;
    char *firstpart;
114
115
116
    const char *comma;

    while (*str == ' ')
117
	str++;
118
119

    comma = strpbrk(str, "m,. /;");
120

121
122
    if (comma == NULL)
	return parse_num(str, line);
123

124
    retval = parse_num(comma + 1, column);
125

126
    if (comma == str)
127
	return retval;
128

129
    firstpart = mallocstrcpy(NULL, str);
130
    firstpart[comma - str] = '\0';
131

132
    retval = parse_num(firstpart, line) && retval;
133

134
    free(firstpart);
135

136
    return retval;
137
138
}

139
140
/* Reduce the memory allocation of a string to what is needed. */
void snuggly_fit(char **str)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
141
{
142
143
    if (*str != NULL)
	*str = charealloc(*str, strlen(*str) + 1);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
144
145
}

Chris Allegretta's avatar
Chris Allegretta committed
146
147
/* Null a string at a certain index and align it. */
void null_at(char **data, size_t index)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
148
{
Chris Allegretta's avatar
Chris Allegretta committed
149
    *data = charealloc(*data, index + 1);
Chris Allegretta's avatar
Chris Allegretta committed
150
    (*data)[index] = '\0';
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
151
152
}

Chris Allegretta's avatar
Chris Allegretta committed
153
154
155
/* For non-null-terminated lines.  A line, by definition, shouldn't
 * normally have newlines in it, so encode its nulls as newlines. */
void unsunder(char *str, size_t true_len)
Chris Allegretta's avatar
Chris Allegretta committed
156
{
157
    for (; true_len > 0; true_len--, str++) {
Chris Allegretta's avatar
Chris Allegretta committed
158
159
	if (*str == '\0')
	    *str = '\n';
160
    }
Chris Allegretta's avatar
Chris Allegretta committed
161
}
Chris Allegretta's avatar
Chris Allegretta committed
162

Chris Allegretta's avatar
Chris Allegretta committed
163
/* For non-null-terminated lines.  A line, by definition, shouldn't
164
 * normally have newlines in it, so decode its newlines as nulls. */
Chris Allegretta's avatar
Chris Allegretta committed
165
166
void sunder(char *str)
{
167
    for (; *str != '\0'; str++) {
Chris Allegretta's avatar
Chris Allegretta committed
168
169
	if (*str == '\n')
	    *str = '\0';
170
    }
Chris Allegretta's avatar
Chris Allegretta committed
171
172
}

173
174
/* Fix the regex if we're on platforms which require an adjustment
 * from GNU-style to BSD-style word boundaries. */
175
176
const char *fixbounds(const char *r)
{
177
178
179
180
181
182
183
184
185
186
#ifndef GNU_WORDBOUNDS
    int i, j = 0;
    char *r2 = charalloc(strlen(r) * 5);
    char *r3;

#ifdef DEBUG
    fprintf(stderr, "fixbounds(): Start string = \"%s\"\n", r);
#endif

    for (i = 0; i < strlen(r); i++) {
187
188
189
190
191
192
193
194
195
	if (r[i] != '\0' && r[i] == '\\' && (r[i + 1] == '>' || r[i + 1] == '<')) {
	    strcpy(&r2[j], "[[:");
	    r2[j + 3] = r[i + 1];
	    strcpy(&r2[j + 4], ":]]");
	    i++;
	    j += 6;
	} else
	    r2[j] = r[i];
	j++;
196
197
198
199
200
201
202
203
    }
    r2[j] = '\0';
    r3 = mallocstrcpy(NULL, r2);
    free(r2);
#ifdef DEBUG
    fprintf(stderr, "fixbounds(): Ending string = \"%s\"\n", r3);
#endif
    return (const char *) r3;
204
#endif /* !GNU_WORDBOUNDS */
205
206
207

    return r;
}
208

209
#ifndef DISABLE_SPELLER
210
211
212
/* Is the word starting at the given position in buf and of the given length
 * a separate word?  That is: is it not part of a longer word?*/
bool is_separate_word(size_t position, size_t length, const char *buf)
213
{
214
    char before[MAXCHARLEN], after[MAXCHARLEN];
215
    size_t word_end = position + length;
216

217
218
219
    /* Get the characters before and after the word, if any. */
    parse_mbchar(buf + move_mbleft(buf, position), before, NULL);
    parse_mbchar(buf + word_end, after, NULL);
220

221
222
223
    /* If the word starts at the beginning of the line OR the character before
     * the word isn't a letter, and if the word ends at the end of the line OR
     * the character after the word isn't a letter, we have a whole word. */
224
225
    return ((position == 0 || !is_alpha_mbchar(before)) &&
		(buf[word_end] == '\0' || !is_alpha_mbchar(after)));
226
}
227
#endif /* !DISABLE_SPELLER */
228

229
230
231
232
233
/* Return the position of the needle in the haystack, or NULL if not found.
 * When searching backwards, we will find the last match that starts no later
 * than the given start; otherwise, we find the first match starting no earlier
 * than start.  If we are doing a regexp search, and we find a match, we fill
 * in the global variable regmatches with at most 9 subexpression matches. */
Chris Allegretta's avatar
Chris Allegretta committed
234
const char *strstrwrapper(const char *haystack, const char *needle,
235
	const char *start)
Chris Allegretta's avatar
Chris Allegretta committed
236
{
237
    if (*needle == '\0') {
238
#ifndef NANO_TINY
239
	statusline(ALERT, "Searching for nothing -- please report a bug");
240
#endif
241
	return (char *)start;
242
    }
243

244
    if (ISSET(USE_REGEXP)) {
245
	if (ISSET(BACKWARDS_SEARCH)) {
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
	    size_t last_find, ceiling, far_end;
	    size_t floor = 0, next_rung = 0;
		/* The start of the search range, and the next start. */

	    if (regexec(&search_regexp, haystack, 1, regmatches, 0) != 0)
		return NULL;

	    far_end = strlen(haystack);
	    ceiling = start - haystack;
	    last_find = regmatches[0].rm_so;

	    /* A result beyond the search range also means: no match. */
	    if (last_find > ceiling)
		return NULL;

	    /* Move the start-of-range forward until there is no more match;
	     * then the last match found is the first match backwards. */
	    while (regmatches[0].rm_so <= ceiling) {
		floor = next_rung;
		last_find = regmatches[0].rm_so;
		/* If this is the last possible match, don't try to advance. */
		if (last_find == ceiling)
		    break;
		next_rung = move_mbright(haystack, last_find);
		regmatches[0].rm_so = next_rung;
		regmatches[0].rm_eo = far_end;
		if (regexec(&search_regexp, haystack, 1, regmatches,
					REG_STARTEND) != 0)
		    break;
Chris Allegretta's avatar
Chris Allegretta committed
275
	    }
276

277
278
279
280
281
	    /* Find the last match again, to get possible submatches. */
	    regmatches[0].rm_so = floor;
	    regmatches[0].rm_eo = far_end;
	    if (regexec(&search_regexp, haystack, 10, regmatches,
					REG_STARTEND) != 0)
282
		return NULL;
283
284

	    return haystack + regmatches[0].rm_so;
285
	}
286
287
288
289
290
291
292
293
294

	/* Do a forward regex search from the starting point. */
	regmatches[0].rm_so = start - haystack;
	regmatches[0].rm_eo = strlen(haystack);
	if (regexec(&search_regexp, haystack, 10, regmatches,
					REG_STARTEND) != 0)
	    return NULL;
	else
	    return haystack + regmatches[0].rm_so;
295
    }
296
    if (ISSET(CASE_SENSITIVE)) {
297
	if (ISSET(BACKWARDS_SEARCH))
298
	    return revstrstr(haystack, needle, start);
299
	else
300
	    return strstr(start, needle);
301
    } else if (ISSET(BACKWARDS_SEARCH))
302
	return mbrevstrcasestr(haystack, needle, start);
303

304
    return mbstrcasestr(start, needle);
Chris Allegretta's avatar
Chris Allegretta committed
305
}
Chris Allegretta's avatar
Chris Allegretta committed
306

307
308
309
310
/* This is a wrapper for the perror() function.  The wrapper temporarily
 * leaves curses mode, calls perror() (which writes to stderr), and then
 * reenters curses mode, updating the screen in the process.  Note that
 * nperror() causes the window to flicker once. */
311
312
void nperror(const char *s)
{
313
314
315
    endwin();
    perror(s);
    doupdate();
316
317
}

318
319
320
/* This is a wrapper for the malloc() function that properly handles
 * things when we run out of memory.  Thanks, BG, many people have been
 * asking for this... */
Chris Allegretta's avatar
Chris Allegretta committed
321
void *nmalloc(size_t howmuch)
Chris Allegretta's avatar
Chris Allegretta committed
322
{
Chris Allegretta's avatar
Chris Allegretta committed
323
    void *r = malloc(howmuch);
Chris Allegretta's avatar
Chris Allegretta committed
324

Chris Allegretta's avatar
Chris Allegretta committed
325
326
    if (r == NULL && howmuch != 0)
	die(_("nano is out of memory!"));
327

Chris Allegretta's avatar
Chris Allegretta committed
328
    return r;
329
330
}

331
332
/* This is a wrapper for the realloc() function that properly handles
 * things when we run out of memory. */
Chris Allegretta's avatar
Chris Allegretta committed
333
void *nrealloc(void *ptr, size_t howmuch)
Chris Allegretta's avatar
Chris Allegretta committed
334
{
Chris Allegretta's avatar
Chris Allegretta committed
335
    void *r = realloc(ptr, howmuch);
Chris Allegretta's avatar
Chris Allegretta committed
336

Chris Allegretta's avatar
Chris Allegretta committed
337
338
    if (r == NULL && howmuch != 0)
	die(_("nano is out of memory!"));
Chris Allegretta's avatar
Chris Allegretta committed
339
340
341

    return r;
}
Robert Siemborski's avatar
Robert Siemborski committed
342

343
344
/* Allocate and copy the first n characters of the given src string, after
 * freeing the destination.  Usage: "dest = mallocstrncpy(dest, src, n);". */
345
char *mallocstrncpy(char *dest, const char *src, size_t n)
346
{
347
348
    if (src == NULL)
	src = "";
349

350
    if (src != dest)
351
352
	free(dest);

353
    dest = charalloc(n);
354
    strncpy(dest, src, n);
355
356
357
358

    return dest;
}

359
/* Free the dest string and return a malloc'ed copy of src.  Should be used as:
360
361
362
 * "dest = mallocstrcpy(dest, src);". */
char *mallocstrcpy(char *dest, const char *src)
{
363
    return mallocstrncpy(dest, src, (src == NULL) ? 1 : strlen(src) + 1);
364
365
}

366
367
/* Free the string at dest and return the string at src. */
char *free_and_assign(char *dest, char *src)
368
369
370
371
372
{
    free(dest);
    return src;
}

373
374
375
/* When not in softwrap mode, nano scrolls horizontally within a line in
 * chunks (a bit smaller than the chunks used in softwrapping).  Return the
 * column number of the first character displayed in the edit window when the
376
377
378
379
 * cursor is at the given column.  Note that (0 <= column -
 * get_page_start(column) < COLS). */
size_t get_page_start(size_t column)
{
380
    if (column < editwincols - 1 || ISSET(SOFTWRAP) || column == 0)
381
	return 0;
382
383
    else if (editwincols > 8)
	return column - 7 - (column - 7) % (editwincols - 8);
384
    else
385
	return column - (editwincols - 2);
386
387
}

388
/* Return the placewewant associated with current_x, i.e. the zero-based
389
 * column position of the cursor. */
390
391
size_t xplustabs(void)
{
392
    return strnlenpt(openfile->current->data, openfile->current_x);
393
394
}

395
396
397
/* Return the index in text of the character that (when displayed) will
 * not overshoot the given column. */
size_t actual_x(const char *text, size_t column)
398
{
399
400
    const char *start = text;
	/* From where we start walking through the text. */
401
    size_t width = 0;
402
	/* The current accumulated span, in columns. */
403

404
405
    while (*text != '\0') {
	int charlen = parse_mbchar(text, NULL, &width);
406

407
	if (width > column)
408
409
	    break;

410
	text += charlen;
411
412
    }

413
    return (text - start);
414
415
}

416
417
418
/* A strnlen() with tabs and multicolumn characters factored in:
 * how many columns wide are the first maxlen bytes of text? */
size_t strnlenpt(const char *text, size_t maxlen)
419
{
420
421
    size_t width = 0;
	/* The screen display width to text[maxlen]. */
422
423
424
425

    if (maxlen == 0)
	return 0;

426
427
    while (*text != '\0') {
	int charlen = parse_mbchar(text, NULL, &width);
428

429
	if (maxlen <= charlen)
430
431
	    break;

432
	maxlen -= charlen;
433
	text += charlen;
434
435
    }

436
    return width;
437
438
}

439
/* Return the number of columns that the given text occupies. */
440
size_t strlenpt(const char *text)
441
{
442
443
444
445
446
447
    size_t span = 0;

    while (*text != '\0')
	text += parse_mbchar(text, NULL, &span);

    return span;
448
449
}

450
/* Append a new magicline to filebot. */
451
452
void new_magicline(void)
{
453
    openfile->filebot->next = make_new_node(openfile->filebot);
454
455
456
    openfile->filebot->next->data = mallocstrcpy(NULL, "");
    openfile->filebot = openfile->filebot->next;
    openfile->totsize++;
Robert Siemborski's avatar
Robert Siemborski committed
457
}
Chris Allegretta's avatar
Chris Allegretta committed
458

459
#if !defined(NANO_TINY) || defined(ENABLE_HELP)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
460
/* Remove the magicline from filebot, if there is one and it isn't the
461
462
 * only line in the file.  Assume that edittop and current are not at
 * filebot. */
463
464
void remove_magicline(void)
{
465
    if (openfile->filebot->data[0] == '\0' &&
466
		openfile->filebot != openfile->fileage) {
467
468
469
470
	openfile->filebot = openfile->filebot->prev;
	free_filestruct(openfile->filebot->next);
	openfile->filebot->next = NULL;
	openfile->totsize--;
471
472
    }
}
473
#endif
474

475
#ifndef NANO_TINY
476
477
/* Set top_x and bot_x to the top and bottom x-coordinates of the mark,
 * respectively, based on the locations of top and bot.  If
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
478
 * right_side_up isn't NULL, set it to TRUE if the mark begins with
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
479
 * (mark_begin, mark_begin_x) and ends with (current, current_x), or
480
481
482
483
 * FALSE otherwise. */
void mark_order(const filestruct **top, size_t *top_x, const filestruct
	**bot, size_t *bot_x, bool *right_side_up)
{
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
484
    if ((openfile->current->lineno == openfile->mark_begin->lineno &&
485
486
		openfile->current_x > openfile->mark_begin_x) ||
		openfile->current->lineno > openfile->mark_begin->lineno) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
487
488
	*top = openfile->mark_begin;
	*top_x = openfile->mark_begin_x;
489
490
	*bot = openfile->current;
	*bot_x = openfile->current_x;
491
492
493
	if (right_side_up != NULL)
	    *right_side_up = TRUE;
    } else {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
494
495
	*bot = openfile->mark_begin;
	*bot_x = openfile->mark_begin_x;
496
497
	*top = openfile->current;
	*top_x = openfile->current_x;
498
499
500
501
	if (right_side_up != NULL)
	    *right_side_up = FALSE;
    }
}
502

503
/* Given a line number, return a pointer to the corresponding struct. */
504
505
506
507
508
filestruct *fsfromline(ssize_t lineno)
{
    filestruct *f = openfile->current;

    if (lineno <= openfile->current->lineno)
509
510
	while (f->lineno != lineno && f->prev != NULL)
	    f = f->prev;
511
    else
512
513
	while (f->lineno != lineno && f->next != NULL)
	    f = f->next;
514

515
    if (f->lineno != lineno) {
516
517
	statusline(ALERT, _("Internal error: can't match line %ld.  "
			"Please save your work."), (long)lineno);
518
	return NULL;
519
    }
520

521
522
    return f;
}
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#endif /* !NANO_TINY */

/* Count the number of characters from begin to end, and return it. */
size_t get_totsize(const filestruct *begin, const filestruct *end)
{
    const filestruct *line;
    size_t totsize = 0;

    /* Sum the number of characters (plus a newline) in each line. */
    for (line = begin; line != end->next; line = line->next)
	totsize += mbstrlen(line->data) + 1;

    /* The last line of a file doesn't have a newline -- otherwise it
     * wouldn't be the last line -- so subtract 1 when at EOF. */
    if (line == NULL)
	totsize--;

    return totsize;
}
542

Chris Allegretta's avatar
Chris Allegretta committed
543
#ifdef DEBUG
544
/* Dump the given buffer to stderr. */
Chris Allegretta's avatar
Chris Allegretta committed
545
546
547
548
549
550
551
552
553
554
555
556
557
558
void dump_filestruct(const filestruct *inptr)
{
    if (inptr == openfile->fileage)
	fprintf(stderr, "Dumping file buffer to stderr...\n");
    else if (inptr == cutbuffer)
	fprintf(stderr, "Dumping cutbuffer to stderr...\n");
    else
	fprintf(stderr, "Dumping a buffer to stderr...\n");

    while (inptr != NULL) {
	fprintf(stderr, "(%ld) %s\n", (long)inptr->lineno, inptr->data);
	inptr = inptr->next;
    }
}
559

560
/* Dump the current buffer to stderr in reverse. */
561
562
563
564
565
566
567
568
569
570
571
void dump_filestruct_reverse(void)
{
    const filestruct *fileptr = openfile->filebot;

    while (fileptr != NULL) {
	fprintf(stderr, "(%ld) %s\n", (long)fileptr->lineno,
		fileptr->data);
	fileptr = fileptr->prev;
    }
}
#endif /* DEBUG */