xref: /vim-8.2.3635/src/if_cscope.c (revision fc65cabb)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * CSCOPE support for Vim added by Andy Kahn <[email protected]>
4  * Ported to Win32 by Sergey Khorev <[email protected]>
5  *
6  * The basic idea/structure of cscope for Vim was borrowed from Nvi.  There
7  * might be a few lines of code that look similar to what Nvi has.
8  *
9  * See README.txt for an overview of the Vim source code.
10  */
11 
12 #include "vim.h"
13 
14 #if defined(FEAT_CSCOPE) || defined(PROTO)
15 
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #if defined(UNIX)
19 # include <sys/wait.h>
20 #endif
21 #include "if_cscope.h"
22 
23 static void	    cs_usage_msg(csid_e x);
24 static int	    cs_add(exarg_T *eap);
25 static void	    cs_stat_emsg(char *fname);
26 static int	    cs_add_common(char *, char *, char *);
27 static int	    cs_check_for_connections(void);
28 static int	    cs_check_for_tags(void);
29 static int	    cs_cnt_connections(void);
30 static void	    cs_reading_emsg(int idx);
31 static int	    cs_cnt_matches(int idx);
32 static char *	    cs_create_cmd(char *csoption, char *pattern);
33 static int	    cs_create_connection(int i);
34 static void	    do_cscope_general(exarg_T *eap, int make_split);
35 #ifdef FEAT_QUICKFIX
36 static void	    cs_file_results(FILE *, int *);
37 #endif
38 static void	    cs_fill_results(char *, int , int *, char ***,
39 			char ***, int *);
40 static int	    cs_find(exarg_T *eap);
41 static int	    cs_find_common(char *opt, char *pat, int, int, int, char_u *cmdline);
42 static int	    cs_help(exarg_T *eap);
43 static void	    clear_csinfo(int i);
44 static int	    cs_insert_filelist(char *, char *, char *,
45 			stat_T *);
46 static int	    cs_kill(exarg_T *eap);
47 static void	    cs_kill_execute(int, char *);
48 static cscmd_T *    cs_lookup_cmd(exarg_T *eap);
49 static char *	    cs_make_vim_style_matches(char *, char *,
50 			char *, char *);
51 static char *	    cs_manage_matches(char **, char **, int, mcmd_e);
52 static char *	    cs_parse_results(int cnumber, char *buf, int bufsize, char **context, char **linenumber, char **search);
53 static char *	    cs_pathcomponents(char *path);
54 static void	    cs_print_tags_priv(char **, char **, int);
55 static int	    cs_read_prompt(int);
56 static void	    cs_release_csp(int, int freefnpp);
57 static int	    cs_reset(exarg_T *eap);
58 static char *	    cs_resolve_file(int, char *);
59 static int	    cs_show(exarg_T *eap);
60 
61 
62 static csinfo_T *   csinfo = NULL;
63 static int	    csinfo_size = 0;	/* number of items allocated in
64 					   csinfo[] */
65 
66 static int	    eap_arg_len;    /* length of eap->arg, set in
67 				       cs_lookup_cmd() */
68 static cscmd_T	    cs_cmds[] =
69 {
70     { "add",	cs_add,
71 		N_("Add a new database"),     "add file|dir [pre-path] [flags]", 0 },
72     { "find",	cs_find,
73 		N_("Query for a pattern"),    "find a|c|d|e|f|g|i|s|t name", 1 },
74     { "help",	cs_help,
75 		N_("Show this message"),      "help", 0 },
76     { "kill",	cs_kill,
77 		N_("Kill a connection"),      "kill #", 0 },
78     { "reset",	cs_reset,
79 		N_("Reinit all connections"), "reset", 0 },
80     { "show",	cs_show,
81 		N_("Show connections"),       "show", 0 },
82     { NULL, NULL, NULL, NULL, 0 }
83 };
84 
85     static void
86 cs_usage_msg(csid_e x)
87 {
88     (void)EMSG2(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage);
89 }
90 
91 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
92 
93 static enum
94 {
95     EXP_CSCOPE_SUBCMD,	/* expand ":cscope" sub-commands */
96     EXP_SCSCOPE_SUBCMD,	/* expand ":scscope" sub-commands */
97     EXP_CSCOPE_FIND,	/* expand ":cscope find" arguments */
98     EXP_CSCOPE_KILL	/* expand ":cscope kill" arguments */
99 } expand_what;
100 
101 /*
102  * Function given to ExpandGeneric() to obtain the cscope command
103  * expansion.
104  */
105     char_u *
106 get_cscope_name(expand_T *xp UNUSED, int idx)
107 {
108     int		current_idx;
109     int		i;
110 
111     switch (expand_what)
112     {
113     case EXP_CSCOPE_SUBCMD:
114 	/* Complete with sub-commands of ":cscope":
115 	 * add, find, help, kill, reset, show */
116 	return (char_u *)cs_cmds[idx].name;
117     case EXP_SCSCOPE_SUBCMD:
118 	/* Complete with sub-commands of ":scscope": same sub-commands as
119 	 * ":cscope" but skip commands which don't support split windows */
120 	for (i = 0, current_idx = 0; cs_cmds[i].name != NULL; i++)
121 	    if (cs_cmds[i].cansplit)
122 		if (current_idx++ == idx)
123 		    break;
124 	return (char_u *)cs_cmds[i].name;
125     case EXP_CSCOPE_FIND:
126 	{
127 	    const char *query_type[] =
128 	    {
129 		"a", "c", "d", "e", "f", "g", "i", "s", "t", NULL
130 	    };
131 
132 	    /* Complete with query type of ":cscope find {query_type}".
133 	     * {query_type} can be letters (c, d, ... a) or numbers (0, 1,
134 	     * ..., 9) but only complete with letters, since numbers are
135 	     * redundant. */
136 	    return (char_u *)query_type[idx];
137 	}
138     case EXP_CSCOPE_KILL:
139 	{
140 	    static char	connection[5];
141 
142 	    /* ":cscope kill" accepts connection numbers or partial names of
143 	     * the pathname of the cscope database as argument.  Only complete
144 	     * with connection numbers. -1 can also be used to kill all
145 	     * connections. */
146 	    for (i = 0, current_idx = 0; i < csinfo_size; i++)
147 	    {
148 		if (csinfo[i].fname == NULL)
149 		    continue;
150 		if (current_idx++ == idx)
151 		{
152 		    vim_snprintf(connection, sizeof(connection), "%d", i);
153 		    return (char_u *)connection;
154 		}
155 	    }
156 	    return (current_idx == idx && idx > 0) ? (char_u *)"-1" : NULL;
157 	}
158     default:
159 	return NULL;
160     }
161 }
162 
163 /*
164  * Handle command line completion for :cscope command.
165  */
166     void
167 set_context_in_cscope_cmd(
168     expand_T	*xp,
169     char_u	*arg,
170     cmdidx_T	cmdidx)
171 {
172     char_u	*p;
173 
174     /* Default: expand subcommands */
175     xp->xp_context = EXPAND_CSCOPE;
176     xp->xp_pattern = arg;
177     expand_what = (cmdidx == CMD_scscope)
178 			? EXP_SCSCOPE_SUBCMD : EXP_CSCOPE_SUBCMD;
179 
180     /* (part of) subcommand already typed */
181     if (*arg != NUL)
182     {
183 	p = skiptowhite(arg);
184 	if (*p != NUL)		    /* past first word */
185 	{
186 	    xp->xp_pattern = skipwhite(p);
187 	    if (*skiptowhite(xp->xp_pattern) != NUL)
188 		xp->xp_context = EXPAND_NOTHING;
189 	    else if (STRNICMP(arg, "add", p - arg) == 0)
190 		xp->xp_context = EXPAND_FILES;
191 	    else if (STRNICMP(arg, "kill", p - arg) == 0)
192 		expand_what = EXP_CSCOPE_KILL;
193 	    else if (STRNICMP(arg, "find", p - arg) == 0)
194 		expand_what = EXP_CSCOPE_FIND;
195 	    else
196 		xp->xp_context = EXPAND_NOTHING;
197 	}
198     }
199 }
200 
201 #endif /* FEAT_CMDL_COMPL */
202 
203 /*
204  * Find the command, print help if invalid, and then call the corresponding
205  * command function.
206  */
207     static void
208 do_cscope_general(
209     exarg_T	*eap,
210     int		make_split UNUSED) /* whether to split window */
211 {
212     cscmd_T *cmdp;
213 
214     if ((cmdp = cs_lookup_cmd(eap)) == NULL)
215     {
216 	cs_help(eap);
217 	return;
218     }
219 
220     if (make_split)
221     {
222 	if (!cmdp->cansplit)
223 	{
224 	    (void)MSG_PUTS(_("This cscope command does not support splitting the window.\n"));
225 	    return;
226 	}
227 	postponed_split = -1;
228 	postponed_split_flags = cmdmod.split;
229 	postponed_split_tab = cmdmod.tab;
230     }
231 
232     cmdp->func(eap);
233 
234     postponed_split_flags = 0;
235     postponed_split_tab = 0;
236 }
237 
238 /*
239  * Implementation of ":cscope" and ":lcscope"
240  */
241     void
242 ex_cscope(exarg_T *eap)
243 {
244     do_cscope_general(eap, FALSE);
245 }
246 
247 /*
248  * Implementation of ":scscope". Same as ex_cscope(), but splits window, too.
249  */
250     void
251 ex_scscope(exarg_T *eap)
252 {
253     do_cscope_general(eap, TRUE);
254 }
255 
256 /*
257  * Implementation of ":cstag"
258  */
259     void
260 ex_cstag(exarg_T *eap)
261 {
262     int ret = FALSE;
263 
264     if (*eap->arg == NUL)
265     {
266 	(void)EMSG(_("E562: Usage: cstag <ident>"));
267 	return;
268     }
269 
270     switch (p_csto)
271     {
272     case 0 :
273 	if (cs_check_for_connections())
274 	{
275 	    ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
276 						       FALSE, *eap->cmdlinep);
277 	    if (ret == FALSE)
278 	    {
279 		cs_free_tags();
280 		if (msg_col)
281 		    msg_putchar('\n');
282 
283 		if (cs_check_for_tags())
284 		    ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
285 	    }
286 	}
287 	else if (cs_check_for_tags())
288 	{
289 	    ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
290 	}
291 	break;
292     case 1 :
293 	if (cs_check_for_tags())
294 	{
295 	    ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
296 	    if (ret == FALSE)
297 	    {
298 		if (msg_col)
299 		    msg_putchar('\n');
300 
301 		if (cs_check_for_connections())
302 		{
303 		    ret = cs_find_common("g", (char *)(eap->arg), eap->forceit,
304 						FALSE, FALSE, *eap->cmdlinep);
305 		    if (ret == FALSE)
306 			cs_free_tags();
307 		}
308 	    }
309 	}
310 	else if (cs_check_for_connections())
311 	{
312 	    ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
313 						       FALSE, *eap->cmdlinep);
314 	    if (ret == FALSE)
315 		cs_free_tags();
316 	}
317 	break;
318     default :
319 	break;
320     }
321 
322     if (!ret)
323     {
324 	(void)EMSG(_("E257: cstag: tag not found"));
325 #if defined(FEAT_QUICKFIX)
326 	g_do_tagpreview = 0;
327 #endif
328     }
329 
330 }
331 
332 
333 /*
334  * This simulates a vim_fgets(), but for cscope, returns the next line
335  * from the cscope output.  should only be called from find_tags()
336  *
337  * returns TRUE if eof, FALSE otherwise
338  */
339     int
340 cs_fgets(char_u *buf, int size)
341 {
342     char *p;
343 
344     if ((p = cs_manage_matches(NULL, NULL, -1, Get)) == NULL)
345 	return TRUE;
346     vim_strncpy(buf, (char_u *)p, size - 1);
347 
348     return FALSE;
349 } /* cs_fgets */
350 
351 
352 /*
353  * Called only from do_tag(), when popping the tag stack.
354  */
355     void
356 cs_free_tags(void)
357 {
358     cs_manage_matches(NULL, NULL, -1, Free);
359 }
360 
361 
362 /*
363  * Called from do_tag().
364  */
365     void
366 cs_print_tags(void)
367 {
368     cs_manage_matches(NULL, NULL, -1, Print);
369 }
370 
371 
372 /*
373  * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
374  *
375  *		Checks for the existence of a |cscope| connection.  If no
376  *		parameters are specified, then the function returns:
377  *
378  *		0, if cscope was not available (not compiled in), or if there
379  *		are no cscope connections; or
380  *		1, if there is at least one cscope connection.
381  *
382  *		If parameters are specified, then the value of {num}
383  *		determines how existence of a cscope connection is checked:
384  *
385  *		{num}	Description of existence check
386  *		-----	------------------------------
387  *		0	Same as no parameters (e.g., "cscope_connection()").
388  *		1	Ignore {prepend}, and use partial string matches for
389  *			{dbpath}.
390  *		2	Ignore {prepend}, and use exact string matches for
391  *			{dbpath}.
392  *		3	Use {prepend}, use partial string matches for both
393  *			{dbpath} and {prepend}.
394  *		4	Use {prepend}, use exact string matches for both
395  *			{dbpath} and {prepend}.
396  *
397  *		Note: All string comparisons are case sensitive!
398  */
399 #if defined(FEAT_EVAL) || defined(PROTO)
400     int
401 cs_connection(int num, char_u *dbpath, char_u *ppath)
402 {
403     int i;
404 
405     if (num < 0 || num > 4 || (num > 0 && !dbpath))
406 	return FALSE;
407 
408     for (i = 0; i < csinfo_size; i++)
409     {
410 	if (!csinfo[i].fname)
411 	    continue;
412 
413 	if (num == 0)
414 	    return TRUE;
415 
416 	switch (num)
417 	{
418 	case 1:
419 	    if (strstr(csinfo[i].fname, (char *)dbpath))
420 		return TRUE;
421 	    break;
422 	case 2:
423 	    if (strcmp(csinfo[i].fname, (char *)dbpath) == 0)
424 		return TRUE;
425 	    break;
426 	case 3:
427 	    if (strstr(csinfo[i].fname, (char *)dbpath)
428 		    && ((!ppath && !csinfo[i].ppath)
429 			|| (ppath
430 			    && csinfo[i].ppath
431 			    && strstr(csinfo[i].ppath, (char *)ppath))))
432 		return TRUE;
433 	    break;
434 	case 4:
435 	    if ((strcmp(csinfo[i].fname, (char *)dbpath) == 0)
436 		    && ((!ppath && !csinfo[i].ppath)
437 			|| (ppath
438 			    && csinfo[i].ppath
439 			    && (strcmp(csinfo[i].ppath, (char *)ppath) == 0))))
440 		return TRUE;
441 	    break;
442 	}
443     }
444 
445     return FALSE;
446 } /* cs_connection */
447 #endif
448 
449 
450 /*
451  * PRIVATE functions
452  ****************************************************************************/
453 
454 /*
455  * Add cscope database or a directory name (to look for cscope.out)
456  * to the cscope connection list.
457  */
458     static int
459 cs_add(exarg_T *eap UNUSED)
460 {
461     char *fname, *ppath, *flags = NULL;
462 
463     if ((fname = strtok((char *)NULL, (const char *)" ")) == NULL)
464     {
465 	cs_usage_msg(Add);
466 	return CSCOPE_FAILURE;
467     }
468     if ((ppath = strtok((char *)NULL, (const char *)" ")) != NULL)
469 	flags = strtok((char *)NULL, (const char *)" ");
470 
471     return cs_add_common(fname, ppath, flags);
472 }
473 
474     static void
475 cs_stat_emsg(char *fname)
476 {
477     char *stat_emsg = _("E563: stat(%s) error: %d");
478     char *buf = (char *)alloc((unsigned)strlen(stat_emsg) + MAXPATHL + 10);
479 
480     if (buf != NULL)
481     {
482 	(void)sprintf(buf, stat_emsg, fname, errno);
483 	(void)EMSG(buf);
484 	vim_free(buf);
485     }
486     else
487 	(void)EMSG(_("E563: stat error"));
488 }
489 
490 
491 /*
492  * The common routine to add a new cscope connection.  Called by
493  * cs_add() and cs_reset().  I really don't like to do this, but this
494  * routine uses a number of goto statements.
495  */
496     static int
497 cs_add_common(
498     char *arg1,	    /* filename - may contain environment variables */
499     char *arg2,	    /* prepend path - may contain environment variables */
500     char *flags)
501 {
502     stat_T	statbuf;
503     int		ret;
504     char	*fname = NULL;
505     char	*fname2 = NULL;
506     char	*ppath = NULL;
507     int		i;
508 #ifdef FEAT_MODIFY_FNAME
509     int		len;
510     int		usedlen = 0;
511     char_u	*fbuf = NULL;
512 #endif
513 
514     /* get the filename (arg1), expand it, and try to stat it */
515     if ((fname = (char *)alloc(MAXPATHL + 1)) == NULL)
516 	goto add_err;
517 
518     expand_env((char_u *)arg1, (char_u *)fname, MAXPATHL);
519 #ifdef FEAT_MODIFY_FNAME
520     len = (int)STRLEN(fname);
521     fbuf = (char_u *)fname;
522     (void)modify_fname((char_u *)":p", FALSE, &usedlen,
523 					      (char_u **)&fname, &fbuf, &len);
524     if (fname == NULL)
525 	goto add_err;
526     fname = (char *)vim_strnsave((char_u *)fname, len);
527     vim_free(fbuf);
528 #endif
529     ret = mch_stat(fname, &statbuf);
530     if (ret < 0)
531     {
532 staterr:
533 	if (p_csverbose)
534 	    cs_stat_emsg(fname);
535 	goto add_err;
536     }
537 
538     /* get the prepend path (arg2), expand it, and try to stat it */
539     if (arg2 != NULL)
540     {
541 	stat_T	    statbuf2;
542 
543 	if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
544 	    goto add_err;
545 
546 	expand_env((char_u *)arg2, (char_u *)ppath, MAXPATHL);
547 	ret = mch_stat(ppath, &statbuf2);
548 	if (ret < 0)
549 	    goto staterr;
550     }
551 
552     /* if filename is a directory, append the cscope database name to it */
553     if (S_ISDIR(statbuf.st_mode))
554     {
555 	fname2 = (char *)alloc((unsigned)(strlen(CSCOPE_DBFILE) + strlen(fname) + 2));
556 	if (fname2 == NULL)
557 	    goto add_err;
558 
559 	while (fname[strlen(fname)-1] == '/'
560 #ifdef WIN32
561 		|| fname[strlen(fname)-1] == '\\'
562 #endif
563 		)
564 	{
565 	    fname[strlen(fname)-1] = '\0';
566 	    if (fname[0] == '\0')
567 		break;
568 	}
569 	if (fname[0] == '\0')
570 	    (void)sprintf(fname2, "/%s", CSCOPE_DBFILE);
571 	else
572 	    (void)sprintf(fname2, "%s/%s", fname, CSCOPE_DBFILE);
573 
574 	ret = mch_stat(fname2, &statbuf);
575 	if (ret < 0)
576 	{
577 	    if (p_csverbose)
578 		cs_stat_emsg(fname2);
579 	    goto add_err;
580 	}
581 
582 	i = cs_insert_filelist(fname2, ppath, flags, &statbuf);
583     }
584     else if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode))
585     {
586 	i = cs_insert_filelist(fname, ppath, flags, &statbuf);
587     }
588     else
589     {
590 	if (p_csverbose)
591 	    (void)EMSG2(
592 		_("E564: %s is not a directory or a valid cscope database"),
593 		fname);
594 	goto add_err;
595     }
596 
597     if (i != -1)
598     {
599 	if (cs_create_connection(i) == CSCOPE_FAILURE
600 		|| cs_read_prompt(i) == CSCOPE_FAILURE)
601 	{
602 	    cs_release_csp(i, TRUE);
603 	    goto add_err;
604 	}
605 
606 	if (p_csverbose)
607 	{
608 	    msg_clr_eos();
609 	    (void)smsg_attr(HL_ATTR(HLF_R),
610 			    (char_u *)_("Added cscope database %s"),
611 			    csinfo[i].fname);
612 	}
613     }
614 
615     vim_free(fname);
616     vim_free(fname2);
617     vim_free(ppath);
618     return CSCOPE_SUCCESS;
619 
620 add_err:
621     vim_free(fname2);
622     vim_free(fname);
623     vim_free(ppath);
624     return CSCOPE_FAILURE;
625 } /* cs_add_common */
626 
627 
628     static int
629 cs_check_for_connections(void)
630 {
631     return (cs_cnt_connections() > 0);
632 } /* cs_check_for_connections */
633 
634 
635     static int
636 cs_check_for_tags(void)
637 {
638     return (p_tags[0] != NUL && curbuf->b_p_tags != NULL);
639 } /* cs_check_for_tags */
640 
641 
642 /*
643  * Count the number of cscope connections.
644  */
645     static int
646 cs_cnt_connections(void)
647 {
648     short i;
649     short cnt = 0;
650 
651     for (i = 0; i < csinfo_size; i++)
652     {
653 	if (csinfo[i].fname != NULL)
654 	    cnt++;
655     }
656     return cnt;
657 } /* cs_cnt_connections */
658 
659     static void
660 cs_reading_emsg(
661     int idx)	/* connection index */
662 {
663     EMSGN(_("E262: error reading cscope connection %ld"), idx);
664 }
665 
666 #define	CSREAD_BUFSIZE	2048
667 /*
668  * Count the number of matches for a given cscope connection.
669  */
670     static int
671 cs_cnt_matches(int idx)
672 {
673     char *stok;
674     char *buf;
675     int nlines = 0;
676 
677     buf = (char *)alloc(CSREAD_BUFSIZE);
678     if (buf == NULL)
679 	return 0;
680     for (;;)
681     {
682 	if (!fgets(buf, CSREAD_BUFSIZE, csinfo[idx].fr_fp))
683 	{
684 	    if (feof(csinfo[idx].fr_fp))
685 		errno = EIO;
686 
687 	    cs_reading_emsg(idx);
688 
689 	    vim_free(buf);
690 	    return -1;
691 	}
692 
693 	/*
694 	 * If the database is out of date, or there's some other problem,
695 	 * cscope will output error messages before the number-of-lines output.
696 	 * Display/discard any output that doesn't match what we want.
697 	 * Accept "\S*cscope: X lines", also matches "mlcscope".
698 	 * Bail out for the "Unable to search" error.
699 	 */
700 	if (strstr((const char *)buf, "Unable to search database") != NULL)
701 	    break;
702 	if ((stok = strtok(buf, (const char *)" ")) == NULL)
703 	    continue;
704 	if (strstr((const char *)stok, "cscope:") == NULL)
705 	    continue;
706 
707 	if ((stok = strtok(NULL, (const char *)" ")) == NULL)
708 	    continue;
709 	nlines = atoi(stok);
710 	if (nlines < 0)
711 	{
712 	    nlines = 0;
713 	    break;
714 	}
715 
716 	if ((stok = strtok(NULL, (const char *)" ")) == NULL)
717 	    continue;
718 	if (strncmp((const char *)stok, "lines", 5))
719 	    continue;
720 
721 	break;
722     }
723 
724     vim_free(buf);
725     return nlines;
726 } /* cs_cnt_matches */
727 
728 
729 /*
730  * Creates the actual cscope command query from what the user entered.
731  */
732     static char *
733 cs_create_cmd(char *csoption, char *pattern)
734 {
735     char *cmd;
736     short search;
737     char *pat;
738 
739     switch (csoption[0])
740     {
741     case '0' : case 's' :
742 	search = 0;
743 	break;
744     case '1' : case 'g' :
745 	search = 1;
746 	break;
747     case '2' : case 'd' :
748 	search = 2;
749 	break;
750     case '3' : case 'c' :
751 	search = 3;
752 	break;
753     case '4' : case 't' :
754 	search = 4;
755 	break;
756     case '6' : case 'e' :
757 	search = 6;
758 	break;
759     case '7' : case 'f' :
760 	search = 7;
761 	break;
762     case '8' : case 'i' :
763 	search = 8;
764 	break;
765     case '9' : case 'a' :
766 	search = 9;
767 	break;
768     default :
769 	(void)EMSG(_("E561: unknown cscope search type"));
770 	cs_usage_msg(Find);
771 	return NULL;
772     }
773 
774     /* Skip white space before the patter, except for text and pattern search,
775      * they may want to use the leading white space. */
776     pat = pattern;
777     if (search != 4 && search != 6)
778 	while VIM_ISWHITE(*pat)
779 	    ++pat;
780 
781     if ((cmd = (char *)alloc((unsigned)(strlen(pat) + 2))) == NULL)
782 	return NULL;
783 
784     (void)sprintf(cmd, "%d%s", search, pat);
785 
786     return cmd;
787 } /* cs_create_cmd */
788 
789 
790 /*
791  * This piece of code was taken/adapted from nvi.  do we need to add
792  * the BSD license notice?
793  */
794     static int
795 cs_create_connection(int i)
796 {
797 #ifdef UNIX
798     int		to_cs[2], from_cs[2];
799 #endif
800     int		len;
801     char	*prog, *cmd, *ppath = NULL;
802 #ifdef WIN32
803     int		fd;
804     SECURITY_ATTRIBUTES sa;
805     PROCESS_INFORMATION pi;
806     STARTUPINFO si;
807     BOOL	pipe_stdin = FALSE, pipe_stdout = FALSE;
808     HANDLE	stdin_rd, stdout_rd;
809     HANDLE	stdout_wr, stdin_wr;
810     BOOL	created;
811 # if (defined(_MSC_VER) && (_MSC_VER >= 1300)) || defined(__MINGW32__)
812 #  define OPEN_OH_ARGTYPE intptr_t
813 # else
814 #  define OPEN_OH_ARGTYPE long
815 # endif
816 #endif
817 
818 #if defined(UNIX)
819     /*
820      * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from
821      * from_cs[0] and writes to to_cs[1].
822      */
823     to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1;
824     if (pipe(to_cs) < 0 || pipe(from_cs) < 0)
825     {
826 	(void)EMSG(_("E566: Could not create cscope pipes"));
827 err_closing:
828 	if (to_cs[0] != -1)
829 	    (void)close(to_cs[0]);
830 	if (to_cs[1] != -1)
831 	    (void)close(to_cs[1]);
832 	if (from_cs[0] != -1)
833 	    (void)close(from_cs[0]);
834 	if (from_cs[1] != -1)
835 	    (void)close(from_cs[1]);
836 	return CSCOPE_FAILURE;
837     }
838 
839     switch (csinfo[i].pid = fork())
840     {
841     case -1:
842 	(void)EMSG(_("E622: Could not fork for cscope"));
843 	goto err_closing;
844     case 0:				/* child: run cscope. */
845 	if (dup2(to_cs[0], STDIN_FILENO) == -1)
846 	    PERROR("cs_create_connection 1");
847 	if (dup2(from_cs[1], STDOUT_FILENO) == -1)
848 	    PERROR("cs_create_connection 2");
849 	if (dup2(from_cs[1], STDERR_FILENO) == -1)
850 	    PERROR("cs_create_connection 3");
851 
852 	/* close unused */
853 	(void)close(to_cs[1]);
854 	(void)close(from_cs[0]);
855 #else
856 	/* WIN32 */
857 	/* Create pipes to communicate with cscope */
858 	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
859 	sa.bInheritHandle = TRUE;
860 	sa.lpSecurityDescriptor = NULL;
861 
862 	if (!(pipe_stdin = CreatePipe(&stdin_rd, &stdin_wr, &sa, 0))
863 		|| !(pipe_stdout = CreatePipe(&stdout_rd, &stdout_wr, &sa, 0)))
864 	{
865 	    (void)EMSG(_("E566: Could not create cscope pipes"));
866 err_closing:
867 	    if (pipe_stdin)
868 	    {
869 		CloseHandle(stdin_rd);
870 		CloseHandle(stdin_wr);
871 	    }
872 	    if (pipe_stdout)
873 	    {
874 		CloseHandle(stdout_rd);
875 		CloseHandle(stdout_wr);
876 	    }
877 	    return CSCOPE_FAILURE;
878 	}
879 #endif
880 	/* expand the cscope exec for env var's */
881 	if ((prog = (char *)alloc(MAXPATHL + 1)) == NULL)
882 	{
883 #ifdef UNIX
884 	    return CSCOPE_FAILURE;
885 #else
886 	    /* WIN32 */
887 	    goto err_closing;
888 #endif
889 	}
890 	expand_env((char_u *)p_csprg, (char_u *)prog, MAXPATHL);
891 
892 	/* alloc space to hold the cscope command */
893 	len = (int)(strlen(prog) + strlen(csinfo[i].fname) + 32);
894 	if (csinfo[i].ppath)
895 	{
896 	    /* expand the prepend path for env var's */
897 	    if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
898 	    {
899 		vim_free(prog);
900 #ifdef UNIX
901 		return CSCOPE_FAILURE;
902 #else
903 		/* WIN32 */
904 		goto err_closing;
905 #endif
906 	    }
907 	    expand_env((char_u *)csinfo[i].ppath, (char_u *)ppath, MAXPATHL);
908 
909 	    len += (int)strlen(ppath);
910 	}
911 
912 	if (csinfo[i].flags)
913 	    len += (int)strlen(csinfo[i].flags);
914 
915 	if ((cmd = (char *)alloc(len)) == NULL)
916 	{
917 	    vim_free(prog);
918 	    vim_free(ppath);
919 #ifdef UNIX
920 	    return CSCOPE_FAILURE;
921 #else
922 	    /* WIN32 */
923 	    goto err_closing;
924 #endif
925 	}
926 
927 	/* run the cscope command; is there execl for non-unix systems? */
928 #if defined(UNIX)
929 	(void)sprintf(cmd, "exec %s -dl -f %s", prog, csinfo[i].fname);
930 #else
931 	/* WIN32 */
932 	(void)sprintf(cmd, "%s -dl -f %s", prog, csinfo[i].fname);
933 #endif
934 	if (csinfo[i].ppath != NULL)
935 	{
936 	    (void)strcat(cmd, " -P");
937 	    (void)strcat(cmd, csinfo[i].ppath);
938 	}
939 	if (csinfo[i].flags != NULL)
940 	{
941 	    (void)strcat(cmd, " ");
942 	    (void)strcat(cmd, csinfo[i].flags);
943 	}
944 # ifdef UNIX
945       /* on Win32 we still need prog */
946 	vim_free(prog);
947 # endif
948 	vim_free(ppath);
949 
950 #if defined(UNIX)
951 # if defined(HAVE_SETSID) || defined(HAVE_SETPGID)
952 	/* Change our process group to avoid cscope receiving SIGWINCH. */
953 #  if defined(HAVE_SETSID)
954 	(void)setsid();
955 #  else
956 	if (setpgid(0, 0) == -1)
957 	    PERROR(_("cs_create_connection setpgid failed"));
958 #  endif
959 # endif
960 	if (execl("/bin/sh", "sh", "-c", cmd, (char *)NULL) == -1)
961 	    PERROR(_("cs_create_connection exec failed"));
962 
963 	exit(127);
964 	/* NOTREACHED */
965     default:	/* parent. */
966 	/*
967 	 * Save the file descriptors for later duplication, and
968 	 * reopen as streams.
969 	 */
970 	if ((csinfo[i].to_fp = fdopen(to_cs[1], "w")) == NULL)
971 	    PERROR(_("cs_create_connection: fdopen for to_fp failed"));
972 	if ((csinfo[i].fr_fp = fdopen(from_cs[0], "r")) == NULL)
973 	    PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
974 
975 	/* close unused */
976 	(void)close(to_cs[0]);
977 	(void)close(from_cs[1]);
978 
979 	break;
980     }
981 
982 #else
983     /* WIN32 */
984     /* Create a new process to run cscope and use pipes to talk with it */
985     GetStartupInfo(&si);
986     si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
987     si.wShowWindow = SW_HIDE;  /* Hide child application window */
988     si.hStdOutput = stdout_wr;
989     si.hStdError  = stdout_wr;
990     si.hStdInput  = stdin_rd;
991     created = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE,
992 							NULL, NULL, &si, &pi);
993     vim_free(prog);
994     vim_free(cmd);
995 
996     if (!created)
997     {
998 	PERROR(_("cs_create_connection exec failed"));
999 	(void)EMSG(_("E623: Could not spawn cscope process"));
1000 	goto err_closing;
1001     }
1002     /* else */
1003     csinfo[i].pid = pi.dwProcessId;
1004     csinfo[i].hProc = pi.hProcess;
1005     CloseHandle(pi.hThread);
1006 
1007     /* TODO - tidy up after failure to create files on pipe handles. */
1008     if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdin_wr,
1009 						      _O_TEXT|_O_APPEND)) < 0)
1010 	    || ((csinfo[i].to_fp = _fdopen(fd, "w")) == NULL))
1011 	PERROR(_("cs_create_connection: fdopen for to_fp failed"));
1012     if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdout_rd,
1013 						      _O_TEXT|_O_RDONLY)) < 0)
1014 	    || ((csinfo[i].fr_fp = _fdopen(fd, "r")) == NULL))
1015 	PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
1016 
1017     /* Close handles for file descriptors inherited by the cscope process */
1018     CloseHandle(stdin_rd);
1019     CloseHandle(stdout_wr);
1020 
1021 #endif /* !UNIX */
1022 
1023     return CSCOPE_SUCCESS;
1024 } /* cs_create_connection */
1025 
1026 
1027 /*
1028  * Query cscope using command line interface.  Parse the output and use tselect
1029  * to allow choices.  Like Nvi, creates a pipe to send to/from query/cscope.
1030  *
1031  * returns TRUE if we jump to a tag or abort, FALSE if not.
1032  */
1033     static int
1034 cs_find(exarg_T *eap)
1035 {
1036     char *opt, *pat;
1037     int i;
1038 
1039     if (cs_check_for_connections() == FALSE)
1040     {
1041 	(void)EMSG(_("E567: no cscope connections"));
1042 	return FALSE;
1043     }
1044 
1045     if ((opt = strtok((char *)NULL, (const char *)" ")) == NULL)
1046     {
1047 	cs_usage_msg(Find);
1048 	return FALSE;
1049     }
1050 
1051     pat = opt + strlen(opt) + 1;
1052     if (pat >= (char *)eap->arg + eap_arg_len)
1053     {
1054 	cs_usage_msg(Find);
1055 	return FALSE;
1056     }
1057 
1058     /*
1059      * Let's replace the NULs written by strtok() with spaces - we need the
1060      * spaces to correctly display the quickfix/location list window's title.
1061      */
1062     for (i = 0; i < eap_arg_len; ++i)
1063 	if (NUL == eap->arg[i])
1064 	    eap->arg[i] = ' ';
1065 
1066     return cs_find_common(opt, pat, eap->forceit, TRUE,
1067 				  eap->cmdidx == CMD_lcscope, *eap->cmdlinep);
1068 } /* cs_find */
1069 
1070 
1071 /*
1072  * Common code for cscope find, shared by cs_find() and ex_cstag().
1073  */
1074     static int
1075 cs_find_common(
1076     char *opt,
1077     char *pat,
1078     int forceit,
1079     int verbose,
1080     int	use_ll UNUSED,
1081     char_u *cmdline UNUSED)
1082 {
1083     int i;
1084     char *cmd;
1085     int *nummatches;
1086     int totmatches;
1087 #ifdef FEAT_QUICKFIX
1088     char cmdletter;
1089     char *qfpos;
1090 
1091     /* get cmd letter */
1092     switch (opt[0])
1093     {
1094     case '0' :
1095 	cmdletter = 's';
1096 	break;
1097     case '1' :
1098 	cmdletter = 'g';
1099 	break;
1100     case '2' :
1101 	cmdletter = 'd';
1102 	break;
1103     case '3' :
1104 	cmdletter = 'c';
1105 	break;
1106     case '4' :
1107 	cmdletter = 't';
1108 	break;
1109     case '6' :
1110 	cmdletter = 'e';
1111 	break;
1112     case '7' :
1113 	cmdletter = 'f';
1114 	break;
1115     case '8' :
1116 	cmdletter = 'i';
1117 	break;
1118     case '9' :
1119 	cmdletter = 'a';
1120 	break;
1121     default :
1122 	cmdletter = opt[0];
1123     }
1124 
1125     qfpos = (char *)vim_strchr(p_csqf, cmdletter);
1126     if (qfpos != NULL)
1127     {
1128 	qfpos++;
1129 	/* next symbol must be + or - */
1130 	if (strchr(CSQF_FLAGS, *qfpos) == NULL)
1131 	{
1132 	    char *nf = _("E469: invalid cscopequickfix flag %c for %c");
1133 	    char *buf = (char *)alloc((unsigned)strlen(nf));
1134 
1135 	    /* strlen will be enough because we use chars */
1136 	    if (buf != NULL)
1137 	    {
1138 		sprintf(buf, nf, *qfpos, *(qfpos-1));
1139 		(void)EMSG(buf);
1140 		vim_free(buf);
1141 	    }
1142 	    return FALSE;
1143 	}
1144 
1145 	if (*qfpos != '0'
1146 		&& apply_autocmds(EVENT_QUICKFIXCMDPRE, (char_u *)"cscope",
1147 					       curbuf->b_fname, TRUE, curbuf))
1148 	{
1149 # ifdef FEAT_EVAL
1150 	    if (aborting())
1151 		return FALSE;
1152 # endif
1153 	}
1154     }
1155 #endif
1156 
1157     /* create the actual command to send to cscope */
1158     cmd = cs_create_cmd(opt, pat);
1159     if (cmd == NULL)
1160 	return FALSE;
1161 
1162     nummatches = (int *)alloc(sizeof(int)*csinfo_size);
1163     if (nummatches == NULL)
1164     {
1165 	vim_free(cmd);
1166 	return FALSE;
1167     }
1168 
1169     /* Send query to all open connections, then count the total number
1170      * of matches so we can alloc all in one swell foop. */
1171     for (i = 0; i < csinfo_size; i++)
1172 	nummatches[i] = 0;
1173     totmatches = 0;
1174     for (i = 0; i < csinfo_size; i++)
1175     {
1176 	if (csinfo[i].fname == NULL || csinfo[i].to_fp == NULL)
1177 	    continue;
1178 
1179 	/* send cmd to cscope */
1180 	(void)fprintf(csinfo[i].to_fp, "%s\n", cmd);
1181 	(void)fflush(csinfo[i].to_fp);
1182 
1183 	nummatches[i] = cs_cnt_matches(i);
1184 
1185 	if (nummatches[i] > -1)
1186 	    totmatches += nummatches[i];
1187 
1188 	if (nummatches[i] == 0)
1189 	    (void)cs_read_prompt(i);
1190     }
1191     vim_free(cmd);
1192 
1193     if (totmatches == 0)
1194     {
1195 	char *nf = _("E259: no matches found for cscope query %s of %s");
1196 	char *buf;
1197 
1198 	if (!verbose)
1199 	{
1200 	    vim_free(nummatches);
1201 	    return FALSE;
1202 	}
1203 
1204 	buf = (char *)alloc((unsigned)(strlen(opt) + strlen(pat) + strlen(nf)));
1205 	if (buf == NULL)
1206 	    (void)EMSG(nf);
1207 	else
1208 	{
1209 	    sprintf(buf, nf, opt, pat);
1210 	    (void)EMSG(buf);
1211 	    vim_free(buf);
1212 	}
1213 	vim_free(nummatches);
1214 	return FALSE;
1215     }
1216 
1217 #ifdef FEAT_QUICKFIX
1218     if (qfpos != NULL && *qfpos != '0' && totmatches > 0)
1219     {
1220 	/* fill error list */
1221 	FILE	    *f;
1222 	char_u	    *tmp = vim_tempname('c', TRUE);
1223 	qf_info_T   *qi = NULL;
1224 	win_T	    *wp = NULL;
1225 
1226 	f = mch_fopen((char *)tmp, "w");
1227 	if (f == NULL)
1228 	    EMSG2(_(e_notopen), tmp);
1229 	else
1230 	{
1231 	    cs_file_results(f, nummatches);
1232 	    fclose(f);
1233 	    if (use_ll)	    /* Use location list */
1234 		wp = curwin;
1235 	    /* '-' starts a new error list */
1236 	    if (qf_init(wp, tmp, (char_u *)"%f%*\\t%l%*\\t%m",
1237 					  *qfpos == '-', cmdline, NULL) > 0)
1238 	    {
1239 		if (postponed_split != 0)
1240 		{
1241 		    (void)win_split(postponed_split > 0 ? postponed_split : 0,
1242 						       postponed_split_flags);
1243 		    RESET_BINDING(curwin);
1244 		    postponed_split = 0;
1245 		}
1246 
1247 		apply_autocmds(EVENT_QUICKFIXCMDPOST, (char_u *)"cscope",
1248 					       curbuf->b_fname, TRUE, curbuf);
1249 		if (use_ll)
1250 		    /*
1251 		     * In the location list window, use the displayed location
1252 		     * list. Otherwise, use the location list for the window.
1253 		     */
1254 		    qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)
1255 			?  wp->w_llist_ref : wp->w_llist;
1256 		qf_jump(qi, 0, 0, forceit);
1257 	    }
1258 	}
1259 	mch_remove(tmp);
1260 	vim_free(tmp);
1261 	vim_free(nummatches);
1262 	return TRUE;
1263     }
1264     else
1265 #endif /* FEAT_QUICKFIX */
1266     {
1267 	char **matches = NULL, **contexts = NULL;
1268 	int matched = 0;
1269 
1270 	/* read output */
1271 	cs_fill_results((char *)pat, totmatches, nummatches, &matches,
1272 							 &contexts, &matched);
1273 	vim_free(nummatches);
1274 	if (matches == NULL)
1275 	    return FALSE;
1276 
1277 	(void)cs_manage_matches(matches, contexts, matched, Store);
1278 
1279 	return do_tag((char_u *)pat, DT_CSCOPE, 0, forceit, verbose);
1280     }
1281 
1282 } /* cs_find_common */
1283 
1284 /*
1285  * Print help.
1286  */
1287     static int
1288 cs_help(exarg_T *eap UNUSED)
1289 {
1290     cscmd_T *cmdp = cs_cmds;
1291 
1292     (void)MSG_PUTS(_("cscope commands:\n"));
1293     while (cmdp->name != NULL)
1294     {
1295 	char *help = _(cmdp->help);
1296 	int  space_cnt = 30 - vim_strsize((char_u *)help);
1297 
1298 	/* Use %*s rather than %30s to ensure proper alignment in utf-8 */
1299 	if (space_cnt < 0)
1300 	    space_cnt = 0;
1301 	(void)smsg((char_u *)_("%-5s: %s%*s (Usage: %s)"),
1302 				      cmdp->name,
1303 				      help, space_cnt, " ",
1304 				      cmdp->usage);
1305 	if (strcmp(cmdp->name, "find") == 0)
1306 	    MSG_PUTS(_("\n"
1307 		       "       a: Find assignments to this symbol\n"
1308 		       "       c: Find functions calling this function\n"
1309 		       "       d: Find functions called by this function\n"
1310 		       "       e: Find this egrep pattern\n"
1311 		       "       f: Find this file\n"
1312 		       "       g: Find this definition\n"
1313 		       "       i: Find files #including this file\n"
1314 		       "       s: Find this C symbol\n"
1315 		       "       t: Find this text string\n"));
1316 
1317 	cmdp++;
1318     }
1319 
1320     wait_return(TRUE);
1321     return 0;
1322 } /* cs_help */
1323 
1324 
1325     static void
1326 clear_csinfo(int i)
1327 {
1328     csinfo[i].fname  = NULL;
1329     csinfo[i].ppath  = NULL;
1330     csinfo[i].flags  = NULL;
1331 #if defined(UNIX)
1332     csinfo[i].st_dev = (dev_t)0;
1333     csinfo[i].st_ino = (ino_t)0;
1334 #else
1335     csinfo[i].nVolume = 0;
1336     csinfo[i].nIndexHigh = 0;
1337     csinfo[i].nIndexLow = 0;
1338 #endif
1339     csinfo[i].pid    = 0;
1340     csinfo[i].fr_fp  = NULL;
1341     csinfo[i].to_fp  = NULL;
1342 #if defined(WIN32)
1343     csinfo[i].hProc = NULL;
1344 #endif
1345 }
1346 
1347 #ifndef UNIX
1348 static char *GetWin32Error(void);
1349 
1350     static char *
1351 GetWin32Error(void)
1352 {
1353     char *msg = NULL;
1354     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1355 	    NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
1356     if (msg != NULL)
1357     {
1358 	/* remove trailing \r\n */
1359 	char *pcrlf = strstr(msg, "\r\n");
1360 	if (pcrlf != NULL)
1361 	    *pcrlf = '\0';
1362     }
1363     return msg;
1364 }
1365 #endif
1366 
1367 /*
1368  * Insert a new cscope database filename into the filelist.
1369  */
1370     static int
1371 cs_insert_filelist(
1372     char *fname,
1373     char *ppath,
1374     char *flags,
1375     stat_T *sb UNUSED)
1376 {
1377     short	i, j;
1378 #ifndef UNIX
1379     BY_HANDLE_FILE_INFORMATION bhfi;
1380 
1381     switch (win32_fileinfo((char_u *)fname, &bhfi))
1382     {
1383 	case FILEINFO_ENC_FAIL:		/* enc_to_utf16() failed */
1384 	case FILEINFO_READ_FAIL:	/* CreateFile() failed */
1385 	    if (p_csverbose)
1386 	    {
1387 		char *cant_msg = _("E625: cannot open cscope database: %s");
1388 		char *winmsg = GetWin32Error();
1389 
1390 		if (winmsg != NULL)
1391 		{
1392 		    (void)EMSG2(cant_msg, winmsg);
1393 		    LocalFree(winmsg);
1394 		}
1395 		else
1396 		    /* subst filename if can't get error text */
1397 		    (void)EMSG2(cant_msg, fname);
1398 	    }
1399 	    return -1;
1400 
1401 	case FILEINFO_INFO_FAIL:    /* GetFileInformationByHandle() failed */
1402 	    if (p_csverbose)
1403 		(void)EMSG(_("E626: cannot get cscope database information"));
1404 	    return -1;
1405     }
1406 #endif
1407 
1408     i = -1; /* can be set to the index of an empty item in csinfo */
1409     for (j = 0; j < csinfo_size; j++)
1410     {
1411 	if (csinfo[j].fname != NULL
1412 #if defined(UNIX)
1413 	    && csinfo[j].st_dev == sb->st_dev && csinfo[j].st_ino == sb->st_ino
1414 #else
1415 	    /* compare pathnames first */
1416 	    && ((fullpathcmp((char_u *)csinfo[j].fname,
1417 			(char_u *)fname, FALSE) & FPC_SAME)
1418 		/* test index file attributes too */
1419 		|| (csinfo[j].nVolume == bhfi.dwVolumeSerialNumber
1420 		    && csinfo[j].nIndexHigh == bhfi.nFileIndexHigh
1421 		    && csinfo[j].nIndexLow == bhfi.nFileIndexLow))
1422 #endif
1423 	    )
1424 	{
1425 	    if (p_csverbose)
1426 		(void)EMSG(_("E568: duplicate cscope database not added"));
1427 	    return -1;
1428 	}
1429 
1430 	if (csinfo[j].fname == NULL && i == -1)
1431 	    i = j; /* remember first empty entry */
1432     }
1433 
1434     if (i == -1)
1435     {
1436 	i = csinfo_size;
1437 	if (csinfo_size == 0)
1438 	{
1439 	    /* First time allocation: allocate only 1 connection. It should
1440 	     * be enough for most users.  If more is needed, csinfo will be
1441 	     * reallocated. */
1442 	    csinfo_size = 1;
1443 	    csinfo = (csinfo_T *)alloc_clear(sizeof(csinfo_T));
1444 	}
1445 	else
1446 	{
1447 	    csinfo_T *t_csinfo = csinfo;
1448 
1449 	    /* Reallocate space for more connections. */
1450 	    csinfo_size *= 2;
1451 	    csinfo = vim_realloc(csinfo, sizeof(csinfo_T)*csinfo_size);
1452 	    if (csinfo == NULL)
1453 	    {
1454 		vim_free(t_csinfo);
1455 		csinfo_size = 0;
1456 	    }
1457 	}
1458 	if (csinfo == NULL)
1459 	    return -1;
1460 	for (j = csinfo_size/2; j < csinfo_size; j++)
1461 	    clear_csinfo(j);
1462     }
1463 
1464     if ((csinfo[i].fname = (char *)alloc((unsigned)strlen(fname)+1)) == NULL)
1465 	return -1;
1466 
1467     (void)strcpy(csinfo[i].fname, (const char *)fname);
1468 
1469     if (ppath != NULL)
1470     {
1471 	if ((csinfo[i].ppath = (char *)alloc((unsigned)strlen(ppath) + 1)) == NULL)
1472 	{
1473 	    VIM_CLEAR(csinfo[i].fname);
1474 	    return -1;
1475 	}
1476 	(void)strcpy(csinfo[i].ppath, (const char *)ppath);
1477     } else
1478 	csinfo[i].ppath = NULL;
1479 
1480     if (flags != NULL)
1481     {
1482 	if ((csinfo[i].flags = (char *)alloc((unsigned)strlen(flags) + 1)) == NULL)
1483 	{
1484 	    VIM_CLEAR(csinfo[i].fname);
1485 	    VIM_CLEAR(csinfo[i].ppath);
1486 	    return -1;
1487 	}
1488 	(void)strcpy(csinfo[i].flags, (const char *)flags);
1489     } else
1490 	csinfo[i].flags = NULL;
1491 
1492 #if defined(UNIX)
1493     csinfo[i].st_dev = sb->st_dev;
1494     csinfo[i].st_ino = sb->st_ino;
1495 
1496 #else
1497     csinfo[i].nVolume = bhfi.dwVolumeSerialNumber;
1498     csinfo[i].nIndexLow = bhfi.nFileIndexLow;
1499     csinfo[i].nIndexHigh = bhfi.nFileIndexHigh;
1500 #endif
1501     return i;
1502 } /* cs_insert_filelist */
1503 
1504 
1505 /*
1506  * Find cscope command in command table.
1507  */
1508     static cscmd_T *
1509 cs_lookup_cmd(exarg_T *eap)
1510 {
1511     cscmd_T *cmdp;
1512     char *stok;
1513     size_t len;
1514 
1515     if (eap->arg == NULL)
1516 	return NULL;
1517 
1518     /* Store length of eap->arg before it gets modified by strtok(). */
1519     eap_arg_len = (int)STRLEN(eap->arg);
1520 
1521     if ((stok = strtok((char *)(eap->arg), (const char *)" ")) == NULL)
1522 	return NULL;
1523 
1524     len = strlen(stok);
1525     for (cmdp = cs_cmds; cmdp->name != NULL; ++cmdp)
1526     {
1527 	if (strncmp((const char *)(stok), cmdp->name, len) == 0)
1528 	    return (cmdp);
1529     }
1530     return NULL;
1531 } /* cs_lookup_cmd */
1532 
1533 
1534 /*
1535  * Nuke em.
1536  */
1537     static int
1538 cs_kill(exarg_T *eap UNUSED)
1539 {
1540     char *stok;
1541     short i;
1542 
1543     if ((stok = strtok((char *)NULL, (const char *)" ")) == NULL)
1544     {
1545 	cs_usage_msg(Kill);
1546 	return CSCOPE_FAILURE;
1547     }
1548 
1549     /* only single digit positive and negative integers are allowed */
1550     if ((strlen(stok) < 2 && VIM_ISDIGIT((int)(stok[0])))
1551 	    || (strlen(stok) < 3 && stok[0] == '-'
1552 					      && VIM_ISDIGIT((int)(stok[1]))))
1553 	i = atoi(stok);
1554     else
1555     {
1556 	/* It must be part of a name.  We will try to find a match
1557 	 * within all the names in the csinfo data structure
1558 	 */
1559 	for (i = 0; i < csinfo_size; i++)
1560 	{
1561 	    if (csinfo[i].fname != NULL && strstr(csinfo[i].fname, stok))
1562 		break;
1563 	}
1564     }
1565 
1566     if ((i != -1) && (i >= csinfo_size || i < -1 || csinfo[i].fname == NULL))
1567     {
1568 	if (p_csverbose)
1569 	    (void)EMSG2(_("E261: cscope connection %s not found"), stok);
1570     }
1571     else
1572     {
1573 	if (i == -1)
1574 	{
1575 	    for (i = 0; i < csinfo_size; i++)
1576 	    {
1577 		if (csinfo[i].fname)
1578 		    cs_kill_execute(i, csinfo[i].fname);
1579 	    }
1580 	}
1581 	else
1582 	    cs_kill_execute(i, stok);
1583     }
1584 
1585     return 0;
1586 } /* cs_kill */
1587 
1588 
1589 /*
1590  * Actually kills a specific cscope connection.
1591  */
1592     static void
1593 cs_kill_execute(
1594     int i,	    /* cscope table index */
1595     char *cname)    /* cscope database name */
1596 {
1597     if (p_csverbose)
1598     {
1599 	msg_clr_eos();
1600 	(void)smsg_attr(HL_ATTR(HLF_R) | MSG_HIST,
1601 		(char_u *)_("cscope connection %s closed"), cname);
1602     }
1603     cs_release_csp(i, TRUE);
1604 }
1605 
1606 
1607 /*
1608  * Convert the cscope output into a ctags style entry (as might be found
1609  * in a ctags tags file).  there's one catch though: cscope doesn't tell you
1610  * the type of the tag you are looking for.  for example, in Darren Hiebert's
1611  * ctags (the one that comes with vim), #define's use a line number to find the
1612  * tag in a file while function definitions use a regexp search pattern.
1613  *
1614  * I'm going to always use the line number because cscope does something
1615  * quirky (and probably other things i don't know about):
1616  *
1617  *     if you have "#  define" in your source file, which is
1618  *     perfectly legal, cscope thinks you have "#define".  this
1619  *     will result in a failed regexp search. :(
1620  *
1621  * Besides, even if this particular case didn't happen, the search pattern
1622  * would still have to be modified to escape all the special regular expression
1623  * characters to comply with ctags formatting.
1624  */
1625     static char *
1626 cs_make_vim_style_matches(
1627     char *fname,
1628     char *slno,
1629     char *search,
1630     char *tagstr)
1631 {
1632     /* vim style is ctags:
1633      *
1634      *	    <tagstr>\t<filename>\t<linenum_or_search>"\t<extra>
1635      *
1636      * but as mentioned above, we'll always use the line number and
1637      * put the search pattern (if one exists) as "extra"
1638      *
1639      * buf is used as part of vim's method of handling tags, and
1640      * (i think) vim frees it when you pop your tags and get replaced
1641      * by new ones on the tag stack.
1642      */
1643     char *buf;
1644     int amt;
1645 
1646     if (search != NULL)
1647     {
1648 	amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + strlen(search)+6);
1649 	if ((buf = (char *)alloc(amt)) == NULL)
1650 	    return NULL;
1651 
1652 	(void)sprintf(buf, "%s\t%s\t%s;\"\t%s", tagstr, fname, slno, search);
1653     }
1654     else
1655     {
1656 	amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + 5);
1657 	if ((buf = (char *)alloc(amt)) == NULL)
1658 	    return NULL;
1659 
1660 	(void)sprintf(buf, "%s\t%s\t%s;\"", tagstr, fname, slno);
1661     }
1662 
1663     return buf;
1664 } /* cs_make_vim_style_matches */
1665 
1666 
1667 /*
1668  * This is kind of hokey, but i don't see an easy way round this.
1669  *
1670  * Store: keep a ptr to the (malloc'd) memory of matches originally
1671  * generated from cs_find().  the matches are originally lines directly
1672  * from cscope output, but transformed to look like something out of a
1673  * ctags.  see cs_make_vim_style_matches for more details.
1674  *
1675  * Get: used only from cs_fgets(), this simulates a vim_fgets() to return
1676  * the next line from the cscope output.  it basically keeps track of which
1677  * lines have been "used" and returns the next one.
1678  *
1679  * Free: frees up everything and resets
1680  *
1681  * Print: prints the tags
1682  */
1683     static char *
1684 cs_manage_matches(
1685     char **matches,
1686     char **contexts,
1687     int totmatches,
1688     mcmd_e cmd)
1689 {
1690     static char **mp = NULL;
1691     static char **cp = NULL;
1692     static int cnt = -1;
1693     static int next = -1;
1694     char *p = NULL;
1695 
1696     switch (cmd)
1697     {
1698     case Store:
1699 	assert(matches != NULL);
1700 	assert(totmatches > 0);
1701 	if (mp != NULL || cp != NULL)
1702 	    (void)cs_manage_matches(NULL, NULL, -1, Free);
1703 	mp = matches;
1704 	cp = contexts;
1705 	cnt = totmatches;
1706 	next = 0;
1707 	break;
1708     case Get:
1709 	if (next >= cnt)
1710 	    return NULL;
1711 
1712 	p = mp[next];
1713 	next++;
1714 	break;
1715     case Free:
1716 	if (mp != NULL)
1717 	{
1718 	    if (cnt > 0)
1719 		while (cnt--)
1720 		{
1721 		    vim_free(mp[cnt]);
1722 		    if (cp != NULL)
1723 			vim_free(cp[cnt]);
1724 		}
1725 	    vim_free(mp);
1726 	    vim_free(cp);
1727 	}
1728 	mp = NULL;
1729 	cp = NULL;
1730 	cnt = 0;
1731 	next = 0;
1732 	break;
1733     case Print:
1734 	cs_print_tags_priv(mp, cp, cnt);
1735 	break;
1736     default:	/* should not reach here */
1737 	IEMSG(_("E570: fatal error in cs_manage_matches"));
1738 	return NULL;
1739     }
1740 
1741     return p;
1742 } /* cs_manage_matches */
1743 
1744 
1745 /*
1746  * Parse cscope output.
1747  */
1748     static char *
1749 cs_parse_results(
1750     int cnumber,
1751     char *buf,
1752     int bufsize,
1753     char **context,
1754     char **linenumber,
1755     char **search)
1756 {
1757     int ch;
1758     char *p;
1759     char *name;
1760 
1761     if (fgets(buf, bufsize, csinfo[cnumber].fr_fp) == NULL)
1762     {
1763 	if (feof(csinfo[cnumber].fr_fp))
1764 	    errno = EIO;
1765 
1766 	cs_reading_emsg(cnumber);
1767 
1768 	return NULL;
1769     }
1770 
1771 	/* If the line's too long for the buffer, discard it. */
1772     if ((p = strchr(buf, '\n')) == NULL)
1773     {
1774 	while ((ch = getc(csinfo[cnumber].fr_fp)) != EOF && ch != '\n')
1775 	    ;
1776 	return NULL;
1777     }
1778     *p = '\0';
1779 
1780     /*
1781      * cscope output is in the following format:
1782      *
1783      *	<filename> <context> <line number> <pattern>
1784      */
1785     if ((name = strtok((char *)buf, (const char *)" ")) == NULL)
1786 	return NULL;
1787     if ((*context = strtok(NULL, (const char *)" ")) == NULL)
1788 	return NULL;
1789     if ((*linenumber = strtok(NULL, (const char *)" ")) == NULL)
1790 	return NULL;
1791     *search = *linenumber + strlen(*linenumber) + 1;	/* +1 to skip \0 */
1792 
1793     /* --- nvi ---
1794      * If the file is older than the cscope database, that is,
1795      * the database was built since the file was last modified,
1796      * or there wasn't a search string, use the line number.
1797      */
1798     if (strcmp(*search, "<unknown>") == 0)
1799 	*search = NULL;
1800 
1801     name = cs_resolve_file(cnumber, name);
1802     return name;
1803 }
1804 
1805 #ifdef FEAT_QUICKFIX
1806 /*
1807  * Write cscope find results to file.
1808  */
1809     static void
1810 cs_file_results(FILE *f, int *nummatches_a)
1811 {
1812     int i, j;
1813     char *buf;
1814     char *search, *slno;
1815     char *fullname;
1816     char *cntx;
1817     char *context;
1818 
1819     buf = (char *)alloc(CSREAD_BUFSIZE);
1820     if (buf == NULL)
1821 	return;
1822 
1823     for (i = 0; i < csinfo_size; i++)
1824     {
1825 	if (nummatches_a[i] < 1)
1826 	    continue;
1827 
1828 	for (j = 0; j < nummatches_a[i]; j++)
1829 	{
1830 	   if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1831 			   &slno, &search)) == NULL)
1832 	       continue;
1833 
1834 	   context = (char *)alloc((unsigned)strlen(cntx)+5);
1835 	   if (context == NULL)
1836 	       continue;
1837 
1838 	   if (strcmp(cntx, "<global>")==0)
1839 	       strcpy(context, "<<global>>");
1840 	   else
1841 	       sprintf(context, "<<%s>>", cntx);
1842 
1843 	   if (search == NULL)
1844 	       fprintf(f, "%s\t%s\t%s\n", fullname, slno, context);
1845 	   else
1846 	       fprintf(f, "%s\t%s\t%s %s\n", fullname, slno, context, search);
1847 
1848 	   vim_free(context);
1849 	   vim_free(fullname);
1850 	} /* for all matches */
1851 
1852 	(void)cs_read_prompt(i);
1853 
1854     } /* for all cscope connections */
1855     vim_free(buf);
1856 }
1857 #endif
1858 
1859 /*
1860  * Get parsed cscope output and calls cs_make_vim_style_matches to convert
1861  * into ctags format.
1862  * When there are no matches sets "*matches_p" to NULL.
1863  */
1864     static void
1865 cs_fill_results(
1866     char *tagstr,
1867     int totmatches,
1868     int *nummatches_a,
1869     char ***matches_p,
1870     char ***cntxts_p,
1871     int *matched)
1872 {
1873     int i, j;
1874     char *buf;
1875     char *search, *slno;
1876     int totsofar = 0;
1877     char **matches = NULL;
1878     char **cntxts = NULL;
1879     char *fullname;
1880     char *cntx;
1881 
1882     assert(totmatches > 0);
1883 
1884     buf = (char *)alloc(CSREAD_BUFSIZE);
1885     if (buf == NULL)
1886 	return;
1887 
1888     if ((matches = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1889 	goto parse_out;
1890     if ((cntxts = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1891 	goto parse_out;
1892 
1893     for (i = 0; i < csinfo_size; i++)
1894     {
1895 	if (nummatches_a[i] < 1)
1896 	    continue;
1897 
1898 	for (j = 0; j < nummatches_a[i]; j++)
1899 	{
1900 	   if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1901 			   &slno, &search)) == NULL)
1902 		continue;
1903 
1904 	    matches[totsofar] = cs_make_vim_style_matches(fullname, slno,
1905 							  search, tagstr);
1906 
1907 	    vim_free(fullname);
1908 
1909 	    if (strcmp(cntx, "<global>") == 0)
1910 		cntxts[totsofar] = NULL;
1911 	    else
1912 		/* note: if vim_strsave returns NULL, then the context
1913 		 * will be "<global>", which is misleading.
1914 		 */
1915 		cntxts[totsofar] = (char *)vim_strsave((char_u *)cntx);
1916 
1917 	    if (matches[totsofar] != NULL)
1918 		totsofar++;
1919 
1920 	} /* for all matches */
1921 
1922 	(void)cs_read_prompt(i);
1923 
1924     } /* for all cscope connections */
1925 
1926 parse_out:
1927     if (totsofar == 0)
1928     {
1929 	/* No matches, free the arrays and return NULL in "*matches_p". */
1930 	VIM_CLEAR(matches);
1931 	VIM_CLEAR(cntxts);
1932     }
1933     *matched = totsofar;
1934     *matches_p = matches;
1935     *cntxts_p = cntxts;
1936 
1937     vim_free(buf);
1938 } /* cs_fill_results */
1939 
1940 
1941 /* get the requested path components */
1942     static char *
1943 cs_pathcomponents(char *path)
1944 {
1945     int		i;
1946     char	*s;
1947 
1948     if (p_cspc == 0)
1949 	return path;
1950 
1951     s = path + strlen(path) - 1;
1952     for (i = 0; i < p_cspc; ++i)
1953 	while (s > path && *--s != '/'
1954 #ifdef WIN32
1955 		&& *--s != '\\'
1956 #endif
1957 		)
1958 	    ;
1959     if ((s > path && *s == '/')
1960 #ifdef WIN32
1961 	|| (s > path && *s == '\\')
1962 #endif
1963 	    )
1964 	++s;
1965     return s;
1966 }
1967 
1968 /*
1969  * Called from cs_manage_matches().
1970  */
1971     static void
1972 cs_print_tags_priv(char **matches, char **cntxts, int num_matches)
1973 {
1974     char	*buf = NULL;
1975     char	*t_buf;
1976     int		bufsize = 0; /* Track available bufsize */
1977     int		newsize = 0;
1978     char	*ptag;
1979     char	*fname, *lno, *extra, *tbuf;
1980     int		i, idx, num;
1981     char	*globalcntx = "GLOBAL";
1982     char	*cntxformat = " <<%s>>";
1983     char	*context;
1984     char	*cstag_msg = _("Cscope tag: %s");
1985     char	*csfmt_str = "%4d %6s  ";
1986 
1987     assert(num_matches > 0);
1988 
1989     if ((tbuf = (char *)alloc((unsigned)strlen(matches[0]) + 1)) == NULL)
1990 	return;
1991 
1992     strcpy(tbuf, matches[0]);
1993     ptag = strtok(tbuf, "\t");
1994     if (ptag == NULL)
1995     {
1996 	vim_free(tbuf);
1997 	return;
1998     }
1999 
2000     newsize = (int)(strlen(cstag_msg) + strlen(ptag));
2001     buf = (char *)alloc(newsize);
2002     if (buf != NULL)
2003     {
2004 	bufsize = newsize;
2005 	(void)sprintf(buf, cstag_msg, ptag);
2006 	MSG_PUTS_ATTR(buf, HL_ATTR(HLF_T));
2007     }
2008 
2009     vim_free(tbuf);
2010 
2011     MSG_PUTS_ATTR(_("\n   #   line"), HL_ATTR(HLF_T));    /* strlen is 7 */
2012     msg_advance(msg_col + 2);
2013     MSG_PUTS_ATTR(_("filename / context / line\n"), HL_ATTR(HLF_T));
2014 
2015     num = 1;
2016     for (i = 0; i < num_matches; i++)
2017     {
2018 	idx = i;
2019 
2020 	/* if we really wanted to, we could avoid this malloc and strcpy
2021 	 * by parsing matches[i] on the fly and placing stuff into buf
2022 	 * directly, but that's too much of a hassle
2023 	 */
2024 	if ((tbuf = (char *)alloc((unsigned)strlen(matches[idx]) + 1)) == NULL)
2025 	    continue;
2026 	(void)strcpy(tbuf, matches[idx]);
2027 
2028 	if (strtok(tbuf, (const char *)"\t") == NULL
2029 		|| (fname = strtok(NULL, (const char *)"\t")) == NULL
2030 		|| (lno = strtok(NULL, (const char *)"\t")) == NULL)
2031 	{
2032 	    vim_free(tbuf);
2033 	    continue;
2034 	}
2035 	extra = strtok(NULL, (const char *)"\t");
2036 
2037 	lno[strlen(lno)-2] = '\0';  /* ignore ;" at the end */
2038 
2039 	/* hopefully 'num' (num of matches) will be less than 10^16 */
2040 	newsize = (int)(strlen(csfmt_str) + 16 + strlen(lno));
2041 	if (bufsize < newsize)
2042 	{
2043 	    t_buf = buf;
2044 	    buf = (char *)vim_realloc(buf, newsize);
2045 	    if (buf == NULL)
2046 	    {
2047 		bufsize = 0;
2048 		vim_free(t_buf);
2049 	    }
2050 	    else
2051 		bufsize = newsize;
2052 	}
2053 	if (buf != NULL)
2054 	{
2055 	    /* csfmt_str = "%4d %6s  "; */
2056 	    (void)sprintf(buf, csfmt_str, num, lno);
2057 	    MSG_PUTS_ATTR(buf, HL_ATTR(HLF_CM));
2058 	}
2059 	MSG_PUTS_LONG_ATTR(cs_pathcomponents(fname), HL_ATTR(HLF_CM));
2060 
2061 	/* compute the required space for the context */
2062 	if (cntxts[idx] != NULL)
2063 	    context = cntxts[idx];
2064 	else
2065 	    context = globalcntx;
2066 	newsize = (int)(strlen(context) + strlen(cntxformat));
2067 
2068 	if (bufsize < newsize)
2069 	{
2070 	    t_buf = buf;
2071 	    buf = (char *)vim_realloc(buf, newsize);
2072 	    if (buf == NULL)
2073 	    {
2074 		bufsize = 0;
2075 		vim_free(t_buf);
2076 	    }
2077 	    else
2078 		bufsize = newsize;
2079 	}
2080 	if (buf != NULL)
2081 	{
2082 	    (void)sprintf(buf, cntxformat, context);
2083 
2084 	    /* print the context only if it fits on the same line */
2085 	    if (msg_col + (int)strlen(buf) >= (int)Columns)
2086 		msg_putchar('\n');
2087 	    msg_advance(12);
2088 	    MSG_PUTS_LONG(buf);
2089 	    msg_putchar('\n');
2090 	}
2091 	if (extra != NULL)
2092 	{
2093 	    msg_advance(13);
2094 	    MSG_PUTS_LONG(extra);
2095 	}
2096 
2097 	vim_free(tbuf); /* only after printing extra due to strtok use */
2098 
2099 	if (msg_col)
2100 	    msg_putchar('\n');
2101 
2102 	ui_breakcheck();
2103 	if (got_int)
2104 	{
2105 	    got_int = FALSE;	/* don't print any more matches */
2106 	    break;
2107 	}
2108 
2109 	num++;
2110     } /* for all matches */
2111 
2112     vim_free(buf);
2113 } /* cs_print_tags_priv */
2114 
2115 
2116 /*
2117  * Read a cscope prompt (basically, skip over the ">> ").
2118  */
2119     static int
2120 cs_read_prompt(int i)
2121 {
2122     int		ch;
2123     char	*buf = NULL; /* buffer for possible error message from cscope */
2124     int		bufpos = 0;
2125     char	*cs_emsg;
2126     int		maxlen;
2127     static char *eprompt = "Press the RETURN key to continue:";
2128     int		epromptlen = (int)strlen(eprompt);
2129     int		n;
2130 
2131     cs_emsg = _("E609: Cscope error: %s");
2132     /* compute maximum allowed len for Cscope error message */
2133     maxlen = (int)(IOSIZE - strlen(cs_emsg));
2134 
2135     for (;;)
2136     {
2137 	while ((ch = getc(csinfo[i].fr_fp)) != EOF && ch != CSCOPE_PROMPT[0])
2138 	    /* if there is room and char is printable */
2139 	    if (bufpos < maxlen - 1 && vim_isprintc(ch))
2140 	    {
2141 		if (buf == NULL) /* lazy buffer allocation */
2142 		    buf = (char *)alloc(maxlen);
2143 		if (buf != NULL)
2144 		{
2145 		    /* append character to the message */
2146 		    buf[bufpos++] = ch;
2147 		    buf[bufpos] = NUL;
2148 		    if (bufpos >= epromptlen
2149 			    && strcmp(&buf[bufpos - epromptlen], eprompt) == 0)
2150 		    {
2151 			/* remove eprompt from buf */
2152 			buf[bufpos - epromptlen] = NUL;
2153 
2154 			/* print message to user */
2155 			(void)EMSG2(cs_emsg, buf);
2156 
2157 			/* send RETURN to cscope */
2158 			(void)putc('\n', csinfo[i].to_fp);
2159 			(void)fflush(csinfo[i].to_fp);
2160 
2161 			/* clear buf */
2162 			bufpos = 0;
2163 			buf[bufpos] = NUL;
2164 		    }
2165 		}
2166 	    }
2167 
2168 	for (n = 0; n < (int)strlen(CSCOPE_PROMPT); ++n)
2169 	{
2170 	    if (n > 0)
2171 		ch = getc(csinfo[i].fr_fp);
2172 	    if (ch == EOF)
2173 	    {
2174 		PERROR("cs_read_prompt EOF");
2175 		if (buf != NULL && buf[0] != NUL)
2176 		    (void)EMSG2(cs_emsg, buf);
2177 		else if (p_csverbose)
2178 		    cs_reading_emsg(i); /* don't have additional information */
2179 		cs_release_csp(i, TRUE);
2180 		vim_free(buf);
2181 		return CSCOPE_FAILURE;
2182 	    }
2183 
2184 	    if (ch != CSCOPE_PROMPT[n])
2185 	    {
2186 		ch = EOF;
2187 		break;
2188 	    }
2189 	}
2190 
2191 	if (ch == EOF)
2192 	    continue;	    /* didn't find the prompt */
2193 	break;		    /* did find the prompt */
2194     }
2195 
2196     vim_free(buf);
2197     return CSCOPE_SUCCESS;
2198 }
2199 
2200 #if defined(UNIX) && defined(SIGALRM)
2201 /*
2202  * Used to catch and ignore SIGALRM below.
2203  */
2204     static RETSIGTYPE
2205 sig_handler SIGDEFARG(sigarg)
2206 {
2207     /* do nothing */
2208     SIGRETURN;
2209 }
2210 #endif
2211 
2212 /*
2213  * Does the actual free'ing for the cs ptr with an optional flag of whether
2214  * or not to free the filename.  Called by cs_kill and cs_reset.
2215  */
2216     static void
2217 cs_release_csp(int i, int freefnpp)
2218 {
2219     /*
2220      * Trying to exit normally (not sure whether it is fit to UNIX cscope
2221      */
2222     if (csinfo[i].to_fp != NULL)
2223     {
2224 	(void)fputs("q\n", csinfo[i].to_fp);
2225 	(void)fflush(csinfo[i].to_fp);
2226     }
2227 #if defined(UNIX)
2228     {
2229 	int waitpid_errno;
2230 	int pstat;
2231 	pid_t pid;
2232 
2233 # if defined(HAVE_SIGACTION)
2234 	struct sigaction sa, old;
2235 
2236 	/* Use sigaction() to limit the waiting time to two seconds. */
2237 	sigemptyset(&sa.sa_mask);
2238 	sa.sa_handler = sig_handler;
2239 #  ifdef SA_NODEFER
2240 	sa.sa_flags = SA_NODEFER;
2241 #  else
2242 	sa.sa_flags = 0;
2243 #  endif
2244 	sigaction(SIGALRM, &sa, &old);
2245 	alarm(2); /* 2 sec timeout */
2246 
2247 	/* Block until cscope exits or until timer expires */
2248 	pid = waitpid(csinfo[i].pid, &pstat, 0);
2249 	waitpid_errno = errno;
2250 
2251 	/* cancel pending alarm if still there and restore signal */
2252 	alarm(0);
2253 	sigaction(SIGALRM, &old, NULL);
2254 # else
2255 	int waited;
2256 
2257 	/* Can't use sigaction(), loop for two seconds.  First yield the CPU
2258 	 * to give cscope a chance to exit quickly. */
2259 	sleep(0);
2260 	for (waited = 0; waited < 40; ++waited)
2261 	{
2262 	    pid = waitpid(csinfo[i].pid, &pstat, WNOHANG);
2263 	    waitpid_errno = errno;
2264 	    if (pid != 0)
2265 		break;  /* break unless the process is still running */
2266 	    mch_delay(50L, FALSE); /* sleep 50 ms */
2267 	}
2268 # endif
2269 	/*
2270 	 * If the cscope process is still running: kill it.
2271 	 * Safety check: If the PID would be zero here, the entire X session
2272 	 * would be killed.  -1 and 1 are dangerous as well.
2273 	 */
2274 	if (pid < 0 && csinfo[i].pid > 1)
2275 	{
2276 # ifdef ECHILD
2277 	    int alive = TRUE;
2278 
2279 	    if (waitpid_errno == ECHILD)
2280 	    {
2281 		/*
2282 		 * When using 'vim -g', vim is forked and cscope process is
2283 		 * no longer a child process but a sibling.  So waitpid()
2284 		 * fails with errno being ECHILD (No child processes).
2285 		 * Don't send SIGKILL to cscope immediately but wait
2286 		 * (polling) for it to exit normally as result of sending
2287 		 * the "q" command, hence giving it a chance to clean up
2288 		 * its temporary files.
2289 		 */
2290 		int waited;
2291 
2292 		sleep(0);
2293 		for (waited = 0; waited < 40; ++waited)
2294 		{
2295 		    /* Check whether cscope process is still alive */
2296 		    if (kill(csinfo[i].pid, 0) != 0)
2297 		    {
2298 			alive = FALSE; /* cscope process no longer exists */
2299 			break;
2300 		    }
2301 		    mch_delay(50L, FALSE); /* sleep 50ms */
2302 		}
2303 	    }
2304 	    if (alive)
2305 # endif
2306 	    {
2307 		kill(csinfo[i].pid, SIGKILL);
2308 		(void)waitpid(csinfo[i].pid, &pstat, 0);
2309 	    }
2310 	}
2311     }
2312 #else  /* !UNIX */
2313     if (csinfo[i].hProc != NULL)
2314     {
2315 	/* Give cscope a chance to exit normally */
2316 	if (WaitForSingleObject(csinfo[i].hProc, 1000) == WAIT_TIMEOUT)
2317 	    TerminateProcess(csinfo[i].hProc, 0);
2318 	CloseHandle(csinfo[i].hProc);
2319     }
2320 #endif
2321 
2322     if (csinfo[i].fr_fp != NULL)
2323 	(void)fclose(csinfo[i].fr_fp);
2324     if (csinfo[i].to_fp != NULL)
2325 	(void)fclose(csinfo[i].to_fp);
2326 
2327     if (freefnpp)
2328     {
2329 	vim_free(csinfo[i].fname);
2330 	vim_free(csinfo[i].ppath);
2331 	vim_free(csinfo[i].flags);
2332     }
2333 
2334     clear_csinfo(i);
2335 } /* cs_release_csp */
2336 
2337 
2338 /*
2339  * Calls cs_kill on all cscope connections then reinits.
2340  */
2341     static int
2342 cs_reset(exarg_T *eap UNUSED)
2343 {
2344     char	**dblist = NULL, **pplist = NULL, **fllist = NULL;
2345     int	i;
2346     char buf[20]; /* for sprintf " (#%d)" */
2347 
2348     if (csinfo_size == 0)
2349 	return CSCOPE_SUCCESS;
2350 
2351     /* malloc our db and ppath list */
2352     dblist = (char **)alloc(csinfo_size * sizeof(char *));
2353     pplist = (char **)alloc(csinfo_size * sizeof(char *));
2354     fllist = (char **)alloc(csinfo_size * sizeof(char *));
2355     if (dblist == NULL || pplist == NULL || fllist == NULL)
2356     {
2357 	vim_free(dblist);
2358 	vim_free(pplist);
2359 	vim_free(fllist);
2360 	return CSCOPE_FAILURE;
2361     }
2362 
2363     for (i = 0; i < csinfo_size; i++)
2364     {
2365 	dblist[i] = csinfo[i].fname;
2366 	pplist[i] = csinfo[i].ppath;
2367 	fllist[i] = csinfo[i].flags;
2368 	if (csinfo[i].fname != NULL)
2369 	    cs_release_csp(i, FALSE);
2370     }
2371 
2372     /* rebuild the cscope connection list */
2373     for (i = 0; i < csinfo_size; i++)
2374     {
2375 	if (dblist[i] != NULL)
2376 	{
2377 	    cs_add_common(dblist[i], pplist[i], fllist[i]);
2378 	    if (p_csverbose)
2379 	    {
2380 		/* don't use smsg_attr() because we want to display the
2381 		 * connection number in the same line as
2382 		 * "Added cscope database..."
2383 		 */
2384 		sprintf(buf, " (#%d)", i);
2385 		MSG_PUTS_ATTR(buf, HL_ATTR(HLF_R));
2386 	    }
2387 	}
2388 	vim_free(dblist[i]);
2389 	vim_free(pplist[i]);
2390 	vim_free(fllist[i]);
2391     }
2392     vim_free(dblist);
2393     vim_free(pplist);
2394     vim_free(fllist);
2395 
2396     if (p_csverbose)
2397 	MSG_ATTR(_("All cscope databases reset"), HL_ATTR(HLF_R) | MSG_HIST);
2398     return CSCOPE_SUCCESS;
2399 } /* cs_reset */
2400 
2401 
2402 /*
2403  * Construct the full pathname to a file found in the cscope database.
2404  * (Prepends ppath, if there is one and if it's not already prepended,
2405  * otherwise just uses the name found.)
2406  *
2407  * We need to prepend the prefix because on some cscope's (e.g., the one that
2408  * ships with Solaris 2.6), the output never has the prefix prepended.
2409  * Contrast this with my development system (Digital Unix), which does.
2410  */
2411     static char *
2412 cs_resolve_file(int i, char *name)
2413 {
2414     char	*fullname;
2415     int		len;
2416     char_u	*csdir = NULL;
2417 
2418     /*
2419      * Ppath is freed when we destroy the cscope connection.
2420      * Fullname is freed after cs_make_vim_style_matches, after it's been
2421      * copied into the tag buffer used by Vim.
2422      */
2423     len = (int)(strlen(name) + 2);
2424     if (csinfo[i].ppath != NULL)
2425 	len += (int)strlen(csinfo[i].ppath);
2426     else if (p_csre && csinfo[i].fname != NULL)
2427     {
2428 	/* If 'cscoperelative' is set and ppath is not set, use cscope.out
2429 	 * path in path resolution. */
2430 	csdir = alloc(MAXPATHL);
2431 	if (csdir != NULL)
2432 	{
2433 	    vim_strncpy(csdir, (char_u *)csinfo[i].fname,
2434 					  gettail((char_u *)csinfo[i].fname)
2435 						 - (char_u *)csinfo[i].fname);
2436 	    len += (int)STRLEN(csdir);
2437 	}
2438     }
2439 
2440     /* Note/example: this won't work if the cscope output already starts
2441      * "../.." and the prefix path is also "../..".  if something like this
2442      * happens, you are screwed up and need to fix how you're using cscope. */
2443     if (csinfo[i].ppath != NULL
2444 	    && (strncmp(name, csinfo[i].ppath, strlen(csinfo[i].ppath)) != 0)
2445 	    && (name[0] != '/')
2446 #ifdef WIN32
2447 	    && name[0] != '\\' && name[1] != ':'
2448 #endif
2449        )
2450     {
2451 	if ((fullname = (char *)alloc(len)) != NULL)
2452 	    (void)sprintf(fullname, "%s/%s", csinfo[i].ppath, name);
2453     }
2454     else if (csdir != NULL && csinfo[i].fname != NULL && *csdir != NUL)
2455     {
2456 	/* Check for csdir to be non empty to avoid empty path concatenated to
2457 	 * cscope output. */
2458 	fullname = (char *)concat_fnames(csdir, (char_u *)name, TRUE);
2459     }
2460     else
2461     {
2462 	fullname = (char *)vim_strsave((char_u *)name);
2463     }
2464 
2465     vim_free(csdir);
2466     return fullname;
2467 }
2468 
2469 
2470 /*
2471  * Show all cscope connections.
2472  */
2473     static int
2474 cs_show(exarg_T *eap UNUSED)
2475 {
2476     short i;
2477     if (cs_cnt_connections() == 0)
2478 	MSG_PUTS(_("no cscope connections\n"));
2479     else
2480     {
2481 	MSG_PUTS_ATTR(
2482 	    _(" # pid    database name                       prepend path\n"),
2483 	    HL_ATTR(HLF_T));
2484 	for (i = 0; i < csinfo_size; i++)
2485 	{
2486 	    if (csinfo[i].fname == NULL)
2487 		continue;
2488 
2489 	    if (csinfo[i].ppath != NULL)
2490 		(void)smsg((char_u *)"%2d %-5ld  %-34s  %-32s",
2491 		    i, (long)csinfo[i].pid, csinfo[i].fname, csinfo[i].ppath);
2492 	    else
2493 		(void)smsg((char_u *)"%2d %-5ld  %-34s  <none>",
2494 			   i, (long)csinfo[i].pid, csinfo[i].fname);
2495 	}
2496     }
2497 
2498     wait_return(TRUE);
2499     return CSCOPE_SUCCESS;
2500 } /* cs_show */
2501 
2502 
2503 /*
2504  * Only called when VIM exits to quit any cscope sessions.
2505  */
2506     void
2507 cs_end(void)
2508 {
2509     int i;
2510 
2511     for (i = 0; i < csinfo_size; i++)
2512 	cs_release_csp(i, TRUE);
2513     vim_free(csinfo);
2514     csinfo_size = 0;
2515 }
2516 
2517 #endif	/* FEAT_CSCOPE */
2518 
2519 /* the end */
2520