Merged from the latest developing branch.
[MacVim.git] / src / if_cscope.c
blob0019559512d68d35e49e97a1d4edb28ca0a1d21e
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 # include <fcntl.h>
27 #endif
28 #include "if_cscope.h"
30 static void cs_usage_msg __ARGS((csid_e x));
31 static int cs_add __ARGS((exarg_T *eap));
32 static void cs_stat_emsg __ARGS((char *fname));
33 static int cs_add_common __ARGS((char *, char *, char *));
34 static int cs_check_for_connections __ARGS((void));
35 static int cs_check_for_tags __ARGS((void));
36 static int cs_cnt_connections __ARGS((void));
37 static void cs_reading_emsg __ARGS((int idx));
38 static int cs_cnt_matches __ARGS((int idx));
39 static char * cs_create_cmd __ARGS((char *csoption, char *pattern));
40 static int cs_create_connection __ARGS((int i));
41 static void do_cscope_general __ARGS((exarg_T *eap, int make_split));
42 #ifdef FEAT_QUICKFIX
43 static void cs_file_results __ARGS((FILE *, int *));
44 #endif
45 static void cs_fill_results __ARGS((char *, int , int *, char ***,
46 char ***, int *));
47 static int cs_find __ARGS((exarg_T *eap));
48 static int cs_find_common __ARGS((char *opt, char *pat, int, int, int));
49 static int cs_help __ARGS((exarg_T *eap));
50 static void cs_init __ARGS((void));
51 static void clear_csinfo __ARGS((int i));
52 static int cs_insert_filelist __ARGS((char *, char *, char *,
53 struct stat *));
54 static int cs_kill __ARGS((exarg_T *eap));
55 static void cs_kill_execute __ARGS((int, char *));
56 static cscmd_T * cs_lookup_cmd __ARGS((exarg_T *eap));
57 static char * cs_make_vim_style_matches __ARGS((char *, char *,
58 char *, char *));
59 static char * cs_manage_matches __ARGS((char **, char **, int, mcmd_e));
60 static char * cs_parse_results __ARGS((int cnumber, char *buf, int bufsize, char **context, char **linenumber, char **search));
61 static char * cs_pathcomponents __ARGS((char *path));
62 static void cs_print_tags_priv __ARGS((char **, char **, int));
63 static int cs_read_prompt __ARGS((int));
64 static void cs_release_csp __ARGS((int, int freefnpp));
65 static int cs_reset __ARGS((exarg_T *eap));
66 static char * cs_resolve_file __ARGS((int, char *));
67 static int cs_show __ARGS((exarg_T *eap));
70 static csinfo_T csinfo[CSCOPE_MAX_CONNECTIONS];
71 static int eap_arg_len; /* length of eap->arg, set in
72 cs_lookup_cmd() */
73 static cscmd_T cs_cmds[] =
75 { "add", cs_add,
76 N_("Add a new database"), "add file|dir [pre-path] [flags]", 0 },
77 { "find", cs_find,
78 N_("Query for a pattern"), FIND_USAGE, 1 },
79 { "help", cs_help,
80 N_("Show this message"), "help", 0 },
81 { "kill", cs_kill,
82 N_("Kill a connection"), "kill #", 0 },
83 { "reset", cs_reset,
84 N_("Reinit all connections"), "reset", 0 },
85 { "show", cs_show,
86 N_("Show connections"), "show", 0 },
87 { NULL }
90 static void
91 cs_usage_msg(x)
92 csid_e x;
94 (void)EMSG2(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage);
98 * PRIVATE: do_cscope_general
100 * find the command, print help if invalid, and the then call the
101 * corresponding command function,
102 * called from do_cscope and do_scscope
104 static void
105 do_cscope_general(eap, make_split)
106 exarg_T *eap;
107 int make_split; /* whether to split window */
109 cscmd_T *cmdp;
111 cs_init();
112 if ((cmdp = cs_lookup_cmd(eap)) == NULL)
114 cs_help(eap);
115 return;
118 #ifdef FEAT_WINDOWS
119 if (make_split)
121 if (!cmdp->cansplit)
123 (void)MSG_PUTS(_("This cscope command does not support splitting the window.\n"));
124 return;
126 postponed_split = -1;
127 postponed_split_flags = cmdmod.split;
128 postponed_split_tab = cmdmod.tab;
130 #endif
132 cmdp->func(eap);
134 #ifdef FEAT_WINDOWS
135 postponed_split_flags = 0;
136 postponed_split_tab = 0;
137 #endif
141 * PUBLIC: do_cscope
143 void
144 do_cscope(eap)
145 exarg_T *eap;
147 do_cscope_general(eap, FALSE);
151 * PUBLIC: do_scscope
153 * same as do_cscope, but splits window, too.
155 void
156 do_scscope(eap)
157 exarg_T *eap;
159 do_cscope_general(eap, TRUE);
163 * PUBLIC: do_cstag
166 void
167 do_cstag(eap)
168 exarg_T *eap;
170 int ret = FALSE;
172 cs_init();
174 if (eap->arg == NULL || strlen((const char *)(eap->arg)) == 0)
176 (void)EMSG(_("E562: Usage: cstag <ident>"));
177 return;
180 switch (p_csto)
182 case 0 :
183 if (cs_check_for_connections())
185 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
186 FALSE);
187 if (ret == FALSE)
189 cs_free_tags();
190 if (msg_col)
191 msg_putchar('\n');
193 if (cs_check_for_tags())
194 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
197 else if (cs_check_for_tags())
199 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
201 break;
202 case 1 :
203 if (cs_check_for_tags())
205 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
206 if (ret == FALSE)
208 if (msg_col)
209 msg_putchar('\n');
211 if (cs_check_for_connections())
213 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit,
214 FALSE, FALSE);
215 if (ret == FALSE)
216 cs_free_tags();
220 else if (cs_check_for_connections())
222 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
223 FALSE);
224 if (ret == FALSE)
225 cs_free_tags();
227 break;
228 default :
229 break;
232 if (!ret)
234 (void)EMSG(_("E257: cstag: tag not found"));
235 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
236 g_do_tagpreview = 0;
237 #endif
240 } /* do_cscope */
244 * PUBLIC: cs_find
246 * this simulates a vim_fgets(), but for cscope, returns the next line
247 * from the cscope output. should only be called from find_tags()
249 * returns TRUE if eof, FALSE otherwise
252 cs_fgets(buf, size)
253 char_u *buf;
254 int size;
256 char *p;
258 if ((p = cs_manage_matches(NULL, NULL, -1, Get)) == NULL)
259 return TRUE;
260 vim_strncpy(buf, (char_u *)p, size - 1);
262 return FALSE;
263 } /* cs_fgets */
267 * PUBLIC: cs_free_tags
269 * called only from do_tag(), when popping the tag stack
271 void
272 cs_free_tags()
274 cs_manage_matches(NULL, NULL, -1, Free);
279 * PUBLIC: cs_print_tags
281 * called from do_tag()
283 void
284 cs_print_tags()
286 cs_manage_matches(NULL, NULL, -1, Print);
291 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
293 * Checks for the existence of a |cscope| connection. If no
294 * parameters are specified, then the function returns:
296 * 0, if cscope was not available (not compiled in), or if there
297 * are no cscope connections; or
298 * 1, if there is at least one cscope connection.
300 * If parameters are specified, then the value of {num}
301 * determines how existence of a cscope connection is checked:
303 * {num} Description of existence check
304 * ----- ------------------------------
305 * 0 Same as no parameters (e.g., "cscope_connection()").
306 * 1 Ignore {prepend}, and use partial string matches for
307 * {dbpath}.
308 * 2 Ignore {prepend}, and use exact string matches for
309 * {dbpath}.
310 * 3 Use {prepend}, use partial string matches for both
311 * {dbpath} and {prepend}.
312 * 4 Use {prepend}, use exact string matches for both
313 * {dbpath} and {prepend}.
315 * Note: All string comparisons are case sensitive!
317 #if defined(FEAT_EVAL) || defined(PROTO)
319 cs_connection(num, dbpath, ppath)
320 int num;
321 char_u *dbpath;
322 char_u *ppath;
324 int i;
326 if (num < 0 || num > 4 || (num > 0 && !dbpath))
327 return FALSE;
329 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
331 if (!csinfo[i].fname)
332 continue;
334 if (num == 0)
335 return TRUE;
337 switch (num)
339 case 1:
340 if (strstr(csinfo[i].fname, (char *)dbpath))
341 return TRUE;
342 break;
343 case 2:
344 if (strcmp(csinfo[i].fname, (char *)dbpath) == 0)
345 return TRUE;
346 break;
347 case 3:
348 if (strstr(csinfo[i].fname, (char *)dbpath)
349 && ((!ppath && !csinfo[i].ppath)
350 || (ppath
351 && csinfo[i].ppath
352 && strstr(csinfo[i].ppath, (char *)ppath))))
353 return TRUE;
354 break;
355 case 4:
356 if ((strcmp(csinfo[i].fname, (char *)dbpath) == 0)
357 && ((!ppath && !csinfo[i].ppath)
358 || (ppath
359 && csinfo[i].ppath
360 && (strcmp(csinfo[i].ppath, (char *)ppath) == 0))))
361 return TRUE;
362 break;
366 return FALSE;
367 } /* cs_connection */
368 #endif
372 * PRIVATE functions
373 ****************************************************************************/
376 * PRIVATE: cs_add
378 * add cscope database or a directory name (to look for cscope.out)
379 * to the cscope connection list
381 * MAXPATHL 256
383 /* ARGSUSED */
384 static int
385 cs_add(eap)
386 exarg_T *eap;
388 char *fname, *ppath, *flags = NULL;
390 if ((fname = strtok((char *)NULL, (const char *)" ")) == NULL)
392 cs_usage_msg(Add);
393 return CSCOPE_FAILURE;
395 if ((ppath = strtok((char *)NULL, (const char *)" ")) != NULL)
396 flags = strtok((char *)NULL, (const char *)" ");
398 return cs_add_common(fname, ppath, flags);
401 static void
402 cs_stat_emsg(fname)
403 char *fname;
405 char *stat_emsg = _("E563: stat(%s) error: %d");
406 char *buf = (char *)alloc((unsigned)strlen(stat_emsg) + MAXPATHL + 10);
408 if (buf != NULL)
410 (void)sprintf(buf, stat_emsg, fname, errno);
411 (void)EMSG(buf);
412 vim_free(buf);
414 else
415 (void)EMSG(_("E563: stat error"));
420 * PRIVATE: cs_add_common
422 * the common routine to add a new cscope connection. called by
423 * cs_add() and cs_reset(). i really don't like to do this, but this
424 * routine uses a number of goto statements.
426 static int
427 cs_add_common(arg1, arg2, flags)
428 char *arg1; /* filename - may contain environment variables */
429 char *arg2; /* prepend path - may contain environment variables */
430 char *flags;
432 struct stat statbuf;
433 int ret;
434 char *fname = NULL;
435 char *fname2 = NULL;
436 char *ppath = NULL;
437 int i;
439 /* get the filename (arg1), expand it, and try to stat it */
440 if ((fname = (char *)alloc(MAXPATHL + 1)) == NULL)
441 goto add_err;
443 expand_env((char_u *)arg1, (char_u *)fname, MAXPATHL);
444 ret = stat(fname, &statbuf);
445 if (ret < 0)
447 staterr:
448 if (p_csverbose)
449 cs_stat_emsg(fname);
450 goto add_err;
453 /* get the prepend path (arg2), expand it, and try to stat it */
454 if (arg2 != NULL)
456 struct stat statbuf2;
458 if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
459 goto add_err;
461 expand_env((char_u *)arg2, (char_u *)ppath, MAXPATHL);
462 ret = stat(ppath, &statbuf2);
463 if (ret < 0)
464 goto staterr;
467 /* if filename is a directory, append the cscope database name to it */
468 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
470 fname2 = (char *)alloc((unsigned)(strlen(CSCOPE_DBFILE) + strlen(fname) + 2));
471 if (fname2 == NULL)
472 goto add_err;
474 while (fname[strlen(fname)-1] == '/'
475 #ifdef WIN32
476 || fname[strlen(fname)-1] == '\\'
477 #endif
480 fname[strlen(fname)-1] = '\0';
481 if (strlen(fname) == 0)
482 break;
484 if (fname[0] == '\0')
485 (void)sprintf(fname2, "/%s", CSCOPE_DBFILE);
486 else
487 (void)sprintf(fname2, "%s/%s", fname, CSCOPE_DBFILE);
489 ret = stat(fname2, &statbuf);
490 if (ret < 0)
492 if (p_csverbose)
493 cs_stat_emsg(fname2);
494 goto add_err;
497 i = cs_insert_filelist(fname2, ppath, flags, &statbuf);
499 #if defined(UNIX)
500 else if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode))
501 #else
502 /* WIN32 - substitute define S_ISREG from os_unix.h */
503 else if (((statbuf.st_mode) & S_IFMT) == S_IFREG)
504 #endif
506 i = cs_insert_filelist(fname, ppath, flags, &statbuf);
508 else
510 if (p_csverbose)
511 (void)EMSG2(
512 _("E564: %s is not a directory or a valid cscope database"),
513 fname);
514 goto add_err;
517 if (i != -1)
519 if (cs_create_connection(i) == CSCOPE_FAILURE
520 || cs_read_prompt(i) == CSCOPE_FAILURE)
522 cs_release_csp(i, TRUE);
523 goto add_err;
526 if (p_csverbose)
528 msg_clr_eos();
529 (void)smsg_attr(hl_attr(HLF_R),
530 (char_u *)_("Added cscope database %s"),
531 csinfo[i].fname);
535 vim_free(fname);
536 vim_free(fname2);
537 vim_free(ppath);
538 return CSCOPE_SUCCESS;
540 add_err:
541 vim_free(fname2);
542 vim_free(fname);
543 vim_free(ppath);
544 return CSCOPE_FAILURE;
545 } /* cs_add_common */
548 static int
549 cs_check_for_connections()
551 return (cs_cnt_connections() > 0);
552 } /* cs_check_for_connections */
555 static int
556 cs_check_for_tags()
558 return (p_tags[0] != NUL && curbuf->b_p_tags != NULL);
559 } /* cs_check_for_tags */
563 * PRIVATE: cs_cnt_connections
565 * count the number of cscope connections
567 static int
568 cs_cnt_connections()
570 short i;
571 short cnt = 0;
573 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
575 if (csinfo[i].fname != NULL)
576 cnt++;
578 return cnt;
579 } /* cs_cnt_connections */
581 static void
582 cs_reading_emsg(idx)
583 int idx; /* connection index */
585 EMSGN(_("E262: error reading cscope connection %ld"), idx);
588 #define CSREAD_BUFSIZE 2048
590 * PRIVATE: cs_cnt_matches
592 * count the number of matches for a given cscope connection.
594 static int
595 cs_cnt_matches(idx)
596 int idx;
598 char *stok;
599 char *buf;
600 int nlines;
602 buf = (char *)alloc(CSREAD_BUFSIZE);
603 if (buf == NULL)
604 return 0;
605 for (;;)
607 if (!fgets(buf, CSREAD_BUFSIZE, csinfo[idx].fr_fp))
609 if (feof(csinfo[idx].fr_fp))
610 errno = EIO;
612 cs_reading_emsg(idx);
614 vim_free(buf);
615 return -1;
619 * If the database is out of date, or there's some other problem,
620 * cscope will output error messages before the number-of-lines output.
621 * Display/discard any output that doesn't match what we want.
622 * Accept "\S*cscope: X lines", also matches "mlcscope".
624 if ((stok = strtok(buf, (const char *)" ")) == NULL)
625 continue;
626 if (strstr((const char *)stok, "cscope:") == NULL)
627 continue;
629 if ((stok = strtok(NULL, (const char *)" ")) == NULL)
630 continue;
631 nlines = atoi(stok);
632 if (nlines < 0)
634 nlines = 0;
635 break;
638 if ((stok = strtok(NULL, (const char *)" ")) == NULL)
639 continue;
640 if (strncmp((const char *)stok, "lines", 5))
641 continue;
643 break;
646 vim_free(buf);
647 return nlines;
648 } /* cs_cnt_matches */
652 * PRIVATE: cs_create_cmd
654 * Creates the actual cscope command query from what the user entered.
656 static char *
657 cs_create_cmd(csoption, pattern)
658 char *csoption;
659 char *pattern;
661 char *cmd;
662 short search;
664 switch (csoption[0])
666 case '0' : case 's' :
667 search = 0;
668 break;
669 case '1' : case 'g' :
670 search = 1;
671 break;
672 case '2' : case 'd' :
673 search = 2;
674 break;
675 case '3' : case 'c' :
676 search = 3;
677 break;
678 case '4' : case 't' :
679 search = 4;
680 break;
681 case '6' : case 'e' :
682 search = 6;
683 break;
684 case '7' : case 'f' :
685 search = 7;
686 break;
687 case '8' : case 'i' :
688 search = 8;
689 break;
690 default :
691 (void)EMSG(_("E561: unknown cscope search type"));
692 cs_usage_msg(Find);
693 return NULL;
696 if ((cmd = (char *)alloc((unsigned)(strlen(pattern) + 2))) == NULL)
697 return NULL;
699 (void)sprintf(cmd, "%d%s", search, pattern);
701 return cmd;
702 } /* cs_create_cmd */
706 * PRIVATE: cs_create_connection
708 * This piece of code was taken/adapted from nvi. do we need to add
709 * the BSD license notice?
711 static int
712 cs_create_connection(i)
713 int i;
715 #ifdef UNIX
716 int to_cs[2], from_cs[2];
717 #endif
718 int len;
719 char *prog, *cmd, *ppath = NULL;
720 #ifdef WIN32
721 int fd;
722 SECURITY_ATTRIBUTES sa;
723 PROCESS_INFORMATION pi;
724 STARTUPINFO si;
725 BOOL pipe_stdin = FALSE, pipe_stdout = FALSE;
726 HANDLE stdin_rd, stdout_rd;
727 HANDLE stdout_wr, stdin_wr;
728 BOOL created;
729 # ifdef __BORLANDC__
730 # define OPEN_OH_ARGTYPE long
731 # else
732 # if (_MSC_VER >= 1300)
733 # define OPEN_OH_ARGTYPE intptr_t
734 # else
735 # define OPEN_OH_ARGTYPE long
736 # endif
737 # endif
738 #endif
740 #if defined(UNIX)
742 * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from
743 * from_cs[0] and writes to to_cs[1].
745 to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1;
746 if (pipe(to_cs) < 0 || pipe(from_cs) < 0)
748 (void)EMSG(_("E566: Could not create cscope pipes"));
749 err_closing:
750 if (to_cs[0] != -1)
751 (void)close(to_cs[0]);
752 if (to_cs[1] != -1)
753 (void)close(to_cs[1]);
754 if (from_cs[0] != -1)
755 (void)close(from_cs[0]);
756 if (from_cs[1] != -1)
757 (void)close(from_cs[1]);
758 return CSCOPE_FAILURE;
761 switch (csinfo[i].pid = fork())
763 case -1:
764 (void)EMSG(_("E622: Could not fork for cscope"));
765 goto err_closing;
766 case 0: /* child: run cscope. */
767 if (dup2(to_cs[0], STDIN_FILENO) == -1)
768 PERROR("cs_create_connection 1");
769 if (dup2(from_cs[1], STDOUT_FILENO) == -1)
770 PERROR("cs_create_connection 2");
771 if (dup2(from_cs[1], STDERR_FILENO) == -1)
772 PERROR("cs_create_connection 3");
774 /* close unused */
775 (void)close(to_cs[1]);
776 (void)close(from_cs[0]);
777 #else
778 /* WIN32 */
779 /* Create pipes to communicate with cscope */
780 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
781 sa.bInheritHandle = TRUE;
782 sa.lpSecurityDescriptor = NULL;
784 if (!(pipe_stdin = CreatePipe(&stdin_rd, &stdin_wr, &sa, 0))
785 || !(pipe_stdout = CreatePipe(&stdout_rd, &stdout_wr, &sa, 0)))
787 (void)EMSG(_("E566: Could not create cscope pipes"));
788 err_closing:
789 if (pipe_stdin)
791 CloseHandle(stdin_rd);
792 CloseHandle(stdin_wr);
794 if (pipe_stdout)
796 CloseHandle(stdout_rd);
797 CloseHandle(stdout_wr);
799 return CSCOPE_FAILURE;
801 #endif
802 /* expand the cscope exec for env var's */
803 if ((prog = (char *)alloc(MAXPATHL + 1)) == NULL)
805 #ifdef UNIX
806 return CSCOPE_FAILURE;
807 #else
808 /* WIN32 */
809 goto err_closing;
810 #endif
812 expand_env((char_u *)p_csprg, (char_u *)prog, MAXPATHL);
814 /* alloc space to hold the cscope command */
815 len = (int)(strlen(prog) + strlen(csinfo[i].fname) + 32);
816 if (csinfo[i].ppath)
818 /* expand the prepend path for env var's */
819 if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
821 vim_free(prog);
822 #ifdef UNIX
823 return CSCOPE_FAILURE;
824 #else
825 /* WIN32 */
826 goto err_closing;
827 #endif
829 expand_env((char_u *)csinfo[i].ppath, (char_u *)ppath, MAXPATHL);
831 len += (int)strlen(ppath);
834 if (csinfo[i].flags)
835 len += (int)strlen(csinfo[i].flags);
837 if ((cmd = (char *)alloc(len)) == NULL)
839 vim_free(prog);
840 vim_free(ppath);
841 #ifdef UNIX
842 return CSCOPE_FAILURE;
843 #else
844 /* WIN32 */
845 goto err_closing;
846 #endif
849 /* run the cscope command; is there execl for non-unix systems? */
850 #if defined(UNIX)
851 (void)sprintf(cmd, "exec %s -dl -f %s", prog, csinfo[i].fname);
852 #else
853 /* WIN32 */
854 (void)sprintf(cmd, "%s -dl -f %s", prog, csinfo[i].fname);
855 #endif
856 if (csinfo[i].ppath != NULL)
858 (void)strcat(cmd, " -P");
859 (void)strcat(cmd, csinfo[i].ppath);
861 if (csinfo[i].flags != NULL)
863 (void)strcat(cmd, " ");
864 (void)strcat(cmd, csinfo[i].flags);
866 # ifdef UNIX
867 /* on Win32 we still need prog */
868 vim_free(prog);
869 # endif
870 vim_free(ppath);
872 #if defined(UNIX)
873 if (execl("/bin/sh", "sh", "-c", cmd, NULL) == -1)
874 PERROR(_("cs_create_connection exec failed"));
876 exit(127);
877 /* NOTREACHED */
878 default: /* parent. */
880 * Save the file descriptors for later duplication, and
881 * reopen as streams.
883 if ((csinfo[i].to_fp = fdopen(to_cs[1], "w")) == NULL)
884 PERROR(_("cs_create_connection: fdopen for to_fp failed"));
885 if ((csinfo[i].fr_fp = fdopen(from_cs[0], "r")) == NULL)
886 PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
888 /* close unused */
889 (void)close(to_cs[0]);
890 (void)close(from_cs[1]);
892 break;
895 #else
896 /* WIN32 */
897 /* Create a new process to run cscope and use pipes to talk with it */
898 GetStartupInfo(&si);
899 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
900 si.wShowWindow = SW_HIDE; /* Hide child application window */
901 si.hStdOutput = stdout_wr;
902 si.hStdError = stdout_wr;
903 si.hStdInput = stdin_rd;
904 created = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE,
905 NULL, NULL, &si, &pi);
906 vim_free(prog);
907 vim_free(cmd);
909 if (!created)
911 PERROR(_("cs_create_connection exec failed"));
912 (void)EMSG(_("E623: Could not spawn cscope process"));
913 goto err_closing;
915 /* else */
916 csinfo[i].pid = pi.dwProcessId;
917 csinfo[i].hProc = pi.hProcess;
918 CloseHandle(pi.hThread);
920 /* TODO - tidy up after failure to create files on pipe handles. */
921 if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdin_wr,
922 _O_TEXT|_O_APPEND)) < 0)
923 || ((csinfo[i].to_fp = _fdopen(fd, "w")) == NULL))
924 PERROR(_("cs_create_connection: fdopen for to_fp failed"));
925 if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdout_rd,
926 _O_TEXT|_O_RDONLY)) < 0)
927 || ((csinfo[i].fr_fp = _fdopen(fd, "r")) == NULL))
928 PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
930 /* Close handles for file descriptors inherited by the cscope process */
931 CloseHandle(stdin_rd);
932 CloseHandle(stdout_wr);
934 #endif /* !UNIX */
936 return CSCOPE_SUCCESS;
937 } /* cs_create_connection */
941 * PRIVATE: cs_find
943 * query cscope using command line interface. parse the output and use tselect
944 * to allow choices. like Nvi, creates a pipe to send to/from query/cscope.
946 * returns TRUE if we jump to a tag or abort, FALSE if not.
948 static int
949 cs_find(eap)
950 exarg_T *eap;
952 char *opt, *pat;
954 if (cs_check_for_connections() == FALSE)
956 (void)EMSG(_("E567: no cscope connections"));
957 return FALSE;
960 if ((opt = strtok((char *)NULL, (const char *)" ")) == NULL)
962 cs_usage_msg(Find);
963 return FALSE;
966 pat = opt + strlen(opt) + 1;
967 if (pat >= (char *)eap->arg + eap_arg_len)
969 cs_usage_msg(Find);
970 return FALSE;
973 return cs_find_common(opt, pat, eap->forceit, TRUE,
974 eap->cmdidx == CMD_lcscope);
975 } /* cs_find */
979 * PRIVATE: cs_find_common
981 * common code for cscope find, shared by cs_find() and do_cstag()
983 static int
984 cs_find_common(opt, pat, forceit, verbose, use_ll)
985 char *opt;
986 char *pat;
987 int forceit;
988 int verbose;
989 int use_ll;
991 int i;
992 char *cmd;
993 int nummatches[CSCOPE_MAX_CONNECTIONS], totmatches;
994 #ifdef FEAT_QUICKFIX
995 char cmdletter;
996 char *qfpos;
997 #endif
999 /* create the actual command to send to cscope */
1000 cmd = cs_create_cmd(opt, pat);
1001 if (cmd == NULL)
1002 return FALSE;
1004 /* send query to all open connections, then count the total number
1005 * of matches so we can alloc matchesp all in one swell foop
1007 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1008 nummatches[i] = 0;
1009 totmatches = 0;
1010 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1012 if (csinfo[i].fname == NULL || csinfo[i].to_fp == NULL)
1013 continue;
1015 /* send cmd to cscope */
1016 (void)fprintf(csinfo[i].to_fp, "%s\n", cmd);
1017 (void)fflush(csinfo[i].to_fp);
1019 nummatches[i] = cs_cnt_matches(i);
1021 if (nummatches[i] > -1)
1022 totmatches += nummatches[i];
1024 if (nummatches[i] == 0)
1025 (void)cs_read_prompt(i);
1027 vim_free(cmd);
1029 if (totmatches == 0)
1031 char *nf = _("E259: no matches found for cscope query %s of %s");
1032 char *buf;
1034 if (!verbose)
1035 return FALSE;
1037 buf = (char *)alloc((unsigned)(strlen(opt) + strlen(pat) + strlen(nf)));
1038 if (buf == NULL)
1039 (void)EMSG(nf);
1040 else
1042 sprintf(buf, nf, opt, pat);
1043 (void)EMSG(buf);
1044 vim_free(buf);
1046 return FALSE;
1049 #ifdef FEAT_QUICKFIX
1050 /* get cmd letter */
1051 switch (opt[0])
1053 case '0' :
1054 cmdletter = 's';
1055 break;
1056 case '1' :
1057 cmdletter = 'g';
1058 break;
1059 case '2' :
1060 cmdletter = 'd';
1061 break;
1062 case '3' :
1063 cmdletter = 'c';
1064 break;
1065 case '4' :
1066 cmdletter = 't';
1067 break;
1068 case '6' :
1069 cmdletter = 'e';
1070 break;
1071 case '7' :
1072 cmdletter = 'f';
1073 break;
1074 case '8' :
1075 cmdletter = 'i';
1076 break;
1077 default :
1078 cmdletter = opt[0];
1081 qfpos = (char *)vim_strchr(p_csqf, cmdletter);
1082 if (qfpos != NULL)
1084 qfpos++;
1085 /* next symbol must be + or - */
1086 if (strchr(CSQF_FLAGS, *qfpos) == NULL)
1088 char *nf = _("E469: invalid cscopequickfix flag %c for %c");
1089 char *buf = (char *)alloc((unsigned)strlen(nf));
1091 /* strlen will be enough because we use chars */
1092 if (buf != NULL)
1094 sprintf(buf, nf, *qfpos, *(qfpos-1));
1095 (void)EMSG(buf);
1096 vim_free(buf);
1098 return FALSE;
1101 if (qfpos != NULL && *qfpos != '0' && totmatches > 0)
1103 /* fill error list */
1104 FILE *f;
1105 char_u *tmp = vim_tempname('c');
1106 qf_info_T *qi = NULL;
1107 win_T *wp = NULL;
1109 f = mch_fopen((char *)tmp, "w");
1110 if (f == NULL)
1111 EMSG2(_(e_notopen), tmp);
1112 else
1114 cs_file_results(f, nummatches);
1115 fclose(f);
1116 if (use_ll) /* Use location list */
1117 wp = curwin;
1118 /* '-' starts a new error list */
1119 if (qf_init(wp, tmp, (char_u *)"%f%*\\t%l%*\\t%m",
1120 *qfpos == '-') > 0)
1122 # ifdef FEAT_WINDOWS
1123 if (postponed_split != 0)
1125 win_split(postponed_split > 0 ? postponed_split : 0,
1126 postponed_split_flags);
1127 # ifdef FEAT_SCROLLBIND
1128 curwin->w_p_scb = FALSE;
1129 # endif
1130 postponed_split = 0;
1132 # endif
1133 if (use_ll)
1135 * In the location list window, use the displayed location
1136 * list. Otherwise, use the location list for the window.
1138 qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)
1139 ? wp->w_llist_ref : wp->w_llist;
1140 qf_jump(qi, 0, 0, forceit);
1143 mch_remove(tmp);
1144 vim_free(tmp);
1145 return TRUE;
1147 else
1148 #endif /* FEAT_QUICKFIX */
1150 char **matches = NULL, **contexts = NULL;
1151 int matched = 0;
1153 /* read output */
1154 cs_fill_results((char *)pat, totmatches, nummatches, &matches,
1155 &contexts, &matched);
1156 if (matches == NULL)
1157 return FALSE;
1159 (void)cs_manage_matches(matches, contexts, matched, Store);
1161 return do_tag((char_u *)pat, DT_CSCOPE, 0, forceit, verbose);
1164 } /* cs_find_common */
1167 * PRIVATE: cs_help
1169 * print help
1171 /* ARGSUSED */
1172 static int
1173 cs_help(eap)
1174 exarg_T *eap;
1176 cscmd_T *cmdp = cs_cmds;
1178 (void)MSG_PUTS(_("cscope commands:\n"));
1179 while (cmdp->name != NULL)
1181 (void)smsg((char_u *)_("%-5s: %-30s (Usage: %s)"),
1182 cmdp->name, _(cmdp->help), cmdp->usage);
1183 if (strcmp(cmdp->name, "find") == 0)
1184 MSG_PUTS(FIND_HELP);
1185 cmdp++;
1188 wait_return(TRUE);
1189 return 0;
1190 } /* cs_help */
1194 * PRIVATE: cs_init
1196 * initialize cscope structure if not already
1198 static void
1199 cs_init()
1201 short i;
1202 static int init_already = FALSE;
1204 if (init_already)
1205 return;
1207 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1208 clear_csinfo(i);
1210 init_already = TRUE;
1211 } /* cs_init */
1213 static void
1214 clear_csinfo(i)
1215 int i;
1217 csinfo[i].fname = NULL;
1218 csinfo[i].ppath = NULL;
1219 csinfo[i].flags = NULL;
1220 #if defined(UNIX)
1221 csinfo[i].st_dev = (dev_t)0;
1222 csinfo[i].st_ino = (ino_t)0;
1223 #else
1224 csinfo[i].nVolume = 0;
1225 csinfo[i].nIndexHigh = 0;
1226 csinfo[i].nIndexLow = 0;
1227 #endif
1228 csinfo[i].pid = -1;
1229 csinfo[i].fr_fp = NULL;
1230 csinfo[i].to_fp = NULL;
1231 #if defined(WIN32)
1232 csinfo[i].hProc = NULL;
1233 #endif
1236 #ifndef UNIX
1237 static char *GetWin32Error __ARGS((void));
1239 static char *
1240 GetWin32Error()
1242 char *msg = NULL;
1243 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1244 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
1245 if (msg != NULL)
1247 /* remove trailing \r\n */
1248 char *pcrlf = strstr(msg, "\r\n");
1249 if (pcrlf != NULL)
1250 *pcrlf = '\0';
1252 return msg;
1254 #endif
1257 * PRIVATE: cs_insert_filelist
1259 * insert a new cscope database filename into the filelist
1261 /*ARGSUSED*/
1262 static int
1263 cs_insert_filelist(fname, ppath, flags, sb)
1264 char *fname;
1265 char *ppath;
1266 char *flags;
1267 struct stat *sb;
1269 short i, j;
1270 #ifndef UNIX
1271 HANDLE hFile;
1272 BY_HANDLE_FILE_INFORMATION bhfi;
1274 vim_memset(&bhfi, 0, sizeof(bhfi));
1275 /* On windows 9x GetFileInformationByHandle doesn't work, so skip it */
1276 if (!mch_windows95())
1278 hFile = CreateFile(fname, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
1279 FILE_ATTRIBUTE_NORMAL, NULL);
1280 if (hFile == INVALID_HANDLE_VALUE)
1282 if (p_csverbose)
1284 char *cant_msg = _("E625: cannot open cscope database: %s");
1285 char *winmsg = GetWin32Error();
1287 if (winmsg != NULL)
1289 (void)EMSG2(cant_msg, winmsg);
1290 LocalFree(winmsg);
1292 else
1293 /* subst filename if can't get error text */
1294 (void)EMSG2(cant_msg, fname);
1296 return -1;
1298 if (!GetFileInformationByHandle(hFile, &bhfi))
1300 CloseHandle(hFile);
1301 if (p_csverbose)
1302 (void)EMSG(_("E626: cannot get cscope database information"));
1303 return -1;
1305 CloseHandle(hFile);
1307 #endif
1309 i = -1; /* can be set to the index of an empty item in csinfo */
1310 for (j = 0; j < CSCOPE_MAX_CONNECTIONS; j++)
1312 if (csinfo[j].fname != NULL
1313 #if defined(UNIX)
1314 && csinfo[j].st_dev == sb->st_dev && csinfo[j].st_ino == sb->st_ino
1315 #else
1316 /* compare pathnames first */
1317 && ((fullpathcmp(csinfo[j].fname, fname, FALSE) & FPC_SAME)
1318 /* if not Windows 9x, test index file attributes too */
1319 || (!mch_windows95()
1320 && csinfo[j].nVolume == bhfi.dwVolumeSerialNumber
1321 && csinfo[j].nIndexHigh == bhfi.nFileIndexHigh
1322 && csinfo[j].nIndexLow == bhfi.nFileIndexLow))
1323 #endif
1326 if (p_csverbose)
1327 (void)EMSG(_("E568: duplicate cscope database not added"));
1328 return -1;
1331 if (csinfo[j].fname == NULL && i == -1)
1332 i = j; /* remember first empty entry */
1335 if (i == -1)
1337 if (p_csverbose)
1338 (void)EMSG(_("E569: maximum number of cscope connections reached"));
1339 return -1;
1342 if ((csinfo[i].fname = (char *)alloc((unsigned)strlen(fname)+1)) == NULL)
1343 return -1;
1345 (void)strcpy(csinfo[i].fname, (const char *)fname);
1347 if (ppath != NULL)
1349 if ((csinfo[i].ppath = (char *)alloc((unsigned)strlen(ppath) + 1)) == NULL)
1351 vim_free(csinfo[i].fname);
1352 csinfo[i].fname = NULL;
1353 return -1;
1355 (void)strcpy(csinfo[i].ppath, (const char *)ppath);
1356 } else
1357 csinfo[i].ppath = NULL;
1359 if (flags != NULL)
1361 if ((csinfo[i].flags = (char *)alloc((unsigned)strlen(flags) + 1)) == NULL)
1363 vim_free(csinfo[i].fname);
1364 vim_free(csinfo[i].ppath);
1365 csinfo[i].fname = NULL;
1366 csinfo[i].ppath = NULL;
1367 return -1;
1369 (void)strcpy(csinfo[i].flags, (const char *)flags);
1370 } else
1371 csinfo[i].flags = NULL;
1373 #if defined(UNIX)
1374 csinfo[i].st_dev = sb->st_dev;
1375 csinfo[i].st_ino = sb->st_ino;
1377 #else
1378 csinfo[i].nVolume = bhfi.dwVolumeSerialNumber;
1379 csinfo[i].nIndexLow = bhfi.nFileIndexLow;
1380 csinfo[i].nIndexHigh = bhfi.nFileIndexHigh;
1381 #endif
1382 return i;
1383 } /* cs_insert_filelist */
1387 * PRIVATE: cs_lookup_cmd
1389 * find cscope command in command table
1391 static cscmd_T *
1392 cs_lookup_cmd(eap)
1393 exarg_T *eap;
1395 cscmd_T *cmdp;
1396 char *stok;
1397 size_t len;
1399 if (eap->arg == NULL)
1400 return NULL;
1402 /* Store length of eap->arg before it gets modified by strtok(). */
1403 eap_arg_len = (int)STRLEN(eap->arg);
1405 if ((stok = strtok((char *)(eap->arg), (const char *)" ")) == NULL)
1406 return NULL;
1408 len = strlen(stok);
1409 for (cmdp = cs_cmds; cmdp->name != NULL; ++cmdp)
1411 if (strncmp((const char *)(stok), cmdp->name, len) == 0)
1412 return (cmdp);
1414 return NULL;
1415 } /* cs_lookup_cmd */
1419 * PRIVATE: cs_kill
1421 * nuke em
1423 /* ARGSUSED */
1424 static int
1425 cs_kill(eap)
1426 exarg_T *eap;
1428 char *stok;
1429 short i;
1431 if ((stok = strtok((char *)NULL, (const char *)" ")) == NULL)
1433 cs_usage_msg(Kill);
1434 return CSCOPE_FAILURE;
1437 /* only single digit positive and negative integers are allowed */
1438 if ((strlen(stok) < 2 && VIM_ISDIGIT((int)(stok[0])))
1439 || (strlen(stok) < 3 && stok[0] == '-'
1440 && VIM_ISDIGIT((int)(stok[1]))))
1441 i = atoi(stok);
1442 else
1444 /* It must be part of a name. We will try to find a match
1445 * within all the names in the csinfo data structure
1447 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1449 if (csinfo[i].fname != NULL && strstr(csinfo[i].fname, stok))
1450 break;
1454 if ((i >= CSCOPE_MAX_CONNECTIONS || i < -1 || csinfo[i].fname == NULL)
1455 && i != -1)
1457 if (p_csverbose)
1458 (void)EMSG2(_("E261: cscope connection %s not found"), stok);
1460 else
1462 if (i == -1)
1464 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1466 if (csinfo[i].fname)
1467 cs_kill_execute(i, csinfo[i].fname);
1470 else
1471 cs_kill_execute(i, stok);
1474 return 0;
1475 } /* cs_kill */
1479 * PRIVATE: cs_kill_execute
1481 * Actually kills a specific cscope connection.
1483 static void
1484 cs_kill_execute(i, cname)
1485 int i; /* cscope table index */
1486 char *cname; /* cscope database name */
1488 if (p_csverbose)
1490 msg_clr_eos();
1491 (void)smsg_attr(hl_attr(HLF_R) | MSG_HIST,
1492 (char_u *)_("cscope connection %s closed"), cname);
1494 cs_release_csp(i, TRUE);
1499 * PRIVATE: cs_make_vim_style_matches
1501 * convert the cscope output into into a ctags style entry (as might be found
1502 * in a ctags tags file). there's one catch though: cscope doesn't tell you
1503 * the type of the tag you are looking for. for example, in Darren Hiebert's
1504 * ctags (the one that comes with vim), #define's use a line number to find the
1505 * tag in a file while function definitions use a regexp search pattern.
1507 * i'm going to always use the line number because cscope does something
1508 * quirky (and probably other things i don't know about):
1510 * if you have "# define" in your source file, which is
1511 * perfectly legal, cscope thinks you have "#define". this
1512 * will result in a failed regexp search. :(
1514 * besides, even if this particular case didn't happen, the search pattern
1515 * would still have to be modified to escape all the special regular expression
1516 * characters to comply with ctags formatting.
1518 static char *
1519 cs_make_vim_style_matches(fname, slno, search, tagstr)
1520 char *fname;
1521 char *slno;
1522 char *search;
1523 char *tagstr;
1525 /* vim style is ctags:
1527 * <tagstr>\t<filename>\t<linenum_or_search>"\t<extra>
1529 * but as mentioned above, we'll always use the line number and
1530 * put the search pattern (if one exists) as "extra"
1532 * buf is used as part of vim's method of handling tags, and
1533 * (i think) vim frees it when you pop your tags and get replaced
1534 * by new ones on the tag stack.
1536 char *buf;
1537 int amt;
1539 if (search != NULL)
1541 amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + strlen(search)+6);
1542 if ((buf = (char *)alloc(amt)) == NULL)
1543 return NULL;
1545 (void)sprintf(buf, "%s\t%s\t%s;\"\t%s", tagstr, fname, slno, search);
1547 else
1549 amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + 5);
1550 if ((buf = (char *)alloc(amt)) == NULL)
1551 return NULL;
1553 (void)sprintf(buf, "%s\t%s\t%s;\"", tagstr, fname, slno);
1556 return buf;
1557 } /* cs_make_vim_style_matches */
1561 * PRIVATE: cs_manage_matches
1563 * this is kind of hokey, but i don't see an easy way round this..
1565 * Store: keep a ptr to the (malloc'd) memory of matches originally
1566 * generated from cs_find(). the matches are originally lines directly
1567 * from cscope output, but transformed to look like something out of a
1568 * ctags. see cs_make_vim_style_matches for more details.
1570 * Get: used only from cs_fgets(), this simulates a vim_fgets() to return
1571 * the next line from the cscope output. it basically keeps track of which
1572 * lines have been "used" and returns the next one.
1574 * Free: frees up everything and resets
1576 * Print: prints the tags
1578 static char *
1579 cs_manage_matches(matches, contexts, totmatches, cmd)
1580 char **matches;
1581 char **contexts;
1582 int totmatches;
1583 mcmd_e cmd;
1585 static char **mp = NULL;
1586 static char **cp = NULL;
1587 static int cnt = -1;
1588 static int next = -1;
1589 char *p = NULL;
1591 switch (cmd)
1593 case Store:
1594 assert(matches != NULL);
1595 assert(totmatches > 0);
1596 if (mp != NULL || cp != NULL)
1597 (void)cs_manage_matches(NULL, NULL, -1, Free);
1598 mp = matches;
1599 cp = contexts;
1600 cnt = totmatches;
1601 next = 0;
1602 break;
1603 case Get:
1604 if (next >= cnt)
1605 return NULL;
1607 p = mp[next];
1608 next++;
1609 break;
1610 case Free:
1611 if (mp != NULL)
1613 if (cnt > 0)
1614 while (cnt--)
1616 vim_free(mp[cnt]);
1617 if (cp != NULL)
1618 vim_free(cp[cnt]);
1620 vim_free(mp);
1621 vim_free(cp);
1623 mp = NULL;
1624 cp = NULL;
1625 cnt = 0;
1626 next = 0;
1627 break;
1628 case Print:
1629 cs_print_tags_priv(mp, cp, cnt);
1630 break;
1631 default: /* should not reach here */
1632 (void)EMSG(_("E570: fatal error in cs_manage_matches"));
1633 return NULL;
1636 return p;
1637 } /* cs_manage_matches */
1641 * PRIVATE: cs_parse_results
1643 * parse cscope output
1645 static char *
1646 cs_parse_results(cnumber, buf, bufsize, context, linenumber, search)
1647 int cnumber;
1648 char *buf;
1649 int bufsize;
1650 char **context;
1651 char **linenumber;
1652 char **search;
1654 int ch;
1655 char *p;
1656 char *name;
1658 if (fgets(buf, bufsize, csinfo[cnumber].fr_fp) == NULL)
1660 if (feof(csinfo[cnumber].fr_fp))
1661 errno = EIO;
1663 cs_reading_emsg(cnumber);
1665 return NULL;
1668 /* If the line's too long for the buffer, discard it. */
1669 if ((p = strchr(buf, '\n')) == NULL)
1671 while ((ch = getc(csinfo[cnumber].fr_fp)) != EOF && ch != '\n')
1673 return NULL;
1675 *p = '\0';
1678 * cscope output is in the following format:
1680 * <filename> <context> <line number> <pattern>
1682 if ((name = strtok((char *)buf, (const char *)" ")) == NULL)
1683 return NULL;
1684 if ((*context = strtok(NULL, (const char *)" ")) == NULL)
1685 return NULL;
1686 if ((*linenumber = strtok(NULL, (const char *)" ")) == NULL)
1687 return NULL;
1688 *search = *linenumber + strlen(*linenumber) + 1; /* +1 to skip \0 */
1690 /* --- nvi ---
1691 * If the file is older than the cscope database, that is,
1692 * the database was built since the file was last modified,
1693 * or there wasn't a search string, use the line number.
1695 if (strcmp(*search, "<unknown>") == 0)
1696 *search = NULL;
1698 name = cs_resolve_file(cnumber, name);
1699 return name;
1702 #ifdef FEAT_QUICKFIX
1704 * PRIVATE: cs_file_results
1706 * write cscope find results to file
1708 static void
1709 cs_file_results(f, nummatches_a)
1710 FILE *f;
1711 int *nummatches_a;
1713 int i, j;
1714 char *buf;
1715 char *search, *slno;
1716 char *fullname;
1717 char *cntx;
1718 char *context;
1720 buf = (char *)alloc(CSREAD_BUFSIZE);
1721 if (buf == NULL)
1722 return;
1724 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1726 if (nummatches_a[i] < 1)
1727 continue;
1729 for (j = 0; j < nummatches_a[i]; j++)
1731 if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1732 &slno, &search)) == NULL)
1733 continue;
1735 context = (char *)alloc((unsigned)strlen(cntx)+5);
1736 if (context == NULL)
1737 continue;
1739 if (strcmp(cntx, "<global>")==0)
1740 strcpy(context, "<<global>>");
1741 else
1742 sprintf(context, "<<%s>>", cntx);
1744 if (search == NULL)
1745 fprintf(f, "%s\t%s\t%s\n", fullname, slno, context);
1746 else
1747 fprintf(f, "%s\t%s\t%s %s\n", fullname, slno, context, search);
1749 vim_free(context);
1750 vim_free(fullname);
1751 } /* for all matches */
1753 (void)cs_read_prompt(i);
1755 } /* for all cscope connections */
1756 vim_free(buf);
1758 #endif
1761 * PRIVATE: cs_fill_results
1763 * get parsed cscope output and calls cs_make_vim_style_matches to convert
1764 * into ctags format
1765 * When there are no matches sets "*matches_p" to NULL.
1767 static void
1768 cs_fill_results(tagstr, totmatches, nummatches_a, matches_p, cntxts_p, matched)
1769 char *tagstr;
1770 int totmatches;
1771 int *nummatches_a;
1772 char ***matches_p;
1773 char ***cntxts_p;
1774 int *matched;
1776 int i, j;
1777 char *buf;
1778 char *search, *slno;
1779 int totsofar = 0;
1780 char **matches = NULL;
1781 char **cntxts = NULL;
1782 char *fullname;
1783 char *cntx;
1785 assert(totmatches > 0);
1787 buf = (char *)alloc(CSREAD_BUFSIZE);
1788 if (buf == NULL)
1789 return;
1791 if ((matches = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1792 goto parse_out;
1793 if ((cntxts = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1794 goto parse_out;
1796 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1798 if (nummatches_a[i] < 1)
1799 continue;
1801 for (j = 0; j < nummatches_a[i]; j++)
1803 if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1804 &slno, &search)) == NULL)
1805 continue;
1807 matches[totsofar] = cs_make_vim_style_matches(fullname, slno,
1808 search, tagstr);
1810 vim_free(fullname);
1812 if (strcmp(cntx, "<global>") == 0)
1813 cntxts[totsofar] = NULL;
1814 else
1815 /* note: if vim_strsave returns NULL, then the context
1816 * will be "<global>", which is misleading.
1818 cntxts[totsofar] = (char *)vim_strsave((char_u *)cntx);
1820 if (matches[totsofar] != NULL)
1821 totsofar++;
1823 } /* for all matches */
1825 (void)cs_read_prompt(i);
1827 } /* for all cscope connections */
1829 parse_out:
1830 if (totsofar == 0)
1832 /* No matches, free the arrays and return NULL in "*matches_p". */
1833 vim_free(matches);
1834 matches = NULL;
1835 vim_free(cntxts);
1836 cntxts = NULL;
1838 *matched = totsofar;
1839 *matches_p = matches;
1840 *cntxts_p = cntxts;
1842 vim_free(buf);
1843 } /* cs_fill_results */
1846 /* get the requested path components */
1847 static char *
1848 cs_pathcomponents(path)
1849 char *path;
1851 int i;
1852 char *s;
1854 if (p_cspc == 0)
1855 return path;
1857 s = path + strlen(path) - 1;
1858 for (i = 0; i < p_cspc; ++i)
1859 while (s > path && *--s != '/'
1860 #ifdef WIN32
1861 && *--s != '\\'
1862 #endif
1865 if ((s > path && *s == '/')
1866 #ifdef WIN32
1867 || (s > path && *s == '\\')
1868 #endif
1870 ++s;
1871 return s;
1875 * PRIVATE: cs_print_tags_priv
1877 * called from cs_manage_matches()
1879 static void
1880 cs_print_tags_priv(matches, cntxts, num_matches)
1881 char **matches;
1882 char **cntxts;
1883 int num_matches;
1885 char *buf = NULL;
1886 int bufsize = 0; /* Track available bufsize */
1887 int newsize = 0;
1888 char *ptag;
1889 char *fname, *lno, *extra, *tbuf;
1890 int i, idx, num;
1891 char *globalcntx = "GLOBAL";
1892 char *cntxformat = " <<%s>>";
1893 char *context;
1894 char *cstag_msg = _("Cscope tag: %s");
1895 char *csfmt_str = "%4d %6s ";
1897 assert (num_matches > 0);
1899 if ((tbuf = (char *)alloc((unsigned)strlen(matches[0]) + 1)) == NULL)
1900 return;
1902 strcpy(tbuf, matches[0]);
1903 ptag = strtok(tbuf, "\t");
1905 newsize = (int)(strlen(cstag_msg) + strlen(ptag));
1906 buf = (char *)alloc(newsize);
1907 if (buf != NULL)
1909 bufsize = newsize;
1910 (void)sprintf(buf, cstag_msg, ptag);
1911 MSG_PUTS_ATTR(buf, hl_attr(HLF_T));
1914 vim_free(tbuf);
1916 MSG_PUTS_ATTR(_("\n # line"), hl_attr(HLF_T)); /* strlen is 7 */
1917 msg_advance(msg_col + 2);
1918 MSG_PUTS_ATTR(_("filename / context / line\n"), hl_attr(HLF_T));
1920 num = 1;
1921 for (i = 0; i < num_matches; i++)
1923 idx = i;
1925 /* if we really wanted to, we could avoid this malloc and strcpy
1926 * by parsing matches[i] on the fly and placing stuff into buf
1927 * directly, but that's too much of a hassle
1929 if ((tbuf = (char *)alloc((unsigned)strlen(matches[idx]) + 1)) == NULL)
1930 continue;
1931 (void)strcpy(tbuf, matches[idx]);
1933 if ((fname = strtok(tbuf, (const char *)"\t")) == NULL)
1934 continue;
1935 if ((fname = strtok(NULL, (const char *)"\t")) == NULL)
1936 continue;
1937 if ((lno = strtok(NULL, (const char *)"\t")) == NULL)
1938 continue;
1939 extra = strtok(NULL, (const char *)"\t");
1941 lno[strlen(lno)-2] = '\0'; /* ignore ;" at the end */
1943 /* hopefully 'num' (num of matches) will be less than 10^16 */
1944 newsize = (int)(strlen(csfmt_str) + 16 + strlen(lno));
1945 if (bufsize < newsize)
1947 buf = (char *)vim_realloc(buf, newsize);
1948 if (buf == NULL)
1949 bufsize = 0;
1950 else
1951 bufsize = newsize;
1953 if (buf != NULL)
1955 /* csfmt_str = "%4d %6s "; */
1956 (void)sprintf(buf, csfmt_str, num, lno);
1957 MSG_PUTS_ATTR(buf, hl_attr(HLF_CM));
1959 MSG_PUTS_LONG_ATTR(cs_pathcomponents(fname), hl_attr(HLF_CM));
1961 /* compute the required space for the context */
1962 if (cntxts[idx] != NULL)
1963 context = cntxts[idx];
1964 else
1965 context = globalcntx;
1966 newsize = (int)(strlen(context) + strlen(cntxformat));
1968 if (bufsize < newsize)
1970 buf = (char *)vim_realloc(buf, newsize);
1971 if (buf == NULL)
1972 bufsize = 0;
1973 else
1974 bufsize = newsize;
1976 if (buf != NULL)
1978 (void)sprintf(buf, cntxformat, context);
1980 /* print the context only if it fits on the same line */
1981 if (msg_col + (int)strlen(buf) >= (int)Columns)
1982 msg_putchar('\n');
1983 msg_advance(12);
1984 MSG_PUTS_LONG(buf);
1985 msg_putchar('\n');
1987 if (extra != NULL)
1989 msg_advance(13);
1990 MSG_PUTS_LONG(extra);
1993 vim_free(tbuf); /* only after printing extra due to strtok use */
1995 if (msg_col)
1996 msg_putchar('\n');
1998 ui_breakcheck();
1999 if (got_int)
2001 got_int = FALSE; /* don't print any more matches */
2002 break;
2005 num++;
2006 } /* for all matches */
2008 vim_free(buf);
2009 } /* cs_print_tags_priv */
2013 * PRIVATE: cs_read_prompt
2015 * read a cscope prompt (basically, skip over the ">> ")
2017 static int
2018 cs_read_prompt(i)
2019 int i;
2021 int ch;
2022 char *buf = NULL; /* buffer for possible error message from cscope */
2023 int bufpos = 0;
2024 char *cs_emsg;
2025 int maxlen;
2026 static char *eprompt = "Press the RETURN key to continue:";
2027 int epromptlen = (int)strlen(eprompt);
2028 int n;
2030 cs_emsg = _("E609: Cscope error: %s");
2031 /* compute maximum allowed len for Cscope error message */
2032 maxlen = (int)(IOSIZE - strlen(cs_emsg));
2034 for (;;)
2036 while ((ch = getc(csinfo[i].fr_fp)) != EOF && ch != CSCOPE_PROMPT[0])
2037 /* if there is room and char is printable */
2038 if (bufpos < maxlen - 1 && vim_isprintc(ch))
2040 if (buf == NULL) /* lazy buffer allocation */
2041 buf = (char *)alloc(maxlen);
2042 if (buf != NULL)
2044 /* append character to the message */
2045 buf[bufpos++] = ch;
2046 buf[bufpos] = NUL;
2047 if (bufpos >= epromptlen
2048 && strcmp(&buf[bufpos - epromptlen], eprompt) == 0)
2050 /* remove eprompt from buf */
2051 buf[bufpos - epromptlen] = NUL;
2053 /* print message to user */
2054 (void)EMSG2(cs_emsg, buf);
2056 /* send RETURN to cscope */
2057 (void)putc('\n', csinfo[i].to_fp);
2058 (void)fflush(csinfo[i].to_fp);
2060 /* clear buf */
2061 bufpos = 0;
2062 buf[bufpos] = NUL;
2067 for (n = 0; n < (int)strlen(CSCOPE_PROMPT); ++n)
2069 if (n > 0)
2070 ch = getc(csinfo[i].fr_fp);
2071 if (ch == EOF)
2073 PERROR("cs_read_prompt EOF");
2074 if (buf != NULL && buf[0] != NUL)
2075 (void)EMSG2(cs_emsg, buf);
2076 else if (p_csverbose)
2077 cs_reading_emsg(i); /* don't have additional information */
2078 cs_release_csp(i, TRUE);
2079 vim_free(buf);
2080 return CSCOPE_FAILURE;
2083 if (ch != CSCOPE_PROMPT[n])
2085 ch = EOF;
2086 break;
2090 if (ch == EOF)
2091 continue; /* didn't find the prompt */
2092 break; /* did find the prompt */
2095 vim_free(buf);
2096 return CSCOPE_SUCCESS;
2099 #if defined(UNIX) && defined(SIGALRM)
2101 * Used to catch and ignore SIGALRM below.
2103 /* ARGSUSED */
2104 static RETSIGTYPE
2105 sig_handler SIGDEFARG(sigarg)
2107 /* do nothing */
2108 SIGRETURN;
2110 #endif
2113 * PRIVATE: cs_release_csp
2115 * Does the actual free'ing for the cs ptr with an optional flag of whether
2116 * or not to free the filename. Called by cs_kill and cs_reset.
2118 static void
2119 cs_release_csp(i, freefnpp)
2120 int i;
2121 int freefnpp;
2124 * Trying to exit normally (not sure whether it is fit to UNIX cscope
2126 if (csinfo[i].to_fp != NULL)
2128 (void)fputs("q\n", csinfo[i].to_fp);
2129 (void)fflush(csinfo[i].to_fp);
2131 #if defined(UNIX)
2133 int waitpid_errno;
2134 int pstat;
2135 pid_t pid;
2137 # if defined(HAVE_SIGACTION)
2138 struct sigaction sa, old;
2140 /* Use sigaction() to limit the waiting time to two seconds. */
2141 sigemptyset(&sa.sa_mask);
2142 sa.sa_handler = sig_handler;
2143 sa.sa_flags = SA_NODEFER;
2144 sigaction(SIGALRM, &sa, &old);
2145 alarm(2); /* 2 sec timeout */
2147 /* Block until cscope exits or until timer expires */
2148 pid = waitpid(csinfo[i].pid, &pstat, 0);
2149 waitpid_errno = errno;
2151 /* cancel pending alarm if still there and restore signal */
2152 alarm(0);
2153 sigaction(SIGALRM, &old, NULL);
2154 # else
2155 int waited;
2157 /* Can't use sigaction(), loop for two seconds. First yield the CPU
2158 * to give cscope a chance to exit quickly. */
2159 sleep(0);
2160 for (waited = 0; waited < 40; ++waited)
2162 pid = waitpid(csinfo[i].pid, &pstat, WNOHANG);
2163 waitpid_errno = errno;
2164 if (pid != 0)
2165 break; /* break unless the process is still running */
2166 mch_delay(50L, FALSE); /* sleep 50 ms */
2168 # endif
2170 * If the cscope process is still running: kill it.
2171 * Safety check: If the PID would be zero here, the entire X session
2172 * would be killed. -1 and 1 are dangerous as well.
2174 if (pid < 0 && csinfo[i].pid > 1)
2176 # ifdef ECHILD
2177 int alive = TRUE;
2179 if (waitpid_errno == ECHILD)
2182 * When using 'vim -g', vim is forked and cscope process is
2183 * no longer a child process but a sibling. So waitpid()
2184 * fails with errno being ECHILD (No child processes).
2185 * Don't send SIGKILL to cscope immediately but wait
2186 * (polling) for it to exit normally as result of sending
2187 * the "q" command, hence giving it a chance to clean up
2188 * its temporary files.
2190 int waited;
2192 sleep(0);
2193 for (waited = 0; waited < 40; ++waited)
2195 /* Check whether cscope process is still alive */
2196 if (kill(csinfo[i].pid, 0) != 0)
2198 alive = FALSE; /* cscope process no longer exists */
2199 break;
2201 mch_delay(50L, FALSE); /* sleep 50ms */
2204 if (alive)
2205 # endif
2207 kill(csinfo[i].pid, SIGKILL);
2208 (void)waitpid(csinfo[i].pid, &pstat, 0);
2212 #else /* !UNIX */
2213 if (csinfo[i].hProc != NULL)
2215 /* Give cscope a chance to exit normally */
2216 if (WaitForSingleObject(csinfo[i].hProc, 1000) == WAIT_TIMEOUT)
2217 TerminateProcess(csinfo[i].hProc, 0);
2218 CloseHandle(csinfo[i].hProc);
2220 #endif
2222 if (csinfo[i].fr_fp != NULL)
2223 (void)fclose(csinfo[i].fr_fp);
2224 if (csinfo[i].to_fp != NULL)
2225 (void)fclose(csinfo[i].to_fp);
2227 if (freefnpp)
2229 vim_free(csinfo[i].fname);
2230 vim_free(csinfo[i].ppath);
2231 vim_free(csinfo[i].flags);
2234 clear_csinfo(i);
2235 } /* cs_release_csp */
2239 * PRIVATE: cs_reset
2241 * calls cs_kill on all cscope connections then reinits
2243 /* ARGSUSED */
2244 static int
2245 cs_reset(eap)
2246 exarg_T *eap;
2248 char **dblist = NULL, **pplist = NULL, **fllist = NULL;
2249 int i;
2250 char buf[20]; /* for sprintf " (#%d)" */
2252 /* malloc our db and ppath list */
2253 dblist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2254 pplist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2255 fllist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2256 if (dblist == NULL || pplist == NULL || fllist == NULL)
2258 vim_free(dblist);
2259 vim_free(pplist);
2260 vim_free(fllist);
2261 return CSCOPE_FAILURE;
2264 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2266 dblist[i] = csinfo[i].fname;
2267 pplist[i] = csinfo[i].ppath;
2268 fllist[i] = csinfo[i].flags;
2269 if (csinfo[i].fname != NULL)
2270 cs_release_csp(i, FALSE);
2273 /* rebuild the cscope connection list */
2274 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2276 if (dblist[i] != NULL)
2278 cs_add_common(dblist[i], pplist[i], fllist[i]);
2279 if (p_csverbose)
2281 /* don't use smsg_attr() because we want to display the
2282 * connection number in the same line as
2283 * "Added cscope database..."
2285 sprintf(buf, " (#%d)", i);
2286 MSG_PUTS_ATTR(buf, hl_attr(HLF_R));
2289 vim_free(dblist[i]);
2290 vim_free(pplist[i]);
2291 vim_free(fllist[i]);
2293 vim_free(dblist);
2294 vim_free(pplist);
2295 vim_free(fllist);
2297 if (p_csverbose)
2298 MSG_ATTR(_("All cscope databases reset"), hl_attr(HLF_R) | MSG_HIST);
2299 return CSCOPE_SUCCESS;
2300 } /* cs_reset */
2304 * PRIVATE: cs_resolve_file
2306 * construct the full pathname to a file found in the cscope database.
2307 * (Prepends ppath, if there is one and if it's not already prepended,
2308 * otherwise just uses the name found.)
2310 * we need to prepend the prefix because on some cscope's (e.g., the one that
2311 * ships with Solaris 2.6), the output never has the prefix prepended.
2312 * contrast this with my development system (Digital Unix), which does.
2314 static char *
2315 cs_resolve_file(i, name)
2316 int i;
2317 char *name;
2319 char *fullname;
2320 int len;
2323 * ppath is freed when we destroy the cscope connection.
2324 * fullname is freed after cs_make_vim_style_matches, after it's been
2325 * copied into the tag buffer used by vim
2327 len = (int)(strlen(name) + 2);
2328 if (csinfo[i].ppath != NULL)
2329 len += (int)strlen(csinfo[i].ppath);
2331 if ((fullname = (char *)alloc(len)) == NULL)
2332 return NULL;
2335 * note/example: this won't work if the cscope output already starts
2336 * "../.." and the prefix path is also "../..". if something like this
2337 * happens, you are screwed up and need to fix how you're using cscope.
2339 if (csinfo[i].ppath != NULL &&
2340 (strncmp(name, csinfo[i].ppath, strlen(csinfo[i].ppath)) != 0) &&
2341 (name[0] != '/')
2342 #ifdef WIN32
2343 && name[0] != '\\' && name[1] != ':'
2344 #endif
2346 (void)sprintf(fullname, "%s/%s", csinfo[i].ppath, name);
2347 else
2348 (void)sprintf(fullname, "%s", name);
2350 return fullname;
2351 } /* cs_resolve_file */
2355 * PRIVATE: cs_show
2357 * show all cscope connections
2359 /* ARGSUSED */
2360 static int
2361 cs_show(eap)
2362 exarg_T *eap;
2364 short i;
2365 if (cs_cnt_connections() == 0)
2366 MSG_PUTS(_("no cscope connections\n"));
2367 else
2369 MSG_PUTS_ATTR(
2370 _(" # pid database name prepend path\n"),
2371 hl_attr(HLF_T));
2372 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2374 if (csinfo[i].fname == NULL)
2375 continue;
2377 if (csinfo[i].ppath != NULL)
2378 (void)smsg((char_u *)"%2d %-5ld %-34s %-32s",
2379 i, (long)csinfo[i].pid, csinfo[i].fname, csinfo[i].ppath);
2380 else
2381 (void)smsg((char_u *)"%2d %-5ld %-34s <none>",
2382 i, (long)csinfo[i].pid, csinfo[i].fname);
2386 wait_return(TRUE);
2387 return CSCOPE_SUCCESS;
2388 } /* cs_show */
2392 * PUBLIC: cs_end
2394 * Only called when VIM exits to quit any cscope sessions.
2396 void
2397 cs_end()
2399 int i;
2401 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2402 cs_release_csp(i, TRUE);
2405 #endif /* FEAT_CSCOPE */
2407 /* the end */