Add clipboard support in non-GUI mode
[MacVim.git] / src / if_cscope.c
blob4dff11631eab7df00c7821974c6c649bd1b21b0b
1 /* vi:set ts=8 sts=4 sw=4:
3 * CSCOPE support for Vim added by Andy Kahn <kahn@zk3.dec.com>
4 * Ported to Win32 by Sergey Khorev <sergey.khorev@gmail.com>
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.
9 * See README.txt for an overview of the Vim source code.
12 #include "vim.h"
14 #if defined(FEAT_CSCOPE) || defined(PROTO)
16 #include <string.h>
17 #include <errno.h>
18 #include <assert.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #if defined(UNIX)
22 # include <sys/wait.h>
23 #else
24 /* not UNIX, must be WIN32 */
25 # include "vimio.h"
26 #endif
27 #include "if_cscope.h"
29 static void cs_usage_msg __ARGS((csid_e x));
30 static int cs_add __ARGS((exarg_T *eap));
31 static void cs_stat_emsg __ARGS((char *fname));
32 static int cs_add_common __ARGS((char *, char *, char *));
33 static int cs_check_for_connections __ARGS((void));
34 static int cs_check_for_tags __ARGS((void));
35 static int cs_cnt_connections __ARGS((void));
36 static void cs_reading_emsg __ARGS((int idx));
37 static int cs_cnt_matches __ARGS((int idx));
38 static char * cs_create_cmd __ARGS((char *csoption, char *pattern));
39 static int cs_create_connection __ARGS((int i));
40 static void do_cscope_general __ARGS((exarg_T *eap, int make_split));
41 #ifdef FEAT_QUICKFIX
42 static void cs_file_results __ARGS((FILE *, int *));
43 #endif
44 static void cs_fill_results __ARGS((char *, int , int *, char ***,
45 char ***, int *));
46 static int cs_find __ARGS((exarg_T *eap));
47 static int cs_find_common __ARGS((char *opt, char *pat, int, int, int));
48 static int cs_help __ARGS((exarg_T *eap));
49 static void cs_init __ARGS((void));
50 static void clear_csinfo __ARGS((int i));
51 static int cs_insert_filelist __ARGS((char *, char *, char *,
52 struct stat *));
53 static int cs_kill __ARGS((exarg_T *eap));
54 static void cs_kill_execute __ARGS((int, char *));
55 static cscmd_T * cs_lookup_cmd __ARGS((exarg_T *eap));
56 static char * cs_make_vim_style_matches __ARGS((char *, char *,
57 char *, char *));
58 static char * cs_manage_matches __ARGS((char **, char **, int, mcmd_e));
59 static char * cs_parse_results __ARGS((int cnumber, char *buf, int bufsize, char **context, char **linenumber, char **search));
60 static char * cs_pathcomponents __ARGS((char *path));
61 static void cs_print_tags_priv __ARGS((char **, char **, int));
62 static int cs_read_prompt __ARGS((int));
63 static void cs_release_csp __ARGS((int, int freefnpp));
64 static int cs_reset __ARGS((exarg_T *eap));
65 static char * cs_resolve_file __ARGS((int, char *));
66 static int cs_show __ARGS((exarg_T *eap));
69 static csinfo_T csinfo[CSCOPE_MAX_CONNECTIONS];
70 static int eap_arg_len; /* length of eap->arg, set in
71 cs_lookup_cmd() */
72 static cscmd_T cs_cmds[] =
74 { "add", cs_add,
75 N_("Add a new database"), "add file|dir [pre-path] [flags]", 0 },
76 { "find", cs_find,
77 N_("Query for a pattern"), "find c|d|e|f|g|i|s|t name", 1 },
78 { "help", cs_help,
79 N_("Show this message"), "help", 0 },
80 { "kill", cs_kill,
81 N_("Kill a connection"), "kill #", 0 },
82 { "reset", cs_reset,
83 N_("Reinit all connections"), "reset", 0 },
84 { "show", cs_show,
85 N_("Show connections"), "show", 0 },
86 { NULL }
89 static void
90 cs_usage_msg(x)
91 csid_e x;
93 (void)EMSG2(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage);
97 * PRIVATE: do_cscope_general
99 * find the command, print help if invalid, and the then call the
100 * corresponding command function,
101 * called from do_cscope and do_scscope
103 static void
104 do_cscope_general(eap, make_split)
105 exarg_T *eap;
106 int make_split; /* whether to split window */
108 cscmd_T *cmdp;
110 cs_init();
111 if ((cmdp = cs_lookup_cmd(eap)) == NULL)
113 cs_help(eap);
114 return;
117 #ifdef FEAT_WINDOWS
118 if (make_split)
120 if (!cmdp->cansplit)
122 (void)MSG_PUTS(_("This cscope command does not support splitting the window.\n"));
123 return;
125 postponed_split = -1;
126 postponed_split_flags = cmdmod.split;
127 postponed_split_tab = cmdmod.tab;
129 #endif
131 cmdp->func(eap);
133 #ifdef FEAT_WINDOWS
134 postponed_split_flags = 0;
135 postponed_split_tab = 0;
136 #endif
140 * PUBLIC: do_cscope
142 void
143 do_cscope(eap)
144 exarg_T *eap;
146 do_cscope_general(eap, FALSE);
150 * PUBLIC: do_scscope
152 * same as do_cscope, but splits window, too.
154 void
155 do_scscope(eap)
156 exarg_T *eap;
158 do_cscope_general(eap, TRUE);
162 * PUBLIC: do_cstag
165 void
166 do_cstag(eap)
167 exarg_T *eap;
169 int ret = FALSE;
171 cs_init();
173 if (*eap->arg == NUL)
175 (void)EMSG(_("E562: Usage: cstag <ident>"));
176 return;
179 switch (p_csto)
181 case 0 :
182 if (cs_check_for_connections())
184 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
185 FALSE);
186 if (ret == FALSE)
188 cs_free_tags();
189 if (msg_col)
190 msg_putchar('\n');
192 if (cs_check_for_tags())
193 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
196 else if (cs_check_for_tags())
198 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
200 break;
201 case 1 :
202 if (cs_check_for_tags())
204 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
205 if (ret == FALSE)
207 if (msg_col)
208 msg_putchar('\n');
210 if (cs_check_for_connections())
212 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit,
213 FALSE, FALSE);
214 if (ret == FALSE)
215 cs_free_tags();
219 else if (cs_check_for_connections())
221 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
222 FALSE);
223 if (ret == FALSE)
224 cs_free_tags();
226 break;
227 default :
228 break;
231 if (!ret)
233 (void)EMSG(_("E257: cstag: tag not found"));
234 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
235 g_do_tagpreview = 0;
236 #endif
239 } /* do_cscope */
243 * PUBLIC: cs_find
245 * this simulates a vim_fgets(), but for cscope, returns the next line
246 * from the cscope output. should only be called from find_tags()
248 * returns TRUE if eof, FALSE otherwise
251 cs_fgets(buf, size)
252 char_u *buf;
253 int size;
255 char *p;
257 if ((p = cs_manage_matches(NULL, NULL, -1, Get)) == NULL)
258 return TRUE;
259 vim_strncpy(buf, (char_u *)p, size - 1);
261 return FALSE;
262 } /* cs_fgets */
266 * PUBLIC: cs_free_tags
268 * called only from do_tag(), when popping the tag stack
270 void
271 cs_free_tags()
273 cs_manage_matches(NULL, NULL, -1, Free);
278 * PUBLIC: cs_print_tags
280 * called from do_tag()
282 void
283 cs_print_tags()
285 cs_manage_matches(NULL, NULL, -1, Print);
290 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
292 * Checks for the existence of a |cscope| connection. If no
293 * parameters are specified, then the function returns:
295 * 0, if cscope was not available (not compiled in), or if there
296 * are no cscope connections; or
297 * 1, if there is at least one cscope connection.
299 * If parameters are specified, then the value of {num}
300 * determines how existence of a cscope connection is checked:
302 * {num} Description of existence check
303 * ----- ------------------------------
304 * 0 Same as no parameters (e.g., "cscope_connection()").
305 * 1 Ignore {prepend}, and use partial string matches for
306 * {dbpath}.
307 * 2 Ignore {prepend}, and use exact string matches for
308 * {dbpath}.
309 * 3 Use {prepend}, use partial string matches for both
310 * {dbpath} and {prepend}.
311 * 4 Use {prepend}, use exact string matches for both
312 * {dbpath} and {prepend}.
314 * Note: All string comparisons are case sensitive!
316 #if defined(FEAT_EVAL) || defined(PROTO)
318 cs_connection(num, dbpath, ppath)
319 int num;
320 char_u *dbpath;
321 char_u *ppath;
323 int i;
325 if (num < 0 || num > 4 || (num > 0 && !dbpath))
326 return FALSE;
328 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
330 if (!csinfo[i].fname)
331 continue;
333 if (num == 0)
334 return TRUE;
336 switch (num)
338 case 1:
339 if (strstr(csinfo[i].fname, (char *)dbpath))
340 return TRUE;
341 break;
342 case 2:
343 if (strcmp(csinfo[i].fname, (char *)dbpath) == 0)
344 return TRUE;
345 break;
346 case 3:
347 if (strstr(csinfo[i].fname, (char *)dbpath)
348 && ((!ppath && !csinfo[i].ppath)
349 || (ppath
350 && csinfo[i].ppath
351 && strstr(csinfo[i].ppath, (char *)ppath))))
352 return TRUE;
353 break;
354 case 4:
355 if ((strcmp(csinfo[i].fname, (char *)dbpath) == 0)
356 && ((!ppath && !csinfo[i].ppath)
357 || (ppath
358 && csinfo[i].ppath
359 && (strcmp(csinfo[i].ppath, (char *)ppath) == 0))))
360 return TRUE;
361 break;
365 return FALSE;
366 } /* cs_connection */
367 #endif
371 * PRIVATE functions
372 ****************************************************************************/
375 * PRIVATE: cs_add
377 * add cscope database or a directory name (to look for cscope.out)
378 * to the cscope connection list
380 * MAXPATHL 256
382 /* ARGSUSED */
383 static int
384 cs_add(eap)
385 exarg_T *eap;
387 char *fname, *ppath, *flags = NULL;
389 if ((fname = strtok((char *)NULL, (const char *)" ")) == NULL)
391 cs_usage_msg(Add);
392 return CSCOPE_FAILURE;
394 if ((ppath = strtok((char *)NULL, (const char *)" ")) != NULL)
395 flags = strtok((char *)NULL, (const char *)" ");
397 return cs_add_common(fname, ppath, flags);
400 static void
401 cs_stat_emsg(fname)
402 char *fname;
404 char *stat_emsg = _("E563: stat(%s) error: %d");
405 char *buf = (char *)alloc((unsigned)strlen(stat_emsg) + MAXPATHL + 10);
407 if (buf != NULL)
409 (void)sprintf(buf, stat_emsg, fname, errno);
410 (void)EMSG(buf);
411 vim_free(buf);
413 else
414 (void)EMSG(_("E563: stat error"));
419 * PRIVATE: cs_add_common
421 * the common routine to add a new cscope connection. called by
422 * cs_add() and cs_reset(). i really don't like to do this, but this
423 * routine uses a number of goto statements.
425 static int
426 cs_add_common(arg1, arg2, flags)
427 char *arg1; /* filename - may contain environment variables */
428 char *arg2; /* prepend path - may contain environment variables */
429 char *flags;
431 struct stat statbuf;
432 int ret;
433 char *fname = NULL;
434 char *fname2 = NULL;
435 char *ppath = NULL;
436 int i;
438 /* get the filename (arg1), expand it, and try to stat it */
439 if ((fname = (char *)alloc(MAXPATHL + 1)) == NULL)
440 goto add_err;
442 expand_env((char_u *)arg1, (char_u *)fname, MAXPATHL);
443 ret = stat(fname, &statbuf);
444 if (ret < 0)
446 staterr:
447 if (p_csverbose)
448 cs_stat_emsg(fname);
449 goto add_err;
452 /* get the prepend path (arg2), expand it, and try to stat it */
453 if (arg2 != NULL)
455 struct stat statbuf2;
457 if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
458 goto add_err;
460 expand_env((char_u *)arg2, (char_u *)ppath, MAXPATHL);
461 ret = stat(ppath, &statbuf2);
462 if (ret < 0)
463 goto staterr;
466 /* if filename is a directory, append the cscope database name to it */
467 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
469 fname2 = (char *)alloc((unsigned)(strlen(CSCOPE_DBFILE) + strlen(fname) + 2));
470 if (fname2 == NULL)
471 goto add_err;
473 while (fname[strlen(fname)-1] == '/'
474 #ifdef WIN32
475 || fname[strlen(fname)-1] == '\\'
476 #endif
479 fname[strlen(fname)-1] = '\0';
480 if (strlen(fname) == 0)
481 break;
483 if (fname[0] == '\0')
484 (void)sprintf(fname2, "/%s", CSCOPE_DBFILE);
485 else
486 (void)sprintf(fname2, "%s/%s", fname, CSCOPE_DBFILE);
488 ret = stat(fname2, &statbuf);
489 if (ret < 0)
491 if (p_csverbose)
492 cs_stat_emsg(fname2);
493 goto add_err;
496 i = cs_insert_filelist(fname2, ppath, flags, &statbuf);
498 #if defined(UNIX)
499 else if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode))
500 #else
501 /* WIN32 - substitute define S_ISREG from os_unix.h */
502 else if (((statbuf.st_mode) & S_IFMT) == S_IFREG)
503 #endif
505 i = cs_insert_filelist(fname, ppath, flags, &statbuf);
507 else
509 if (p_csverbose)
510 (void)EMSG2(
511 _("E564: %s is not a directory or a valid cscope database"),
512 fname);
513 goto add_err;
516 if (i != -1)
518 if (cs_create_connection(i) == CSCOPE_FAILURE
519 || cs_read_prompt(i) == CSCOPE_FAILURE)
521 cs_release_csp(i, TRUE);
522 goto add_err;
525 if (p_csverbose)
527 msg_clr_eos();
528 (void)smsg_attr(hl_attr(HLF_R),
529 (char_u *)_("Added cscope database %s"),
530 csinfo[i].fname);
534 vim_free(fname);
535 vim_free(fname2);
536 vim_free(ppath);
537 return CSCOPE_SUCCESS;
539 add_err:
540 vim_free(fname2);
541 vim_free(fname);
542 vim_free(ppath);
543 return CSCOPE_FAILURE;
544 } /* cs_add_common */
547 static int
548 cs_check_for_connections()
550 return (cs_cnt_connections() > 0);
551 } /* cs_check_for_connections */
554 static int
555 cs_check_for_tags()
557 return (p_tags[0] != NUL && curbuf->b_p_tags != NULL);
558 } /* cs_check_for_tags */
562 * PRIVATE: cs_cnt_connections
564 * count the number of cscope connections
566 static int
567 cs_cnt_connections()
569 short i;
570 short cnt = 0;
572 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
574 if (csinfo[i].fname != NULL)
575 cnt++;
577 return cnt;
578 } /* cs_cnt_connections */
580 static void
581 cs_reading_emsg(idx)
582 int idx; /* connection index */
584 EMSGN(_("E262: error reading cscope connection %ld"), idx);
587 #define CSREAD_BUFSIZE 2048
589 * PRIVATE: cs_cnt_matches
591 * count the number of matches for a given cscope connection.
593 static int
594 cs_cnt_matches(idx)
595 int idx;
597 char *stok;
598 char *buf;
599 int nlines;
601 buf = (char *)alloc(CSREAD_BUFSIZE);
602 if (buf == NULL)
603 return 0;
604 for (;;)
606 if (!fgets(buf, CSREAD_BUFSIZE, csinfo[idx].fr_fp))
608 if (feof(csinfo[idx].fr_fp))
609 errno = EIO;
611 cs_reading_emsg(idx);
613 vim_free(buf);
614 return -1;
618 * If the database is out of date, or there's some other problem,
619 * cscope will output error messages before the number-of-lines output.
620 * Display/discard any output that doesn't match what we want.
621 * Accept "\S*cscope: X lines", also matches "mlcscope".
623 if ((stok = strtok(buf, (const char *)" ")) == NULL)
624 continue;
625 if (strstr((const char *)stok, "cscope:") == NULL)
626 continue;
628 if ((stok = strtok(NULL, (const char *)" ")) == NULL)
629 continue;
630 nlines = atoi(stok);
631 if (nlines < 0)
633 nlines = 0;
634 break;
637 if ((stok = strtok(NULL, (const char *)" ")) == NULL)
638 continue;
639 if (strncmp((const char *)stok, "lines", 5))
640 continue;
642 break;
645 vim_free(buf);
646 return nlines;
647 } /* cs_cnt_matches */
651 * PRIVATE: cs_create_cmd
653 * Creates the actual cscope command query from what the user entered.
655 static char *
656 cs_create_cmd(csoption, pattern)
657 char *csoption;
658 char *pattern;
660 char *cmd;
661 short search;
663 switch (csoption[0])
665 case '0' : case 's' :
666 search = 0;
667 break;
668 case '1' : case 'g' :
669 search = 1;
670 break;
671 case '2' : case 'd' :
672 search = 2;
673 break;
674 case '3' : case 'c' :
675 search = 3;
676 break;
677 case '4' : case 't' :
678 search = 4;
679 break;
680 case '6' : case 'e' :
681 search = 6;
682 break;
683 case '7' : case 'f' :
684 search = 7;
685 break;
686 case '8' : case 'i' :
687 search = 8;
688 break;
689 default :
690 (void)EMSG(_("E561: unknown cscope search type"));
691 cs_usage_msg(Find);
692 return NULL;
695 if ((cmd = (char *)alloc((unsigned)(strlen(pattern) + 2))) == NULL)
696 return NULL;
698 (void)sprintf(cmd, "%d%s", search, pattern);
700 return cmd;
701 } /* cs_create_cmd */
705 * PRIVATE: cs_create_connection
707 * This piece of code was taken/adapted from nvi. do we need to add
708 * the BSD license notice?
710 static int
711 cs_create_connection(i)
712 int i;
714 #ifdef UNIX
715 int to_cs[2], from_cs[2];
716 #endif
717 int len;
718 char *prog, *cmd, *ppath = NULL;
719 #ifdef WIN32
720 int fd;
721 SECURITY_ATTRIBUTES sa;
722 PROCESS_INFORMATION pi;
723 STARTUPINFO si;
724 BOOL pipe_stdin = FALSE, pipe_stdout = FALSE;
725 HANDLE stdin_rd, stdout_rd;
726 HANDLE stdout_wr, stdin_wr;
727 BOOL created;
728 # ifdef __BORLANDC__
729 # define OPEN_OH_ARGTYPE long
730 # else
731 # if (_MSC_VER >= 1300)
732 # define OPEN_OH_ARGTYPE intptr_t
733 # else
734 # define OPEN_OH_ARGTYPE long
735 # endif
736 # endif
737 #endif
739 #if defined(UNIX)
741 * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from
742 * from_cs[0] and writes to to_cs[1].
744 to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1;
745 if (pipe(to_cs) < 0 || pipe(from_cs) < 0)
747 (void)EMSG(_("E566: Could not create cscope pipes"));
748 err_closing:
749 if (to_cs[0] != -1)
750 (void)close(to_cs[0]);
751 if (to_cs[1] != -1)
752 (void)close(to_cs[1]);
753 if (from_cs[0] != -1)
754 (void)close(from_cs[0]);
755 if (from_cs[1] != -1)
756 (void)close(from_cs[1]);
757 return CSCOPE_FAILURE;
760 switch (csinfo[i].pid = fork())
762 case -1:
763 (void)EMSG(_("E622: Could not fork for cscope"));
764 goto err_closing;
765 case 0: /* child: run cscope. */
766 if (dup2(to_cs[0], STDIN_FILENO) == -1)
767 PERROR("cs_create_connection 1");
768 if (dup2(from_cs[1], STDOUT_FILENO) == -1)
769 PERROR("cs_create_connection 2");
770 if (dup2(from_cs[1], STDERR_FILENO) == -1)
771 PERROR("cs_create_connection 3");
773 /* close unused */
774 (void)close(to_cs[1]);
775 (void)close(from_cs[0]);
776 #else
777 /* WIN32 */
778 /* Create pipes to communicate with cscope */
779 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
780 sa.bInheritHandle = TRUE;
781 sa.lpSecurityDescriptor = NULL;
783 if (!(pipe_stdin = CreatePipe(&stdin_rd, &stdin_wr, &sa, 0))
784 || !(pipe_stdout = CreatePipe(&stdout_rd, &stdout_wr, &sa, 0)))
786 (void)EMSG(_("E566: Could not create cscope pipes"));
787 err_closing:
788 if (pipe_stdin)
790 CloseHandle(stdin_rd);
791 CloseHandle(stdin_wr);
793 if (pipe_stdout)
795 CloseHandle(stdout_rd);
796 CloseHandle(stdout_wr);
798 return CSCOPE_FAILURE;
800 #endif
801 /* expand the cscope exec for env var's */
802 if ((prog = (char *)alloc(MAXPATHL + 1)) == NULL)
804 #ifdef UNIX
805 return CSCOPE_FAILURE;
806 #else
807 /* WIN32 */
808 goto err_closing;
809 #endif
811 expand_env((char_u *)p_csprg, (char_u *)prog, MAXPATHL);
813 /* alloc space to hold the cscope command */
814 len = (int)(strlen(prog) + strlen(csinfo[i].fname) + 32);
815 if (csinfo[i].ppath)
817 /* expand the prepend path for env var's */
818 if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
820 vim_free(prog);
821 #ifdef UNIX
822 return CSCOPE_FAILURE;
823 #else
824 /* WIN32 */
825 goto err_closing;
826 #endif
828 expand_env((char_u *)csinfo[i].ppath, (char_u *)ppath, MAXPATHL);
830 len += (int)strlen(ppath);
833 if (csinfo[i].flags)
834 len += (int)strlen(csinfo[i].flags);
836 if ((cmd = (char *)alloc(len)) == NULL)
838 vim_free(prog);
839 vim_free(ppath);
840 #ifdef UNIX
841 return CSCOPE_FAILURE;
842 #else
843 /* WIN32 */
844 goto err_closing;
845 #endif
848 /* run the cscope command; is there execl for non-unix systems? */
849 #if defined(UNIX)
850 (void)sprintf(cmd, "exec %s -dl -f %s", prog, csinfo[i].fname);
851 #else
852 /* WIN32 */
853 (void)sprintf(cmd, "%s -dl -f %s", prog, csinfo[i].fname);
854 #endif
855 if (csinfo[i].ppath != NULL)
857 (void)strcat(cmd, " -P");
858 (void)strcat(cmd, csinfo[i].ppath);
860 if (csinfo[i].flags != NULL)
862 (void)strcat(cmd, " ");
863 (void)strcat(cmd, csinfo[i].flags);
865 # ifdef UNIX
866 /* on Win32 we still need prog */
867 vim_free(prog);
868 # endif
869 vim_free(ppath);
871 #if defined(UNIX)
872 if (execl("/bin/sh", "sh", "-c", cmd, NULL) == -1)
873 PERROR(_("cs_create_connection exec failed"));
875 exit(127);
876 /* NOTREACHED */
877 default: /* parent. */
879 * Save the file descriptors for later duplication, and
880 * reopen as streams.
882 if ((csinfo[i].to_fp = fdopen(to_cs[1], "w")) == NULL)
883 PERROR(_("cs_create_connection: fdopen for to_fp failed"));
884 if ((csinfo[i].fr_fp = fdopen(from_cs[0], "r")) == NULL)
885 PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
887 /* close unused */
888 (void)close(to_cs[0]);
889 (void)close(from_cs[1]);
891 break;
894 #else
895 /* WIN32 */
896 /* Create a new process to run cscope and use pipes to talk with it */
897 GetStartupInfo(&si);
898 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
899 si.wShowWindow = SW_HIDE; /* Hide child application window */
900 si.hStdOutput = stdout_wr;
901 si.hStdError = stdout_wr;
902 si.hStdInput = stdin_rd;
903 created = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE,
904 NULL, NULL, &si, &pi);
905 vim_free(prog);
906 vim_free(cmd);
908 if (!created)
910 PERROR(_("cs_create_connection exec failed"));
911 (void)EMSG(_("E623: Could not spawn cscope process"));
912 goto err_closing;
914 /* else */
915 csinfo[i].pid = pi.dwProcessId;
916 csinfo[i].hProc = pi.hProcess;
917 CloseHandle(pi.hThread);
919 /* TODO - tidy up after failure to create files on pipe handles. */
920 if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdin_wr,
921 _O_TEXT|_O_APPEND)) < 0)
922 || ((csinfo[i].to_fp = _fdopen(fd, "w")) == NULL))
923 PERROR(_("cs_create_connection: fdopen for to_fp failed"));
924 if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdout_rd,
925 _O_TEXT|_O_RDONLY)) < 0)
926 || ((csinfo[i].fr_fp = _fdopen(fd, "r")) == NULL))
927 PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
929 /* Close handles for file descriptors inherited by the cscope process */
930 CloseHandle(stdin_rd);
931 CloseHandle(stdout_wr);
933 #endif /* !UNIX */
935 return CSCOPE_SUCCESS;
936 } /* cs_create_connection */
940 * PRIVATE: cs_find
942 * query cscope using command line interface. parse the output and use tselect
943 * to allow choices. like Nvi, creates a pipe to send to/from query/cscope.
945 * returns TRUE if we jump to a tag or abort, FALSE if not.
947 static int
948 cs_find(eap)
949 exarg_T *eap;
951 char *opt, *pat;
953 if (cs_check_for_connections() == FALSE)
955 (void)EMSG(_("E567: no cscope connections"));
956 return FALSE;
959 if ((opt = strtok((char *)NULL, (const char *)" ")) == NULL)
961 cs_usage_msg(Find);
962 return FALSE;
965 pat = opt + strlen(opt) + 1;
966 if (pat >= (char *)eap->arg + eap_arg_len)
968 cs_usage_msg(Find);
969 return FALSE;
972 return cs_find_common(opt, pat, eap->forceit, TRUE,
973 eap->cmdidx == CMD_lcscope);
974 } /* cs_find */
978 * PRIVATE: cs_find_common
980 * common code for cscope find, shared by cs_find() and do_cstag()
982 static int
983 cs_find_common(opt, pat, forceit, verbose, use_ll)
984 char *opt;
985 char *pat;
986 int forceit;
987 int verbose;
988 int use_ll;
990 int i;
991 char *cmd;
992 int nummatches[CSCOPE_MAX_CONNECTIONS], totmatches;
993 #ifdef FEAT_QUICKFIX
994 char cmdletter;
995 char *qfpos;
996 #endif
998 /* create the actual command to send to cscope */
999 cmd = cs_create_cmd(opt, pat);
1000 if (cmd == NULL)
1001 return FALSE;
1003 /* send query to all open connections, then count the total number
1004 * of matches so we can alloc matchesp all in one swell foop
1006 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1007 nummatches[i] = 0;
1008 totmatches = 0;
1009 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1011 if (csinfo[i].fname == NULL || csinfo[i].to_fp == NULL)
1012 continue;
1014 /* send cmd to cscope */
1015 (void)fprintf(csinfo[i].to_fp, "%s\n", cmd);
1016 (void)fflush(csinfo[i].to_fp);
1018 nummatches[i] = cs_cnt_matches(i);
1020 if (nummatches[i] > -1)
1021 totmatches += nummatches[i];
1023 if (nummatches[i] == 0)
1024 (void)cs_read_prompt(i);
1026 vim_free(cmd);
1028 if (totmatches == 0)
1030 char *nf = _("E259: no matches found for cscope query %s of %s");
1031 char *buf;
1033 if (!verbose)
1034 return FALSE;
1036 buf = (char *)alloc((unsigned)(strlen(opt) + strlen(pat) + strlen(nf)));
1037 if (buf == NULL)
1038 (void)EMSG(nf);
1039 else
1041 sprintf(buf, nf, opt, pat);
1042 (void)EMSG(buf);
1043 vim_free(buf);
1045 return FALSE;
1048 #ifdef FEAT_QUICKFIX
1049 /* get cmd letter */
1050 switch (opt[0])
1052 case '0' :
1053 cmdletter = 's';
1054 break;
1055 case '1' :
1056 cmdletter = 'g';
1057 break;
1058 case '2' :
1059 cmdletter = 'd';
1060 break;
1061 case '3' :
1062 cmdletter = 'c';
1063 break;
1064 case '4' :
1065 cmdletter = 't';
1066 break;
1067 case '6' :
1068 cmdletter = 'e';
1069 break;
1070 case '7' :
1071 cmdletter = 'f';
1072 break;
1073 case '8' :
1074 cmdletter = 'i';
1075 break;
1076 default :
1077 cmdletter = opt[0];
1080 qfpos = (char *)vim_strchr(p_csqf, cmdletter);
1081 if (qfpos != NULL)
1083 qfpos++;
1084 /* next symbol must be + or - */
1085 if (strchr(CSQF_FLAGS, *qfpos) == NULL)
1087 char *nf = _("E469: invalid cscopequickfix flag %c for %c");
1088 char *buf = (char *)alloc((unsigned)strlen(nf));
1090 /* strlen will be enough because we use chars */
1091 if (buf != NULL)
1093 sprintf(buf, nf, *qfpos, *(qfpos-1));
1094 (void)EMSG(buf);
1095 vim_free(buf);
1097 return FALSE;
1100 if (qfpos != NULL && *qfpos != '0' && totmatches > 0)
1102 /* fill error list */
1103 FILE *f;
1104 char_u *tmp = vim_tempname('c');
1105 qf_info_T *qi = NULL;
1106 win_T *wp = NULL;
1108 f = mch_fopen((char *)tmp, "w");
1109 if (f == NULL)
1110 EMSG2(_(e_notopen), tmp);
1111 else
1113 cs_file_results(f, nummatches);
1114 fclose(f);
1115 if (use_ll) /* Use location list */
1116 wp = curwin;
1117 /* '-' starts a new error list */
1118 if (qf_init(wp, tmp, (char_u *)"%f%*\\t%l%*\\t%m",
1119 *qfpos == '-') > 0)
1121 # ifdef FEAT_WINDOWS
1122 if (postponed_split != 0)
1124 win_split(postponed_split > 0 ? postponed_split : 0,
1125 postponed_split_flags);
1126 # ifdef FEAT_SCROLLBIND
1127 curwin->w_p_scb = FALSE;
1128 # endif
1129 postponed_split = 0;
1131 # endif
1132 if (use_ll)
1134 * In the location list window, use the displayed location
1135 * list. Otherwise, use the location list for the window.
1137 qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)
1138 ? wp->w_llist_ref : wp->w_llist;
1139 qf_jump(qi, 0, 0, forceit);
1142 mch_remove(tmp);
1143 vim_free(tmp);
1144 return TRUE;
1146 else
1147 #endif /* FEAT_QUICKFIX */
1149 char **matches = NULL, **contexts = NULL;
1150 int matched = 0;
1152 /* read output */
1153 cs_fill_results((char *)pat, totmatches, nummatches, &matches,
1154 &contexts, &matched);
1155 if (matches == NULL)
1156 return FALSE;
1158 (void)cs_manage_matches(matches, contexts, matched, Store);
1160 return do_tag((char_u *)pat, DT_CSCOPE, 0, forceit, verbose);
1163 } /* cs_find_common */
1166 * PRIVATE: cs_help
1168 * print help
1170 /* ARGSUSED */
1171 static int
1172 cs_help(eap)
1173 exarg_T *eap;
1175 cscmd_T *cmdp = cs_cmds;
1177 (void)MSG_PUTS(_("cscope commands:\n"));
1178 while (cmdp->name != NULL)
1180 (void)smsg((char_u *)_("%-5s: %-30s (Usage: %s)"),
1181 cmdp->name, _(cmdp->help), cmdp->usage);
1182 if (strcmp(cmdp->name, "find") == 0)
1183 MSG_PUTS(_("\n"
1184 " c: Find functions calling this function\n"
1185 " d: Find functions called by this function\n"
1186 " e: Find this egrep pattern\n"
1187 " f: Find this file\n"
1188 " g: Find this definition\n"
1189 " i: Find files #including this file\n"
1190 " s: Find this C symbol\n"
1191 " t: Find assignments to\n"));
1193 cmdp++;
1196 wait_return(TRUE);
1197 return 0;
1198 } /* cs_help */
1202 * PRIVATE: cs_init
1204 * initialize cscope structure if not already
1206 static void
1207 cs_init()
1209 short i;
1210 static int init_already = FALSE;
1212 if (init_already)
1213 return;
1215 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1216 clear_csinfo(i);
1218 init_already = TRUE;
1219 } /* cs_init */
1221 static void
1222 clear_csinfo(i)
1223 int i;
1225 csinfo[i].fname = NULL;
1226 csinfo[i].ppath = NULL;
1227 csinfo[i].flags = NULL;
1228 #if defined(UNIX)
1229 csinfo[i].st_dev = (dev_t)0;
1230 csinfo[i].st_ino = (ino_t)0;
1231 #else
1232 csinfo[i].nVolume = 0;
1233 csinfo[i].nIndexHigh = 0;
1234 csinfo[i].nIndexLow = 0;
1235 #endif
1236 csinfo[i].pid = 0;
1237 csinfo[i].fr_fp = NULL;
1238 csinfo[i].to_fp = NULL;
1239 #if defined(WIN32)
1240 csinfo[i].hProc = NULL;
1241 #endif
1244 #ifndef UNIX
1245 static char *GetWin32Error __ARGS((void));
1247 static char *
1248 GetWin32Error()
1250 char *msg = NULL;
1251 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1252 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
1253 if (msg != NULL)
1255 /* remove trailing \r\n */
1256 char *pcrlf = strstr(msg, "\r\n");
1257 if (pcrlf != NULL)
1258 *pcrlf = '\0';
1260 return msg;
1262 #endif
1265 * PRIVATE: cs_insert_filelist
1267 * insert a new cscope database filename into the filelist
1269 /*ARGSUSED*/
1270 static int
1271 cs_insert_filelist(fname, ppath, flags, sb)
1272 char *fname;
1273 char *ppath;
1274 char *flags;
1275 struct stat *sb;
1277 short i, j;
1278 #ifndef UNIX
1279 HANDLE hFile;
1280 BY_HANDLE_FILE_INFORMATION bhfi;
1282 vim_memset(&bhfi, 0, sizeof(bhfi));
1283 /* On windows 9x GetFileInformationByHandle doesn't work, so skip it */
1284 if (!mch_windows95())
1286 hFile = CreateFile(fname, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
1287 FILE_ATTRIBUTE_NORMAL, NULL);
1288 if (hFile == INVALID_HANDLE_VALUE)
1290 if (p_csverbose)
1292 char *cant_msg = _("E625: cannot open cscope database: %s");
1293 char *winmsg = GetWin32Error();
1295 if (winmsg != NULL)
1297 (void)EMSG2(cant_msg, winmsg);
1298 LocalFree(winmsg);
1300 else
1301 /* subst filename if can't get error text */
1302 (void)EMSG2(cant_msg, fname);
1304 return -1;
1306 if (!GetFileInformationByHandle(hFile, &bhfi))
1308 CloseHandle(hFile);
1309 if (p_csverbose)
1310 (void)EMSG(_("E626: cannot get cscope database information"));
1311 return -1;
1313 CloseHandle(hFile);
1315 #endif
1317 i = -1; /* can be set to the index of an empty item in csinfo */
1318 for (j = 0; j < CSCOPE_MAX_CONNECTIONS; j++)
1320 if (csinfo[j].fname != NULL
1321 #if defined(UNIX)
1322 && csinfo[j].st_dev == sb->st_dev && csinfo[j].st_ino == sb->st_ino
1323 #else
1324 /* compare pathnames first */
1325 && ((fullpathcmp(csinfo[j].fname, fname, FALSE) & FPC_SAME)
1326 /* if not Windows 9x, test index file attributes too */
1327 || (!mch_windows95()
1328 && csinfo[j].nVolume == bhfi.dwVolumeSerialNumber
1329 && csinfo[j].nIndexHigh == bhfi.nFileIndexHigh
1330 && csinfo[j].nIndexLow == bhfi.nFileIndexLow))
1331 #endif
1334 if (p_csverbose)
1335 (void)EMSG(_("E568: duplicate cscope database not added"));
1336 return -1;
1339 if (csinfo[j].fname == NULL && i == -1)
1340 i = j; /* remember first empty entry */
1343 if (i == -1)
1345 if (p_csverbose)
1346 (void)EMSG(_("E569: maximum number of cscope connections reached"));
1347 return -1;
1350 if ((csinfo[i].fname = (char *)alloc((unsigned)strlen(fname)+1)) == NULL)
1351 return -1;
1353 (void)strcpy(csinfo[i].fname, (const char *)fname);
1355 if (ppath != NULL)
1357 if ((csinfo[i].ppath = (char *)alloc((unsigned)strlen(ppath) + 1)) == NULL)
1359 vim_free(csinfo[i].fname);
1360 csinfo[i].fname = NULL;
1361 return -1;
1363 (void)strcpy(csinfo[i].ppath, (const char *)ppath);
1364 } else
1365 csinfo[i].ppath = NULL;
1367 if (flags != NULL)
1369 if ((csinfo[i].flags = (char *)alloc((unsigned)strlen(flags) + 1)) == NULL)
1371 vim_free(csinfo[i].fname);
1372 vim_free(csinfo[i].ppath);
1373 csinfo[i].fname = NULL;
1374 csinfo[i].ppath = NULL;
1375 return -1;
1377 (void)strcpy(csinfo[i].flags, (const char *)flags);
1378 } else
1379 csinfo[i].flags = NULL;
1381 #if defined(UNIX)
1382 csinfo[i].st_dev = sb->st_dev;
1383 csinfo[i].st_ino = sb->st_ino;
1385 #else
1386 csinfo[i].nVolume = bhfi.dwVolumeSerialNumber;
1387 csinfo[i].nIndexLow = bhfi.nFileIndexLow;
1388 csinfo[i].nIndexHigh = bhfi.nFileIndexHigh;
1389 #endif
1390 return i;
1391 } /* cs_insert_filelist */
1395 * PRIVATE: cs_lookup_cmd
1397 * find cscope command in command table
1399 static cscmd_T *
1400 cs_lookup_cmd(eap)
1401 exarg_T *eap;
1403 cscmd_T *cmdp;
1404 char *stok;
1405 size_t len;
1407 if (eap->arg == NULL)
1408 return NULL;
1410 /* Store length of eap->arg before it gets modified by strtok(). */
1411 eap_arg_len = (int)STRLEN(eap->arg);
1413 if ((stok = strtok((char *)(eap->arg), (const char *)" ")) == NULL)
1414 return NULL;
1416 len = strlen(stok);
1417 for (cmdp = cs_cmds; cmdp->name != NULL; ++cmdp)
1419 if (strncmp((const char *)(stok), cmdp->name, len) == 0)
1420 return (cmdp);
1422 return NULL;
1423 } /* cs_lookup_cmd */
1427 * PRIVATE: cs_kill
1429 * nuke em
1431 /* ARGSUSED */
1432 static int
1433 cs_kill(eap)
1434 exarg_T *eap;
1436 char *stok;
1437 short i;
1439 if ((stok = strtok((char *)NULL, (const char *)" ")) == NULL)
1441 cs_usage_msg(Kill);
1442 return CSCOPE_FAILURE;
1445 /* only single digit positive and negative integers are allowed */
1446 if ((strlen(stok) < 2 && VIM_ISDIGIT((int)(stok[0])))
1447 || (strlen(stok) < 3 && stok[0] == '-'
1448 && VIM_ISDIGIT((int)(stok[1]))))
1449 i = atoi(stok);
1450 else
1452 /* It must be part of a name. We will try to find a match
1453 * within all the names in the csinfo data structure
1455 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1457 if (csinfo[i].fname != NULL && strstr(csinfo[i].fname, stok))
1458 break;
1462 if ((i >= CSCOPE_MAX_CONNECTIONS || i < -1 || csinfo[i].fname == NULL)
1463 && i != -1)
1465 if (p_csverbose)
1466 (void)EMSG2(_("E261: cscope connection %s not found"), stok);
1468 else
1470 if (i == -1)
1472 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1474 if (csinfo[i].fname)
1475 cs_kill_execute(i, csinfo[i].fname);
1478 else
1479 cs_kill_execute(i, stok);
1482 return 0;
1483 } /* cs_kill */
1487 * PRIVATE: cs_kill_execute
1489 * Actually kills a specific cscope connection.
1491 static void
1492 cs_kill_execute(i, cname)
1493 int i; /* cscope table index */
1494 char *cname; /* cscope database name */
1496 if (p_csverbose)
1498 msg_clr_eos();
1499 (void)smsg_attr(hl_attr(HLF_R) | MSG_HIST,
1500 (char_u *)_("cscope connection %s closed"), cname);
1502 cs_release_csp(i, TRUE);
1507 * PRIVATE: cs_make_vim_style_matches
1509 * convert the cscope output into into a ctags style entry (as might be found
1510 * in a ctags tags file). there's one catch though: cscope doesn't tell you
1511 * the type of the tag you are looking for. for example, in Darren Hiebert's
1512 * ctags (the one that comes with vim), #define's use a line number to find the
1513 * tag in a file while function definitions use a regexp search pattern.
1515 * i'm going to always use the line number because cscope does something
1516 * quirky (and probably other things i don't know about):
1518 * if you have "# define" in your source file, which is
1519 * perfectly legal, cscope thinks you have "#define". this
1520 * will result in a failed regexp search. :(
1522 * besides, even if this particular case didn't happen, the search pattern
1523 * would still have to be modified to escape all the special regular expression
1524 * characters to comply with ctags formatting.
1526 static char *
1527 cs_make_vim_style_matches(fname, slno, search, tagstr)
1528 char *fname;
1529 char *slno;
1530 char *search;
1531 char *tagstr;
1533 /* vim style is ctags:
1535 * <tagstr>\t<filename>\t<linenum_or_search>"\t<extra>
1537 * but as mentioned above, we'll always use the line number and
1538 * put the search pattern (if one exists) as "extra"
1540 * buf is used as part of vim's method of handling tags, and
1541 * (i think) vim frees it when you pop your tags and get replaced
1542 * by new ones on the tag stack.
1544 char *buf;
1545 int amt;
1547 if (search != NULL)
1549 amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + strlen(search)+6);
1550 if ((buf = (char *)alloc(amt)) == NULL)
1551 return NULL;
1553 (void)sprintf(buf, "%s\t%s\t%s;\"\t%s", tagstr, fname, slno, search);
1555 else
1557 amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + 5);
1558 if ((buf = (char *)alloc(amt)) == NULL)
1559 return NULL;
1561 (void)sprintf(buf, "%s\t%s\t%s;\"", tagstr, fname, slno);
1564 return buf;
1565 } /* cs_make_vim_style_matches */
1569 * PRIVATE: cs_manage_matches
1571 * this is kind of hokey, but i don't see an easy way round this..
1573 * Store: keep a ptr to the (malloc'd) memory of matches originally
1574 * generated from cs_find(). the matches are originally lines directly
1575 * from cscope output, but transformed to look like something out of a
1576 * ctags. see cs_make_vim_style_matches for more details.
1578 * Get: used only from cs_fgets(), this simulates a vim_fgets() to return
1579 * the next line from the cscope output. it basically keeps track of which
1580 * lines have been "used" and returns the next one.
1582 * Free: frees up everything and resets
1584 * Print: prints the tags
1586 static char *
1587 cs_manage_matches(matches, contexts, totmatches, cmd)
1588 char **matches;
1589 char **contexts;
1590 int totmatches;
1591 mcmd_e cmd;
1593 static char **mp = NULL;
1594 static char **cp = NULL;
1595 static int cnt = -1;
1596 static int next = -1;
1597 char *p = NULL;
1599 switch (cmd)
1601 case Store:
1602 assert(matches != NULL);
1603 assert(totmatches > 0);
1604 if (mp != NULL || cp != NULL)
1605 (void)cs_manage_matches(NULL, NULL, -1, Free);
1606 mp = matches;
1607 cp = contexts;
1608 cnt = totmatches;
1609 next = 0;
1610 break;
1611 case Get:
1612 if (next >= cnt)
1613 return NULL;
1615 p = mp[next];
1616 next++;
1617 break;
1618 case Free:
1619 if (mp != NULL)
1621 if (cnt > 0)
1622 while (cnt--)
1624 vim_free(mp[cnt]);
1625 if (cp != NULL)
1626 vim_free(cp[cnt]);
1628 vim_free(mp);
1629 vim_free(cp);
1631 mp = NULL;
1632 cp = NULL;
1633 cnt = 0;
1634 next = 0;
1635 break;
1636 case Print:
1637 cs_print_tags_priv(mp, cp, cnt);
1638 break;
1639 default: /* should not reach here */
1640 (void)EMSG(_("E570: fatal error in cs_manage_matches"));
1641 return NULL;
1644 return p;
1645 } /* cs_manage_matches */
1649 * PRIVATE: cs_parse_results
1651 * parse cscope output
1653 static char *
1654 cs_parse_results(cnumber, buf, bufsize, context, linenumber, search)
1655 int cnumber;
1656 char *buf;
1657 int bufsize;
1658 char **context;
1659 char **linenumber;
1660 char **search;
1662 int ch;
1663 char *p;
1664 char *name;
1666 if (fgets(buf, bufsize, csinfo[cnumber].fr_fp) == NULL)
1668 if (feof(csinfo[cnumber].fr_fp))
1669 errno = EIO;
1671 cs_reading_emsg(cnumber);
1673 return NULL;
1676 /* If the line's too long for the buffer, discard it. */
1677 if ((p = strchr(buf, '\n')) == NULL)
1679 while ((ch = getc(csinfo[cnumber].fr_fp)) != EOF && ch != '\n')
1681 return NULL;
1683 *p = '\0';
1686 * cscope output is in the following format:
1688 * <filename> <context> <line number> <pattern>
1690 if ((name = strtok((char *)buf, (const char *)" ")) == NULL)
1691 return NULL;
1692 if ((*context = strtok(NULL, (const char *)" ")) == NULL)
1693 return NULL;
1694 if ((*linenumber = strtok(NULL, (const char *)" ")) == NULL)
1695 return NULL;
1696 *search = *linenumber + strlen(*linenumber) + 1; /* +1 to skip \0 */
1698 /* --- nvi ---
1699 * If the file is older than the cscope database, that is,
1700 * the database was built since the file was last modified,
1701 * or there wasn't a search string, use the line number.
1703 if (strcmp(*search, "<unknown>") == 0)
1704 *search = NULL;
1706 name = cs_resolve_file(cnumber, name);
1707 return name;
1710 #ifdef FEAT_QUICKFIX
1712 * PRIVATE: cs_file_results
1714 * write cscope find results to file
1716 static void
1717 cs_file_results(f, nummatches_a)
1718 FILE *f;
1719 int *nummatches_a;
1721 int i, j;
1722 char *buf;
1723 char *search, *slno;
1724 char *fullname;
1725 char *cntx;
1726 char *context;
1728 buf = (char *)alloc(CSREAD_BUFSIZE);
1729 if (buf == NULL)
1730 return;
1732 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1734 if (nummatches_a[i] < 1)
1735 continue;
1737 for (j = 0; j < nummatches_a[i]; j++)
1739 if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1740 &slno, &search)) == NULL)
1741 continue;
1743 context = (char *)alloc((unsigned)strlen(cntx)+5);
1744 if (context == NULL)
1745 continue;
1747 if (strcmp(cntx, "<global>")==0)
1748 strcpy(context, "<<global>>");
1749 else
1750 sprintf(context, "<<%s>>", cntx);
1752 if (search == NULL)
1753 fprintf(f, "%s\t%s\t%s\n", fullname, slno, context);
1754 else
1755 fprintf(f, "%s\t%s\t%s %s\n", fullname, slno, context, search);
1757 vim_free(context);
1758 vim_free(fullname);
1759 } /* for all matches */
1761 (void)cs_read_prompt(i);
1763 } /* for all cscope connections */
1764 vim_free(buf);
1766 #endif
1769 * PRIVATE: cs_fill_results
1771 * get parsed cscope output and calls cs_make_vim_style_matches to convert
1772 * into ctags format
1773 * When there are no matches sets "*matches_p" to NULL.
1775 static void
1776 cs_fill_results(tagstr, totmatches, nummatches_a, matches_p, cntxts_p, matched)
1777 char *tagstr;
1778 int totmatches;
1779 int *nummatches_a;
1780 char ***matches_p;
1781 char ***cntxts_p;
1782 int *matched;
1784 int i, j;
1785 char *buf;
1786 char *search, *slno;
1787 int totsofar = 0;
1788 char **matches = NULL;
1789 char **cntxts = NULL;
1790 char *fullname;
1791 char *cntx;
1793 assert(totmatches > 0);
1795 buf = (char *)alloc(CSREAD_BUFSIZE);
1796 if (buf == NULL)
1797 return;
1799 if ((matches = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1800 goto parse_out;
1801 if ((cntxts = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1802 goto parse_out;
1804 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1806 if (nummatches_a[i] < 1)
1807 continue;
1809 for (j = 0; j < nummatches_a[i]; j++)
1811 if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1812 &slno, &search)) == NULL)
1813 continue;
1815 matches[totsofar] = cs_make_vim_style_matches(fullname, slno,
1816 search, tagstr);
1818 vim_free(fullname);
1820 if (strcmp(cntx, "<global>") == 0)
1821 cntxts[totsofar] = NULL;
1822 else
1823 /* note: if vim_strsave returns NULL, then the context
1824 * will be "<global>", which is misleading.
1826 cntxts[totsofar] = (char *)vim_strsave((char_u *)cntx);
1828 if (matches[totsofar] != NULL)
1829 totsofar++;
1831 } /* for all matches */
1833 (void)cs_read_prompt(i);
1835 } /* for all cscope connections */
1837 parse_out:
1838 if (totsofar == 0)
1840 /* No matches, free the arrays and return NULL in "*matches_p". */
1841 vim_free(matches);
1842 matches = NULL;
1843 vim_free(cntxts);
1844 cntxts = NULL;
1846 *matched = totsofar;
1847 *matches_p = matches;
1848 *cntxts_p = cntxts;
1850 vim_free(buf);
1851 } /* cs_fill_results */
1854 /* get the requested path components */
1855 static char *
1856 cs_pathcomponents(path)
1857 char *path;
1859 int i;
1860 char *s;
1862 if (p_cspc == 0)
1863 return path;
1865 s = path + strlen(path) - 1;
1866 for (i = 0; i < p_cspc; ++i)
1867 while (s > path && *--s != '/'
1868 #ifdef WIN32
1869 && *--s != '\\'
1870 #endif
1873 if ((s > path && *s == '/')
1874 #ifdef WIN32
1875 || (s > path && *s == '\\')
1876 #endif
1878 ++s;
1879 return s;
1883 * PRIVATE: cs_print_tags_priv
1885 * called from cs_manage_matches()
1887 static void
1888 cs_print_tags_priv(matches, cntxts, num_matches)
1889 char **matches;
1890 char **cntxts;
1891 int num_matches;
1893 char *buf = NULL;
1894 int bufsize = 0; /* Track available bufsize */
1895 int newsize = 0;
1896 char *ptag;
1897 char *fname, *lno, *extra, *tbuf;
1898 int i, idx, num;
1899 char *globalcntx = "GLOBAL";
1900 char *cntxformat = " <<%s>>";
1901 char *context;
1902 char *cstag_msg = _("Cscope tag: %s");
1903 char *csfmt_str = "%4d %6s ";
1905 assert (num_matches > 0);
1907 if ((tbuf = (char *)alloc((unsigned)strlen(matches[0]) + 1)) == NULL)
1908 return;
1910 strcpy(tbuf, matches[0]);
1911 ptag = strtok(tbuf, "\t");
1913 newsize = (int)(strlen(cstag_msg) + strlen(ptag));
1914 buf = (char *)alloc(newsize);
1915 if (buf != NULL)
1917 bufsize = newsize;
1918 (void)sprintf(buf, cstag_msg, ptag);
1919 MSG_PUTS_ATTR(buf, hl_attr(HLF_T));
1922 vim_free(tbuf);
1924 MSG_PUTS_ATTR(_("\n # line"), hl_attr(HLF_T)); /* strlen is 7 */
1925 msg_advance(msg_col + 2);
1926 MSG_PUTS_ATTR(_("filename / context / line\n"), hl_attr(HLF_T));
1928 num = 1;
1929 for (i = 0; i < num_matches; i++)
1931 idx = i;
1933 /* if we really wanted to, we could avoid this malloc and strcpy
1934 * by parsing matches[i] on the fly and placing stuff into buf
1935 * directly, but that's too much of a hassle
1937 if ((tbuf = (char *)alloc((unsigned)strlen(matches[idx]) + 1)) == NULL)
1938 continue;
1939 (void)strcpy(tbuf, matches[idx]);
1941 if ((fname = strtok(tbuf, (const char *)"\t")) == NULL)
1942 continue;
1943 if ((fname = strtok(NULL, (const char *)"\t")) == NULL)
1944 continue;
1945 if ((lno = strtok(NULL, (const char *)"\t")) == NULL)
1946 continue;
1947 extra = strtok(NULL, (const char *)"\t");
1949 lno[strlen(lno)-2] = '\0'; /* ignore ;" at the end */
1951 /* hopefully 'num' (num of matches) will be less than 10^16 */
1952 newsize = (int)(strlen(csfmt_str) + 16 + strlen(lno));
1953 if (bufsize < newsize)
1955 buf = (char *)vim_realloc(buf, newsize);
1956 if (buf == NULL)
1957 bufsize = 0;
1958 else
1959 bufsize = newsize;
1961 if (buf != NULL)
1963 /* csfmt_str = "%4d %6s "; */
1964 (void)sprintf(buf, csfmt_str, num, lno);
1965 MSG_PUTS_ATTR(buf, hl_attr(HLF_CM));
1967 MSG_PUTS_LONG_ATTR(cs_pathcomponents(fname), hl_attr(HLF_CM));
1969 /* compute the required space for the context */
1970 if (cntxts[idx] != NULL)
1971 context = cntxts[idx];
1972 else
1973 context = globalcntx;
1974 newsize = (int)(strlen(context) + strlen(cntxformat));
1976 if (bufsize < newsize)
1978 buf = (char *)vim_realloc(buf, newsize);
1979 if (buf == NULL)
1980 bufsize = 0;
1981 else
1982 bufsize = newsize;
1984 if (buf != NULL)
1986 (void)sprintf(buf, cntxformat, context);
1988 /* print the context only if it fits on the same line */
1989 if (msg_col + (int)strlen(buf) >= (int)Columns)
1990 msg_putchar('\n');
1991 msg_advance(12);
1992 MSG_PUTS_LONG(buf);
1993 msg_putchar('\n');
1995 if (extra != NULL)
1997 msg_advance(13);
1998 MSG_PUTS_LONG(extra);
2001 vim_free(tbuf); /* only after printing extra due to strtok use */
2003 if (msg_col)
2004 msg_putchar('\n');
2006 ui_breakcheck();
2007 if (got_int)
2009 got_int = FALSE; /* don't print any more matches */
2010 break;
2013 num++;
2014 } /* for all matches */
2016 vim_free(buf);
2017 } /* cs_print_tags_priv */
2021 * PRIVATE: cs_read_prompt
2023 * read a cscope prompt (basically, skip over the ">> ")
2025 static int
2026 cs_read_prompt(i)
2027 int i;
2029 int ch;
2030 char *buf = NULL; /* buffer for possible error message from cscope */
2031 int bufpos = 0;
2032 char *cs_emsg;
2033 int maxlen;
2034 static char *eprompt = "Press the RETURN key to continue:";
2035 int epromptlen = (int)strlen(eprompt);
2036 int n;
2038 cs_emsg = _("E609: Cscope error: %s");
2039 /* compute maximum allowed len for Cscope error message */
2040 maxlen = (int)(IOSIZE - strlen(cs_emsg));
2042 for (;;)
2044 while ((ch = getc(csinfo[i].fr_fp)) != EOF && ch != CSCOPE_PROMPT[0])
2045 /* if there is room and char is printable */
2046 if (bufpos < maxlen - 1 && vim_isprintc(ch))
2048 if (buf == NULL) /* lazy buffer allocation */
2049 buf = (char *)alloc(maxlen);
2050 if (buf != NULL)
2052 /* append character to the message */
2053 buf[bufpos++] = ch;
2054 buf[bufpos] = NUL;
2055 if (bufpos >= epromptlen
2056 && strcmp(&buf[bufpos - epromptlen], eprompt) == 0)
2058 /* remove eprompt from buf */
2059 buf[bufpos - epromptlen] = NUL;
2061 /* print message to user */
2062 (void)EMSG2(cs_emsg, buf);
2064 /* send RETURN to cscope */
2065 (void)putc('\n', csinfo[i].to_fp);
2066 (void)fflush(csinfo[i].to_fp);
2068 /* clear buf */
2069 bufpos = 0;
2070 buf[bufpos] = NUL;
2075 for (n = 0; n < (int)strlen(CSCOPE_PROMPT); ++n)
2077 if (n > 0)
2078 ch = getc(csinfo[i].fr_fp);
2079 if (ch == EOF)
2081 PERROR("cs_read_prompt EOF");
2082 if (buf != NULL && buf[0] != NUL)
2083 (void)EMSG2(cs_emsg, buf);
2084 else if (p_csverbose)
2085 cs_reading_emsg(i); /* don't have additional information */
2086 cs_release_csp(i, TRUE);
2087 vim_free(buf);
2088 return CSCOPE_FAILURE;
2091 if (ch != CSCOPE_PROMPT[n])
2093 ch = EOF;
2094 break;
2098 if (ch == EOF)
2099 continue; /* didn't find the prompt */
2100 break; /* did find the prompt */
2103 vim_free(buf);
2104 return CSCOPE_SUCCESS;
2107 #if defined(UNIX) && defined(SIGALRM)
2109 * Used to catch and ignore SIGALRM below.
2111 /* ARGSUSED */
2112 static RETSIGTYPE
2113 sig_handler SIGDEFARG(sigarg)
2115 /* do nothing */
2116 SIGRETURN;
2118 #endif
2121 * PRIVATE: cs_release_csp
2123 * Does the actual free'ing for the cs ptr with an optional flag of whether
2124 * or not to free the filename. Called by cs_kill and cs_reset.
2126 static void
2127 cs_release_csp(i, freefnpp)
2128 int i;
2129 int freefnpp;
2132 * Trying to exit normally (not sure whether it is fit to UNIX cscope
2134 if (csinfo[i].to_fp != NULL)
2136 (void)fputs("q\n", csinfo[i].to_fp);
2137 (void)fflush(csinfo[i].to_fp);
2139 #if defined(UNIX)
2141 int waitpid_errno;
2142 int pstat;
2143 pid_t pid;
2145 # if defined(HAVE_SIGACTION)
2146 struct sigaction sa, old;
2148 /* Use sigaction() to limit the waiting time to two seconds. */
2149 sigemptyset(&sa.sa_mask);
2150 sa.sa_handler = sig_handler;
2151 sa.sa_flags = SA_NODEFER;
2152 sigaction(SIGALRM, &sa, &old);
2153 alarm(2); /* 2 sec timeout */
2155 /* Block until cscope exits or until timer expires */
2156 pid = waitpid(csinfo[i].pid, &pstat, 0);
2157 waitpid_errno = errno;
2159 /* cancel pending alarm if still there and restore signal */
2160 alarm(0);
2161 sigaction(SIGALRM, &old, NULL);
2162 # else
2163 int waited;
2165 /* Can't use sigaction(), loop for two seconds. First yield the CPU
2166 * to give cscope a chance to exit quickly. */
2167 sleep(0);
2168 for (waited = 0; waited < 40; ++waited)
2170 pid = waitpid(csinfo[i].pid, &pstat, WNOHANG);
2171 waitpid_errno = errno;
2172 if (pid != 0)
2173 break; /* break unless the process is still running */
2174 mch_delay(50L, FALSE); /* sleep 50 ms */
2176 # endif
2178 * If the cscope process is still running: kill it.
2179 * Safety check: If the PID would be zero here, the entire X session
2180 * would be killed. -1 and 1 are dangerous as well.
2182 if (pid < 0 && csinfo[i].pid > 1)
2184 # ifdef ECHILD
2185 int alive = TRUE;
2187 if (waitpid_errno == ECHILD)
2190 * When using 'vim -g', vim is forked and cscope process is
2191 * no longer a child process but a sibling. So waitpid()
2192 * fails with errno being ECHILD (No child processes).
2193 * Don't send SIGKILL to cscope immediately but wait
2194 * (polling) for it to exit normally as result of sending
2195 * the "q" command, hence giving it a chance to clean up
2196 * its temporary files.
2198 int waited;
2200 sleep(0);
2201 for (waited = 0; waited < 40; ++waited)
2203 /* Check whether cscope process is still alive */
2204 if (kill(csinfo[i].pid, 0) != 0)
2206 alive = FALSE; /* cscope process no longer exists */
2207 break;
2209 mch_delay(50L, FALSE); /* sleep 50ms */
2212 if (alive)
2213 # endif
2215 kill(csinfo[i].pid, SIGKILL);
2216 (void)waitpid(csinfo[i].pid, &pstat, 0);
2220 #else /* !UNIX */
2221 if (csinfo[i].hProc != NULL)
2223 /* Give cscope a chance to exit normally */
2224 if (WaitForSingleObject(csinfo[i].hProc, 1000) == WAIT_TIMEOUT)
2225 TerminateProcess(csinfo[i].hProc, 0);
2226 CloseHandle(csinfo[i].hProc);
2228 #endif
2230 if (csinfo[i].fr_fp != NULL)
2231 (void)fclose(csinfo[i].fr_fp);
2232 if (csinfo[i].to_fp != NULL)
2233 (void)fclose(csinfo[i].to_fp);
2235 if (freefnpp)
2237 vim_free(csinfo[i].fname);
2238 vim_free(csinfo[i].ppath);
2239 vim_free(csinfo[i].flags);
2242 clear_csinfo(i);
2243 } /* cs_release_csp */
2247 * PRIVATE: cs_reset
2249 * calls cs_kill on all cscope connections then reinits
2251 /* ARGSUSED */
2252 static int
2253 cs_reset(eap)
2254 exarg_T *eap;
2256 char **dblist = NULL, **pplist = NULL, **fllist = NULL;
2257 int i;
2258 char buf[20]; /* for sprintf " (#%d)" */
2260 /* malloc our db and ppath list */
2261 dblist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2262 pplist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2263 fllist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2264 if (dblist == NULL || pplist == NULL || fllist == NULL)
2266 vim_free(dblist);
2267 vim_free(pplist);
2268 vim_free(fllist);
2269 return CSCOPE_FAILURE;
2272 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2274 dblist[i] = csinfo[i].fname;
2275 pplist[i] = csinfo[i].ppath;
2276 fllist[i] = csinfo[i].flags;
2277 if (csinfo[i].fname != NULL)
2278 cs_release_csp(i, FALSE);
2281 /* rebuild the cscope connection list */
2282 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2284 if (dblist[i] != NULL)
2286 cs_add_common(dblist[i], pplist[i], fllist[i]);
2287 if (p_csverbose)
2289 /* don't use smsg_attr() because we want to display the
2290 * connection number in the same line as
2291 * "Added cscope database..."
2293 sprintf(buf, " (#%d)", i);
2294 MSG_PUTS_ATTR(buf, hl_attr(HLF_R));
2297 vim_free(dblist[i]);
2298 vim_free(pplist[i]);
2299 vim_free(fllist[i]);
2301 vim_free(dblist);
2302 vim_free(pplist);
2303 vim_free(fllist);
2305 if (p_csverbose)
2306 MSG_ATTR(_("All cscope databases reset"), hl_attr(HLF_R) | MSG_HIST);
2307 return CSCOPE_SUCCESS;
2308 } /* cs_reset */
2312 * PRIVATE: cs_resolve_file
2314 * construct the full pathname to a file found in the cscope database.
2315 * (Prepends ppath, if there is one and if it's not already prepended,
2316 * otherwise just uses the name found.)
2318 * we need to prepend the prefix because on some cscope's (e.g., the one that
2319 * ships with Solaris 2.6), the output never has the prefix prepended.
2320 * contrast this with my development system (Digital Unix), which does.
2322 static char *
2323 cs_resolve_file(i, name)
2324 int i;
2325 char *name;
2327 char *fullname;
2328 int len;
2331 * ppath is freed when we destroy the cscope connection.
2332 * fullname is freed after cs_make_vim_style_matches, after it's been
2333 * copied into the tag buffer used by vim
2335 len = (int)(strlen(name) + 2);
2336 if (csinfo[i].ppath != NULL)
2337 len += (int)strlen(csinfo[i].ppath);
2339 if ((fullname = (char *)alloc(len)) == NULL)
2340 return NULL;
2343 * note/example: this won't work if the cscope output already starts
2344 * "../.." and the prefix path is also "../..". if something like this
2345 * happens, you are screwed up and need to fix how you're using cscope.
2347 if (csinfo[i].ppath != NULL &&
2348 (strncmp(name, csinfo[i].ppath, strlen(csinfo[i].ppath)) != 0) &&
2349 (name[0] != '/')
2350 #ifdef WIN32
2351 && name[0] != '\\' && name[1] != ':'
2352 #endif
2354 (void)sprintf(fullname, "%s/%s", csinfo[i].ppath, name);
2355 else
2356 (void)sprintf(fullname, "%s", name);
2358 return fullname;
2359 } /* cs_resolve_file */
2363 * PRIVATE: cs_show
2365 * show all cscope connections
2367 /* ARGSUSED */
2368 static int
2369 cs_show(eap)
2370 exarg_T *eap;
2372 short i;
2373 if (cs_cnt_connections() == 0)
2374 MSG_PUTS(_("no cscope connections\n"));
2375 else
2377 MSG_PUTS_ATTR(
2378 _(" # pid database name prepend path\n"),
2379 hl_attr(HLF_T));
2380 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2382 if (csinfo[i].fname == NULL)
2383 continue;
2385 if (csinfo[i].ppath != NULL)
2386 (void)smsg((char_u *)"%2d %-5ld %-34s %-32s",
2387 i, (long)csinfo[i].pid, csinfo[i].fname, csinfo[i].ppath);
2388 else
2389 (void)smsg((char_u *)"%2d %-5ld %-34s <none>",
2390 i, (long)csinfo[i].pid, csinfo[i].fname);
2394 wait_return(TRUE);
2395 return CSCOPE_SUCCESS;
2396 } /* cs_show */
2400 * PUBLIC: cs_end
2402 * Only called when VIM exits to quit any cscope sessions.
2404 void
2405 cs_end()
2407 int i;
2409 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2410 cs_release_csp(i, TRUE);
2413 #endif /* FEAT_CSCOPE */
2415 /* the end */