Sync with newest CVS repository.
[MacVim/jjgod.git] / src / if_cscope.c
blob1eb3616e7516e4eca62d818bf1107305f6c54c29
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 # include <process.h>
28 # define STDIN_FILENO 0
29 # define STDOUT_FILENO 1
30 # define STDERR_FILENO 2
31 # define pipe(fds) _pipe(fds, 256, O_TEXT|O_NOINHERIT)
32 #endif
33 #include "if_cscope.h"
35 static void cs_usage_msg __ARGS((csid_e x));
36 static int cs_add __ARGS((exarg_T *eap));
37 static void cs_stat_emsg __ARGS((char *fname));
38 static int cs_add_common __ARGS((char *, char *, char *));
39 static int cs_check_for_connections __ARGS((void));
40 static int cs_check_for_tags __ARGS((void));
41 static int cs_cnt_connections __ARGS((void));
42 static void cs_reading_emsg __ARGS((int idx));
43 static int cs_cnt_matches __ARGS((int idx));
44 static char * cs_create_cmd __ARGS((char *csoption, char *pattern));
45 static int cs_create_connection __ARGS((int i));
46 static void do_cscope_general __ARGS((exarg_T *eap, int make_split));
47 #ifdef FEAT_QUICKFIX
48 static void cs_file_results __ARGS((FILE *, int *));
49 #endif
50 static void cs_fill_results __ARGS((char *, int , int *, char ***,
51 char ***, int *));
52 static int cs_find __ARGS((exarg_T *eap));
53 static int cs_find_common __ARGS((char *opt, char *pat, int, int, int));
54 static int cs_help __ARGS((exarg_T *eap));
55 static void cs_init __ARGS((void));
56 static void clear_csinfo __ARGS((int i));
57 static int cs_insert_filelist __ARGS((char *, char *, char *,
58 struct stat *));
59 static int cs_kill __ARGS((exarg_T *eap));
60 static void cs_kill_execute __ARGS((int, char *));
61 static cscmd_T * cs_lookup_cmd __ARGS((exarg_T *eap));
62 static char * cs_make_vim_style_matches __ARGS((char *, char *,
63 char *, char *));
64 static char * cs_manage_matches __ARGS((char **, char **, int, mcmd_e));
65 static char * cs_parse_results __ARGS((int cnumber, char *buf, int bufsize, char **context, char **linenumber, char **search));
66 static char * cs_pathcomponents __ARGS((char *path));
67 static void cs_print_tags_priv __ARGS((char **, char **, int));
68 static int cs_read_prompt __ARGS((int ));
69 static void cs_release_csp __ARGS((int, int freefnpp));
70 static int cs_reset __ARGS((exarg_T *eap));
71 static char * cs_resolve_file __ARGS((int, char *));
72 static int cs_show __ARGS((exarg_T *eap));
75 static csinfo_T csinfo[CSCOPE_MAX_CONNECTIONS];
76 static cscmd_T cs_cmds[] =
78 { "add", cs_add,
79 N_("Add a new database"), "add file|dir [pre-path] [flags]", 0 },
80 { "find", cs_find,
81 N_("Query for a pattern"), FIND_USAGE, 1 },
82 { "help", cs_help,
83 N_("Show this message"), "help", 0 },
84 { "kill", cs_kill,
85 N_("Kill a connection"), "kill #", 0 },
86 { "reset", cs_reset,
87 N_("Reinit all connections"), "reset", 0 },
88 { "show", cs_show,
89 N_("Show connections"), "show", 0 },
90 { NULL }
93 static void
94 cs_usage_msg(x)
95 csid_e x;
97 (void)EMSG2(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage);
101 * PRIVATE: do_cscope_general
103 * find the command, print help if invalid, and the then call the
104 * corresponding command function,
105 * called from do_cscope and do_scscope
107 static void
108 do_cscope_general(eap, make_split)
109 exarg_T *eap;
110 int make_split; /* whether to split window */
112 cscmd_T *cmdp;
114 cs_init();
115 if ((cmdp = cs_lookup_cmd(eap)) == NULL)
117 cs_help(eap);
118 return;
121 #ifdef FEAT_WINDOWS
122 if (make_split)
124 if (!cmdp->cansplit)
126 (void)MSG_PUTS(_("This cscope command does not support splitting the window.\n"));
127 return;
129 postponed_split = -1;
130 postponed_split_flags = cmdmod.split;
132 #endif
134 cmdp->func(eap);
136 #ifdef FEAT_WINDOWS
137 postponed_split_flags = 0;
138 #endif
142 * PUBLIC: do_cscope
144 void
145 do_cscope(eap)
146 exarg_T *eap;
148 do_cscope_general(eap, FALSE);
152 * PUBLIC: do_scscope
154 * same as do_cscope, but splits window, too.
156 void
157 do_scscope(eap)
158 exarg_T *eap;
160 do_cscope_general(eap, TRUE);
164 * PUBLIC: do_cstag
167 void
168 do_cstag(eap)
169 exarg_T *eap;
171 int ret = FALSE;
173 cs_init();
175 if (eap->arg == NULL || strlen((const char *)(eap->arg)) == 0)
177 (void)EMSG(_("E562: Usage: cstag <ident>"));
178 return;
181 switch (p_csto)
183 case 0 :
184 if (cs_check_for_connections())
186 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
187 FALSE);
188 if (ret == FALSE)
190 cs_free_tags();
191 if (msg_col)
192 msg_putchar('\n');
194 if (cs_check_for_tags())
195 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
198 else if (cs_check_for_tags())
200 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
202 break;
203 case 1 :
204 if (cs_check_for_tags())
206 ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE);
207 if (ret == FALSE)
209 if (msg_col)
210 msg_putchar('\n');
212 if (cs_check_for_connections())
214 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit,
215 FALSE, FALSE);
216 if (ret == FALSE)
217 cs_free_tags();
221 else if (cs_check_for_connections())
223 ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE,
224 FALSE);
225 if (ret == FALSE)
226 cs_free_tags();
228 break;
229 default :
230 break;
233 if (!ret)
235 (void)EMSG(_("E257: cstag: tag not found"));
236 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
237 g_do_tagpreview = 0;
238 #endif
241 } /* do_cscope */
245 * PUBLIC: cs_find
247 * this simulates a vim_fgets(), but for cscope, returns the next line
248 * from the cscope output. should only be called from find_tags()
250 * returns TRUE if eof, FALSE otherwise
253 cs_fgets(buf, size)
254 char_u *buf;
255 int size;
257 char *p;
259 if ((p = cs_manage_matches(NULL, NULL, -1, Get)) == NULL)
260 return TRUE;
262 if ((int)strlen(p) > size)
264 strncpy((char *)buf, p, size - 1);
265 buf[size] = '\0';
267 else
268 (void)strcpy((char *)buf, p);
270 return FALSE;
271 } /* cs_fgets */
275 * PUBLIC: cs_free_tags
277 * called only from do_tag(), when popping the tag stack
279 void
280 cs_free_tags()
282 cs_manage_matches(NULL, NULL, -1, Free);
287 * PUBLIC: cs_print_tags
289 * called from do_tag()
291 void
292 cs_print_tags()
294 cs_manage_matches(NULL, NULL, -1, Print);
299 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
301 * Checks for the existence of a |cscope| connection. If no
302 * parameters are specified, then the function returns:
304 * 0, if cscope was not available (not compiled in), or if there
305 * are no cscope connections; or
306 * 1, if there is at least one cscope connection.
308 * If parameters are specified, then the value of {num}
309 * determines how existence of a cscope connection is checked:
311 * {num} Description of existence check
312 * ----- ------------------------------
313 * 0 Same as no parameters (e.g., "cscope_connection()").
314 * 1 Ignore {prepend}, and use partial string matches for
315 * {dbpath}.
316 * 2 Ignore {prepend}, and use exact string matches for
317 * {dbpath}.
318 * 3 Use {prepend}, use partial string matches for both
319 * {dbpath} and {prepend}.
320 * 4 Use {prepend}, use exact string matches for both
321 * {dbpath} and {prepend}.
323 * Note: All string comparisons are case sensitive!
325 #if defined(FEAT_EVAL) || defined(PROTO)
327 cs_connection(num, dbpath, ppath)
328 int num;
329 char_u *dbpath;
330 char_u *ppath;
332 int i;
334 if (num < 0 || num > 4 || (num > 0 && !dbpath))
335 return FALSE;
337 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
339 if (!csinfo[i].fname)
340 continue;
342 if (num == 0)
343 return TRUE;
345 switch (num)
347 case 1:
348 if (strstr(csinfo[i].fname, (char *)dbpath))
349 return TRUE;
350 break;
351 case 2:
352 if (strcmp(csinfo[i].fname, (char *)dbpath) == 0)
353 return TRUE;
354 break;
355 case 3:
356 if (strstr(csinfo[i].fname, (char *)dbpath)
357 && ((!ppath && !csinfo[i].ppath)
358 || (ppath
359 && csinfo[i].ppath
360 && strstr(csinfo[i].ppath, (char *)ppath))))
361 return TRUE;
362 break;
363 case 4:
364 if ((strcmp(csinfo[i].fname, (char *)dbpath) == 0)
365 && ((!ppath && !csinfo[i].ppath)
366 || (ppath
367 && csinfo[i].ppath
368 && (strcmp(csinfo[i].ppath, (char *)ppath) == 0))))
369 return TRUE;
370 break;
374 return FALSE;
375 } /* cs_connection */
376 #endif
380 * PRIVATE functions
381 ****************************************************************************/
384 * PRIVATE: cs_add
386 * add cscope database or a directory name (to look for cscope.out)
387 * the the cscope connection list
389 * MAXPATHL 256
391 /* ARGSUSED */
392 static int
393 cs_add(eap)
394 exarg_T *eap;
396 char *fname, *ppath, *flags = NULL;
398 if ((fname = strtok((char *)NULL, (const char *)" ")) == NULL)
400 cs_usage_msg(Add);
401 return CSCOPE_FAILURE;
403 if ((ppath = strtok((char *)NULL, (const char *)" ")) != NULL)
404 flags = strtok((char *)NULL, (const char *)" ");
406 return cs_add_common(fname, ppath, flags);
409 static void
410 cs_stat_emsg(fname)
411 char *fname;
413 char *stat_emsg = _("E563: stat(%s) error: %d");
414 char *buf = (char *)alloc((unsigned)strlen(stat_emsg) + MAXPATHL + 10);
416 if (buf != NULL)
418 (void)sprintf(buf, stat_emsg, fname, errno);
419 (void)EMSG(buf);
420 vim_free(buf);
422 else
423 (void)EMSG(_("E563: stat error"));
428 * PRIVATE: cs_add_common
430 * the common routine to add a new cscope connection. called by
431 * cs_add() and cs_reset(). i really don't like to do this, but this
432 * routine uses a number of goto statements.
434 static int
435 cs_add_common(arg1, arg2, flags)
436 char *arg1; /* filename - may contain environment variables */
437 char *arg2; /* prepend path - may contain environment variables */
438 char *flags;
440 struct stat statbuf;
441 int ret;
442 char *fname = NULL;
443 char *fname2 = NULL;
444 char *ppath = NULL;
445 int i;
447 /* get the filename (arg1), expand it, and try to stat it */
448 if ((fname = (char *)alloc(MAXPATHL + 1)) == NULL)
449 goto add_err;
451 expand_env((char_u *)arg1, (char_u *)fname, MAXPATHL);
452 ret = stat(fname, &statbuf);
453 if (ret < 0)
455 staterr:
456 if (p_csverbose)
457 cs_stat_emsg(fname);
458 goto add_err;
461 /* get the prepend path (arg2), expand it, and try to stat it */
462 if (arg2 != NULL)
464 struct stat statbuf2;
466 if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
467 goto add_err;
469 expand_env((char_u *)arg2, (char_u *)ppath, MAXPATHL);
470 ret = stat(ppath, &statbuf2);
471 if (ret < 0)
472 goto staterr;
475 /* if filename is a directory, append the cscope database name to it */
476 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
478 fname2 = (char *)alloc((unsigned)(strlen(CSCOPE_DBFILE) + strlen(fname) + 2));
479 if (fname2 == NULL)
480 goto add_err;
482 while (fname[strlen(fname)-1] == '/'
483 #ifdef WIN32
484 || fname[strlen(fname)-1] == '\\'
485 #endif
488 fname[strlen(fname)-1] = '\0';
489 if (strlen(fname) == 0)
490 break;
492 if (fname[0] == '\0')
493 (void)sprintf(fname2, "/%s", CSCOPE_DBFILE);
494 else
495 (void)sprintf(fname2, "%s/%s", fname, CSCOPE_DBFILE);
497 ret = stat(fname2, &statbuf);
498 if (ret < 0)
500 if (p_csverbose)
501 cs_stat_emsg(fname2);
502 goto add_err;
505 i = cs_insert_filelist(fname2, ppath, flags, &statbuf);
507 #if defined(UNIX)
508 else if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode))
509 #else
510 /* substitute define S_ISREG from os_unix.h */
511 else if (((statbuf.st_mode) & S_IFMT) == S_IFREG)
512 #endif
514 i = cs_insert_filelist(fname, ppath, flags, &statbuf);
516 else
518 if (p_csverbose)
519 (void)EMSG2(
520 _("E564: %s is not a directory or a valid cscope database"),
521 fname);
522 goto add_err;
525 if (i != -1)
527 if (cs_create_connection(i) == CSCOPE_FAILURE
528 || cs_read_prompt(i) == CSCOPE_FAILURE)
530 cs_release_csp(i, TRUE);
531 goto add_err;
534 if (p_csverbose)
536 msg_clr_eos();
537 (void)smsg_attr(hl_attr(HLF_R),
538 (char_u *)_("Added cscope database %s"),
539 csinfo[i].fname);
543 vim_free(fname);
544 vim_free(fname2);
545 vim_free(ppath);
546 return CSCOPE_SUCCESS;
548 add_err:
549 vim_free(fname2);
550 vim_free(fname);
551 vim_free(ppath);
552 return CSCOPE_FAILURE;
553 } /* cs_add_common */
556 static int
557 cs_check_for_connections()
559 return (cs_cnt_connections() > 0);
560 } /* cs_check_for_connections */
563 static int
564 cs_check_for_tags()
566 return (p_tags[0] != NUL && curbuf->b_p_tags != NULL);
567 } /* cs_check_for_tags */
571 * PRIVATE: cs_cnt_connections
573 * count the number of cscope connections
575 static int
576 cs_cnt_connections()
578 short i;
579 short cnt = 0;
581 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
583 if (csinfo[i].fname != NULL)
584 cnt++;
586 return cnt;
587 } /* cs_cnt_connections */
589 static void
590 cs_reading_emsg(idx)
591 int idx; /* connection index */
593 EMSGN(_("E262: error reading cscope connection %ld"), idx);
596 #define CSREAD_BUFSIZE 2048
598 * PRIVATE: cs_cnt_matches
600 * count the number of matches for a given cscope connection.
602 static int
603 cs_cnt_matches(idx)
604 int idx;
606 char *stok;
607 char *buf;
608 int nlines;
610 buf = (char *)alloc(CSREAD_BUFSIZE);
611 if (buf == NULL)
612 return 0;
613 for (;;)
615 if (!fgets(buf, CSREAD_BUFSIZE, csinfo[idx].fr_fp))
617 if (feof(csinfo[idx].fr_fp))
618 errno = EIO;
620 cs_reading_emsg(idx);
622 vim_free(buf);
623 return -1;
627 * If the database is out of date, or there's some other problem,
628 * cscope will output error messages before the number-of-lines output.
629 * Display/discard any output that doesn't match what we want.
631 if ((stok = strtok(buf, (const char *)" ")) == NULL)
632 continue;
633 if (strcmp((const char *)stok, "cscope:"))
634 continue;
636 if ((stok = strtok(NULL, (const char *)" ")) == NULL)
637 continue;
638 nlines = atoi(stok);
639 if (nlines < 0)
641 nlines = 0;
642 break;
645 if ((stok = strtok(NULL, (const char *)" ")) == NULL)
646 continue;
647 if (strncmp((const char *)stok, "lines", 5))
648 continue;
650 break;
653 vim_free(buf);
654 return nlines;
655 } /* cs_cnt_matches */
659 * PRIVATE: cs_create_cmd
661 * Creates the actual cscope command query from what the user entered.
663 static char *
664 cs_create_cmd(csoption, pattern)
665 char *csoption;
666 char *pattern;
668 char *cmd;
669 short search;
671 switch (csoption[0])
673 case '0' : case 's' :
674 search = 0;
675 break;
676 case '1' : case 'g' :
677 search = 1;
678 break;
679 case '2' : case 'd' :
680 search = 2;
681 break;
682 case '3' : case 'c' :
683 search = 3;
684 break;
685 case '4' : case 't' :
686 search = 4;
687 break;
688 case '6' : case 'e' :
689 search = 6;
690 break;
691 case '7' : case 'f' :
692 search = 7;
693 break;
694 case '8' : case 'i' :
695 search = 8;
696 break;
697 default :
698 (void)EMSG(_("E561: unknown cscope search type"));
699 cs_usage_msg(Find);
700 return NULL;
703 if ((cmd = (char *)alloc((unsigned)(strlen(pattern) + 2))) == NULL)
704 return NULL;
706 (void)sprintf(cmd, "%d%s", search, pattern);
708 return cmd;
709 } /* cs_create_cmd */
713 * PRIVATE: cs_create_connection
715 * This piece of code was taken/adapted from nvi. do we need to add
716 * the BSD license notice?
718 static int
719 cs_create_connection(i)
720 int i;
722 int to_cs[2], from_cs[2], len;
723 char *prog, *cmd, *ppath = NULL;
724 #ifndef UNIX
725 int in_save, out_save, err_save;
726 long_i ph;
727 # ifdef FEAT_GUI
728 HWND activewnd = NULL;
729 HWND consolewnd = NULL;
730 # endif
731 #endif
734 * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from
735 * from_cs[0] and writes to to_cs[1].
737 to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1;
738 if (pipe(to_cs) < 0 || pipe(from_cs) < 0)
740 (void)EMSG(_("E566: Could not create cscope pipes"));
741 err_closing:
742 if (to_cs[0] != -1)
743 (void)close(to_cs[0]);
744 if (to_cs[1] != -1)
745 (void)close(to_cs[1]);
746 if (from_cs[0] != -1)
747 (void)close(from_cs[0]);
748 if (from_cs[1] != -1)
749 (void)close(from_cs[1]);
750 return CSCOPE_FAILURE;
753 #if defined(UNIX)
754 switch (csinfo[i].pid = fork())
756 case -1:
757 (void)EMSG(_("E622: Could not fork for cscope"));
758 goto err_closing;
759 case 0: /* child: run cscope. */
760 #else
761 in_save = dup(STDIN_FILENO);
762 out_save = dup(STDOUT_FILENO);
763 err_save = dup(STDERR_FILENO);
764 #endif
765 if (dup2(to_cs[0], STDIN_FILENO) == -1)
766 PERROR("cs_create_connection 1");
767 if (dup2(from_cs[1], STDOUT_FILENO) == -1)
768 PERROR("cs_create_connection 2");
769 if (dup2(from_cs[1], STDERR_FILENO) == -1)
770 PERROR("cs_create_connection 3");
772 /* close unused */
773 #if defined(UNIX)
774 (void)close(to_cs[1]);
775 (void)close(from_cs[0]);
776 #else
777 /* On win32 we must close opposite ends because we are the parent */
778 (void)close(to_cs[0]);
779 to_cs[0] = -1;
780 (void)close(from_cs[1]);
781 from_cs[1] = -1;
782 #endif
783 /* expand the cscope exec for env var's */
784 if ((prog = (char *)alloc(MAXPATHL + 1)) == NULL)
786 #ifdef UNIX
787 return CSCOPE_FAILURE;
788 #else
789 goto err_closing;
790 #endif
792 expand_env((char_u *)p_csprg, (char_u *)prog, MAXPATHL);
794 /* alloc space to hold the cscope command */
795 len = (int)(strlen(prog) + strlen(csinfo[i].fname) + 32);
796 if (csinfo[i].ppath)
798 /* expand the prepend path for env var's */
799 if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL)
801 vim_free(prog);
802 #ifdef UNIX
803 return CSCOPE_FAILURE;
804 #else
805 goto err_closing;
806 #endif
808 expand_env((char_u *)csinfo[i].ppath, (char_u *)ppath, MAXPATHL);
810 len += (int)strlen(ppath);
813 if (csinfo[i].flags)
814 len += (int)strlen(csinfo[i].flags);
816 if ((cmd = (char *)alloc(len)) == NULL)
818 vim_free(prog);
819 vim_free(ppath);
820 #ifdef UNIX
821 return CSCOPE_FAILURE;
822 #else
823 goto err_closing;
824 #endif
827 /* run the cscope command; is there execl for non-unix systems? */
828 #if defined(UNIX)
829 (void)sprintf(cmd, "exec %s -dl -f %s", prog, csinfo[i].fname);
830 #else
831 (void)sprintf(cmd, "%s -dl -f %s", prog, csinfo[i].fname);
832 #endif
833 if (csinfo[i].ppath != NULL)
835 (void)strcat(cmd, " -P");
836 (void)strcat(cmd, csinfo[i].ppath);
838 if (csinfo[i].flags != NULL)
840 (void)strcat(cmd, " ");
841 (void)strcat(cmd, csinfo[i].flags);
843 # ifdef UNIX
844 /* on Win32 we still need prog */
845 vim_free(prog);
846 # endif
847 vim_free(ppath);
849 #if defined(UNIX)
850 if (execl("/bin/sh", "sh", "-c", cmd, NULL) == -1)
851 PERROR(_("cs_create_connection exec failed"));
853 exit(127);
854 /* NOTREACHED */
855 default: /* parent. */
856 #else
857 # ifdef FEAT_GUI
858 activewnd = GetForegroundWindow(); /* on win9x cscope steals focus */
859 /* Dirty hack to hide annoying console window */
860 if (AllocConsole())
862 char *title;
863 title = (char *)alloc(1024);
864 if (title == NULL)
865 FreeConsole();
866 else
868 GetConsoleTitle(title, 1024); /* save for future restore */
869 SetConsoleTitle(
870 "GVIMCS{5499421B-CBEF-45b0-85EF-38167FDEA5C5}GVIMCS");
871 Sleep(40); /* as stated in MS KB we must wait 40 ms */
872 consolewnd = FindWindow(NULL,
873 "GVIMCS{5499421B-CBEF-45b0-85EF-38167FDEA5C5}GVIMCS");
874 if (consolewnd != NULL)
875 ShowWindow(consolewnd, SW_HIDE);
876 SetConsoleTitle(title);
877 vim_free(title);
880 # endif
881 /* May be use &shell, &shellquote etc */
882 # ifdef __BORLANDC__
883 /* BCC 5.5 uses a different function name for spawnlp */
884 ph = (long_i)spawnlp(P_NOWAIT, prog, cmd, NULL);
885 # else
886 ph = (long_i)_spawnlp(_P_NOWAIT, prog, cmd, NULL);
887 # endif
888 vim_free(prog);
889 vim_free(cmd);
890 # ifdef FEAT_GUI
891 /* Dirty hack part two */
892 if (activewnd != NULL)
893 /* restoring focus */
894 SetForegroundWindow(activewnd);
895 if (consolewnd != NULL)
896 FreeConsole();
898 # endif
899 if (ph == -1)
901 PERROR(_("cs_create_connection exec failed"));
902 (void)EMSG(_("E623: Could not spawn cscope process"));
903 goto err_closing;
905 /* else */
906 csinfo[i].pid = 0;
907 csinfo[i].hProc = (HANDLE)ph;
909 #endif /* !UNIX */
911 * Save the file descriptors for later duplication, and
912 * reopen as streams.
914 if ((csinfo[i].to_fp = fdopen(to_cs[1], "w")) == NULL)
915 PERROR(_("cs_create_connection: fdopen for to_fp failed"));
916 if ((csinfo[i].fr_fp = fdopen(from_cs[0], "r")) == NULL)
917 PERROR(_("cs_create_connection: fdopen for fr_fp failed"));
919 #if defined(UNIX)
920 /* close unused */
921 (void)close(to_cs[0]);
922 (void)close(from_cs[1]);
924 break;
926 #else
927 /* restore stdhandles */
928 dup2(in_save, STDIN_FILENO);
929 dup2(out_save, STDOUT_FILENO);
930 dup2(err_save, STDERR_FILENO);
931 close(in_save);
932 close(out_save);
933 close(err_save);
934 #endif
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 == NULL || (pat != NULL && pat[0] == '\0'))
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 char **matches, **contexts;
993 int nummatches[CSCOPE_MAX_CONNECTIONS], totmatches, matched;
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)
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 cs_file_results(f, nummatches);
1111 fclose(f);
1112 if (use_ll) /* Use location list */
1113 wp = curwin;
1114 /* '-' starts a new error list */
1115 if (qf_init(wp, tmp, (char_u *)"%f%*\\t%l%*\\t%m", *qfpos == '-') > 0)
1117 # ifdef FEAT_WINDOWS
1118 if (postponed_split != 0)
1120 win_split(postponed_split > 0 ? postponed_split : 0,
1121 postponed_split_flags);
1122 # ifdef FEAT_SCROLLBIND
1123 curwin->w_p_scb = FALSE;
1124 # endif
1125 postponed_split = 0;
1127 # endif
1128 if (use_ll)
1130 * In the location list window, use the displayed location
1131 * list. Otherwise, use the location list for the window.
1133 qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL) ?
1134 wp->w_llist_ref : wp->w_llist;
1135 qf_jump(qi, 0, 0, forceit);
1137 mch_remove(tmp);
1138 vim_free(tmp);
1139 return TRUE;
1141 else
1142 #endif /* FEAT_QUICKFIX */
1144 /* read output */
1145 cs_fill_results((char *)pat, totmatches, nummatches, &matches,
1146 &contexts, &matched);
1147 if (matches == NULL)
1148 return FALSE;
1150 (void)cs_manage_matches(matches, contexts, matched, Store);
1152 return do_tag((char_u *)pat, DT_CSCOPE, 0, forceit, verbose);
1155 } /* cs_find_common */
1158 * PRIVATE: cs_help
1160 * print help
1162 /* ARGSUSED */
1163 static int
1164 cs_help(eap)
1165 exarg_T *eap;
1167 cscmd_T *cmdp = cs_cmds;
1169 (void)MSG_PUTS(_("cscope commands:\n"));
1170 while (cmdp->name != NULL)
1172 (void)smsg((char_u *)_("%-5s: %-30s (Usage: %s)"),
1173 cmdp->name, _(cmdp->help), cmdp->usage);
1174 if (strcmp(cmdp->name, "find") == 0)
1175 MSG_PUTS(FIND_HELP);
1176 cmdp++;
1179 wait_return(TRUE);
1180 return 0;
1181 } /* cs_help */
1185 * PRIVATE: cs_init
1187 * initialize cscope structure if not already
1189 static void
1190 cs_init()
1192 short i;
1193 static int init_already = FALSE;
1195 if (init_already)
1196 return;
1198 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1199 clear_csinfo(i);
1201 init_already = TRUE;
1202 } /* cs_init */
1204 static void
1205 clear_csinfo(i)
1206 int i;
1208 csinfo[i].fname = NULL;
1209 csinfo[i].ppath = NULL;
1210 csinfo[i].flags = NULL;
1211 #if defined(UNIX)
1212 csinfo[i].st_dev = (dev_t)0;
1213 csinfo[i].st_ino = (ino_t)0;
1214 #else
1215 csinfo[i].nVolume = 0;
1216 csinfo[i].nIndexHigh = 0;
1217 csinfo[i].nIndexLow = 0;
1218 #endif
1219 csinfo[i].pid = -1;
1220 csinfo[i].fr_fp = NULL;
1221 csinfo[i].to_fp = NULL;
1222 #if defined(WIN32)
1223 csinfo[i].hProc = NULL;
1224 #endif
1227 #ifndef UNIX
1228 static char *GetWin32Error __ARGS((void));
1230 static char *
1231 GetWin32Error()
1233 char *msg = NULL;
1234 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1235 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
1236 if (msg != NULL)
1238 /* remove trailing \r\n */
1239 char *pcrlf = strstr(msg, "\r\n");
1240 if (pcrlf != NULL)
1241 *pcrlf = '\0';
1243 return msg;
1245 #endif
1248 * PRIVATE: cs_insert_filelist
1250 * insert a new cscope database filename into the filelist
1252 /*ARGSUSED*/
1253 static int
1254 cs_insert_filelist(fname, ppath, flags, sb)
1255 char *fname;
1256 char *ppath;
1257 char *flags;
1258 struct stat *sb;
1260 short i, j;
1261 #ifndef UNIX
1262 HANDLE hFile;
1263 BY_HANDLE_FILE_INFORMATION bhfi;
1265 vim_memset(&bhfi, 0, sizeof(bhfi));
1266 /* On windows 9x GetFileInformationByHandle doesn't work, so skip it */
1267 if (!mch_windows95())
1269 hFile = CreateFile(fname, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
1270 FILE_ATTRIBUTE_NORMAL, NULL);
1271 if (hFile == INVALID_HANDLE_VALUE)
1273 if (p_csverbose)
1275 char *cant_msg = _("E625: cannot open cscope database: %s");
1276 char *winmsg = GetWin32Error();
1278 if (winmsg != NULL)
1280 (void)EMSG2(cant_msg, winmsg);
1281 LocalFree(winmsg);
1283 else
1284 /* subst filename if can't get error text */
1285 (void)EMSG2(cant_msg, fname);
1287 return -1;
1289 if (!GetFileInformationByHandle(hFile, &bhfi))
1291 CloseHandle(hFile);
1292 if (p_csverbose)
1293 (void)EMSG(_("E626: cannot get cscope database information"));
1294 return -1;
1296 CloseHandle(hFile);
1298 #endif
1300 i = -1; /* can be set to the index of an empty item in csinfo */
1301 for (j = 0; j < CSCOPE_MAX_CONNECTIONS; j++)
1303 if (csinfo[j].fname != NULL
1304 #if defined(UNIX)
1305 && csinfo[j].st_dev == sb->st_dev && csinfo[j].st_ino == sb->st_ino
1306 #else
1307 /* compare pathnames first */
1308 && ((fullpathcmp(csinfo[j].fname, fname, FALSE) & FPC_SAME)
1309 /* if not Windows 9x, test index file atributes too */
1310 || (!mch_windows95()
1311 && csinfo[j].nVolume == bhfi.dwVolumeSerialNumber
1312 && csinfo[j].nIndexHigh == bhfi.nFileIndexHigh
1313 && csinfo[j].nIndexLow == bhfi.nFileIndexLow))
1314 #endif
1317 if (p_csverbose)
1318 (void)EMSG(_("E568: duplicate cscope database not added"));
1319 return -1;
1322 if (csinfo[j].fname == NULL && i == -1)
1323 i = j; /* remember first empty entry */
1326 if (i == -1)
1328 if (p_csverbose)
1329 (void)EMSG(_("E569: maximum number of cscope connections reached"));
1330 return -1;
1333 if ((csinfo[i].fname = (char *)alloc((unsigned)strlen(fname)+1)) == NULL)
1334 return -1;
1336 (void)strcpy(csinfo[i].fname, (const char *)fname);
1338 if (ppath != NULL)
1340 if ((csinfo[i].ppath = (char *)alloc((unsigned)strlen(ppath) + 1)) == NULL)
1342 vim_free(csinfo[i].fname);
1343 csinfo[i].fname = NULL;
1344 return -1;
1346 (void)strcpy(csinfo[i].ppath, (const char *)ppath);
1347 } else
1348 csinfo[i].ppath = NULL;
1350 if (flags != NULL)
1352 if ((csinfo[i].flags = (char *)alloc((unsigned)strlen(flags) + 1)) == NULL)
1354 vim_free(csinfo[i].fname);
1355 vim_free(csinfo[i].ppath);
1356 csinfo[i].fname = NULL;
1357 csinfo[i].ppath = NULL;
1358 return -1;
1360 (void)strcpy(csinfo[i].flags, (const char *)flags);
1361 } else
1362 csinfo[i].flags = NULL;
1364 #if defined(UNIX)
1365 csinfo[i].st_dev = sb->st_dev;
1366 csinfo[i].st_ino = sb->st_ino;
1368 #else
1369 csinfo[i].nVolume = bhfi.dwVolumeSerialNumber;
1370 csinfo[i].nIndexLow = bhfi.nFileIndexLow;
1371 csinfo[i].nIndexHigh = bhfi.nFileIndexHigh;
1372 #endif
1373 return i;
1374 } /* cs_insert_filelist */
1378 * PRIVATE: cs_lookup_cmd
1380 * find cscope command in command table
1382 static cscmd_T *
1383 cs_lookup_cmd(eap)
1384 exarg_T *eap;
1386 cscmd_T *cmdp;
1387 char *stok;
1388 size_t len;
1390 if (eap->arg == NULL)
1391 return NULL;
1393 if ((stok = strtok((char *)(eap->arg), (const char *)" ")) == NULL)
1394 return NULL;
1396 len = strlen(stok);
1397 for (cmdp = cs_cmds; cmdp->name != NULL; ++cmdp)
1399 if (strncmp((const char *)(stok), cmdp->name, len) == 0)
1400 return (cmdp);
1402 return NULL;
1403 } /* cs_lookup_cmd */
1407 * PRIVATE: cs_kill
1409 * nuke em
1411 /* ARGSUSED */
1412 static int
1413 cs_kill(eap)
1414 exarg_T *eap;
1416 char *stok;
1417 short i;
1419 if ((stok = strtok((char *)NULL, (const char *)" ")) == NULL)
1421 cs_usage_msg(Kill);
1422 return CSCOPE_FAILURE;
1425 /* only single digit positive and negative integers are allowed */
1426 if ((strlen(stok) < 2 && VIM_ISDIGIT((int)(stok[0])))
1427 || (strlen(stok) < 3 && stok[0] == '-'
1428 && VIM_ISDIGIT((int)(stok[1]))))
1429 i = atoi(stok);
1430 else
1432 /* It must be part of a name. We will try to find a match
1433 * within all the names in the csinfo data structure
1435 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1437 if (csinfo[i].fname != NULL && strstr(csinfo[i].fname, stok))
1438 break;
1442 if ((i >= CSCOPE_MAX_CONNECTIONS || i < -1 || csinfo[i].fname == NULL)
1443 && i != -1)
1445 if (p_csverbose)
1446 (void)EMSG2(_("E261: cscope connection %s not found"), stok);
1448 else
1450 if (i == -1)
1452 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1454 if (csinfo[i].fname)
1455 cs_kill_execute(i, csinfo[i].fname);
1458 else
1459 cs_kill_execute(i, stok);
1462 return 0;
1463 } /* cs_kill */
1467 * PRIVATE: cs_kill_execute
1469 * Actually kills a specific cscope connection.
1471 static void
1472 cs_kill_execute(i, cname)
1473 int i; /* cscope table index */
1474 char *cname; /* cscope database name */
1476 if (p_csverbose)
1478 msg_clr_eos();
1479 (void)smsg_attr(hl_attr(HLF_R) | MSG_HIST,
1480 (char_u *)_("cscope connection %s closed"), cname);
1482 cs_release_csp(i, TRUE);
1487 * PRIVATE: cs_make_vim_style_matches
1489 * convert the cscope output into into a ctags style entry (as might be found
1490 * in a ctags tags file). there's one catch though: cscope doesn't tell you
1491 * the type of the tag you are looking for. for example, in Darren Hiebert's
1492 * ctags (the one that comes with vim), #define's use a line number to find the
1493 * tag in a file while function definitions use a regexp search pattern.
1495 * i'm going to always use the line number because cscope does something
1496 * quirky (and probably other things i don't know about):
1498 * if you have "# define" in your source file, which is
1499 * perfectly legal, cscope thinks you have "#define". this
1500 * will result in a failed regexp search. :(
1502 * besides, even if this particular case didn't happen, the search pattern
1503 * would still have to be modified to escape all the special regular expression
1504 * characters to comply with ctags formatting.
1506 static char *
1507 cs_make_vim_style_matches(fname, slno, search, tagstr)
1508 char *fname;
1509 char *slno;
1510 char *search;
1511 char *tagstr;
1513 /* vim style is ctags:
1515 * <tagstr>\t<filename>\t<linenum_or_search>"\t<extra>
1517 * but as mentioned above, we'll always use the line number and
1518 * put the search pattern (if one exists) as "extra"
1520 * buf is used as part of vim's method of handling tags, and
1521 * (i think) vim frees it when you pop your tags and get replaced
1522 * by new ones on the tag stack.
1524 char *buf;
1525 int amt;
1527 if (search != NULL)
1529 amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + strlen(search)+6);
1530 if ((buf = (char *)alloc(amt)) == NULL)
1531 return NULL;
1533 (void)sprintf(buf, "%s\t%s\t%s;\"\t%s", tagstr, fname, slno, search);
1535 else
1537 amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + 5);
1538 if ((buf = (char *)alloc(amt)) == NULL)
1539 return NULL;
1541 (void)sprintf(buf, "%s\t%s\t%s;\"", tagstr, fname, slno);
1544 return buf;
1545 } /* cs_make_vim_style_matches */
1549 * PRIVATE: cs_manage_matches
1551 * this is kind of hokey, but i don't see an easy way round this..
1553 * Store: keep a ptr to the (malloc'd) memory of matches originally
1554 * generated from cs_find(). the matches are originally lines directly
1555 * from cscope output, but transformed to look like something out of a
1556 * ctags. see cs_make_vim_style_matches for more details.
1558 * Get: used only from cs_fgets(), this simulates a vim_fgets() to return
1559 * the next line from the cscope output. it basically keeps track of which
1560 * lines have been "used" and returns the next one.
1562 * Free: frees up everything and resets
1564 * Print: prints the tags
1566 static char *
1567 cs_manage_matches(matches, contexts, totmatches, cmd)
1568 char **matches;
1569 char **contexts;
1570 int totmatches;
1571 mcmd_e cmd;
1573 static char **mp = NULL;
1574 static char **cp = NULL;
1575 static int cnt = -1;
1576 static int next = -1;
1577 char *p = NULL;
1579 switch (cmd)
1581 case Store:
1582 assert(matches != NULL);
1583 assert(totmatches > 0);
1584 if (mp != NULL || cp != NULL)
1585 (void)cs_manage_matches(NULL, NULL, -1, Free);
1586 mp = matches;
1587 cp = contexts;
1588 cnt = totmatches;
1589 next = 0;
1590 break;
1591 case Get:
1592 if (next >= cnt)
1593 return NULL;
1595 p = mp[next];
1596 next++;
1597 break;
1598 case Free:
1599 if (mp != NULL)
1601 if (cnt > 0)
1602 while (cnt--)
1604 vim_free(mp[cnt]);
1605 if (cp != NULL)
1606 vim_free(cp[cnt]);
1608 vim_free(mp);
1609 vim_free(cp);
1611 mp = NULL;
1612 cp = NULL;
1613 cnt = 0;
1614 next = 0;
1615 break;
1616 case Print:
1617 cs_print_tags_priv(mp, cp, cnt);
1618 break;
1619 default: /* should not reach here */
1620 (void)EMSG(_("E570: fatal error in cs_manage_matches"));
1621 return NULL;
1624 return p;
1625 } /* cs_manage_matches */
1629 * PRIVATE: cs_parse_results
1631 * parse cscope output
1633 static char *
1634 cs_parse_results(cnumber, buf, bufsize, context, linenumber, search)
1635 int cnumber;
1636 char *buf;
1637 int bufsize;
1638 char **context;
1639 char **linenumber;
1640 char **search;
1642 int ch;
1643 char *p;
1644 char *name;
1646 if (fgets(buf, bufsize, csinfo[cnumber].fr_fp) == NULL)
1648 if (feof(csinfo[cnumber].fr_fp))
1649 errno = EIO;
1651 cs_reading_emsg(cnumber);
1653 return NULL;
1656 /* If the line's too long for the buffer, discard it. */
1657 if ((p = strchr(buf, '\n')) == NULL)
1659 while ((ch = getc(csinfo[cnumber].fr_fp)) != EOF && ch != '\n')
1661 return NULL;
1663 *p = '\0';
1666 * cscope output is in the following format:
1668 * <filename> <context> <line number> <pattern>
1670 if ((name = strtok((char *)buf, (const char *)" ")) == NULL)
1671 return NULL;
1672 if ((*context = strtok(NULL, (const char *)" ")) == NULL)
1673 return NULL;
1674 if ((*linenumber = strtok(NULL, (const char *)" ")) == NULL)
1675 return NULL;
1676 *search = *linenumber + strlen(*linenumber) + 1; /* +1 to skip \0 */
1678 /* --- nvi ---
1679 * If the file is older than the cscope database, that is,
1680 * the database was built since the file was last modified,
1681 * or there wasn't a search string, use the line number.
1683 if (strcmp(*search, "<unknown>") == 0)
1684 *search = NULL;
1686 name = cs_resolve_file(cnumber, name);
1687 return name;
1690 #ifdef FEAT_QUICKFIX
1692 * PRIVATE: cs_file_results
1694 * write cscope find results to file
1696 static void
1697 cs_file_results(f, nummatches_a)
1698 FILE *f;
1699 int *nummatches_a;
1701 int i, j;
1702 char *buf;
1703 char *search, *slno;
1704 char *fullname;
1705 char *cntx;
1706 char *context;
1708 buf = (char *)alloc(CSREAD_BUFSIZE);
1709 if (buf == NULL)
1710 return;
1712 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1714 if (nummatches_a[i] < 1)
1715 continue;
1717 for (j = 0; j < nummatches_a[i]; j++)
1719 if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1720 &slno, &search)) == NULL)
1721 continue;
1723 context = (char *)alloc((unsigned)strlen(cntx)+5);
1724 if (context==NULL)
1725 continue;
1727 if (strcmp(cntx, "<global>")==0)
1728 strcpy(context, "<<global>>");
1729 else
1730 sprintf(context, "<<%s>>", cntx);
1732 if (search==NULL)
1733 fprintf(f, "%s\t%s\t%s\n", fullname, slno, context);
1734 else
1735 fprintf(f, "%s\t%s\t%s %s\n", fullname, slno, context, search);
1737 vim_free(context);
1738 vim_free(fullname);
1739 } /* for all matches */
1741 (void)cs_read_prompt(i);
1743 } /* for all cscope connections */
1744 vim_free(buf);
1746 #endif
1749 * PRIVATE: cs_fill_results
1751 * get parsed cscope output and calls cs_make_vim_style_matches to convert
1752 * into ctags format
1753 * When there are no matches sets "*matches_p" to NULL.
1755 static void
1756 cs_fill_results(tagstr, totmatches, nummatches_a, matches_p, cntxts_p, matched)
1757 char *tagstr;
1758 int totmatches;
1759 int *nummatches_a;
1760 char ***matches_p;
1761 char ***cntxts_p;
1762 int *matched;
1764 int i, j;
1765 char *buf;
1766 char *search, *slno;
1767 int totsofar = 0;
1768 char **matches = NULL;
1769 char **cntxts = NULL;
1770 char *fullname;
1771 char *cntx;
1773 assert(totmatches > 0);
1775 buf = (char *)alloc(CSREAD_BUFSIZE);
1776 if (buf == NULL)
1777 return;
1779 if ((matches = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1780 goto parse_out;
1781 if ((cntxts = (char **)alloc(sizeof(char *) * totmatches)) == NULL)
1782 goto parse_out;
1784 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
1786 if (nummatches_a[i] < 1)
1787 continue;
1789 for (j = 0; j < nummatches_a[i]; j++)
1791 if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx,
1792 &slno, &search)) == NULL)
1793 continue;
1795 matches[totsofar] = cs_make_vim_style_matches(fullname, slno,
1796 search, tagstr);
1798 vim_free(fullname);
1800 if (strcmp(cntx, "<global>") == 0)
1801 cntxts[totsofar] = NULL;
1802 else
1803 /* note: if vim_strsave returns NULL, then the context
1804 * will be "<global>", which is misleading.
1806 cntxts[totsofar] = (char *)vim_strsave((char_u *)cntx);
1808 if (matches[totsofar] != NULL)
1809 totsofar++;
1811 } /* for all matches */
1813 (void)cs_read_prompt(i);
1815 } /* for all cscope connections */
1817 parse_out:
1818 if (totsofar == 0)
1820 /* No matches, free the arrays and return NULL in "*matches_p". */
1821 vim_free(matches);
1822 matches = NULL;
1823 vim_free(cntxts);
1824 cntxts = NULL;
1826 *matched = totsofar;
1827 *matches_p = matches;
1828 *cntxts_p = cntxts;
1830 vim_free(buf);
1831 } /* cs_fill_results */
1834 /* get the requested path components */
1835 static char *
1836 cs_pathcomponents(path)
1837 char *path;
1839 int i;
1840 char *s;
1842 if (p_cspc == 0)
1843 return path;
1845 s = path + strlen(path) - 1;
1846 for (i = 0; i < p_cspc; ++i)
1847 while (s > path && *--s != '/'
1848 #ifdef WIN32
1849 && *--s != '\\'
1850 #endif
1853 if ((s > path && *s == '/')
1854 #ifdef WIN32
1855 || (s > path && *s == '\\')
1856 #endif
1858 ++s;
1859 return s;
1863 * PRIVATE: cs_print_tags_priv
1865 * called from cs_manage_matches()
1867 static void
1868 cs_print_tags_priv(matches, cntxts, num_matches)
1869 char **matches;
1870 char **cntxts;
1871 int num_matches;
1873 char *buf = NULL;
1874 int bufsize = 0; /* Track available bufsize */
1875 int newsize = 0;
1876 char *ptag;
1877 char *fname, *lno, *extra, *tbuf;
1878 int i, idx, num;
1879 char *globalcntx = "GLOBAL";
1880 char *cntxformat = " <<%s>>";
1881 char *context;
1882 char *cstag_msg = _("Cscope tag: %s");
1883 char *csfmt_str = "%4d %6s ";
1885 assert (num_matches > 0);
1887 if ((tbuf = (char *)alloc((unsigned)strlen(matches[0]) + 1)) == NULL)
1888 return;
1890 strcpy(tbuf, matches[0]);
1891 ptag = strtok(tbuf, "\t");
1893 newsize = (int)(strlen(cstag_msg) + strlen(ptag));
1894 buf = (char *)alloc(newsize);
1895 if (buf != NULL)
1897 bufsize = newsize;
1898 (void)sprintf(buf, cstag_msg, ptag);
1899 MSG_PUTS_ATTR(buf, hl_attr(HLF_T));
1902 vim_free(tbuf);
1904 MSG_PUTS_ATTR(_("\n # line"), hl_attr(HLF_T)); /* strlen is 7 */
1905 msg_advance(msg_col + 2);
1906 MSG_PUTS_ATTR(_("filename / context / line\n"), hl_attr(HLF_T));
1908 num = 1;
1909 for (i = 0; i < num_matches; i++)
1911 idx = i;
1913 /* if we really wanted to, we could avoid this malloc and strcpy
1914 * by parsing matches[i] on the fly and placing stuff into buf
1915 * directly, but that's too much of a hassle
1917 if ((tbuf = (char *)alloc((unsigned)strlen(matches[idx]) + 1)) == NULL)
1918 continue;
1919 (void)strcpy(tbuf, matches[idx]);
1921 if ((fname = strtok(tbuf, (const char *)"\t")) == NULL)
1922 continue;
1923 if ((fname = strtok(NULL, (const char *)"\t")) == NULL)
1924 continue;
1925 if ((lno = strtok(NULL, (const char *)"\t")) == NULL)
1927 /* if NULL, then no "extra", although in cscope's case, there
1928 * should always be "extra".
1930 extra = NULL;
1933 extra = lno + strlen(lno) + 1;
1935 lno[strlen(lno)-2] = '\0'; /* ignore ;" at the end */
1937 /* hopefully 'num' (num of matches) will be less than 10^16 */
1938 newsize = (int)(strlen(csfmt_str) + 16 + strlen(lno));
1939 if (bufsize < newsize)
1941 buf = (char *)vim_realloc(buf, newsize);
1942 if (buf == NULL)
1943 bufsize = 0;
1944 else
1945 bufsize = newsize;
1947 if (buf != NULL)
1949 /* csfmt_str = "%4d %6s "; */
1950 (void)sprintf(buf, csfmt_str, num, lno);
1951 MSG_PUTS_ATTR(buf, hl_attr(HLF_CM));
1953 MSG_PUTS_LONG_ATTR(cs_pathcomponents(fname), hl_attr(HLF_CM));
1955 /* compute the required space for the context */
1956 if (cntxts[idx] != NULL)
1957 context = cntxts[idx];
1958 else
1959 context = globalcntx;
1960 newsize = (int)(strlen(context) + strlen(cntxformat));
1962 if (bufsize < newsize)
1964 buf = (char *)vim_realloc(buf, newsize);
1965 if (buf == NULL)
1966 bufsize = 0;
1967 else
1968 bufsize = newsize;
1970 if (buf != NULL)
1972 (void)sprintf(buf, cntxformat, context);
1974 /* print the context only if it fits on the same line */
1975 if (msg_col + (int)strlen(buf) >= (int)Columns)
1976 msg_putchar('\n');
1977 msg_advance(12);
1978 MSG_PUTS_LONG(buf);
1979 msg_putchar('\n');
1981 if (extra != NULL)
1983 msg_advance(13);
1984 MSG_PUTS_LONG(extra);
1987 vim_free(tbuf); /* only after printing extra due to strtok use */
1989 if (msg_col)
1990 msg_putchar('\n');
1992 ui_breakcheck();
1993 if (got_int)
1995 got_int = FALSE; /* don't print any more matches */
1996 break;
1999 num++;
2000 } /* for all matches */
2002 vim_free(buf);
2003 } /* cs_print_tags_priv */
2007 * PRIVATE: cs_read_prompt
2009 * read a cscope prompt (basically, skip over the ">> ")
2011 static int
2012 cs_read_prompt(i)
2013 int i;
2015 int ch;
2016 char *buf = NULL; /* buffer for possible error message from cscope */
2017 int bufpos = 0;
2018 char *cs_emsg;
2019 int maxlen;
2020 static char *eprompt = "Press the RETURN key to continue:";
2021 int epromptlen = (int)strlen(eprompt);
2022 int n;
2024 cs_emsg = _("E609: Cscope error: %s");
2025 /* compute maximum allowed len for Cscope error message */
2026 maxlen = (int)(IOSIZE - strlen(cs_emsg));
2028 for (;;)
2030 while ((ch = getc(csinfo[i].fr_fp)) != EOF && ch != CSCOPE_PROMPT[0])
2031 /* if there is room and char is printable */
2032 if (bufpos < maxlen - 1 && vim_isprintc(ch))
2034 if (buf == NULL) /* lazy buffer allocation */
2035 buf = (char *)alloc(maxlen);
2036 if (buf != NULL)
2038 /* append character to the message */
2039 buf[bufpos++] = ch;
2040 buf[bufpos] = NUL;
2041 if (bufpos >= epromptlen
2042 && strcmp(&buf[bufpos - epromptlen], eprompt) == 0)
2044 /* remove eprompt from buf */
2045 buf[bufpos - epromptlen] = NUL;
2047 /* print message to user */
2048 (void)EMSG2(cs_emsg, buf);
2050 /* send RETURN to cscope */
2051 (void)putc('\n', csinfo[i].to_fp);
2052 (void)fflush(csinfo[i].to_fp);
2054 /* clear buf */
2055 bufpos = 0;
2056 buf[bufpos] = NUL;
2061 for (n = 0; n < (int)strlen(CSCOPE_PROMPT); ++n)
2063 if (n > 0)
2064 ch = getc(csinfo[i].fr_fp);
2065 if (ch == EOF)
2067 PERROR("cs_read_prompt EOF");
2068 if (buf != NULL && buf[0] != NUL)
2069 (void)EMSG2(cs_emsg, buf);
2070 else if (p_csverbose)
2071 cs_reading_emsg(i); /* don't have additional information */
2072 cs_release_csp(i, TRUE);
2073 vim_free(buf);
2074 return CSCOPE_FAILURE;
2077 if (ch != CSCOPE_PROMPT[n])
2079 ch = EOF;
2080 break;
2084 if (ch == EOF)
2085 continue; /* didn't find the prompt */
2086 break; /* did find the prompt */
2089 vim_free(buf);
2090 return CSCOPE_SUCCESS;
2095 * PRIVATE: cs_release_csp
2097 * does the actual free'ing for the cs ptr with an optional flag of whether
2098 * or not to free the filename. called by cs_kill and cs_reset.
2100 static void
2101 cs_release_csp(i, freefnpp)
2102 int i;
2103 int freefnpp;
2105 #if defined(UNIX)
2106 int pstat;
2107 #else
2109 * Trying to exit normally (not sure whether it is fit to UNIX cscope
2111 if (csinfo[i].to_fp != NULL)
2113 (void)fputs("q\n", csinfo[i].to_fp);
2114 (void)fflush(csinfo[i].to_fp);
2116 /* give cscope chance to exit normally */
2117 if (csinfo[i].hProc != NULL
2118 && WaitForSingleObject(csinfo[i].hProc, 1000) == WAIT_TIMEOUT)
2119 TerminateProcess(csinfo[i].hProc, 0);
2120 #endif
2122 if (csinfo[i].fr_fp != NULL)
2123 (void)fclose(csinfo[i].fr_fp);
2124 if (csinfo[i].to_fp != NULL)
2125 (void)fclose(csinfo[i].to_fp);
2128 * Safety check: If the PID would be zero here, the entire X session would
2129 * be killed. -1 and 1 are dangerous as well.
2131 #if defined(UNIX)
2132 if (csinfo[i].pid > 1)
2134 kill(csinfo[i].pid, SIGTERM);
2135 (void)waitpid(csinfo[i].pid, &pstat, 0);
2137 #endif
2139 if (freefnpp)
2141 vim_free(csinfo[i].fname);
2142 vim_free(csinfo[i].ppath);
2143 vim_free(csinfo[i].flags);
2146 clear_csinfo(i);
2147 } /* cs_release_csp */
2151 * PRIVATE: cs_reset
2153 * calls cs_kill on all cscope connections then reinits
2155 /* ARGSUSED */
2156 static int
2157 cs_reset(eap)
2158 exarg_T *eap;
2160 char **dblist = NULL, **pplist = NULL, **fllist = NULL;
2161 int i;
2162 char buf[20]; /* for sprintf " (#%d)" */
2164 /* malloc our db and ppath list */
2165 dblist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2166 pplist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2167 fllist = (char **)alloc(CSCOPE_MAX_CONNECTIONS * sizeof(char *));
2168 if (dblist == NULL || pplist == NULL || fllist == NULL)
2170 vim_free(dblist);
2171 vim_free(pplist);
2172 vim_free(fllist);
2173 return CSCOPE_FAILURE;
2176 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2178 dblist[i] = csinfo[i].fname;
2179 pplist[i] = csinfo[i].ppath;
2180 fllist[i] = csinfo[i].flags;
2181 if (csinfo[i].fname != NULL)
2182 cs_release_csp(i, FALSE);
2185 /* rebuild the cscope connection list */
2186 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2188 if (dblist[i] != NULL)
2190 cs_add_common(dblist[i], pplist[i], fllist[i]);
2191 if (p_csverbose)
2193 /* dont' use smsg_attr because want to display
2194 * connection number in the same line as
2195 * "Added cscope database..."
2197 sprintf(buf, " (#%d)", i);
2198 MSG_PUTS_ATTR(buf, hl_attr(HLF_R));
2201 vim_free(dblist[i]);
2202 vim_free(pplist[i]);
2203 vim_free(fllist[i]);
2205 vim_free(dblist);
2206 vim_free(pplist);
2207 vim_free(fllist);
2209 if (p_csverbose)
2210 MSG_ATTR(_("All cscope databases reset"), hl_attr(HLF_R) | MSG_HIST);
2211 return CSCOPE_SUCCESS;
2212 } /* cs_reset */
2216 * PRIVATE: cs_resolve_file
2218 * construct the full pathname to a file found in the cscope database.
2219 * (Prepends ppath, if there is one and if it's not already prepended,
2220 * otherwise just uses the name found.)
2222 * we need to prepend the prefix because on some cscope's (e.g., the one that
2223 * ships with Solaris 2.6), the output never has the prefix prepended.
2224 * contrast this with my development system (Digital Unix), which does.
2226 static char *
2227 cs_resolve_file(i, name)
2228 int i;
2229 char *name;
2231 char *fullname;
2232 int len;
2235 * ppath is freed when we destroy the cscope connection.
2236 * fullname is freed after cs_make_vim_style_matches, after it's been
2237 * copied into the tag buffer used by vim
2239 len = (int)(strlen(name) + 2);
2240 if (csinfo[i].ppath != NULL)
2241 len += (int)strlen(csinfo[i].ppath);
2243 if ((fullname = (char *)alloc(len)) == NULL)
2244 return NULL;
2247 * note/example: this won't work if the cscope output already starts
2248 * "../.." and the prefix path is also "../..". if something like this
2249 * happens, you are screwed up and need to fix how you're using cscope.
2251 if (csinfo[i].ppath != NULL &&
2252 (strncmp(name, csinfo[i].ppath, strlen(csinfo[i].ppath)) != 0) &&
2253 (name[0] != '/')
2254 #ifdef WIN32
2255 && name[0] != '\\' && name[1] != ':'
2256 #endif
2258 (void)sprintf(fullname, "%s/%s", csinfo[i].ppath, name);
2259 else
2260 (void)sprintf(fullname, "%s", name);
2262 return fullname;
2263 } /* cs_resolve_file */
2267 * PRIVATE: cs_show
2269 * show all cscope connections
2271 /* ARGSUSED */
2272 static int
2273 cs_show(eap)
2274 exarg_T *eap;
2276 short i;
2277 if (cs_cnt_connections() == 0)
2278 MSG_PUTS(_("no cscope connections\n"));
2279 else
2281 MSG_PUTS_ATTR(
2282 _(" # pid database name prepend path\n"),
2283 hl_attr(HLF_T));
2284 for (i = 0; i < CSCOPE_MAX_CONNECTIONS; i++)
2286 if (csinfo[i].fname == NULL)
2287 continue;
2289 if (csinfo[i].ppath != NULL)
2290 (void)smsg((char_u *)"%2d %-5ld %-34s %-32s",
2291 i, (long)csinfo[i].pid, csinfo[i].fname, csinfo[i].ppath);
2292 else
2293 (void)smsg((char_u *)"%2d %-5ld %-34s <none>",
2294 i, (long)csinfo[i].pid, csinfo[i].fname);
2298 wait_return(TRUE);
2299 return CSCOPE_SUCCESS;
2300 } /* cs_show */
2302 #endif /* FEAT_CSCOPE */
2304 /* the end */