File: completion.c

package info (click to toggle)
shell-fm 0.7%2Bgit20100414-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 444 kB
  • ctags: 305
  • sloc: ansic: 4,422; makefile: 135; python: 80; haskell: 76; sh: 67; perl: 19
file content (75 lines) | stat: -rw-r--r-- 1,478 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
	Copyright (C) 2006 by Jonas Kramer
	Published under the terms of the GNU General Public License (GPL).
*/

#define _GNU_SOURCE


#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/time.h>
#include <signal.h>
#include <stdarg.h>

#include <assert.h>

#include "compatibility.h"
#include "completion.h"


const char * nextmatch(char ** list, char * needle, unsigned * nres) {
	static char lastneedle[64] = { 0 };
	static int lastmatch = 0, matches = 0, nlen = 0;
	register unsigned i;

	if(!list)
		return NULL;

	/* Check if a new search is needed or wanted. */
	if(needle != NULL) {
		/* Remember needle for repeated calls. */
		memset(lastneedle, 0, sizeof(lastneedle));
		strncpy(lastneedle, needle, sizeof(lastneedle) - 1);

		/* Count number of matches of needle in list. */
		nlen = strlen(needle);
		for(matches = i = 0; list[i] != NULL; ++i)
			if(!strncasecmp(list[i], needle, nlen))
				++matches;

		/* Start search at first item. */
		i = 0;
	} else {
		/* Search for the last given needle. */
		needle = lastneedle;
		nlen = strlen(needle);

		/* Start search at first item after the last matched one. */
		i = lastmatch + 1;
	}

	if(nres != NULL)
		* nres = matches;

	if(matches) {
		while(matches > 0) {
			if(!list[i])
				i = 0;

			if(!strncasecmp(list[i], needle, nlen)) {
				lastmatch = i;
				return list[i];
			}

			++i;
		}
	}

	return NULL;
}