(main): Avoid a buffer overrun with sprintf.
[bpt/emacs.git] / lib-src / etags.c
index 9685c7a..b21175e 100644 (file)
@@ -1,5 +1,5 @@
-/* Tags file maker to go with GNU Emacs
-   Copyright (C) 1984, 87, 88, 89, 93, 94, 95, 98, 99, 2000
+/* Tags file maker to go with GNU Emacs           -*- coding: latin-1 -*-
+   Copyright (C) 1984, 1987-1989, 1993-1995, 1998-2001, 2002
    Free Software Foundation, Inc. and Ken Arnold
 
 This file is not considered part of GNU Emacs.
@@ -24,26 +24,26 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  *     Fortran added by Jim Kleckner.
  *     Ed Pelegri-Llopart added C typedefs.
  *     Gnu Emacs TAGS format and modifications by RMS?
- *     Sam Kendall added C++.
- *     Francesco Potorti` reorganised C and C++ based on work by Joe Wells.
- *     Regexp tags by Tom Tromey.
+ * 1989        Sam Kendall added C++.
+ * 1992 Joseph B. Wells improved C and C++ parsing.
+ * 1993        Francesco Potortì reorganised C and C++.
+ * 1994        Regexp tags by Tom Tromey.
+ * 2001 Nested classes by Francesco Potortì (ideas by Mykola Dzyuba).
  *
- *     Francesco Potorti` (pot@gnu.org) is the current maintainer.
+ *     Francesco Potortì <pot@gnu.org> has maintained it since 1993.
  */
 
-char pot_etags_version[] = "@(#) pot revision number is 13.44";
+char pot_etags_version[] = "@(#) pot revision number is $Revision: 15.18 $";
 
 #define        TRUE    1
 #define        FALSE   0
 
-#ifndef DEBUG
-# define DEBUG FALSE
-#endif
-
-#if defined(__STDC__) && (__STDC__ || defined(__SUNPRO_C))
-# define P_(proto) proto
+#ifdef DEBUG
+#  undef DEBUG
+#  define DEBUG TRUE
 #else
-# define P_(proto) ()
+#  define DEBUG  FALSE
+#  define NDEBUG               /* disable assert */
 #endif
 
 #ifdef HAVE_CONFIG_H
@@ -53,12 +53,35 @@ char pot_etags_version[] = "@(#) pot revision number is 13.44";
 # undef static
 # define ETAGS_REGEXPS         /* use the regexp features */
 # define LONG_OPTIONS          /* accept long options */
-#endif /* HAVE_CONFIG_H */
+# ifndef PTR                   /* for Xemacs */
+#   define PTR void *
+# endif
+# ifndef __P                   /* for Xemacs */
+#   define __P(args) args
+# endif
+#else
+# if defined(__STDC__) && (__STDC__ || defined(__SUNPRO_C))
+#   define __P(args) args      /* use prototypes */
+#   define PTR void *          /* for generic pointers */
+# else
+#   define __P(args) ()                /* no prototypes */
+#   define const               /* remove const for old compilers' sake */
+#   define PTR long *          /* don't use void* */
+# endif
+#endif /* !HAVE_CONFIG_H */
 
 #ifndef _GNU_SOURCE
 # define _GNU_SOURCE 1         /* enables some compiler checks on GNU */
 #endif
 
+/* WIN32_NATIVE is for Xemacs.
+   MSDOS, WINDOWSNT, DOS_NT are for Emacs. */
+#ifdef WIN32_NATIVE
+# undef MSDOS
+# undef  WINDOWSNT
+# define WINDOWSNT
+#endif /* WIN32_NATIVE */
+
 #ifdef MSDOS
 # undef MSDOS
 # define MSDOS TRUE
@@ -80,11 +103,9 @@ char pot_etags_version[] = "@(#) pot revision number is 13.44";
 # include <direct.h>
 # include <io.h>
 # define MAXPATHLEN _MAX_PATH
-# ifdef HAVE_CONFIG_H
-#   undef HAVE_NTGUI
-# else
-#   define DOS_NT
-# endif /* not HAVE_CONFIG_H */
+# undef HAVE_NTGUI
+# undef  DOS_NT
+# define DOS_NT
 # ifndef HAVE_GETCWD
 #   define HAVE_GETCWD
 # endif /* undef HAVE_GETCWD */
@@ -100,7 +121,7 @@ char pot_etags_version[] = "@(#) pot revision number is 13.44";
 #ifdef HAVE_UNISTD_H
 # include <unistd.h>
 #else
-# if defined (HAVE_GETCWD) && !WINDOWSNT
+# if defined (HAVE_GETCWD) && !defined (WINDOWSNT)
     extern char *getcwd (char *buf, size_t size);
 # endif
 #endif /* HAVE_UNISTD_H */
@@ -114,6 +135,12 @@ char pot_etags_version[] = "@(#) pot revision number is 13.44";
 #include <sys/types.h>
 #include <sys/stat.h>
 
+#include <assert.h>
+#ifdef NDEBUG
+# undef  assert                        /* some systems have a buggy assert.h */
+# define assert(x) ((void) 0)
+#endif
+
 #if !defined (S_ISREG) && defined (S_IFREG)
 # define S_ISREG(m)    (((m) & S_IFMT) == S_IFREG)
 #endif
@@ -127,6 +154,14 @@ char pot_etags_version[] = "@(#) pot revision number is 13.44";
 #endif /* LONG_OPTIONS */
 
 #ifdef ETAGS_REGEXPS
+# ifndef HAVE_CONFIG_H         /* this is a standalone compilation */
+#   ifdef __CYGWIN__           /* compiling on Cygwin */
+                            !!! NOTICE !!!
+ the regex.h distributed with Cygwin is not compatible with etags, alas!
+If you want regular expression support, you should delete this notice and
+             arrange to use the GNU regex.h and regex.c.
+#   endif
+# endif
 # include <regex.h>
 #endif /* ETAGS_REGEXPS */
 
@@ -149,79 +184,87 @@ char pot_etags_version[] = "@(#) pot revision number is 13.44";
 # define       BAD     1
 #endif
 
-/* C extensions. */
-#define C_PLPL 0x00001         /* C++ */
-#define C_STAR 0x00003         /* C* */
-#define C_JAVA 0x00005         /* JAVA */
-#define YACC   0x10000         /* yacc file */
-
-#define streq(s,t)     ((DEBUG && (s) == NULL && (t) == NULL   \
-                         && (abort (), 1)) || !strcmp (s, t))
-#define strneq(s,t,n)  ((DEBUG && (s) == NULL && (t) == NULL   \
-                         && (abort (), 1)) || !strncmp (s, t, n))
-
-#define lowcase(c)     tolower ((unsigned char)(c))
-#define UPCASE(c)      toupper ((unsigned char)(c))
+#define streq(s,t)     (assert((s)!=NULL || (t)!=NULL), !strcmp (s, t))
+#define strneq(s,t,n)  (assert((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
 
 #define CHARS 256              /* 2^sizeof(char) */
-#define CHAR(x)                ((unsigned int)x & (CHARS - 1))
+#define CHAR(x)                ((unsigned int)(x) & (CHARS - 1))
 #define        iswhite(c)      (_wht[CHAR(c)]) /* c is white */
 #define notinname(c)   (_nin[CHAR(c)]) /* c is not in a name */
 #define        begtoken(c)     (_btk[CHAR(c)]) /* c can start token */
 #define        intoken(c)      (_itk[CHAR(c)]) /* c can be in token */
 #define        endtoken(c)     (_etk[CHAR(c)]) /* c ends tokens */
 
-#define ISALNUM(c)     isalnum ((unsigned char) (c))
-#define ISALPHA(c)     isalpha ((unsigned char) (c))
-#define ISDIGIT(c)     isdigit ((unsigned char) (c))
-#define ISLOWER(c)     islower ((unsigned char) (c))
+#define ISALNUM(c)     isalnum (CHAR(c))
+#define ISALPHA(c)     isalpha (CHAR(c))
+#define ISDIGIT(c)     isdigit (CHAR(c))
+#define ISLOWER(c)     islower (CHAR(c))
+
+#define lowcase(c)     tolower (CHAR(c))
+#define upcase(c)      toupper (CHAR(c))
 
 
 /*
  *     xnew, xrnew -- allocate, reallocate storage
  *
  * SYNOPSIS:   Type *xnew (int n, Type);
- *             Type *xrnew (OldPointer, int n, Type);
+ *             void xrnew (OldPointer, int n, Type);
  */
-#ifdef chkmalloc
+#if DEBUG
 # include "chkmalloc.h"
 # define xnew(n,Type)    ((Type *) trace_malloc (__FILE__, __LINE__, \
                                                  (n) * sizeof (Type)))
-# define xrnew(op,n,Type) ((Type *) trace_realloc (__FILE__, __LINE__, \
-                                                  (op), (n) * sizeof (Type)))
+# define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
+                                       (char *) (op), (n) * sizeof (Type)))
 #else
 # define xnew(n,Type)    ((Type *) xmalloc ((n) * sizeof (Type)))
-# define xrnew(op,n,Type) ((Type *) xrealloc ((op), (n) * sizeof (Type)))
+# define xrnew(op,n,Type) ((op) = (Type *) xrealloc ( \
+                                       (char *) (op), (n) * sizeof (Type)))
 #endif
 
-typedef int bool;
+#define bool int
 
-typedef void Lang_function P_((FILE *));
+typedef void Lang_function __P((FILE *));
 
 typedef struct
 {
-  char *suffix;
-  char *command;               /* Takes one arg and decompresses to stdout */
+  char *suffix;                        /* file name suffix for this compressor */
+  char *command;               /* takes one arg and decompresses to stdout */
 } compressor;
 
 typedef struct
 {
-  char *name;
-  Lang_function *function;
-  char **suffixes;
-  char **interpreters;
+  char *name;                  /* language name */
+  bool metasource;             /* source used to generate other sources */
+  Lang_function *function;     /* parse function */
+  char **filenames;            /* names of this language's files */
+  char **suffixes;             /* name suffixes of this language's files */
+  char **interpreters;         /* interpreters for this language */
 } language;
 
+typedef struct fdesc
+{
+  struct fdesc *next;          /* for the linked list */
+  char *infname;               /* uncompressed input file name */
+  char *infabsname;            /* absolute uncompressed input file name */
+  char *infabsdir;             /* absolute dir of input file */
+  char *taggedfname;           /* file name to write in tagfile */
+  language *lang;              /* language of file */
+  char *prop;                  /* file properties to write in tagfile */
+  bool usecharno;              /* etags tags shall contain char number */
+} fdesc;
+
 typedef struct node_st
-{                              /* sorting structure            */
-  char *name;                  /* function or type name        */
-  char *file;                  /* file name                    */
-  bool is_func;                        /* use pattern or line no       */
-  bool been_warned;            /* set if noticed dup           */
-  int lno;                     /* line number tag is on        */
+{                              /* sorting structure */
+  struct node_st *left, *right;        /* left and right sons */
+  fdesc *fdp;                  /* description of file to whom tag belongs */
+  char *name;                  /* tag name */
+  char *pat;                   /* search pattern */
+  bool valid;                  /* write this tag on the tag file */
+  bool is_func;                        /* function tag: use pattern in CTAGS mode */
+  bool been_warned;            /* warning already given for duplicated tag */
+  int lno;                     /* line number tag is on */
   long cno;                    /* character number line starts on */
-  char *pat;                   /* search pattern               */
-  struct node_st *left, *right;        /* left and right sons          */
 } node;
 
 /*
@@ -238,119 +281,147 @@ typedef struct
   char *buffer;
 } linebuffer;
 
+/* Used to support mixing of --lang and file names. */
+typedef struct
+{
+  enum {
+    at_language,               /* a language specification */
+    at_regexp,                 /* a regular expression */
+    at_icregexp,               /* same, but with case ignored */
+    at_filename                        /* a file name */
+  } arg_type;                  /* argument type */
+  language *lang;              /* language associated with the argument */
+  char *what;                  /* the argument itself */
+} argument;
+
+#ifdef ETAGS_REGEXPS
+/* Structure defining a regular expression. */
+typedef struct pattern
+{
+  struct pattern *p_next;
+  language *lang;
+  char *regex;
+  struct re_pattern_buffer *pat;
+  struct re_registers regs;
+  char *name_pattern;
+  bool error_signaled;
+  bool ignore_case;
+} pattern;
+#endif /* ETAGS_REGEXPS */
+
+
 /* Many compilers barf on this:
        Lang_function Ada_funcs;
    so let's write it this way */
-static void Ada_funcs P_((FILE *));
-static void Asm_labels P_((FILE *));
-static void C_entries P_((int c_ext, FILE *));
-static void default_C_entries P_((FILE *));
-static void plain_C_entries P_((FILE *));
-static void Cjava_entries P_((FILE *));
-static void Cobol_paragraphs P_((FILE *));
-static void Cplusplus_entries P_((FILE *));
-static void Cstar_entries P_((FILE *));
-static void Erlang_functions P_((FILE *));
-static void Fortran_functions P_((FILE *));
-static void Yacc_entries P_((FILE *));
-static void Lisp_functions P_((FILE *));
-static void Pascal_functions P_((FILE *));
-static void Perl_functions P_((FILE *));
-static void Postscript_functions P_((FILE *));
-static void Prolog_functions P_((FILE *));
-static void Python_functions P_((FILE *));
-static void Scheme_functions P_((FILE *));
-static void TeX_functions P_((FILE *));
-static void Texinfo_functions P_ ((FILE *));
-static void just_read_file P_((FILE *));
-
-static void print_language_names P_((void));
-static void print_version P_((void));
-static void print_help P_((void));
-int main P_((int, char **));
-static int number_len P_((long));
-
-static compressor *get_compressor_from_suffix P_((char *, char **));
-static language *get_language_from_name P_((char *));
-static language *get_language_from_interpreter P_((char *));
-static language *get_language_from_suffix P_((char *));
-static int total_size_of_entries P_((node *));
-static long readline P_((linebuffer *, FILE *));
-static long readline_internal P_((linebuffer *, FILE *));
-static void get_tag P_((char *));
+static void Ada_funcs __P((FILE *));
+static void Asm_labels __P((FILE *));
+static void C_entries __P((int c_ext, FILE *));
+static void default_C_entries __P((FILE *));
+static void plain_C_entries __P((FILE *));
+static void Cjava_entries __P((FILE *));
+static void Cobol_paragraphs __P((FILE *));
+static void Cplusplus_entries __P((FILE *));
+static void Cstar_entries __P((FILE *));
+static void Erlang_functions __P((FILE *));
+static void Fortran_functions __P((FILE *));
+static void Yacc_entries __P((FILE *));
+static void Lisp_functions __P((FILE *));
+static void Makefile_targets __P((FILE *));
+static void Pascal_functions __P((FILE *));
+static void Perl_functions __P((FILE *));
+static void PHP_functions __P((FILE *));
+static void Postscript_functions __P((FILE *));
+static void Prolog_functions __P((FILE *));
+static void Python_functions __P((FILE *));
+static void Scheme_functions __P((FILE *));
+static void TeX_commands __P((FILE *));
+static void Texinfo_nodes __P((FILE *));
+static void just_read_file __P((FILE *));
+
+static void print_language_names __P((void));
+static void print_version __P((void));
+static void print_help __P((void));
+int main __P((int, char **));
+
+static compressor *get_compressor_from_suffix __P((char *, char **));
+static language *get_language_from_langname __P((const char *));
+static language *get_language_from_interpreter __P((char *));
+static language *get_language_from_filename __P((char *, bool));
+static long readline __P((linebuffer *, FILE *));
+static long readline_internal __P((linebuffer *, FILE *));
+static bool nocase_tail __P((char *));
+static char *get_tag __P((char *));
 
 #ifdef ETAGS_REGEXPS
-static void analyse_regex P_((char *, bool));
-static void add_regex P_((char *, bool, language *));
-static void free_patterns P_((void));
+static void analyse_regex __P((char *, bool));
+static void add_regex __P((char *, bool, language *));
+static void free_patterns __P((void));
 #endif /* ETAGS_REGEXPS */
-static void error P_((const char *, const char *));
-static void suggest_asking_for_help P_((void));
-static void fatal P_((char *, char *));
-static void pfatal P_((char *));
-static void add_node P_((node *, node **));
-
-static void init P_((void));
-static void initbuffer P_((linebuffer *));
-static void find_entries P_((char *, FILE *));
-static void free_tree P_((node *));
-static void pfnote P_((char *, bool, char *, int, int, long));
-static void new_pfnote P_((char *, int, bool, char *, int, int, long));
-static void process_file P_((char *));
-static void put_entries P_((node *));
-static void takeprec P_((void));
-
-static char *concat P_((char *, char *, char *));
-static char *skip_spaces P_((char *));
-static char *skip_non_spaces P_((char *));
-static char *savenstr P_((char *, int));
-static char *savestr P_((char *));
-static char *etags_strchr P_((const char *, int));
-static char *etags_strrchr P_((const char *, int));
-static char *etags_getcwd P_((void));
-static char *relative_filename P_((char *, char *));
-static char *absolute_filename P_((char *, char *));
-static char *absolute_dirname P_((char *, char *));
-static bool filename_is_absolute P_((char *f));
-static void canonicalize_filename P_((char *));
-static void grow_linebuffer P_((linebuffer *, int));
-long *xmalloc P_((unsigned int));
-long *xrealloc P_((char *, unsigned int));
+static void error __P((const char *, const char *));
+static void suggest_asking_for_help __P((void));
+void fatal __P((char *, char *));
+static void pfatal __P((char *));
+static void add_node __P((node *, node **));
+
+static void init __P((void));
+static void initbuffer __P((linebuffer *));
+static void process_file __P((char *, language *));
+static void find_entries __P((FILE *));
+static void free_tree __P((node *));
+static void free_fdesc __P((fdesc *));
+static void pfnote __P((char *, bool, char *, int, int, long));
+static void new_pfnote __P((char *, int, bool, char *, int, int, long));
+static void invalidate_nodes __P((fdesc *, node **));
+static void put_entries __P((node *));
+
+static char *concat __P((char *, char *, char *));
+static char *skip_spaces __P((char *));
+static char *skip_non_spaces __P((char *));
+static char *savenstr __P((char *, int));
+static char *savestr __P((char *));
+static char *etags_strchr __P((const char *, int));
+static char *etags_strrchr __P((const char *, int));
+static bool strcaseeq __P((const char *, const char *));
+static char *etags_getcwd __P((void));
+static char *relative_filename __P((char *, char *));
+static char *absolute_filename __P((char *, char *));
+static char *absolute_dirname __P((char *, char *));
+static bool filename_is_absolute __P((char *f));
+static void canonicalize_filename __P((char *));
+static void linebuffer_setlen __P((linebuffer *, int));
+static PTR xmalloc __P((unsigned int));
+static PTR xrealloc __P((char *, unsigned int));
 
 \f
-char searchar = '/';           /* use /.../ searches */
+static char searchar = '/';    /* use /.../ searches */
 
-char *tagfile;                 /* output file */
-char *progname;                        /* name this program was invoked with */
-char *cwd;                     /* current working directory */
-char *tagfiledir;              /* directory of tagfile */
-FILE *tagf;                    /* ioptr for tags file */
+static char *tagfile;          /* output file */
+static char *progname;         /* name this program was invoked with */
+static char *cwd;              /* current working directory */
+static char *tagfiledir;       /* directory of tagfile */
+static FILE *tagf;             /* ioptr for tags file */
 
-char *curfile;                 /* current input file name */
-language *curlang;             /* current language */
+static fdesc *fdhead;          /* head of file description list */
+static fdesc *curfdp;          /* current file description */
+static int lineno;             /* line number of current line */
+static long charno;            /* current character number */
+static long linecharno;                /* charno of start of current line */
+static char *dbp;              /* pointer to start of current tag */
 
-int lineno;                    /* line number of current line */
-long charno;                   /* current character number */
-long linecharno;               /* charno of start of current line */
-char *dbp;                     /* pointer to start of current tag */
+static const int invalidcharno = -1;
 
-node *head;                    /* the head of the binary tree of tags */
+static node *nodehead;         /* the head of the binary tree of tags */
+static node *last_node;                /* the last node created */
 
-linebuffer lb;                 /* the current line */
-linebuffer token_name;         /* used by C_entries as a temporary area */
-struct
-{
-  long linepos;
-  linebuffer lb;               /* used by C_entries instead of lb */
-} lbs[2];
+static linebuffer lb;          /* the current line */
 
 /* boolean "functions" (see init)      */
-bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
-char
+static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
+static char
   /* white chars */
   *white = " \f\t\n\r\v",
   /* not in a name */
-  *nonam = " \f\t\n\r(=,[;",
+  *nonam = " \f\t\n\r()=,;",
   /* token ending chars */
   *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
   /* token starting chars */
@@ -358,86 +429,80 @@ char
   /* valid in-token chars */
   *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
 
-bool append_to_tagfile;                /* -a: append to tags */
-/* The following four default to TRUE for etags, but to FALSE for ctags.  */
-bool typedefs;                 /* -t: create tags for C and Ada typedefs */
-bool typedefs_and_cplusplus;   /* -T: create tags for C typedefs, level */
+static bool append_to_tagfile; /* -a: append to tags */
+/* The next four default to TRUE for etags, but to FALSE for ctags.  */
+static bool typedefs;          /* -t: create tags for C and Ada typedefs */
+static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
                                /* 0 struct/enum/union decls, and C++ */
                                /* member functions. */
-bool constantypedefs;          /* -d: create tags for C #define, enum */
+static bool constantypedefs;   /* -d: create tags for C #define, enum */
                                /* constants and variables. */
                                /* -D: opposite of -d.  Default under ctags. */
-bool declarations;             /* --declarations: tag them and extern in C&Co*/
-bool globals;                  /* create tags for global variables */
-bool members;                  /* create tags for C member variables */
-bool update;                   /* -u: update tags */
-bool vgrind_style;             /* -v: create vgrind style index output */
-bool no_warnings;              /* -w: suppress warnings */
-bool cxref_style;              /* -x: create cxref style output */
-bool cplusplus;                        /* .[hc] means C++, not C */
-bool noindentypedefs;          /* -I: ignore indentation in C */
-bool packages_only;            /* --packages-only: in Ada, only tag packages*/
-
-#ifdef LONG_OPTIONS
-struct option longopts[] =
-{
-  { "packages-only",      no_argument,      &packages_only, TRUE  },
-  { "append",            no_argument,       NULL,           'a'   },
-  { "backward-search",   no_argument,       NULL,           'B'   },
-  { "c++",               no_argument,       NULL,           'C'   },
-  { "cxref",             no_argument,       NULL,           'x'   },
-  { "defines",           no_argument,       NULL,           'd'   },
-  { "declarations",      no_argument,       &declarations,  TRUE  },
-  { "no-defines",        no_argument,       NULL,           'D'   },
-  { "globals",           no_argument,       &globals,       TRUE  },
-  { "no-globals",        no_argument,       &globals,       FALSE },
-  { "help",              no_argument,       NULL,           'h'   },
-  { "help",              no_argument,       NULL,           'H'   },
-  { "ignore-indentation", no_argument,      NULL,           'I'   },
-  { "include",           required_argument, NULL,           'i'   },
-  { "language",           required_argument, NULL,                  'l'   },
-  { "members",           no_argument,       &members,       TRUE  },
-  { "no-members",        no_argument,       &members,       FALSE },
-  { "no-warn",           no_argument,       NULL,           'w'   },
-  { "output",            required_argument, NULL,           'o'   },
-#ifdef ETAGS_REGEXPS
-  { "regex",             required_argument, NULL,           'r'   },
-  { "no-regex",                  no_argument,       NULL,           'R'   },
-  { "ignore-case-regex",  required_argument, NULL,          'c'   },
-#endif /* ETAGS_REGEXPS */
-  { "typedefs",                  no_argument,       NULL,           't'   },
-  { "typedefs-and-c++",          no_argument,       NULL,           'T'   },
-  { "update",            no_argument,       NULL,           'u'   },
-  { "version",           no_argument,       NULL,           'V'   },
-  { "vgrind",            no_argument,       NULL,           'v'   },
-  { NULL }
-};
-#endif /* LONG_OPTIONS */
+static bool globals;           /* create tags for global variables */
+static bool declarations;      /* --declarations: tag them and extern in C&Co*/
+static bool members;           /* create tags for C member variables */
+static bool no_line_directive; /* ignore #line directives (undocumented) */
+static bool update;            /* -u: update tags */
+static bool vgrind_style;      /* -v: create vgrind style index output */
+static bool no_warnings;       /* -w: suppress warnings */
+static bool cxref_style;       /* -x: create cxref style output */
+static bool cplusplus;         /* .[hc] means C++, not C */
+static bool noindentypedefs;   /* -I: ignore indentation in C */
+static bool packages_only;     /* --packages-only: in Ada, only tag packages*/
 
 #ifdef ETAGS_REGEXPS
-/* Structure defining a regular expression.  Elements are
-   the compiled pattern, and the name string. */
-typedef struct pattern
-{
-  struct pattern *p_next;
-  language *language;
-  char *regex;
-  struct re_pattern_buffer *pattern;
-  struct re_registers regs;
-  char *name_pattern;
-  bool error_signaled;
-} pattern;
-
 /* List of all regexps. */
-pattern *p_head = NULL;
+static pattern *p_head;
 
 /* How many characters in the character set.  (From regex.c.)  */
 #define CHAR_SET_SIZE 256
 /* Translation table for case-insensitive matching. */
-char lc_trans[CHAR_SET_SIZE];
+static char lc_trans[CHAR_SET_SIZE];
+#endif /* ETAGS_REGEXPS */
+
+#ifdef LONG_OPTIONS
+static struct option longopts[] =
+{
+  { "packages-only",      no_argument,      &packages_only,     TRUE  },
+  { "c++",               no_argument,       NULL,               'C'   },
+  { "declarations",      no_argument,       &declarations,      TRUE  },
+  { "no-line-directive",  no_argument,      &no_line_directive, TRUE  },
+  { "help",              no_argument,       NULL,               'h'   },
+  { "help",              no_argument,       NULL,               'H'   },
+  { "ignore-indentation", no_argument,      NULL,               'I'   },
+  { "language",           required_argument, NULL,                      'l'   },
+  { "members",           no_argument,       &members,           TRUE  },
+  { "no-members",        no_argument,       &members,           FALSE },
+  { "output",            required_argument, NULL,               'o'   },
+#ifdef ETAGS_REGEXPS
+  { "regex",             required_argument, NULL,               'r'   },
+  { "no-regex",                  no_argument,       NULL,               'R'   },
+  { "ignore-case-regex",  required_argument, NULL,              'c'   },
 #endif /* ETAGS_REGEXPS */
+  { "version",           no_argument,       NULL,               'V'   },
+
+#if CTAGS /* Etags options */
+  { "backward-search",   no_argument,       NULL,               'B'   },
+  { "cxref",             no_argument,       NULL,               'x'   },
+  { "defines",           no_argument,       NULL,               'd'   },
+  { "globals",           no_argument,       &globals,           TRUE  },
+  { "typedefs",                  no_argument,       NULL,               't'   },
+  { "typedefs-and-c++",          no_argument,       NULL,               'T'   },
+  { "update",            no_argument,       NULL,               'u'   },
+  { "vgrind",            no_argument,       NULL,               'v'   },
+  { "no-warn",           no_argument,       NULL,               'w'   },
+
+#else /* Ctags options */
+  { "append",            no_argument,       NULL,               'a'   },
+  { "no-defines",        no_argument,       NULL,               'D'   },
+  { "no-globals",        no_argument,       &globals,           FALSE },
+  { "include",           required_argument, NULL,               'i'   },
+#endif
+  { NULL }
+};
+#endif /* LONG_OPTIONS */
 
-compressor compressors[] =
+static compressor compressors[] =
 {
   { "z", "gzip -d -c"},
   { "Z", "gzip -d -c"},
@@ -451,89 +516,95 @@ compressor compressors[] =
  * Language stuff.
  */
 
-/* Non-NULL if language fixed. */
-language *forced_lang = NULL;
-
 /* Ada code */
-char *Ada_suffixes [] =
+static char *Ada_suffixes [] =
   { "ads", "adb", "ada", NULL };
 
 /* Assembly code */
-char *Asm_suffixes [] = { "a", /* Unix assembler */
-                         "asm", /* Microcontroller assembly */
-                         "def", /* BSO/Tasking definition includes  */
-                         "inc", /* Microcontroller include files */
-                         "ins", /* Microcontroller include files */
-                         "s", "sa", /* Unix assembler */
-                         "S",   /* cpp-processed Unix assembler */
-                         "src", /* BSO/Tasking C compiler output */
-                         NULL
-                       };
+static char *Asm_suffixes [] =
+  { "a",       /* Unix assembler */
+    "asm", /* Microcontroller assembly */
+    "def", /* BSO/Tasking definition includes  */
+    "inc", /* Microcontroller include files */
+    "ins", /* Microcontroller include files */
+    "s", "sa", /* Unix assembler */
+    "S",   /* cpp-processed Unix assembler */
+    "src", /* BSO/Tasking C compiler output */
+    NULL
+  };
 
 /* Note that .c and .h can be considered C++, if the --c++ flag was
-   given.  That is why default_C_entries is called here. */
-char *default_C_suffixes [] =
+   given, or if the `class' keyowrd is met inside the file.
+   That is why default_C_entries is called for these. */
+static char *default_C_suffixes [] =
   { "c", "h", NULL };
 
-char *Cplusplus_suffixes [] =
-  { "C", "H", "c++", "cc", "cpp", "cxx", "h++", "hh", "hpp", "hxx",
+static char *Cplusplus_suffixes [] =
+  { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
     "M",                       /* Objective C++ */
     "pdb",                     /* Postscript with C syntax */
     NULL };
 
-char *Cjava_suffixes [] =
+static char *Cjava_suffixes [] =
   { "java", NULL };
 
-char *Cobol_suffixes [] =
+static char *Cobol_suffixes [] =
   { "COB", "cob", NULL };
 
-char *Cstar_suffixes [] =
+static char *Cstar_suffixes [] =
   { "cs", "hs", NULL };
 
-char *Erlang_suffixes [] =
+static char *Erlang_suffixes [] =
   { "erl", "hrl", NULL };
 
-char *Fortran_suffixes [] =
+static char *Fortran_suffixes [] =
   { "F", "f", "f90", "for", NULL };
 
-char *Lisp_suffixes [] =
-  { "cl", "clisp", "el", "l", "lisp", "lsp", "ml", "LSP", NULL };
+static char *Lisp_suffixes [] =
+  { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
 
-char *Pascal_suffixes [] =
+static char *Makefile_filenames [] =
+  { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
+
+static char *Pascal_suffixes [] =
   { "p", "pas", NULL };
 
-char *Perl_suffixes [] =
+static char *Perl_suffixes [] =
   { "pl", "pm", NULL };
-char *Perl_interpreters [] =
+
+static char *Perl_interpreters [] =
   { "perl", "@PERL@", NULL };
 
-char *plain_C_suffixes [] =
-  { "pc",                      /* Pro*C file */
+static char *PHP_suffixes [] =
+  { "php", "php3", "php4", NULL };
+
+static char *plain_C_suffixes [] =
+  { "lm",                      /* Objective lex file */
     "m",                       /* Objective C file */
-    "lm",                      /* Objective lex file */
+    "pc",                      /* Pro*C file */
      NULL };
 
-char *Postscript_suffixes [] =
+static char *Postscript_suffixes [] =
   { "ps", "psw", NULL };       /* .psw is for PSWrap */
 
-char *Prolog_suffixes [] =
+static char *Prolog_suffixes [] =
   { "prolog", NULL };
 
-char *Python_suffixes [] =
+static char *Python_suffixes [] =
   { "py", NULL };
 
 /* Can't do the `SCM' or `scm' prefix with a version number. */
-char *Scheme_suffixes [] =
-  { "SCM", "SM", "oak", "sch", "scheme", "scm", "sm", "ss", "t", NULL };
+static char *Scheme_suffixes [] =
+  { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
 
-char *TeX_suffixes [] =
-  { "TeX", "bib", "clo", "cls", "ltx", "sty", "tex", NULL };
+static char *TeX_suffixes [] =
+  { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
 
-char *Texinfo_suffixes [] =
-  { "texi", "txi", "texinfo", NULL };
+static char *Texinfo_suffixes [] =
+  { "texi", "texinfo", "txi", NULL };
 
-char *Yacc_suffixes [] =
-  { "y", "ym", "yy", "yxx", "y++", NULL }; /* .ym is Objective yacc file */
+static char *Yacc_suffixes [] =
+  { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
 
 /*
  * Table of languages.
@@ -542,44 +613,50 @@ char *Yacc_suffixes [] =
  * name.  I just didn't.
  */
 
-language lang_names [] =
+static language lang_names [] =
 {
-  { "ada",     Ada_funcs,           Ada_suffixes,         NULL              },
-  { "asm",     Asm_labels,          Asm_suffixes,         NULL              },
-  { "c",       default_C_entries,   default_C_suffixes,   NULL              },
-  { "c++",     Cplusplus_entries,   Cplusplus_suffixes,   NULL              },
-  { "c*",      Cstar_entries,       Cstar_suffixes,       NULL              },
-  { "cobol",   Cobol_paragraphs,    Cobol_suffixes,       NULL              },
-  { "erlang",  Erlang_functions,    Erlang_suffixes,      NULL              },
-  { "fortran", Fortran_functions,   Fortran_suffixes,     NULL              },
-  { "java",    Cjava_entries,       Cjava_suffixes,       NULL              },
-  { "lisp",    Lisp_functions,      Lisp_suffixes,        NULL              },
-  { "pascal",  Pascal_functions,    Pascal_suffixes,      NULL              },
-  { "perl",    Perl_functions,      Perl_suffixes,        Perl_interpreters },
-  { "postscript", Postscript_functions, Postscript_suffixes, NULL           },
-  { "proc",    plain_C_entries,     plain_C_suffixes,     NULL              },
-  { "prolog",  Prolog_functions,    Prolog_suffixes,      NULL              },
-  { "python",  Python_functions,    Python_suffixes,      NULL              },
-  { "scheme",  Scheme_functions,    Scheme_suffixes,      NULL              },
-  { "tex",     TeX_functions,       TeX_suffixes,         NULL              },
-  { "texinfo", Texinfo_functions,   Texinfo_suffixes,     NULL              },
-  { "yacc",    Yacc_entries,        Yacc_suffixes,        NULL              },
-  { "auto", NULL },             /* default guessing scheme */
-  { "none", just_read_file },   /* regexp matching only */
-  { NULL, NULL }                /* end of list */
+  { "ada",      FALSE, Ada_funcs,            NULL, Ada_suffixes,        NULL },
+  { "asm",      FALSE, Asm_labels,           NULL, Asm_suffixes,        NULL },
+  { "c",        FALSE, default_C_entries,    NULL, default_C_suffixes,  NULL },
+  { "c++",      FALSE, Cplusplus_entries,    NULL, Cplusplus_suffixes,  NULL },
+  { "c*",       FALSE, Cstar_entries,        NULL, Cstar_suffixes,      NULL },
+  { "cobol",    FALSE, Cobol_paragraphs,     NULL, Cobol_suffixes,      NULL },
+  { "erlang",   FALSE, Erlang_functions,     NULL, Erlang_suffixes,     NULL },
+  { "fortran",  FALSE, Fortran_functions,    NULL, Fortran_suffixes,    NULL },
+  { "java",     FALSE, Cjava_entries,        NULL, Cjava_suffixes,      NULL },
+  { "lisp",     FALSE, Lisp_functions,       NULL, Lisp_suffixes,       NULL },
+  { "makefile", FALSE, Makefile_targets,     Makefile_filenames, NULL,  NULL },
+  { "pascal",   FALSE, Pascal_functions,     NULL, Pascal_suffixes,     NULL },
+  { "perl",     FALSE, Perl_functions,NULL, Perl_suffixes, Perl_interpreters },
+  { "php",      FALSE, PHP_functions,        NULL, PHP_suffixes,        NULL },
+  { "postscript",FALSE, Postscript_functions,NULL, Postscript_suffixes, NULL },
+  { "proc",     FALSE, plain_C_entries,      NULL, plain_C_suffixes,    NULL },
+  { "prolog",   FALSE, Prolog_functions,     NULL, Prolog_suffixes,     NULL },
+  { "python",   FALSE, Python_functions,     NULL, Python_suffixes,     NULL },
+  { "scheme",   FALSE, Scheme_functions,     NULL, Scheme_suffixes,     NULL },
+  { "tex",      FALSE, TeX_commands,         NULL, TeX_suffixes,        NULL },
+  { "texinfo",  FALSE, Texinfo_nodes,        NULL, Texinfo_suffixes,    NULL },
+  { "yacc",      TRUE, Yacc_entries,         NULL, Yacc_suffixes,       NULL },
+  { "auto", FALSE, NULL },             /* default guessing scheme */
+  { "none", FALSE, just_read_file },   /* regexp matching only */
+  { NULL, FALSE, NULL }                /* end of list */
 };
+
 \f
 static void
 print_language_names ()
 {
   language *lang;
-  char **ext;
+  char **name, **ext;
 
   puts ("\nThese are the currently supported languages, along with the\n\
-default file name suffixes:");
+default file names and dot suffixes:");
   for (lang = lang_names; lang->name != NULL; lang++)
     {
-      printf ("\t%s\t", lang->name);
+      printf ("  %-*s", 10, lang->name);
+      if (lang->filenames != NULL)
+       for (name = lang->filenames; *name != NULL; name++)
+         printf (" %s", *name);
       if (lang->suffixes != NULL)
        for (ext = lang->suffixes; *ext != NULL; ext++)
          printf (" .%s", *ext);
@@ -591,6 +668,7 @@ If no language is specified and no matching suffix is found,\n\
 the first line of the file is read for a sharp-bang (#!) sequence\n\
 followed by the name of an interpreter.  If no such sequence is found,\n\
 Fortran is tried first; if no tags are found, C is tried next.\n\
+When parsing any C file, a \"class\" keyword switches to C++.\n\
 Compressed files are supported using gzip and bzip2.");
 }
 
@@ -604,7 +682,7 @@ static void
 print_version ()
 {
   printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION);
-  puts ("Copyright (C) 1999 Free Software Foundation, Inc. and Ken Arnold");
+  puts ("Copyright (C) 2002 Free Software Foundation, Inc. and Ken Arnold");
   puts ("This program is distributed under the same terms as Emacs");
 
   exit (GOOD);
@@ -622,25 +700,29 @@ These are the options accepted by %s.\n", progname, progname);
   puts ("Long option names do not work with this executable, as it is not\n\
 linked with GNU getopt.");
 #endif /* LONG_OPTIONS */
-  puts ("A - as file name means read names from stdin (one per line).");
-  if (!CTAGS)
-    printf ("  Absolute names are stored in the output file as they are.\n\
-Relative ones are stored relative to the output file's directory.");
-  puts ("\n");
+  puts ("  A - as file name means read names from stdin (one per line).\n\
+Absolute names are stored in the output file as they are.\n\
+Relative ones are stored relative to the output file's directory.\n");
 
-  puts ("-a, --append\n\
+  if (!CTAGS)
+    puts ("-a, --append\n\
         Append tag entries to existing tags file.");
 
   puts ("--packages-only\n\
-        For Ada files, only generate tags for packages .");
+        For Ada files, only generate tags for packages.");
 
   if (CTAGS)
     puts ("-B, --backward-search\n\
         Write the search commands for the tag entries using '?', the\n\
         backward-search command instead of '/', the forward-search command.");
 
+  /* This option is mostly obsolete, because etags can now automatically
+     detect C++.  Retained for backward compatibility and for debugging and
+     experimentation.  In principle, we could want to tag as C++ even
+     before any "class" keyword.
   puts ("-C, --c++\n\
         Treat files whose name suffix defaults to C language as C++ files.");
+  */
 
   puts ("--declarations\n\
        In C and derived languages, create tags for function declarations,");
@@ -659,15 +741,14 @@ Relative ones are stored relative to the output file's directory.");
        This makes the tags file smaller.");
 
   if (!CTAGS)
-    {
-      puts ("-i FILE, --include=FILE\n\
+    puts ("-i FILE, --include=FILE\n\
         Include a note in tag file indicating that, when searching for\n\
         a tag, one should also consult the tags file FILE after\n\
         checking the current file.");
-      puts ("-l LANG, --language=LANG\n\
+
+  puts ("-l LANG, --language=LANG\n\
         Force the following files to be considered as written in the\n\
        named language up to the next --language=LANG option.");
-    }
 
   if (CTAGS)
     puts ("--globals\n\
@@ -687,7 +768,7 @@ Relative ones are stored relative to the output file's directory.");
        REGEXP is anchored (as if preceded by ^).\n\
        The form /REGEXP/NAME/ creates a named tag.\n\
        For example Tcl named tags can be created with:\n\
-       --regex=/proc[ \\t]+\\([^ \\t]+\\)/\\1/.");
+       --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\"");
   puts ("-c /REGEXP/, --ignore-case-regex=/REGEXP/ or --ignore-case-regex=@regexfile\n\
         Like -r, --regex but ignore case when matching expressions.");
   puts ("-R, --no-regex\n\
@@ -708,13 +789,19 @@ Relative ones are stored relative to the output file's directory.");
       puts ("-T, --typedefs-and-c++\n\
         Generate tag entries for C typedefs, C struct/enum/union tags,\n\
         and C++ member functions.");
-      puts ("-u, --update\n\
+    }
+
+  if (CTAGS)
+    puts ("-u, --update\n\
         Update the tag entries for the given files, leaving tag\n\
         entries for other files in place.  Currently, this is\n\
         implemented by deleting the existing entries for the given\n\
         files and then rewriting the new entries at the end of the\n\
         tags file.  It is often faster to simply rebuild the entire\n\
         tag file than to use this.");
+
+  if (CTAGS)
+    {
       puts ("-v, --vgrind\n\
         Generates an index of items intended for human consumption,\n\
         similar to the output of vgrind.  The index is sorted, and\n\
@@ -743,22 +830,6 @@ Relative ones are stored relative to the output file's directory.");
 }
 
 \f
-enum argument_type
-{
-  at_language,
-  at_regexp,
-  at_filename,
-  at_icregexp
-};
-
-/* This structure helps us allow mixing of --lang and file names. */
-typedef struct
-{
-  enum argument_type arg_type;
-  char *what;
-  language *lang;              /* language of the regexp */
-} argument;
-
 #ifdef VMS                     /* VMS specific functions */
 
 #define        EOS     '\0'
@@ -892,7 +963,6 @@ main (argc, argv)
   int i;
   unsigned int nincluded_files;
   char **included_files;
-  char *this_file;
   argument *argbuffer;
   int current_arg, file_count;
   linebuffer filename_lb;
@@ -924,31 +994,32 @@ main (argc, argv)
 
   /*
    * If etags, always find typedefs and structure tags.  Why not?
-   * Also default is to find macro constants, enum constants and
+   * Also default to find macro constants, enum constants and
    * global variables.
    */
   if (!CTAGS)
     {
-      typedefs = typedefs_and_cplusplus = constantypedefs = TRUE;
+      typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
       globals = TRUE;
-      members = FALSE;
     }
 
   while (1)
     {
       int opt;
-      char *optstring;
+      char *optstring = "-";
 
 #ifdef ETAGS_REGEXPS
-      optstring = "-aCdDf:Il:o:r:c:RStTi:BuvxwVhH";
-#else
-      optstring = "-aCdDf:Il:o:StTi:BuvxwVhH";
+      optstring = "-r:Rc:";
 #endif /* ETAGS_REGEXPS */
 
 #ifndef LONG_OPTIONS
       optstring = optstring + 1;
 #endif /* LONG_OPTIONS */
 
+      optstring = concat (optstring,
+                         "Cf:Il:o:SVhH",
+                         (CTAGS) ? "BxdtTuvw" : "aDi:");
+
       opt = getopt_long (argc, argv, optstring, longopts, 0);
       if (opt == EOF)
        break;
@@ -969,10 +1040,7 @@ main (argc, argv)
          break;
 
          /* Common options. */
-       case 'a': append_to_tagfile = TRUE;     break;
        case 'C': cplusplus = TRUE;             break;
-       case 'd': constantypedefs = TRUE;       break;
-       case 'D': constantypedefs = FALSE;      break;
        case 'f':               /* for compatibility with old makefiles */
        case 'o':
          if (tagfile)
@@ -988,7 +1056,7 @@ main (argc, argv)
          break;
        case 'l':
          {
-           language *lang = get_language_from_name (optarg);
+           language *lang = get_language_from_langname (optarg);
            if (lang != NULL)
              {
                argbuffer[current_arg].lang = lang;
@@ -997,7 +1065,6 @@ main (argc, argv)
              }
          }
          break;
-#ifdef ETAGS_REGEXPS
        case 'r':
          argbuffer[current_arg].arg_type = at_regexp;
          argbuffer[current_arg].what = optarg;
@@ -1013,7 +1080,6 @@ main (argc, argv)
          argbuffer[current_arg].what = optarg;
          ++current_arg;
          break;
-#endif /* ETAGS_REGEXPS */
        case 'V':
          print_version ();
          break;
@@ -1021,25 +1087,21 @@ main (argc, argv)
        case 'H':
          print_help ();
          break;
-       case 't':
-         typedefs = TRUE;
-         break;
-       case 'T':
-         typedefs = typedefs_and_cplusplus = TRUE;
-         break;
-#if (!CTAGS)
+
          /* Etags options */
-       case 'i':
-         included_files[nincluded_files++] = optarg;
-         break;
-#else /* CTAGS */
+       case 'a': append_to_tagfile = TRUE;                     break;
+       case 'D': constantypedefs = FALSE;                      break;
+       case 'i': included_files[nincluded_files++] = optarg;   break;
+
          /* Ctags options. */
-       case 'B': searchar = '?';       break;
-       case 'u': update = TRUE;        break;
-       case 'v': vgrind_style = TRUE;  /*FALLTHRU*/
-       case 'x': cxref_style = TRUE;   break;
-       case 'w': no_warnings = TRUE;   break;
-#endif /* CTAGS */
+       case 'B': searchar = '?';                               break;
+       case 'd': constantypedefs = TRUE;                       break;
+       case 't': typedefs = TRUE;                              break;
+       case 'T': typedefs = typedefs_or_cplusplus = TRUE;      break;
+       case 'u': update = TRUE;                                break;
+       case 'v': vgrind_style = TRUE;                    /*FALLTHRU*/
+       case 'x': cxref_style = TRUE;                           break;
+       case 'w': no_warnings = TRUE;                           break;
        default:
          suggest_asking_for_help ();
        }
@@ -1076,9 +1138,6 @@ main (argc, argv)
   init ();                     /* set up boolean "functions" */
 
   initbuffer (&lb);
-  initbuffer (&token_name);
-  initbuffer (&lbs[0].lb);
-  initbuffer (&lbs[1].lb);
   initbuffer (&filename_lb);
 
   if (!CTAGS)
@@ -1104,10 +1163,13 @@ main (argc, argv)
    */
   for (i = 0; i < current_arg; ++i)
     {
+      static language *lang;   /* non-NULL if language is forced */
+      char *this_file;
+
       switch (argbuffer[i].arg_type)
        {
        case at_language:
-         forced_lang = argbuffer[i].lang;
+         lang = argbuffer[i].lang;
          break;
 #ifdef ETAGS_REGEXPS
        case at_regexp:
@@ -1137,9 +1199,9 @@ main (argc, argv)
                 (one per line) and use them. */
              if (streq (this_file, "-"))
                while (readline_internal (&filename_lb, stdin) > 0)
-                 process_file (filename_lb.buffer);
+                 process_file (filename_lb.buffer, lang);
              else
-               process_file (this_file);
+               process_file (this_file, lang);
 #ifdef VMS
            }
 #endif
@@ -1151,22 +1213,17 @@ main (argc, argv)
   free_patterns ();
 #endif /* ETAGS_REGEXPS */
 
-  if (!CTAGS)
-    {
-      while (nincluded_files-- > 0)
-       fprintf (tagf, "\f\n%s,include\n", *included_files++);
-
-      fclose (tagf);
-      exit (GOOD);
-    }
-
-  /* If CTAGS, we are here.  process_file did not write the tags yet,
-     because we want them ordered.  Let's do it now. */
-  if (cxref_style)
+  if (!CTAGS || cxref_style)
     {
-      put_entries (head);
-      free_tree (head);
-      head = NULL;
+      put_entries (nodehead);
+      free_tree (nodehead);
+      nodehead = NULL;
+      if (!CTAGS)
+       while (nincluded_files-- > 0)
+         fprintf (tagf, "\f\n%s,include\n", *included_files++);
+
+      if (fclose (tagf) == EOF)
+       pfatal (tagfile);
       exit (GOOD);
     }
 
@@ -1189,28 +1246,28 @@ main (argc, argv)
   tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
   if (tagf == NULL)
     pfatal (tagfile);
-  put_entries (head);
-  free_tree (head);
-  head = NULL;
-  fclose (tagf);
+  put_entries (nodehead);
+  free_tree (nodehead);
+  nodehead = NULL;
+  if (fclose (tagf) == EOF)
+    pfatal (tagfile);
 
   if (update)
     {
-      char cmd[BUFSIZ];
-      sprintf (cmd, "sort %s -o %s", tagfile, tagfile);
+      char cmd[2*BUFSIZ+10];
+      sprintf (cmd, "sort -o %.*s %.*s", BUFSIZ, tagfile, BUFSIZ, tagfile);
       exit (system (cmd));
     }
   return GOOD;
 }
 
 
-
 /*
  * Return a compressor given the file name.  If EXTPTR is non-zero,
  * return a pointer into FILE where the compressor-specific
  * extension begins.  If no compressor is found, NULL is returned
  * and EXTPTR is not significant.
- * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca>
+ * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
  */
 static compressor *
 get_compressor_from_suffix (file, extptr)
@@ -1251,8 +1308,8 @@ get_compressor_from_suffix (file, extptr)
  * Return a language given the name.
  */
 static language *
-get_language_from_name (name)
-     char *name;
+get_language_from_langname (name)
+     const char *name;
 {
   language *lang;
 
@@ -1297,12 +1354,23 @@ get_language_from_interpreter (interpreter)
  * Return a language given the file name.
  */
 static language *
-get_language_from_suffix (file)
+get_language_from_filename (file, case_sensitive)
      char *file;
+     bool case_sensitive;
 {
   language *lang;
-  char **ext, *suffix;
+  char **name, **ext, *suffix;
 
+  /* Try whole file name first. */
+  for (lang = lang_names; lang->name != NULL; lang++)
+    if (lang->filenames != NULL)
+      for (name = lang->filenames; *name != NULL; name++)
+       if ((case_sensitive)
+           ? streq (*name, file)
+           : strcaseeq (*name, file))
+         return lang;
+
+  /* If not found, try suffix after last dot. */
   suffix = etags_strrchr (file, '.');
   if (suffix == NULL)
     return NULL;
@@ -1310,25 +1378,30 @@ get_language_from_suffix (file)
   for (lang = lang_names; lang->name != NULL; lang++)
     if (lang->suffixes != NULL)
       for (ext = lang->suffixes; *ext != NULL; ext++)
-       if (streq (*ext, suffix))
+       if ((case_sensitive)
+           ? streq (*ext, suffix)
+           : strcaseeq (*ext, suffix))
          return lang;
   return NULL;
 }
 
-
-
+\f
 /*
  * This routine is called on each file argument.
  */
 static void
-process_file (file)
+process_file (file, lang)
      char *file;
+     language *lang;
 {
   struct stat stat_buf;
   FILE *inf;
+  static const fdesc emptyfdesc;
+  fdesc *fdp;
   compressor *compr;
   char *compressed_name, *uncompressed_name;
   char *ext, *real_name;
+  int retval;
 
 
   canonicalize_filename (file);
@@ -1348,25 +1421,14 @@ process_file (file)
       uncompressed_name = savenstr (file, ext - file);
     }
 
-  /* If the canonicalised uncompressed name has already be dealt with,
-     skip it silently, else add it to the list. */
-  {
-    typedef struct processed_file
+  /* If the canonicalized uncompressed name
+     has already been dealt with, skip it silently. */
+  for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
     {
-      char *filename;
-      struct processed_file *next;
-    } processed_file;
-    static processed_file *pf_head = NULL;
-    register processed_file *fnp;
-
-    for (fnp = pf_head; fnp != NULL; fnp = fnp->next)
-      if (streq (uncompressed_name, fnp->filename))
-       goto exit;
-    fnp = pf_head;
-    pf_head = xnew (1, struct processed_file);
-    pf_head->filename = savestr (uncompressed_name);
-    pf_head->next = fnp;
-  }
+      assert (fdp->infname != NULL);
+      if (streq (uncompressed_name, fdp->infname))
+       goto cleanup;
+    }
 
   if (stat (real_name, &stat_buf) != 0)
     {
@@ -1413,19 +1475,19 @@ process_file (file)
       if (real_name == NULL)
        {
          perror (file);
-         goto exit;
+         goto cleanup;
        }
     } /* try with a different name */
 
   if (!S_ISREG (stat_buf.st_mode))
     {
       error ("skipping %s: it is not a regular file.", real_name);
-      goto exit;
+      goto cleanup;
     }
   if (real_name == compressed_name)
     {
       char *cmd = concat (compr->command, " ", real_name);
-      inf = popen (cmd, "r");
+      inf = (FILE *) popen (cmd, "r");
       free (cmd);
     }
   else
@@ -1433,41 +1495,82 @@ process_file (file)
   if (inf == NULL)
     {
       perror (real_name);
-      goto exit;
+      goto cleanup;
+    }
+
+  /* Create a new input file description entry. */
+  fdp = xnew (1, fdesc);
+  *fdp = emptyfdesc;
+  fdp->next = fdhead;
+  fdp->infname = savestr (uncompressed_name);
+  fdp->lang = lang;
+  fdp->infabsname = absolute_filename (uncompressed_name, cwd);
+  fdp->infabsdir = absolute_dirname (uncompressed_name, cwd);
+  if (filename_is_absolute (uncompressed_name))
+    {
+      /* file is an absolute file name.  Canonicalize it. */
+      fdp->taggedfname = absolute_filename (uncompressed_name, NULL);
+    }
+  else
+    {
+      /* file is a file name relative to cwd.  Make it relative
+        to the directory of the tags file. */
+      fdp->taggedfname = relative_filename (uncompressed_name, tagfiledir);
     }
+  fdp->usecharno = TRUE;       /* use char position when making tags */
+  fdp->prop = NULL;
 
-  find_entries (uncompressed_name, inf);
+  fdhead = fdp;
+  curfdp = fdhead;             /* the current file description */
+
+  find_entries (inf);
 
   if (real_name == compressed_name)
-    pclose (inf);
+    retval = pclose (inf);
   else
-    fclose (inf);
-
-  if (!CTAGS)
+    retval = fclose (inf);
+  if (retval < 0)
+    pfatal (file);
+
+  /* If not Ctags, and if this is not metasource and if it contained no #line
+     directives, we can write the tags and free all nodes pointing to
+     curfdp. */
+  if (!CTAGS
+      && curfdp->usecharno     /* no #line directives in this file */
+      && !curfdp->lang->metasource)
     {
-      char *filename;
+      node *np, *prev;
 
-      if (filename_is_absolute (uncompressed_name))
-       {
-         /* file is an absolute file name.  Canonicalise it. */
-         filename = absolute_filename (uncompressed_name, cwd);
-       }
-      else
+      /* Look for the head of the sublist relative to this file.  See add_node
+        for the structure of the node tree. */
+      prev = NULL;
+      for (np = nodehead; np != NULL; prev = np, np = np->left)
+       if (np->fdp == curfdp)
+         break;
+
+      /* If we generated tags for this file, write and delete them. */
+      if (np != NULL)
        {
-         /* file is a file name relative to cwd.  Make it relative
-            to the directory of the tags file. */
-         filename = relative_filename (uncompressed_name, tagfiledir);
+         /* This is the head of the last sublist, if any.  The following
+            instructions depend on this being true. */
+         assert (np->left == NULL);
+
+         assert (fdhead == curfdp);
+         assert (last_node->fdp == curfdp);
+         put_entries (np);     /* write tags for file curfdp->taggedfname */
+         free_tree (np);       /* remove the written nodes */
+         if (prev == NULL)
+           nodehead = NULL;    /* no nodes left */
+         else
+           prev->left = NULL;  /* delete the pointer to the sublist */
        }
-      fprintf (tagf, "\f\n%s,%d\n", filename, total_size_of_entries (head));
-      free (filename);
-      put_entries (head);
-      free_tree (head);
-      head = NULL;
     }
 
- exit:
-  if (compressed_name) free(compressed_name);
-  if (uncompressed_name) free(uncompressed_name);
+ cleanup:
+  if (compressed_name) free (compressed_name);
+  if (uncompressed_name) free (uncompressed_name);
+  last_node = NULL;
+  curfdp = NULL;
   return;
 }
 
@@ -1502,44 +1605,35 @@ init ()
  * This routine opens the specified file and calls the function
  * which finds the function and type definitions.
  */
-node *last_node = NULL;
-
 static void
-find_entries (file, inf)
-     char *file;
+find_entries (inf)
      FILE *inf;
 {
   char *cp;
-  language *lang;
   node *old_last_node;
-
-  /* Memory leakage here: the string pointed by curfile is
-     never released, because curfile is copied into np->file
-     for each node, to be used in CTAGS mode.  The amount of
-     memory leaked here is the sum of the lengths of the
-     file names. */
-  curfile = savestr (file);
+  language *lang = curfdp->lang;
+  Lang_function *parser = NULL;
 
   /* If user specified a language, use it. */
-  lang = forced_lang;
   if (lang != NULL && lang->function != NULL)
     {
-      curlang = lang;
-      lang->function (inf);
-      return;
+      parser = lang->function;
     }
 
-  /* Try to guess the language given the file name. */
-  lang = get_language_from_suffix (file);
-  if (lang != NULL && lang->function != NULL)
+  /* Else try to guess the language given the file name. */
+  if (parser == NULL)
     {
-      curlang = lang;
-      lang->function (inf);
-      return;
+      lang = get_language_from_filename (curfdp->infname, TRUE);
+      if (lang != NULL && lang->function != NULL)
+       {
+         curfdp->lang = lang;
+         parser = lang->function;
+       }
     }
 
-  /* Look for sharp-bang as the first two characters. */
-  if (readline_internal (&lb, inf) > 0
+  /* Else look for sharp-bang as the first two characters. */
+  if (parser == NULL
+      && readline_internal (&lb, inf) > 0
       && lb.len >= 2
       && lb.buffer[0] == '#'
       && lb.buffer[1] == '!')
@@ -1562,33 +1656,84 @@ find_entries (file, inf)
          lang = get_language_from_interpreter (lp);
          if (lang != NULL && lang->function != NULL)
            {
-             curlang = lang;
-             lang->function (inf);
-             return;
+             curfdp->lang = lang;
+             parser = lang->function;
            }
        }
     }
+
   /* We rewind here, even if inf may be a pipe.  We fail if the
      length of the first line is longer than the pipe block size,
      which is unlikely. */
-  rewind (inf);
+  if (parser == NULL)
+    rewind (inf);
+
+  /* Else try to guess the language given the case insensitive file name. */
+  if (parser == NULL)
+    {
+      lang = get_language_from_filename (curfdp->infname, FALSE);
+      if (lang != NULL && lang->function != NULL)
+       {
+         curfdp->lang = lang;
+         parser = lang->function;
+       }
+    }
+
+  if (!no_line_directive
+      && curfdp->lang != NULL && curfdp->lang->metasource)
+    /* It may be that this is a bingo.y file, and we already parsed a bingo.c
+       file, or anyway we parsed a file that is automatically generated from
+       this one.  If this is the case, the bingo.c file contained #line
+       directives that generated tags pointing to this file.  Let's delete
+       them all before parsing this file, which is the real source. */
+    {
+      fdesc **fdpp = &fdhead;
+      while (*fdpp != NULL)
+       if (*fdpp != curfdp
+           && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
+         /* We found one of those!  We must delete both the file description
+            and all tags referring to it. */
+         {
+           fdesc *badfdp = *fdpp;
+
+           if (DEBUG)
+             fprintf (stderr,
+                      "Removing references to \"%s\" obtained from \"%s\"\n",
+                      badfdp->taggedfname, badfdp->infname);
+
+           /* Delete the tags referring to badfdp. */
+           invalidate_nodes (badfdp, &nodehead);
+
+           *fdpp = badfdp->next; /* remove the bad description from the list */
+           free_fdesc (badfdp);
+         }
+       else
+         fdpp = &(*fdpp)->next; /* advance the list pointer */
+    }
+
+  if (parser != NULL)
+    {
+      parser (inf);
+      return;
+    }
 
-  /* Try Fortran. */
+  /* Else try Fortran. */
   old_last_node = last_node;
-  curlang = get_language_from_name ("fortran");
+  curfdp->lang = get_language_from_langname ("fortran");
   Fortran_functions (inf);
 
-  /* No Fortran entries found.  Try C. */
   if (old_last_node == last_node)
+    /* No Fortran entries found.  Try C. */
     {
       /* We do not tag if rewind fails.
         Only the file name will be recorded in the tags file. */
       rewind (inf);
-      curlang = get_language_from_name (cplusplus ? "c++" : "c");
+      curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
       default_C_entries (inf);
     }
   return;
 }
+
 \f
 /* Record a tag. */
 static void
@@ -1610,24 +1755,28 @@ pfnote (name, is_func, linestart, linelen, lno, cno)
   /* If ctags mode, change name "main" to M<thisfilename>. */
   if (CTAGS && !cxref_style && streq (name, "main"))
     {
-      register char *fp = etags_strrchr (curfile, '/');
-      np->name = concat ("M", fp == NULL ? curfile : fp + 1, "");
+      register char *fp = etags_strrchr (curfdp->taggedfname, '/');
+      np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
       fp = etags_strrchr (np->name, '.');
       if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
        fp[0] = '\0';
     }
   else
     np->name = name;
+  np->valid = TRUE;
   np->been_warned = FALSE;
-  np->file = curfile;
+  np->fdp = curfdp;
   np->is_func = is_func;
   np->lno = lno;
-  /* Our char numbers are 0-base, because of C language tradition?
-     ctags compatibility?  old versions compatibility?   I don't know.
-     Anyway, since emacs's are 1-base we expect etags.el to take care
-     of the difference.  If we wanted to have 1-based numbers, we would
-     uncomment the +1 below. */
-  np->cno = cno /* + 1 */ ;
+  if (np->fdp->usecharno)
+    /* Our char numbers are 0-base, because of C language tradition?
+       ctags compatibility?  old versions compatibility?   I don't know.
+       Anyway, since emacs's are 1-base we expect etags.el to take care
+       of the difference.  If we wanted to have 1-based numbers, we would
+       uncomment the +1 below. */
+    np->cno = cno /* + 1 */ ;
+  else
+    np->cno = invalidcharno;
   np->left = np->right = NULL;
   if (CTAGS && !cxref_style)
     {
@@ -1639,13 +1788,12 @@ pfnote (name, is_func, linestart, linelen, lno, cno)
   else
     np->pat = savenstr (linestart, linelen);
 
-  add_node (np, &head);
+  add_node (np, &nodehead);
 }
 
-/* Date: Wed, 22 Jan 1997 02:56:31 -0500 [last amended 18 Sep 1997]
- * From: Sam Kendall <kendall@mv.mv.com>
- * Subject: Proposal for firming up the TAGS format specification
- * To: F.Potorti@cnuce.cnr.it
+/*
+ * TAGS format specification
+ * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
  *
  * pfnote should emit the optimized form [unnamed tag] only if:
  *  1. name does not contain any of the characters " \t\r\n(),;";
@@ -1657,7 +1805,7 @@ pfnote (name, is_func, linestart, linelen, lno, cno)
  *     also be one of the characters " \t(),;".
  *
  * The real implementation uses the notinname() macro, which recognises
- * characters slightly different form " \t\r\n(),;".  See the variable
+ * characters slightly different from " \t\r\n(),;".  See the variable
  * `nonam'.
  */
 #define traditional_tag_style TRUE
@@ -1719,11 +1867,27 @@ free_tree (np)
     }
 }
 
+/*
+ * free_fdesc ()
+ *     delete a file description
+ */
+static void
+free_fdesc (fdp)
+     register fdesc *fdp;
+{
+  if (fdp->infname != NULL) free (fdp->infname);
+  if (fdp->infabsname != NULL) free (fdp->infabsname);
+  if (fdp->infabsdir != NULL) free (fdp->infabsdir);
+  if (fdp->taggedfname != NULL) free (fdp->taggedfname);
+  if (fdp->prop != NULL) free (fdp->prop);
+  free (fdp);
+}
+
 /*
  * add_node ()
- *     Adds a node to the tree of nodes.  In etags mode, we don't keep
- *     it sorted; we just keep a linear list.  In ctags mode, maintain
- *     an ordered tree, with no attempt at balancing.
+ *     Adds a node to the tree of nodes.  In etags mode, sort by file
+ *     name.  In ctags mode, sort by tag name.  Make no attempt at
+ *     balancing.
  *
  *     add_node is the only function allowed to add nodes, so it can
  *     maintain state.
@@ -1743,13 +1907,31 @@ add_node (np, cur_node_p)
     }
 
   if (!CTAGS)
+    /* Etags Mode */
     {
-      /* Etags Mode */
-      if (last_node == NULL)
-       fatal ("internal error in add_node", (char *)NULL);
-      last_node->right = np;
-      last_node = np;
-    }
+      /* For each file name, tags are in a linked sublist on the right
+        pointer.  The first tags of different files are a linked list
+        on the left pointer.  last_node points to the end of the last
+        used sublist. */
+      if (last_node != NULL && last_node->fdp == np->fdp)
+       {
+         /* Let's use the same sublist as the last added node. */
+         assert (last_node->right == NULL);
+         last_node->right = np;
+         last_node = np;
+       }
+      else if (cur_node->fdp == np->fdp)
+       {
+         /* Scanning the list we found the head of a sublist which is
+            good for us.  Let's scan this sublist. */
+         add_node (np, &cur_node->right);
+       }
+      else
+       /* The head of this sublist is not good for us.  Let's try the
+          next one. */
+       add_node (np, &cur_node->left);
+    } /* if ETAGS mode */
+
   else
     {
       /* Ctags Mode */
@@ -1761,12 +1943,12 @@ add_node (np, cur_node_p)
        */
       if (!dif)
        {
-         if (streq (np->file, cur_node->file))
+         if (np->fdp == cur_node->fdp)
            {
              if (!no_warnings)
                {
                  fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
-                          np->file, lineno, np->name);
+                          np->fdp->infname, lineno, np->name);
                  fprintf (stderr, "Second entry ignored\n");
                }
            }
@@ -1775,7 +1957,7 @@ add_node (np, cur_node_p)
              fprintf
                (stderr,
                 "Duplicate entry in files %s and %s: %s (Warning only)\n",
-                np->file, cur_node->file, np->name);
+                np->fdp->infname, cur_node->fdp->infname, np->name);
              cur_node->been_warned = TRUE;
            }
          return;
@@ -1783,76 +1965,51 @@ add_node (np, cur_node_p)
 
       /* Actually add the node */
       add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
-    }
+    } /* if CTAGS mode */
 }
-\f
+
+/*
+ * invalidate_nodes ()
+ *     Scan the node tree and invalidate all nodes pointing to the
+ *     given file description (CTAGS case) or free them (ETAGS case).
+ */
 static void
-put_entries (np)
-     register node *np;
+invalidate_nodes (badfdp, npp)
+     fdesc *badfdp;
+     node **npp;
 {
-  register char *sp;
+  node *np = *npp;
 
   if (np == NULL)
     return;
 
-  /* Output subentries that precede this one */
-  put_entries (np->left);
-
-  /* Output this entry */
-
-  if (!CTAGS)
+  if (CTAGS)
     {
-      if (np->name != NULL)
-       fprintf (tagf, "%s\177%s\001%d,%ld\n",
-                np->pat, np->name, np->lno, np->cno);
-      else
-       fprintf (tagf, "%s\177%d,%ld\n",
-                np->pat, np->lno, np->cno);
+      if (np->left != NULL)
+       invalidate_nodes (badfdp, &np->left);
+      if (np->fdp == badfdp)
+       np-> valid = FALSE;
+      if (np->right != NULL)
+       invalidate_nodes (badfdp, &np->right);
     }
   else
     {
-      if (np->name == NULL)
-       error ("internal error: NULL name in ctags mode.", (char *)NULL);
-
-      if (cxref_style)
+      node **next = &np->left;
+      if (np->fdp == badfdp)
        {
-         if (vgrind_style)
-           fprintf (stdout, "%s %s %d\n",
-                    np->name, np->file, (np->lno + 63) / 64);
-         else
-           fprintf (stdout, "%-16s %3d %-16s %s\n",
-                    np->name, np->lno, np->file, np->pat);
-       }
-      else
-       {
-         fprintf (tagf, "%s\t%s\t", np->name, np->file);
-
-         if (np->is_func)
-           {                   /* a function */
-             putc (searchar, tagf);
-             putc ('^', tagf);
-
-             for (sp = np->pat; *sp; sp++)
-               {
-                 if (*sp == '\\' || *sp == searchar)
-                   putc ('\\', tagf);
-                 putc (*sp, tagf);
-               }
-             putc (searchar, tagf);
-           }
-         else
-           {                   /* a typedef; text pattern inadequate */
-             fprintf (tagf, "%d", np->lno);
-           }
-         putc ('\n', tagf);
+         *npp = *next;         /* detach the sublist from the list */
+         np->left = NULL;      /* isolate it */
+         free_tree (np);       /* free it */
        }
+      invalidate_nodes (badfdp, next);
     }
-
-  /* Output subentries that follow this one */
-  put_entries (np->right);
 }
 
-/* Length of a number's decimal representation. */
+\f
+static int total_size_of_entries __P((node *));
+static int number_len __P((long));
+
+/* Length of a non-negative number's decimal representation. */
 static int
 number_len (num)
      long num;
@@ -1865,61 +2022,152 @@ number_len (num)
 
 /*
  * Return total number of characters that put_entries will output for
- * the nodes in the subtree of the specified node.  Works only if
- * we are not ctags, but called only in that case.  This count
- * is irrelevant with the new tags.el, but is still supplied for
- * backward compatibility.
+ * the nodes in the linked list at the right of the specified node.
+ * This count is irrelevant with etags.el since emacs 19.34 at least,
+ * but is still supplied for backward compatibility.
  */
 static int
 total_size_of_entries (np)
      register node *np;
 {
-  register int total;
+  register int total = 0;
 
-  if (np == NULL)
-    return 0;
-
-  for (total = 0; np != NULL; np = np->right)
+  for (; np != NULL; np = np->right)
     {
-      /* Count left subentries. */
-      total += total_size_of_entries (np->left);
-
-      /* Count this entry */
-      total += strlen (np->pat) + 1;
-      total += number_len ((long) np->lno) + 1 + number_len (np->cno) + 1;
+      total += strlen (np->pat) + 1;           /* pat\177 */
       if (np->name != NULL)
-       total += 1 + strlen (np->name); /* \001name */
+       total += strlen (np->name) + 1;         /* name\001 */
+      total += number_len ((long) np->lno) + 1;        /* lno, */
+      if (np->cno != invalidcharno)            /* cno */
+       total += number_len (np->cno);
+      total += 1;                              /* newline */
     }
 
   return total;
 }
-\f
-/*
- * The C symbol tables.
- */
-enum sym_type
+
+static void
+put_entries (np)
+     register node *np;
 {
-  st_none,
-  st_C_objprot, st_C_objimpl, st_C_objend,
-  st_C_gnumacro,
-  st_C_ignore,
-  st_C_javastruct,
-  st_C_operator,
-  st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
-};
+  register char *sp;
+  static fdesc *fdp = NULL;
 
-static unsigned int hash P_((const char *, unsigned int));
-static struct C_stab_entry * in_word_set P_((const char *, unsigned int));
-static enum sym_type C_symtype P_((char *, int, int));
+  if (np == NULL)
+    return;
 
-/* Feed stuff between (but not including) %[ and %] lines to:
-      gperf -c -k 1,3 -o -p -r -t
-%[
-struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
-%%
-if,            0,      st_C_ignore
-for,           0,      st_C_ignore
-while,         0,      st_C_ignore
+  /* Output subentries that precede this one */
+  if (CTAGS)
+    put_entries (np->left);
+
+  /* Output this entry */
+  if (np->valid)
+    {
+      if (!CTAGS)
+       {
+         /* Etags mode */
+         if (fdp != np->fdp)
+           {
+             fdp = np->fdp;
+             fprintf (tagf, "\f\n%s,%d\n",
+                      fdp->taggedfname, total_size_of_entries (np));
+           }
+         fputs (np->pat, tagf);
+         fputc ('\177', tagf);
+         if (np->name != NULL)
+           {
+             fputs (np->name, tagf);
+             fputc ('\001', tagf);
+           }
+         fprintf (tagf, "%d,", np->lno);
+         if (np->cno != invalidcharno)
+           fprintf (tagf, "%ld", np->cno);
+         fputs ("\n", tagf);
+       }
+      else
+       {
+         /* Ctags mode */
+         if (np->name == NULL)
+           error ("internal error: NULL name in ctags mode.", (char *)NULL);
+
+         if (cxref_style)
+           {
+             if (vgrind_style)
+               fprintf (stdout, "%s %s %d\n",
+                        np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
+             else
+               fprintf (stdout, "%-16s %3d %-16s %s\n",
+                        np->name, np->lno, np->fdp->taggedfname, np->pat);
+           }
+         else
+           {
+             fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
+
+             if (np->is_func)
+               {               /* function or #define macro with args */
+                 putc (searchar, tagf);
+                 putc ('^', tagf);
+
+                 for (sp = np->pat; *sp; sp++)
+                   {
+                     if (*sp == '\\' || *sp == searchar)
+                       putc ('\\', tagf);
+                     putc (*sp, tagf);
+                   }
+                 putc (searchar, tagf);
+               }
+             else
+               {               /* anything else; text pattern inadequate */
+                 fprintf (tagf, "%d", np->lno);
+               }
+             putc ('\n', tagf);
+           }
+       }
+    } /* if this node contains a valid tag */
+
+  /* Output subentries that follow this one */
+  put_entries (np->right);
+  if (!CTAGS)
+    put_entries (np->left);
+}
+
+\f
+/* C extensions. */
+#define C_EXT  0x00fff         /* C extensions */
+#define C_PLAIN 0x00000                /* C */
+#define C_PLPL 0x00001         /* C++ */
+#define C_STAR 0x00003         /* C* */
+#define C_JAVA 0x00005         /* JAVA */
+#define C_AUTO  0x01000                /* C, but switch to C++ if `class' is met */
+#define YACC   0x10000         /* yacc file */
+
+/*
+ * The C symbol tables.
+ */
+enum sym_type
+{
+  st_none,
+  st_C_objprot, st_C_objimpl, st_C_objend,
+  st_C_gnumacro,
+  st_C_ignore,
+  st_C_javastruct,
+  st_C_operator,
+  st_C_class, st_C_template,
+  st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
+};
+
+static unsigned int hash __P((const char *, unsigned int));
+static struct C_stab_entry * in_word_set __P((const char *, unsigned int));
+static enum sym_type C_symtype __P((char *, int, int));
+
+/* Feed stuff between (but not including) %[ and %] lines to:
+      gperf -c -k 1,3 -o -p -r -t
+%[
+struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
+%%
+if,            0,      st_C_ignore
+for,           0,      st_C_ignore
+while,         0,      st_C_ignore
 switch,                0,      st_C_ignore
 return,                0,      st_C_ignore
 @interface,    0,      st_C_objprot
@@ -1932,7 +2180,7 @@ friend,           C_PLPL, st_C_ignore
 extends,       C_JAVA, st_C_javastruct
 implements,    C_JAVA, st_C_javastruct
 interface,     C_JAVA, st_C_struct
-class,         C_PLPL, st_C_struct
+class,         0,      st_C_class
 namespace,     C_PLPL, st_C_struct
 domain,        C_STAR, st_C_struct
 union,         0,      st_C_struct
@@ -1942,6 +2190,7 @@ enum,     0,      st_C_enum
 typedef,       0,      st_C_typedef
 define,        0,      st_C_define
 operator,      C_PLPL, st_C_operator
+template,      0,      st_C_template
 bool,          C_PLPL, st_C_typespec
 long,          0,      st_C_typespec
 short,         0,      st_C_typespec
@@ -1969,18 +2218,19 @@ PSEUDO,         0,      st_C_gnumacro
 #EXFUN,                0,      st_C_gnumacro
 #DEFVAR_,      0,      st_C_gnumacro
 %]
-and replace lines between %< and %> with its output. */
+and replace lines between %< and %> with its output,
+then make in_word_set and C_stab_entry static. */
 /*%<*/
 /* C code produced by gperf version 2.7.1 (19981006 egcs) */
 /* Command-line: gperf -c -k 1,3 -o -p -r -t  */
 struct C_stab_entry { char *name; int c_ext; enum sym_type type; };
 
-#define TOTAL_KEYWORDS 46
+#define TOTAL_KEYWORDS 47
 #define MIN_WORD_LENGTH 2
 #define MAX_WORD_LENGTH 15
-#define MIN_HASH_VALUE 13
-#define MAX_HASH_VALUE 123
-/* maximum key range = 111, duplicates = 0 */
+#define MIN_HASH_VALUE 18
+#define MAX_HASH_VALUE 138
+/* maximum key range = 121, duplicates = 0 */
 
 #ifdef __GNUC__
 __inline
@@ -1992,32 +2242,32 @@ hash (str, len)
 {
   static unsigned char asso_values[] =
     {
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124,   3, 124, 124, 124,  43,   6,
-       11, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-       11, 124, 124,  58,   7, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124,  57,   7,  42,
-        4,  14,  52,   0, 124,  53, 124, 124,  29,  11,
-        6,  35,  32, 124,  29,  34,  59,  58,  51,  24,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-      124, 124, 124, 124, 124, 124
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139,  63, 139, 139, 139,  33,  44,
+       62, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+       42, 139, 139,  12,  32, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139,  34,  59,  37,
+       24,  58,  33,   3, 139,  16, 139, 139,  42,  60,
+       18,  11,  39, 139,  23,  57,   4,  63,   6,  20,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
+      139, 139, 139, 139, 139, 139
     };
   register int hval = len;
 
@@ -2045,78 +2295,79 @@ in_word_set (str, len)
   static struct C_stab_entry wordlist[] =
     {
       {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
+      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
+      {"if",           0,      st_C_ignore},
       {""}, {""}, {""}, {""},
-      {"@end",         0,      st_C_objend},
-      {""}, {""}, {""}, {""},
-      {"ENTRY",                0,      st_C_gnumacro},
-      {"@interface",   0,      st_C_objprot},
+      {"int",          0,      st_C_typespec},
+      {""}, {""},
+      {"void",         0,      st_C_typespec},
+      {""}, {""},
+      {"interface",    C_JAVA, st_C_struct},
       {""},
-      {"domain",       C_STAR, st_C_struct},
+      {"SYSCALL",      0,      st_C_gnumacro},
       {""},
-      {"PSEUDO",               0,      st_C_gnumacro},
-      {""}, {""},
-      {"namespace",    C_PLPL, st_C_struct},
+      {"return",               0,      st_C_ignore},
+      {""}, {""}, {""}, {""}, {""}, {""}, {""},
+      {"while",                0,      st_C_ignore},
+      {"auto",         0,      st_C_typespec},
+      {""}, {""}, {""}, {""}, {""}, {""},
+      {"float",        0,      st_C_typespec},
+      {"typedef",      0,      st_C_typedef},
+      {"typename",     C_PLPL, st_C_typespec},
+      {""}, {""}, {""},
+      {"friend",               C_PLPL, st_C_ignore},
+      {"volatile",     0,      st_C_typespec},
       {""}, {""},
-      {"@implementation",0,    st_C_objimpl},
-      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
+      {"for",          0,      st_C_ignore},
+      {"const",        0,      st_C_typespec},
+      {"import",               C_JAVA, st_C_ignore},
+      {""},
+      {"define",       0,      st_C_define},
       {"long",         0,      st_C_typespec},
+      {"implements",   C_JAVA, st_C_javastruct},
       {"signed",       0,      st_C_typespec},
-      {"@protocol",    0,      st_C_objprot},
-      {""}, {""}, {""}, {""},
-      {"bool",         C_PLPL, st_C_typespec},
-      {""}, {""}, {""}, {""}, {""}, {""},
-      {"const",        0,      st_C_typespec},
-      {"explicit",     C_PLPL, st_C_typespec},
-      {"if",           0,      st_C_ignore},
       {""},
-      {"operator",     C_PLPL, st_C_operator},
+      {"extern",       0,      st_C_extern},
+      {"extends",      C_JAVA, st_C_javastruct},
       {""},
-      {"DEFUN",                0,      st_C_gnumacro},
-      {""}, {""},
-      {"define",       0,      st_C_define},
-      {""}, {""}, {""}, {""}, {""},
-      {"double",       0,      st_C_typespec},
-      {"struct",       0,      st_C_struct},
-      {""}, {""}, {""}, {""},
+      {"mutable",      C_PLPL, st_C_typespec},
+      {"template",     0,      st_C_template},
       {"short",        0,      st_C_typespec},
+      {"bool",         C_PLPL, st_C_typespec},
+      {"char",         0,      st_C_typespec},
+      {"class",        0,      st_C_class},
+      {"operator",     C_PLPL, st_C_operator},
       {""},
-      {"enum",         0,      st_C_enum},
-      {"mutable",      C_PLPL, st_C_typespec},
+      {"switch",               0,      st_C_ignore},
       {""},
-      {"extern",       0,      st_C_extern},
-      {"extends",      C_JAVA, st_C_javastruct},
-      {"package",      C_JAVA, st_C_ignore},
-      {"while",                0,      st_C_ignore},
+      {"ENTRY",                0,      st_C_gnumacro},
       {""},
-      {"for",          0,      st_C_ignore},
-      {""}, {""}, {""},
-      {"volatile",     0,      st_C_typespec},
+      {"package",      C_JAVA, st_C_ignore},
+      {"union",        0,      st_C_struct},
+      {"@end",         0,      st_C_objend},
+      {"struct",       0,      st_C_struct},
+      {"namespace",    C_PLPL, st_C_struct},
       {""}, {""},
-      {"import",               C_JAVA, st_C_ignore},
-      {"float",        0,      st_C_typespec},
-      {"switch",               0,      st_C_ignore},
-      {"return",               0,      st_C_ignore},
-      {"implements",   C_JAVA, st_C_javastruct},
+      {"domain",       C_STAR, st_C_struct},
+      {"@interface",   0,      st_C_objprot},
+      {"PSEUDO",               0,      st_C_gnumacro},
+      {"double",       0,      st_C_typespec},
+      {""},
+      {"@protocol",    0,      st_C_objprot},
       {""},
       {"static",       0,      st_C_typespec},
-      {"typedef",      0,      st_C_typedef},
-      {"typename",     C_PLPL, st_C_typespec},
-      {"unsigned",     0,      st_C_typespec},
-      {""}, {""},
-      {"char",         0,      st_C_typespec},
-      {"class",        C_PLPL, st_C_struct},
-      {""}, {""}, {""},
-      {"void",         0,      st_C_typespec},
       {""}, {""},
-      {"friend",               C_PLPL, st_C_ignore},
-      {""}, {""}, {""},
-      {"int",          0,      st_C_typespec},
-      {"union",        0,      st_C_struct},
-      {""}, {""}, {""},
-      {"auto",         0,      st_C_typespec},
-      {"interface",    C_JAVA, st_C_struct},
+      {"DEFUN",                0,      st_C_gnumacro},
+      {""}, {""}, {""}, {""},
+      {"explicit",     C_PLPL, st_C_typespec},
+      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
+      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
       {""},
-      {"SYSCALL",      0,      st_C_gnumacro}
+      {"enum",         0,      st_C_enum},
+      {""}, {""},
+      {"unsigned",     0,      st_C_typespec},
+      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
+      {"@implementation",0,    st_C_objimpl}
     };
 
   if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
@@ -2147,14 +2398,17 @@ C_symtype (str, len, c_ext)
     return st_none;
   return se->type;
 }
+
 \f
- /*
 * C functions and variables are recognized using a simple
 * finite automaton.  fvdef is its state variable.
 */
-enum
+/*
+ * C functions and variables are recognized using a simple
+ * finite automaton.  fvdef is its state variable.
+ */
+static enum
 {
   fvnone,                      /* nothing seen */
+  fdefunkey,                   /* Emacs DEFUN keyword seen */
+  fdefunname,                  /* Emacs DEFUN name seen */
   foperator,                   /* func: operator keyword seen (cplpl) */
   fvnameseen,                  /* function or variable name seen */
   fstartlist,                  /* func: just after open parenthesis */
@@ -2164,13 +2418,13 @@ enum
   vignore                      /* var-like: ignore until ';' */
 } fvdef;
 
-bool fvextern;                 /* func or var: extern keyword seen; */
+static bool fvextern;          /* func or var: extern keyword seen; */
 
- /*
 * typedefs are recognized using a simple finite automaton.
 * typdef is its state variable.
 */
-enum
+/*
+ * typedefs are recognized using a simple finite automaton.
+ * typdef is its state variable.
+ */
+static enum
 {
   tnone,                       /* nothing seen */
   tkeyseen,                    /* typedef keyword seen */
@@ -2180,38 +2434,30 @@ enum
   tignore                      /* junk after typedef tag */
 } typdef;
 
-
- /*
-  * struct-like structures (enum, struct and union) are recognized
-  * using another simple finite automaton.  `structdef' is its state
-  * variable.
-  */
-enum
+/*
+ * struct-like structures (enum, struct and union) are recognized
+ * using another simple finite automaton.  `structdef' is its state
+ * variable.
+ */
+static enum
 {
-  snone,                       /* nothing seen yet */
+  snone,                       /* nothing seen yet,
+                                  or in struct body if cblev > 0 */
   skeyseen,                    /* struct-like keyword seen */
   stagseen,                    /* struct-like tag seen */
-  scolonseen,                  /* colon seen after struct-like tag */
-  sinbody                      /* in struct body: recognize member func defs*/
+  sintemplate,                 /* inside template (ignore) */
+  scolonseen                   /* colon seen after struct-like tag */
 } structdef;
 
-/*
- * When structdef is stagseen, scolonseen, or sinbody, structtag is the
- * struct tag, and structtype is the type of the preceding struct-like
- * keyword.
- */
-char *structtag = "<uninited>";
-enum sym_type structtype;
-
 /*
  * When objdef is different from onone, objtag is the name of the class.
  */
-char *objtag = "<uninited>";
+static char *objtag = "<uninited>";
 
 /*
  * Yet another little state machine to deal with preprocessor lines.
  */
-enum
+static enum
 {
   dnone,                       /* nothing seen */
   dsharpseen,                  /* '#' seen as first char on line */
@@ -2221,9 +2467,9 @@ enum
 
 /*
  * State machine for Objective C protocols and implementations.
- * Tom R.Hageman <tom@basil.icce.rug.nl>
+ * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
  */
-enum
+static enum
 {
   onone,                       /* nothing seen */
   oprotocol,                   /* @interface or @protocol seen */
@@ -2244,37 +2490,115 @@ enum
  * Use this structure to keep info about the token read, and how it
  * should be tagged.  Used by the make_C_tag function to build a tag.
  */
-typedef struct
+static struct tok
 {
   bool valid;
-  char *str;
   bool named;
-  int linelen;
+  int offset;
+  int length;
   int lineno;
   long linepos;
-  char *buffer;
-} token;
-
-token tok;                     /* latest token read */
+  char *line;
+} token;                       /* latest token read */
+static linebuffer token_name;  /* its name */
 
 /*
- * Set this to TRUE, and the next token considered is called a function.
- * Used only for GNU emacs's function-defining macros.
+ * Variables and functions for dealing with nested structures.
+ * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
  */
-bool next_token_is_func;
+static void pushclass_above __P((int, char *, int));
+static void popclass_above __P((int));
+static void write_classname __P((linebuffer *, char *qualifier));
+
+static struct {
+  char **cname;                        /* nested class names */
+  int *cblev;                  /* nested class curly brace level */
+  int nl;                      /* class nesting level (elements used) */
+  int size;                    /* length of the array */
+} cstack;                      /* stack for nested declaration tags */
+/* Current struct nesting depth (namespace, class, struct, union, enum). */
+#define nestlev                (cstack.nl)
+/* After struct keyword or in struct body, not inside an nested function. */
+#define instruct       (structdef == snone && nestlev > 0                      \
+                        && cblev == cstack.cblev[nestlev-1] + 1)
 
-/*
- * TRUE in the rules part of a yacc file, FALSE outside (parse as C).
- */
-bool yacc_rules;
+static void
+pushclass_above (cblev, str, len)
+     int cblev;
+     char *str;
+     int len;
+{
+  int nl;
 
-/*
- * methodlen is the length of the method name stored in token_name.
- */
-int methodlen;
+  popclass_above (cblev);
+  nl = cstack.nl;
+  if (nl >= cstack.size)
+    {
+      int size = cstack.size *= 2;
+      xrnew (cstack.cname, size, char *);
+      xrnew (cstack.cblev, size, int);
+    }
+  assert (nl == 0 || cstack.cblev[nl-1] < cblev);
+  cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
+  cstack.cblev[nl] = cblev;
+  cstack.nl = nl + 1;
+}
+
+static void
+popclass_above (cblev)
+     int cblev;
+{
+  int nl;
+
+  for (nl = cstack.nl - 1;
+       nl >= 0 && cstack.cblev[nl] >= cblev;
+       nl--)
+    {
+      if (cstack.cname[nl] != NULL)
+       free (cstack.cname[nl]);
+      cstack.nl = nl;
+    }
+}
+
+static void
+write_classname (cn, qualifier)
+     linebuffer *cn;
+     char *qualifier;
+{
+  int i, len;
+  int qlen = strlen (qualifier);
+
+  if (cstack.nl == 0 || cstack.cname[0] == NULL)
+    {
+      len = 0;
+      cn->len = 0;
+      cn->buffer[0] = '\0';
+    }
+  else
+    {
+      len = strlen (cstack.cname[0]);
+      linebuffer_setlen (cn, len);
+      strcpy (cn->buffer, cstack.cname[0]);
+    }
+  for (i = 1; i < cstack.nl; i++)
+    {
+      char *s;
+      int slen;
+
+      s = cstack.cname[i];
+      if (s == NULL)
+       continue;
+      slen = strlen (s);
+      len += slen + qlen;
+      linebuffer_setlen (cn, len);
+      strncat (cn->buffer, qualifier, qlen);
+      strncat (cn->buffer, s, slen);
+    }
+}
 
-static bool consider_token P_((char *, int, int, int, int, int, bool *));
-static void make_C_tag P_((bool));
+\f
+static bool consider_token __P((char *, int, int, int *, int, int, bool *));
+static void make_C_tag __P((bool));
 
 /*
  * consider_token ()
@@ -2283,7 +2607,7 @@ static void make_C_tag P_((bool));
  *     is a struct/union/enum tag, or #define, or an enum constant.
  *
  *     *IS_FUNC gets TRUE iff the token is a function or #define macro
- *     with args.  C_EXT is which language we are looking at.
+ *     with args.  C_EXTP points to which language we are looking at.
  *
  * Globals
  *     fvdef                   IN OUT
@@ -2291,20 +2615,27 @@ static void make_C_tag P_((bool));
  *     definedef               IN OUT
  *     typdef                  IN OUT
  *     objdef                  IN OUT
- *     next_token_is_func      IN OUT
  */
 
 static bool
-consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
+consider_token (str, len, c, c_extp, cblev, parlev, is_func_or_var)
      register char *str;       /* IN: token pointer */
      register int len;         /* IN: token length */
      register int c;           /* IN: first char after the token */
-     int c_ext;                        /* IN: C extensions mask */
+     int *c_extp;              /* IN, OUT: C extensions mask */
      int cblev;                        /* IN: curly brace level */
      int parlev;               /* IN: parenthesis level */
      bool *is_func_or_var;     /* OUT: function or variable found */
 {
-  enum sym_type toktype = C_symtype (str, len, c_ext);
+  /* When structdef is stagseen, scolonseen, or snone with cblev > 0,
+     structtype is the type of the preceding struct-like keyword, and
+     structcblev is the curly brace level where it has been seen. */
+  static enum sym_type structtype;
+  static int structcblev;
+  static enum sym_type toktype;
+
+
+  toktype = C_symtype (str, len, *c_extp);
 
   /*
    * Advance the definedef state machine.
@@ -2313,6 +2644,11 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
     {
     case dnone:
       /* We're not on a preprocessor line. */
+      if (toktype == st_C_gnumacro)
+       {
+         fvdef = fdefunkey;
+         return FALSE;
+       }
       break;
     case dsharpseen:
       if (toktype == st_C_define)
@@ -2361,17 +2697,25 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
        {
        case st_none:
        case st_C_typespec:
+       case st_C_class:
        case st_C_struct:
        case st_C_enum:
          typdef = ttypeseen;
          break;
        }
-      /* Do not return here, so the structdef stuff has a chance. */
+      break;
+    case ttypeseen:
+      if (structdef == snone && fvdef == fvnone)
+       {
+         fvdef = fvnameseen;
+         return TRUE;
+       }
       break;
     case tend:
       switch (toktype)
        {
        case st_C_typespec:
+       case st_C_class:
        case st_C_struct:
        case st_C_enum:
          return FALSE;
@@ -2380,11 +2724,6 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
     }
 
   /*
-   * This structdef business is currently only invoked when cblev==0.
-   * It should be recursively invoked whatever the curly brace level,
-   * and a stack of states kept, to allow for definitions of structs
-   * within structs.
-   *
    * This structdef business is NOT invoked when we are ctags and the
    * file is plain C.  This is because a struct tag may have the same
    * name as another tag, and this loses with ctags.
@@ -2395,25 +2734,32 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
       if (structdef == stagseen)
         structdef = scolonseen;
       return FALSE;
+    case st_C_template:
+    case st_C_class:
+      if (cblev == 0
+         && (*c_extp & C_AUTO) /* automatic detection of C++ language */
+         && definedef == dnone && structdef == snone
+         && typdef == tnone && fvdef == fvnone)
+       *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
+      if (toktype == st_C_template)
+       break;
+      /* FALLTHRU */
     case st_C_struct:
     case st_C_enum:
-      if (typdef == tkeyseen
-         || (typedefs_and_cplusplus && cblev == 0 && structdef == snone))
+      if (parlev == 0
+         && fvdef != vignore
+         && (typdef == tkeyseen
+             || (typedefs_or_cplusplus && structdef == snone)))
        {
          structdef = skeyseen;
          structtype = toktype;
+         structcblev = cblev;
        }
       return FALSE;
     }
 
   if (structdef == skeyseen)
     {
-      /* Save the tag for struct/union/class, for functions and variables
-        that may be defined inside. */
-      if (structtype == st_C_struct)
-       structtag = savenstr (str, len);
-      else
-       structtag = "<enum>";
       structdef = stagseen;
       return TRUE;
     }
@@ -2421,34 +2767,6 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
   if (typdef != tnone)
     definedef = dnone;
 
-  /* Detect GNU macros.
-
-     Writers of emacs code are recommended to put the
-     first two args of a DEFUN on the same line.
-
-      The DEFUN macro, used in emacs C source code, has a first arg
-     that is a string (the lisp function name), and a second arg that
-     is a C function name.  Since etags skips strings, the second arg
-     is tagged.  This is unfortunate, as it would be better to tag the
-     first arg.  The simplest way to deal with this problem would be
-     to name the tag with a name built from the function name, by
-     removing the initial 'F' character and substituting '-' for '_'.
-     Anyway, this assumes that the conventions of naming lisp
-     functions will never change.  Currently, this method is not
-     implemented. */
-  if (definedef == dnone && toktype == st_C_gnumacro)
-    {
-      next_token_is_func = TRUE;
-      return FALSE;
-    }
-  if (next_token_is_func)
-    {
-      next_token_is_func = FALSE;
-      fvdef = fignore;
-      *is_func_or_var = TRUE;
-      return TRUE;
-    }
-
   /* Detect Objective C constructs. */
   switch (objdef)
     {
@@ -2484,11 +2802,9 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
       if (parlev == 0)
        {
          objdef = omethodtag;
-         methodlen = len;
-         grow_linebuffer (&token_name, methodlen + 1);
+         linebuffer_setlen (&token_name, len);
          strncpy (token_name.buffer, str, len);
-         token_name.buffer[methodlen] = '\0';
-         token_name.len = methodlen;
+         token_name.buffer[len] = '\0';
          return TRUE;
        }
       return FALSE;
@@ -2500,10 +2816,8 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
       if (parlev == 0)
        {
          objdef = omethodtag;
-         methodlen += len;
-         grow_linebuffer (&token_name, methodlen + 1);
+         linebuffer_setlen (&token_name, token_name.len + len);
          strncat (token_name.buffer, str, len);
-         token_name.len = methodlen;
          return TRUE;
        }
       return FALSE;
@@ -2540,16 +2854,33 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
       *is_func_or_var = TRUE;
       return TRUE;
     case st_none:
-      if ((c_ext & C_PLPL) && strneq (str+len-10, "::operator", 10))
+      if (constantypedefs
+         && structdef == snone
+         && structtype == st_C_enum && cblev > structcblev)
+       return TRUE;            /* enum constant */
+      switch (fvdef)
        {
-         fvdef = foperator;
+       case fdefunkey:
+         if (cblev > 0)
+           break;
+         fvdef = fdefunname;   /* GNU macro */
          *is_func_or_var = TRUE;
          return TRUE;
-       }
-      if (constantypedefs && structdef == sinbody && structtype == st_C_enum)
-       return TRUE;
-      if (fvdef == fvnone)
-       {
+       case fvnone:
+         if ((strneq (str, "asm", 3) && endtoken (str[3]))
+             || (strneq (str, "__asm__", 7) && endtoken (str[7])))
+           {
+             fvdef = vignore;
+             return FALSE;
+           }
+         if ((*c_extp & C_PLPL) && strneq (str+len-10, "::operator", 10))
+           {
+             fvdef = foperator;
+             *is_func_or_var = TRUE;
+             return TRUE;
+           }
+         if (cblev > 0 && !instruct)
+           break;
          fvdef = fvnameseen;   /* function or variable */
          *is_func_or_var = TRUE;
          return TRUE;
@@ -2560,20 +2891,24 @@ consider_token (str, len, c, c_ext, cblev, parlev, is_func_or_var)
   return FALSE;
 }
 
+\f
 /*
- * C_entries ()
- *     This routine finds functions, variables, typedefs,
- *     #define's, enum constants and struct/union/enum definitions in
- *     C syntax and adds them to the list.
+ * C_entries often keeps pointers to tokens or lines which are older than
+ * the line currently read.  By keeping two line buffers, and switching
+ * them at end of line, it is possible to use those pointers.
  */
+static struct
+{
+  long linepos;
+  linebuffer lb;
+} lbs[2];
+
 #define current_lb_is_new (newndx == curndx)
 #define switch_line_buffers() (curndx = 1 - curndx)
 
 #define curlb (lbs[curndx].lb)
-#define othlb (lbs[1-curndx].lb)
 #define newlb (lbs[newndx].lb)
 #define curlinepos (lbs[curndx].linepos)
-#define othlinepos (lbs[1-curndx].linepos)
 #define newlinepos (lbs[newndx].linepos)
 
 #define CNL_SAVE_DEFINEDEF()                                           \
@@ -2590,10 +2925,10 @@ do {                                                                    \
 #define CNL()                                                          \
 do {                                                                   \
   CNL_SAVE_DEFINEDEF();                                                        \
-  if (savetok.valid)                                                   \
+  if (savetoken.valid)                                                 \
     {                                                                  \
-      tok = savetok;                                                   \
-      savetok.valid = FALSE;                                           \
+      token = savetoken;                                               \
+      savetoken.valid = FALSE;                                         \
     }                                                                  \
   definedef = dnone;                                                   \
 } while (0)
@@ -2603,9 +2938,9 @@ static void
 make_C_tag (isfun)
      bool isfun;
 {
-  /* This function should never be called when tok.valid is FALSE, but
+  /* This function should never be called when token.valid is FALSE, but
      we must protect against invalid input or internal errors. */
-  if (tok.valid)
+  if (DEBUG || token.valid)
     {
       if (traditional_tag_style)
        {
@@ -2613,21 +2948,32 @@ make_C_tag (isfun)
             which uses the new method for naming tags (see new_pfnote). */
          char *name = NULL;
 
-         if (CTAGS || tok.named)
+         if (CTAGS || token.named)
            name = savestr (token_name.buffer);
-         pfnote (name, isfun,
-                 tok.buffer, tok.linelen, tok.lineno, tok.linepos);
+         if (DEBUG && !token.valid)
+           {
+             if (token.named)
+               name = concat (name, "##invalid##", "");
+             else
+               name = savestr ("##invalid##");
+           }
+         pfnote (name, isfun, token.line,
+                 token.offset+token.length+1, token.lineno, token.linepos);
        }
       else
-       new_pfnote (token_name.buffer, token_name.len, isfun,
-                   tok.buffer, tok.linelen, tok.lineno, tok.linepos);
-      tok.valid = FALSE;
+       new_pfnote (token_name.buffer, token_name.len, isfun, token.line,
+                   token.offset+token.length+1, token.lineno, token.linepos);
+      token.valid = FALSE;
     }
-  else if (DEBUG)
-    abort ();
 }
 
 
+/*
+ * C_entries ()
+ *     This routine finds functions, variables, typedefs,
+ *     #define's, enum constants and struct/union/enum definitions in
+ *     C syntax and adds them to the list.
+ */
 static void
 C_entries (c_ext, inf)
      int c_ext;                        /* extension of C */
@@ -2642,12 +2988,25 @@ C_entries (c_ext, inf)
   int qlen;                    /* length of qualifier */
   int cblev;                   /* current curly brace level */
   int parlev;                  /* current parenthesis level */
+  int typdefcblev;             /* cblev where a typedef struct body begun */
   bool incomm, inquote, inchar, quotednl, midtoken;
-  bool purec, cplpl, cjava;
-  token savetok;               /* token saved during preprocessor handling */
+  bool cplpl, cjava;
+  bool yacc_rules;             /* in the rules part of a yacc file */
+  struct tok savetoken;                /* token saved during preprocessor handling */
 
 
-  tokoff = toklen = 0;         /* keep compiler quiet */
+  initbuffer (&token_name);
+  initbuffer (&lbs[0].lb);
+  initbuffer (&lbs[1].lb);
+  if (cstack.size == 0)
+    {
+      cstack.size = (DEBUG) ? 1 : 4;
+      cstack.nl = 0;
+      cstack.cname = xnew (cstack.size, char *);
+      cstack.cblev = xnew (cstack.size, int);
+    }
+
+  tokoff = toklen = typdefcblev = 0; /* keep compiler quiet */
   curndx = newndx = 0;
   lineno = 0;
   charno = 0;
@@ -2656,12 +3015,11 @@ C_entries (c_ext, inf)
 
   fvdef = fvnone; fvextern = FALSE; typdef = tnone;
   structdef = snone; definedef = dnone; objdef = onone;
-  next_token_is_func = yacc_rules = FALSE;
+  yacc_rules = FALSE;
   midtoken = inquote = inchar = incomm = quotednl = FALSE;
-  tok.valid = savetok.valid = FALSE;
+  token.valid = savetoken.valid = FALSE;
   cblev = 0;
   parlev = 0;
-  purec = !(c_ext & ~YACC);    /* no extensions (apart from possibly yacc) */
   cplpl = (c_ext & C_PLPL) == C_PLPL;
   cjava = (c_ext & C_JAVA) == C_JAVA;
   if (cjava)
@@ -2669,6 +3027,7 @@ C_entries (c_ext, inf)
   else
     { qualifier = "::"; qlen = 2; }
 
+
   while (!feof (inf))
     {
       c = *lp++;
@@ -2739,8 +3098,15 @@ C_entries (c_ext, inf)
          {
          case '"':
            inquote = TRUE;
-           if (fvdef != finlist && fvdef != fignore && fvdef !=vignore)
+           switch (fvdef)
              {
+             case fdefunkey:
+             case fstartlist:
+             case finlist:
+             case fignore:
+             case vignore:
+               break;
+             default:
                fvextern = FALSE;
                fvdef = fvnone;
              }
@@ -2770,11 +3136,10 @@ C_entries (c_ext, inf)
          case '%':
            if ((c_ext & YACC) && *lp == '%')
              {
-               /* entering or exiting rules section in yacc file */
+               /* Entering or exiting rules section in yacc file. */
                lp++;
                definedef = dnone; fvdef = fvnone; fvextern = FALSE;
                typdef = tnone; structdef = snone;
-               next_token_is_func = FALSE;
                midtoken = inquote = inchar = incomm = quotednl = FALSE;
                cblev = 0;
                yacc_rules = !yacc_rules;
@@ -2810,21 +3175,18 @@ C_entries (c_ext, inf)
          } /* switch (c) */
 
 
-      /* Consider token only if some complicated conditions are satisfied. */
-      if ((definedef != dnone
-          || (cblev == 0 && structdef != scolonseen)
-          || (cblev == 1 && cplpl && structdef == sinbody)
-          || (structdef == sinbody && purec))
-         && typdef != tignore
+      /* Consider token only if some involved conditions are satisfied. */
+      if (typdef != tignore
          && definedef != dignorerest
-         && fvdef != finlist)
+         && fvdef != finlist
+         && structdef != sintemplate
+         && (definedef != dnone
+             || structdef != scolonseen))
        {
          if (midtoken)
            {
              if (endtoken (c))
                {
-                 bool funorvar = FALSE;
-
                  if (c == ':' && cplpl && *lp == ':' && begtoken (lp[1]))
                    {
                      /*
@@ -2835,13 +3197,15 @@ C_entries (c_ext, inf)
                      lp += 2;
                      toklen += 2;
                      c = lp[-1];
-                     goto intok;
+                     goto still_in_token;
                    }
                  else
                    {
+                     bool funorvar = FALSE;
+
                      if (yacc_rules
                          || consider_token (newlb.buffer + tokoff, toklen, c,
-                                            c_ext, cblev, parlev, &funorvar))
+                                            &c_ext, cblev, parlev, &funorvar))
                        {
                          if (fvdef == foperator)
                            {
@@ -2855,82 +3219,107 @@ C_entries (c_ext, inf)
                              c = *lp++;
                              toklen += lp - oldlp;
                            }
-                         tok.named = FALSE;
-                         if (!purec
-                             && funorvar
-                             && definedef == dnone
-                             && structdef == sinbody)
-                           /* function or var defined in C++ class body */
+                         token.named = FALSE;
+                         if ((c_ext & C_EXT)   /* not pure C */
+                             && nestlev > 0 && definedef == dnone)
+                           /* in struct body */
                            {
-                             int len = strlen (structtag) + qlen + toklen;
-                             grow_linebuffer (&token_name, len + 1);
-                             strcpy (token_name.buffer, structtag);
+                              write_classname (&token_name, qualifier);
+                             linebuffer_setlen (&token_name,
+                                                token_name.len+qlen+toklen);
                              strcat (token_name.buffer, qualifier);
                              strncat (token_name.buffer,
                                       newlb.buffer + tokoff, toklen);
-                             token_name.len = len;
-                             tok.named = TRUE;
+                             token.named = TRUE;
                            }
                          else if (objdef == ocatseen)
                            /* Objective C category */
                            {
                              int len = strlen (objtag) + 2 + toklen;
-                             grow_linebuffer (&token_name, len + 1);
+                             linebuffer_setlen (&token_name, len);
                              strcpy (token_name.buffer, objtag);
                              strcat (token_name.buffer, "(");
                              strncat (token_name.buffer,
                                       newlb.buffer + tokoff, toklen);
                              strcat (token_name.buffer, ")");
-                             token_name.len = len;
-                             tok.named = TRUE;
+                             token.named = TRUE;
                            }
                          else if (objdef == omethodtag
                                   || objdef == omethodparm)
                            /* Objective C method */
                            {
-                             tok.named = TRUE;
+                             token.named = TRUE;
+                           }
+                         else if (fvdef == fdefunname)
+                           /* GNU DEFUN and similar macros */
+                           {
+                             bool defun = (newlb.buffer[tokoff] == 'F');
+                             int off = tokoff;
+                             int len = toklen;
+
+                             /* Rewrite the tag so that emacs lisp DEFUNs
+                                can be found by their elisp name */
+                             if (defun)
+                               {
+                                 off += 1;
+                                 len -= 1;
+                               }
+                             len = toklen;
+                             linebuffer_setlen (&token_name, len);
+                             strncpy (token_name.buffer,
+                                      newlb.buffer + off, len);
+                             token_name.buffer[len] = '\0';
+                             if (defun)
+                               while (--len >= 0)
+                                 if (token_name.buffer[len] == '_')
+                                   token_name.buffer[len] = '-';
+                             token.named = defun;
                            }
                          else
                            {
-                             grow_linebuffer (&token_name, toklen + 1);
+                             linebuffer_setlen (&token_name, toklen);
                              strncpy (token_name.buffer,
                                       newlb.buffer + tokoff, toklen);
                              token_name.buffer[toklen] = '\0';
-                             token_name.len = toklen;
                              /* Name macros and members. */
-                             tok.named = (structdef == stagseen
-                                          || typdef == ttypeseen
-                                          || typdef == tend
-                                          || (funorvar
-                                              && definedef == dignorerest)
-                                          || (funorvar
-                                              && definedef == dnone
-                                              && structdef == sinbody));
+                             token.named = (structdef == stagseen
+                                            || typdef == ttypeseen
+                                            || typdef == tend
+                                            || (funorvar
+                                                && definedef == dignorerest)
+                                            || (funorvar
+                                                && definedef == dnone
+                                                && structdef == snone
+                                                && cblev > 0));
                            }
-                         tok.lineno = lineno;
-                         tok.linelen = tokoff + toklen + 1;
-                         tok.buffer = newlb.buffer;
-                         tok.linepos = newlinepos;
-                         tok.valid = TRUE;
+                         token.lineno = lineno;
+                         token.offset = tokoff;
+                         token.length = toklen;
+                         token.line = newlb.buffer;
+                         token.linepos = newlinepos;
+                         token.valid = TRUE;
 
                          if (definedef == dnone
                              && (fvdef == fvnameseen
                                  || fvdef == foperator
                                  || structdef == stagseen
                                  || typdef == tend
+                                 || typdef == ttypeseen
                                  || objdef != onone))
                            {
                              if (current_lb_is_new)
                                switch_line_buffers ();
                            }
-                         else
+                         else if (definedef != dnone
+                                  || fvdef == fdefunname
+                                  || instruct)
                            make_C_tag (funorvar);
                        }
                      midtoken = FALSE;
                    }
                } /* if (endtoken (c)) */
              else if (intoken (c))
-               intok:
+               still_in_token:
                {
                  toklen++;
                  continue;
@@ -2955,10 +3344,13 @@ C_entries (c_ext, inf)
                      break;
                    }
                  if (structdef == stagseen && !cjava)
-                   structdef = snone;
+                   {
+                     popclass_above (cblev);
+                     structdef = snone;
+                   }
                  break;
                case dsharpseen:
-                 savetok = tok;
+                 savetoken = token;
                }
              if (!yacc_rules || lp == newlb.buffer + 1)
                {
@@ -2976,6 +3368,11 @@ C_entries (c_ext, inf)
       switch (c)
        {
        case ':':
+         if (yacc_rules && token.offset == 0 && token.valid)
+           {
+             make_C_tag (FALSE); /* a yacc function */
+             break;
+           }
          if (definedef != dnone)
            break;
          switch (objdef)
@@ -2987,65 +3384,62 @@ C_entries (c_ext, inf)
            case omethodtag:
            case omethodparm:
              objdef = omethodcolon;
-             methodlen += 1;
-             grow_linebuffer (&token_name, methodlen + 1);
+             linebuffer_setlen (&token_name, token_name.len + 1);
              strcat (token_name.buffer, ":");
-             token_name.len = methodlen;
              break;
            }
          if (structdef == stagseen)
            structdef = scolonseen;
-         else
-           switch (fvdef)
-             {
-             case fvnameseen:
-               if (yacc_rules)
-                 {
-                   make_C_tag (FALSE); /* a yacc function */
-                   fvdef = fignore;
-                 }
-               break;
-             case fstartlist:
-               fvextern = FALSE;
-               fvdef = fvnone;
-               break;
-             }
          break;
        case ';':
          if (definedef != dnone)
            break;
-         if (cblev == 0)
-           switch (typdef)
-             {
-             case tend:
-               make_C_tag (FALSE); /* a typedef */
-               /* FALLTHRU */
-             default:
-               typdef = tnone;
-             }
-         switch (fvdef)
+         switch (typdef)
            {
-           case fignore:
-             break;
-           case fvnameseen:
-             if ((members && cblev == 1)
-                 || (globals && cblev == 0 && (!fvextern || declarations)))
-               make_C_tag (FALSE); /* a variable */
-             fvextern = FALSE;
+           case tend:
+           case ttypeseen:
+             make_C_tag (FALSE); /* a typedef */
+             typdef = tnone;
              fvdef = fvnone;
-             tok.valid = FALSE;
              break;
-           case flistseen:
-             if (declarations && (cblev == 0 || cblev == 1))
-               make_C_tag (TRUE); /* a function declaration */
+           case tnone:
+           case tinbody:
+           case tignore:
+             switch (fvdef)
+               {
+               case fignore:
+                 if (typdef == tignore)
+                   fvdef = fvnone;
+                 break;
+               case fvnameseen:
+                 if ((globals && cblev == 0 && (!fvextern || declarations))
+                     || (members && instruct))
+                   make_C_tag (FALSE); /* a variable */
+                 fvextern = FALSE;
+                 fvdef = fvnone;
+                 token.valid = FALSE;
+                 break;
+               case flistseen:
+                 if ((declarations && typdef == tnone && !instruct)
+                     || (members && typdef != tignore && instruct))
+                   make_C_tag (TRUE);  /* a function declaration */
+                 /* FALLTHRU */
+               default:
+                 fvextern = FALSE;
+                 fvdef = fvnone;
+                 if (declarations
+                     && structdef == stagseen && (c_ext & C_PLPL))
+                   make_C_tag (FALSE); /* forward declaration */
+                 else
+                   /* The following instruction invalidates the token.
+                      Probably the token should be invalidated in all other
+                      cases where some state machine is reset prematurely. */
+                   token.valid = FALSE;
+               } /* switch (fvdef) */
              /* FALLTHRU */
            default:
-             fvextern = FALSE;
-             fvdef = fvnone;
-             /* The following instruction invalidates the token.
-                Probably the token should be invalidated in all
-                other cases  where some state machine is reset. */
-             tok.valid = FALSE;
+             if (!instruct)
+               typdef = tnone;
            }
          if (structdef == stagseen)
            structdef = snone;
@@ -3063,15 +3457,31 @@ C_entries (c_ext, inf)
            }
          switch (fvdef)
            {
+           case fdefunkey:
            case foperator:
+           case fstartlist:
            case finlist:
            case fignore:
            case vignore:
              break;
-           case fvnameseen:
-             if ((members && cblev == 1)
-                 || (globals && cblev == 0 && (!fvextern || declarations)))
-               make_C_tag (FALSE); /* a variable */
+           case fdefunname:
+             fvdef = fignore;
+             break;
+           case fvnameseen:    /* a variable */
+             if ((globals && cblev == 0 && (!fvextern || declarations))
+                 || (members && instruct))
+               make_C_tag (FALSE);
+             break;
+           case flistseen:     /* a function */
+             if ((declarations && typdef == tnone && !instruct)
+                 || (members && typdef != tignore && instruct))
+               {
+                 make_C_tag (TRUE); /* a function declaration */
+                 fvdef = fvnameseen;
+               }
+             else if (!declarations)
+               fvdef = fvnone;
+             token.valid = FALSE;
              break;
            default:
              fvdef = fvnone;
@@ -3082,29 +3492,35 @@ C_entries (c_ext, inf)
        case '[':
          if (definedef != dnone)
            break;
-         if (cblev == 0 && typdef == tend)
+         if (structdef == stagseen)
+           structdef = snone;
+         switch (typdef)
            {
+           case ttypeseen:
+           case tend:
              typdef = tignore;
              make_C_tag (FALSE);       /* a typedef */
              break;
-           }
-         switch (fvdef)
-           {
-           case foperator:
-           case finlist:
-           case fignore:
-           case vignore:
+           case tnone:
+           case tinbody:
+             switch (fvdef)
+               {
+               case foperator:
+               case finlist:
+               case fignore:
+               case vignore:
+                 break;
+               case fvnameseen:
+                 if ((members && cblev == 1)
+                     || (globals && cblev == 0
+                         && (!fvextern || declarations)))
+                   make_C_tag (FALSE); /* a variable */
+                 /* FALLTHRU */
+               default:
+                 fvdef = fvnone;
+               }
              break;
-           case fvnameseen:
-             if ((members && cblev == 1)
-                 || (globals && cblev == 0 && (!fvextern || declarations)))
-               make_C_tag (FALSE); /* a variable */
-             /* FALLTHRU */
-           default:
-             fvdef = fvnone;
            }
-         if (structdef == stagseen)
-           structdef = snone;
          break;
        case '(':
          if (definedef != dnone)
@@ -3115,14 +3531,15 @@ C_entries (c_ext, inf)
            {
            case fvnameseen:
              if (typdef == ttypeseen
-                 && tok.valid
                  && *lp != '*'
-                 && structdef != sinbody)
+                 && !instruct)
                {
                  /* This handles constructs like:
                     typedef void OperatorFun (int fun); */
                  make_C_tag (FALSE);
                  typdef = tignore;
+                 fvdef = fignore;
+                 break;
                }
              /* FALLTHRU */
            case foperator:
@@ -3151,7 +3568,9 @@ C_entries (c_ext, inf)
                  fvdef = flistseen;
                  break;
                }
-             if (cblev == 0 && (typdef == tend))
+             if (!instruct
+                 && (typdef == tend
+                     || typdef == ttypeseen))
                {
                  typdef = tignore;
                  make_C_tag (FALSE); /* a typedef */
@@ -3164,23 +3583,16 @@ C_entries (c_ext, inf)
          if (definedef != dnone)
            break;
          if (typdef == ttypeseen)
-           typdef = tinbody;
-         switch (structdef)
            {
-           case skeyseen:      /* unnamed struct */
-             structdef = sinbody;
-             structtag = "_anonymous_";
-             break;
-           case stagseen:
-           case scolonseen:    /* named struct */
-             structdef = sinbody;
-             make_C_tag (FALSE);       /* a struct */
-             break;
+             /* Whenever typdef is set to tinbody (currently only
+                here), typdefcblev should be set to cblev. */
+             typdef = tinbody;
+             typdefcblev = cblev;
            }
          switch (fvdef)
            {
            case flistseen:
-             make_C_tag (TRUE); /* a function */
+             make_C_tag (TRUE);    /* a function */
              /* FALLTHRU */
            case fignore:
              fvdef = fvnone;
@@ -3199,10 +3611,24 @@ C_entries (c_ext, inf)
                  break;
                default:
                  /* Neutralize `extern "C" {' grot. */
-                 if (cblev == 0 && structdef == snone && typdef == tnone)
+                 if (cblev == 0 && structdef == snone && nestlev == 0
+                     && typdef == tnone)
                    cblev = -1;
                }
            }
+         switch (structdef)
+           {
+           case skeyseen:         /* unnamed struct */
+             pushclass_above (cblev, NULL, 0);
+             structdef = snone;
+             break;
+           case stagseen:         /* named struct or enum */
+           case scolonseen:       /* a class */
+             pushclass_above (cblev, token.line+token.offset, token.length);
+             structdef = snone;
+             make_C_tag (FALSE);  /* a struct or enum */
+             break;
+           }
          cblev++;
          break;
        case '*':
@@ -3221,20 +3647,13 @@ C_entries (c_ext, inf)
            }
          else if (cblev > 0)
            cblev--;
-         if (cblev == 0)
+         popclass_above (cblev);
+         structdef = snone;
+         /* Only if typdef == tinbody is typdefcblev significant. */
+         if (typdef == tinbody && cblev <= typdefcblev)
            {
-             if (typdef == tinbody)
-               typdef = tend;
-             /* Memory leakage here: the string pointed by structtag is
-                never released, because I fear to miss something and
-                break things while freeing the area.  The amount of
-                memory leaked here is the sum of the lengths of the
-                struct tags.
-             if (structdef == sinbody)
-               free (structtag); */
-
-             structdef = snone;
-             structtag = "<error>";
+             assert (cblev == typdefcblev);
+             typdef = tend;
            }
          break;
        case '=':
@@ -3255,7 +3674,21 @@ C_entries (c_ext, inf)
            default:
              fvdef = vignore;
            }
-         break;
+         break;
+       case '<':
+         if (cplpl && structdef == stagseen)
+           {
+             structdef = sintemplate;
+             break;
+           }
+         goto resetfvdef;
+       case '>':
+         if (structdef == sintemplate)
+           {
+             structdef = stagseen;
+             break;
+           }
+         goto resetfvdef;
        case '+':
        case '-':
          if (objdef == oinbody && cblev == 0)
@@ -3264,8 +3697,9 @@ C_entries (c_ext, inf)
              break;
            }
          /* FALLTHRU */
+       resetfvdef:
        case '#': case '~': case '&': case '%': case '/': case '|':
-       case '^': case '!': case '<': case '>': case '.': case '?': case ']':
+       case '^': case '!': case '.': case '?': case ']':
          if (definedef != dnone)
            break;
          /* These surely cannot follow a function tag in C. */
@@ -3295,6 +3729,10 @@ C_entries (c_ext, inf)
        } /* switch (c) */
 
     } /* while not eof */
+
+  free (token_name.buffer);
+  free (lbs[0].lb.buffer);
+  free (lbs[1].lb.buffer);
 }
 
 /*
@@ -3305,10 +3743,10 @@ static void
 default_C_entries (inf)
      FILE *inf;
 {
-  C_entries (cplusplus ? C_PLPL : 0, inf);
+  C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
 }
 
-/* Always do plain ANSI C. */
+/* Always do plain C. */
 static void
 plain_C_entries (inf)
      FILE *inf;
@@ -3347,8 +3785,9 @@ Yacc_entries (inf)
 {
   C_entries (YACC, inf);
 }
+
 \f
-/* A useful macro. */
+/* Useful macros. */
 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer)   \
   for (lineno = charno = 0;    /* loop initialization */               \
        !feof (file_pointer)    /* loop test */                         \
@@ -3358,7 +3797,10 @@ Yacc_entries (inf)
           char_pointer = lb.buffer,                                    \
           TRUE);                                                       \
       )
-
+#define LOOKING_AT(cp, keyword)        /* keyword is a constant string */      \
+  (strneq ((cp), keyword, sizeof(keyword)-1) /* cp points at keyword */        \
+   && notinname ((cp)[sizeof(keyword)-1])      /* end of keyword */    \
+   && ((cp) = skip_spaces((cp)+sizeof(keyword)-1))) /* skip spaces */
 
 /*
  * Read a file, but do no processing.  This is used to do regexp
@@ -3373,31 +3815,15 @@ just_read_file (inf)
   LOOP_ON_INPUT_LINES (inf, lb, dummy)
     continue;
 }
+
 \f
 /* Fortran parsing */
 
-static bool tail P_((char *));
-static void takeprec P_((void));
-static void getit P_((FILE *));
-
-static bool
-tail (cp)
-     char *cp;
-{
-  register int len = 0;
-
-  while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
-    cp++, len++;
-  if (*cp == '\0' && !intoken (dbp[len]))
-    {
-      dbp += len;
-      return TRUE;
-    }
-  return FALSE;
-}
+static void F_takeprec __P((void));
+static void F_getit __P((FILE *));
 
 static void
-takeprec ()
+F_takeprec ()
 {
   dbp = skip_spaces (dbp);
   if (*dbp != '*')
@@ -3420,7 +3846,7 @@ takeprec ()
 }
 
 static void
-getit (inf)
+F_getit (inf)
      FILE *inf;
 {
   register char *cp;
@@ -3460,28 +3886,28 @@ Fortran_functions (inf)
       switch (lowcase (*dbp))
        {
        case 'i':
-         if (tail ("integer"))
-           takeprec ();
+         if (nocase_tail ("integer"))
+           F_takeprec ();
          break;
        case 'r':
-         if (tail ("real"))
-           takeprec ();
+         if (nocase_tail ("real"))
+           F_takeprec ();
          break;
        case 'l':
-         if (tail ("logical"))
-           takeprec ();
+         if (nocase_tail ("logical"))
+           F_takeprec ();
          break;
        case 'c':
-         if (tail ("complex") || tail ("character"))
-           takeprec ();
+         if (nocase_tail ("complex") || nocase_tail ("character"))
+           F_takeprec ();
          break;
        case 'd':
-         if (tail ("double"))
+         if (nocase_tail ("double"))
            {
              dbp = skip_spaces (dbp);
              if (*dbp == '\0')
                continue;
-             if (tail ("precision"))
+             if (nocase_tail ("precision"))
                break;
              continue;
            }
@@ -3493,43 +3919,45 @@ Fortran_functions (inf)
       switch (lowcase (*dbp))
        {
        case 'f':
-         if (tail ("function"))
-           getit (inf);
+         if (nocase_tail ("function"))
+           F_getit (inf);
          continue;
        case 's':
-         if (tail ("subroutine"))
-           getit (inf);
+         if (nocase_tail ("subroutine"))
+           F_getit (inf);
          continue;
        case 'e':
-         if (tail ("entry"))
-           getit (inf);
+         if (nocase_tail ("entry"))
+           F_getit (inf);
          continue;
        case 'b':
-         if (tail ("blockdata") || tail ("block data"))
+         if (nocase_tail ("blockdata") || nocase_tail ("block data"))
            {
              dbp = skip_spaces (dbp);
              if (*dbp == '\0') /* assume un-named */
                pfnote (savestr ("blockdata"), TRUE,
                        lb.buffer, dbp - lb.buffer, lineno, linecharno);
              else
-               getit (inf);    /* look for name */
+               F_getit (inf);  /* look for name */
            }
          continue;
        }
     }
 }
+
 \f
 /*
- * Philippe Waroquiers <philippe.waroquiers@eurocontrol.be>, 1998-04-24
  * Ada parsing
+ * Original code by
+ * Philippe Waroquiers <philippe.waroquiers@eurocontrol.be> (1998)
  */
 
-static void adagetit P_((FILE *, char *));
+static void Ada_getit __P((FILE *, char *));
 
 /* Once we are positioned after an "interesting" keyword, let's get
    the real tag value necessary. */
 static void
-adagetit (inf, name_qualifier)
+Ada_getit (inf, name_qualifier)
      FILE *inf;
      char *name_qualifier;
 {
@@ -3548,11 +3976,10 @@ adagetit (inf, name_qualifier)
          charno += readline (&lb, inf);
          dbp = lb.buffer;
        }
-      switch (*dbp)
+      switch (lowcase(*dbp))
         {
         case 'b':
-        case 'B':
-          if (tail ("body"))
+          if (nocase_tail ("body"))
             {
               /* Skipping body of   procedure body   or   package body or ....
                 resetting qualifier to body instead of spec. */
@@ -3561,9 +3988,8 @@ adagetit (inf, name_qualifier)
             }
           break;
         case 't':
-        case 'T':
           /* Skipping type of   task type   or   protected type ... */
-          if (tail ("type"))
+          if (nocase_tail ("type"))
             continue;
           break;
         }
@@ -3644,33 +4070,30 @@ Ada_funcs (inf)
            }
 
          /* We are at the beginning of a token. */
-         switch (*dbp)
+         switch (lowcase(*dbp))
            {
            case 'f':
-           case 'F':
-             if (!packages_only && tail ("function"))
-               adagetit (inf, "/f");
+             if (!packages_only && nocase_tail ("function"))
+               Ada_getit (inf, "/f");
              else
                break;          /* from switch */
              continue;         /* advance char */
            case 'p':
-           case 'P':
-             if (!packages_only && tail ("procedure"))
-               adagetit (inf, "/p");
-             else if (tail ("package"))
-               adagetit (inf, "/s");
-             else if (tail ("protected")) /* protected type */
-               adagetit (inf, "/t");
+             if (!packages_only && nocase_tail ("procedure"))
+               Ada_getit (inf, "/p");
+             else if (nocase_tail ("package"))
+               Ada_getit (inf, "/s");
+             else if (nocase_tail ("protected")) /* protected type */
+               Ada_getit (inf, "/t");
              else
                break;          /* from switch */
              continue;         /* advance char */
            case 't':
-           case 'T':
-             if (!packages_only && tail ("task"))
-               adagetit (inf, "/k");
-             else if (typedefs && !packages_only && tail ("type"))
+             if (!packages_only && nocase_tail ("task"))
+               Ada_getit (inf, "/k");
+             else if (typedefs && !packages_only && nocase_tail ("type"))
                {
-                 adagetit (inf, "/t");
+                 Ada_getit (inf, "/t");
                  while (*dbp != '\0')
                    dbp += 1;
                }
@@ -3686,11 +4109,12 @@ Ada_funcs (inf)
        } /* advance char */
     } /* advance line */
 }
+
 \f
 /*
- * Bob Weiner, Motorola Inc., 4/3/94
  * Unix and microcontroller assembly tag handling
- * look for '^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]'
+ * Labels:  /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
+ * Idea by Bob Weiner, Motorola Inc. (1994)
  */
 static void
 Asm_labels (inf)
@@ -3717,52 +4141,61 @@ Asm_labels (inf)
        }
     }
 }
+
 \f
 /*
- * Perl support by Bart Robinson <lomew@cs.utah.edu>
- *              enhanced by Michael Ernst <mernst@alum.mit.edu>
- * Perl sub names: look for /^sub[ \t\n]+[^ \t\n{]+/
+ * Perl support
+ * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
  * Perl variable names: /^(my|local).../
+ * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
+ * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
+ * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
  */
 static void
 Perl_functions (inf)
      FILE *inf;
 {
+  char *package = savestr ("main"); /* current package name */
   register char *cp;
 
   LOOP_ON_INPUT_LINES (inf, lb, cp)
     {
-      if (*cp++ == 's'
-         && *cp++ == 'u'
-         && *cp++ == 'b' && iswhite (*cp++))
+      skip_spaces(cp);
+
+      if (LOOKING_AT (cp, "package"))
        {
-         cp = skip_spaces (cp);
-         if (*cp != '\0')
-           {
-             char *sp = cp;
-             while (*cp != '\0'
-                    && !iswhite (*cp) && *cp != '{' && *cp != '(')
-               cp++;
-             pfnote (savenstr (sp, cp-sp), TRUE,
-                     lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
-           }
+         free (package);
+         package = get_tag (cp);
+         if (package == NULL)  /* can't parse package name */
+           package = savestr ("");
+         else
+           package = savestr(package); /* make a copy */
+       }
+      else if (LOOKING_AT (cp, "sub"))
+       {
+         char *name, *fullname, *pos;
+         char *sp = cp;
+
+         while (!notinname (*cp))
+           cp++;
+         if (cp == sp)
+           continue;
+         name = savenstr (sp, cp-sp);
+         if ((pos = etags_strchr (name, ':')) != NULL && pos[1] == ':')
+           fullname = name;
+         else
+           fullname = concat (package, "::", name);
+         pfnote (fullname, TRUE,
+                 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+         if (name != fullname)
+           free (name);
        }
        else if (globals                /* only if tagging global vars is enabled */
-               && ((cp = lb.buffer,
-                    *cp++ == 'm'
-                    && *cp++ == 'y')
-                   || (cp = lb.buffer,
-                       *cp++ == 'l'
-                       && *cp++ == 'o'
-                       && *cp++ == 'c'
-                       && *cp++ == 'a'
-                       && *cp++ == 'l'))
-               && (*cp == '(' || iswhite (*cp)))
+               && (LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local")))
        {
          /* After "my" or "local", but before any following paren or space. */
          char *varname = NULL;
 
-         cp = skip_spaces (cp);
          if (*cp == '$' || *cp == '@' || *cp == '%')
            {
              char* varstart = ++cp;
@@ -3780,15 +4213,18 @@ Perl_functions (inf)
 
          /* Perhaps I should back cp up one character, so the TAGS table
             doesn't mention (and so depend upon) the following char. */
-         pfnote ((CTAGS) ? savenstr (lb.buffer, cp-lb.buffer) : varname,
-                 FALSE, lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+         pfnote (varname, FALSE,
+                 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
        }
     }
 }
-\f
+
+
 /*
- * Python support by Eric S. Raymond <esr@thyrsus.com>
- * Look for /^def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
+ * Python support
+ * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
+ * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
+ * More ideas by seb bacon <seb@jamkit.com> (2002)
  */
 static void
 Python_functions (inf)
@@ -3798,37 +4234,108 @@ Python_functions (inf)
 
   LOOP_ON_INPUT_LINES (inf, lb, cp)
     {
-      if (*cp++ == 'd'
-         && *cp++ == 'e'
-         && *cp++ == 'f' && iswhite (*cp++))
+      cp = skip_spaces (cp);
+      if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
        {
-         cp = skip_spaces (cp);
-         while (*cp != '\0' && !iswhite (*cp) && *cp != '(' && *cp != ':')
+         char *name = cp;
+         while (!notinname (*cp) && *cp != ':')
            cp++;
-         pfnote (NULL, TRUE,
+         pfnote (savenstr (name, cp-name), TRUE,
                  lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
        }
+    }
+}
+
+\f
+/*
+ * PHP support
+ * Look for:
+ *  - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
+ *  - /^[ \t]*class[ \t\n]+[^ \t\n]+/
+ *  - /^[ \t]*define\(\"[^\"]+/
+ * Only with --members:
+ *  - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
+ * Idea by Diez B. Roggisch (2001)
+ */
+static void
+PHP_functions (inf)
+     FILE *inf;
+{
+  register char *cp, *name;
+  bool search_identifier = FALSE;
 
-      cp = lb.buffer;
-      if (*cp++ == 'c'
-         && *cp++ == 'l'
-         && *cp++ == 'a'
-         && *cp++ == 's'
-         && *cp++ == 's' && iswhite (*cp++))
+  LOOP_ON_INPUT_LINES (inf, lb, cp)
+    {
+      cp = skip_spaces (cp);
+      name = cp;
+      if (search_identifier
+         && *cp != '\0')
+       {
+         while (!notinname (*cp))
+           cp++;
+         pfnote (savenstr (name, cp-name), TRUE,
+                 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+         search_identifier = FALSE;
+       }
+      else if (LOOKING_AT (cp, "function"))
+       {
+         if(*cp == '&')
+           cp = skip_spaces (cp+1);
+         if(*cp != '\0')
+           {
+             name = cp;
+             while (!notinname (*cp))
+               cp++;
+             pfnote (savenstr (name, cp-name), TRUE,
+                     lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+           }
+         else
+           search_identifier = TRUE;
+       }
+      else if (LOOKING_AT (cp, "class"))
+       {
+         if (*cp != '\0')
+           {
+             name = cp;
+             while (*cp != '\0' && !iswhite (*cp))
+               cp++;
+             pfnote (savenstr (name, cp-name), FALSE,
+                     lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+           }
+         else
+           search_identifier = TRUE;
+       }
+      else if (strneq (cp, "define", 6)
+              && (cp = skip_spaces (cp+6))
+              && *cp++ == '('
+              && (*cp == '"' || *cp == '\''))
+       {
+         char quote = *cp++;
+         name = cp;
+         while (*cp != quote && *cp != '\0')
+           cp++;
+         pfnote (savenstr (name, cp-name), FALSE,
+                 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+       }
+      else if (members
+              && LOOKING_AT (cp, "var")
+              && *cp == '$')
        {
-         cp = skip_spaces (cp);
-         while (*cp != '\0' && !iswhite (*cp) && *cp != '(' && *cp != ':')
+         name = cp;
+         while (!notinname(*cp))
            cp++;
-         pfnote (NULL, TRUE,
+         pfnote (savenstr (name, cp-name), FALSE,
                  lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
        }
     }
 }
+
 \f
-/* Idea by Corny de Souza
+/*
  * Cobol tag functions
  * We could look for anything that could be a paragraph name.
  * i.e. anything that starts in column 8 is one word and ends in a full stop.
+ * Idea by Corny de Souza (1993)
  */
 static void
 Cobol_paragraphs (inf)
@@ -3853,11 +4360,35 @@ Cobol_paragraphs (inf)
                lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
     }
 }
+
 \f
-/* Added by Mosur Mohan, 4/22/88 */
-/* Pascal parsing                */
+/*
+ * Makefile support
+ * Idea by Assar Westerlund <assar@sics.se> (2001)
+ */
+static void
+Makefile_targets (inf)
+     FILE *inf;
+{
+  register char *bp;
+
+  LOOP_ON_INPUT_LINES (inf, lb, bp)
+    {
+      if (*bp == '\t' || *bp == '#')
+       continue;
+      while (*bp != '\0' && *bp != '=' && *bp != ':')
+       bp++;
+      if (*bp == ':')
+       pfnote (savenstr (lb.buffer, bp - lb.buffer), TRUE,
+               lb.buffer, bp - lb.buffer + 1, lineno, linecharno);
+    }
+}
 
+\f
 /*
+ * Pascal parsing
+ * Original code by Mosur K. Mohan (1989)
+ *
  *  Locates tags for procedures & functions.  Doesn't do any type- or
  *  var-definitions.  It does look for the keyword "extern" or
  *  "forward" immediately following the procedure statement; if found,
@@ -3970,7 +4501,7 @@ Pascal_functions (inf)
            continue;
          if (lowcase (*dbp == 'e'))
            {
-             if (tail ("extern"))      /* superfluous, really! */
+             if (nocase_tail ("extern")) /* superfluous, really! */
                {
                  found_tag = FALSE;
                  verify_tag = FALSE;
@@ -3978,7 +4509,7 @@ Pascal_functions (inf)
            }
          else if (lowcase (*dbp) == 'f')
            {
-             if (tail ("forward"))     /*  check for forward reference */
+             if (nocase_tail ("forward")) /*  check for forward reference */
                {
                  found_tag = FALSE;
                  verify_tag = FALSE;
@@ -3999,7 +4530,7 @@ Pascal_functions (inf)
            continue;
 
          /* save all values for later tagging */
-         grow_linebuffer (&tline, lb.len + 1);
+         linebuffer_setlen (&tline, lb.len);
          strcpy (tline.buffer, lb.buffer);
          save_lineno = lineno;
          save_lcno = linecharno;
@@ -4022,11 +4553,11 @@ Pascal_functions (inf)
          switch (lowcase (c))
            {
            case 'p':
-             if (tail ("rocedure"))    /* c = 'p', dbp has advanced */
+             if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
                get_tagname = TRUE;
              continue;
            case 'f':
-             if (tail ("unction"))
+             if (nocase_tail ("unction"))
                get_tagname = TRUE;
              continue;
            }
@@ -4035,62 +4566,29 @@ Pascal_functions (inf)
 
   free (tline.buffer);
 }
+
 \f
 /*
- * lisp tag functions
+ * Lisp tag functions
  *  look for (def or (DEF, quote or QUOTE
  */
 
-static int L_isdef P_((char *));
-static int L_isquote P_((char *));
-static void L_getit P_((void));
-
-static int
-L_isdef (strp)
-     register char *strp;
-{
-  return ((strp[1] == 'd' || strp[1] == 'D')
-         && (strp[2] == 'e' || strp[2] == 'E')
-         && (strp[3] == 'f' || strp[3] == 'F'));
-}
-
-static int
-L_isquote (strp)
-     register char *strp;
-{
-  return ((*++strp == 'q' || *strp == 'Q')
-         && (*++strp == 'u' || *strp == 'U')
-         && (*++strp == 'o' || *strp == 'O')
-         && (*++strp == 't' || *strp == 'T')
-         && (*++strp == 'e' || *strp == 'E')
-         && iswhite (*++strp));
-}
+static void L_getit __P((void));
 
 static void
 L_getit ()
 {
-  register char *cp;
-
   if (*dbp == '\'')            /* Skip prefix quote */
     dbp++;
   else if (*dbp == '(')
   {
-    if (L_isquote (dbp))
-      dbp += 7;                        /* Skip "(quote " */
-    else
-      dbp += 1;                        /* Skip "(" before name in (defstruct (foo)) */
-    dbp = skip_spaces (dbp);
+    dbp++;
+    /* Try to skip "(quote " */
+    if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
+      /* Ok, then skip "(" before name in (defstruct (foo)) */
+      dbp = skip_spaces (dbp);
   }
-
-  for (cp = dbp /*+1*/;
-       *cp != '\0' && *cp != '(' && !iswhite(*cp) && *cp != ')';
-       cp++)
-    continue;
-  if (cp == dbp)
-    return;
-
-  pfnote (savenstr (dbp, cp-dbp), TRUE,
-         lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+  get_tag (dbp);
 }
 
 static void
@@ -4099,45 +4597,46 @@ Lisp_functions (inf)
 {
   LOOP_ON_INPUT_LINES (inf, lb, dbp)
     {
-      if (dbp[0] == '(')
+      if (dbp[0] != '(')
+       continue;
+
+      if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
        {
-         if (L_isdef (dbp))
-           {
-             dbp = skip_non_spaces (dbp);
-             dbp = skip_spaces (dbp);
-             L_getit ();
-           }
-         else
+         dbp = skip_non_spaces (dbp);
+         dbp = skip_spaces (dbp);
+         L_getit ();
+       }
+      else
+       {
+         /* Check for (foo::defmumble name-defined ... */
+         do
+           dbp++;
+         while (!notinname (*dbp) && *dbp != ':');
+         if (*dbp == ':')
            {
-             /* Check for (foo::defmumble name-defined ... */
              do
                dbp++;
-             while (*dbp != '\0' && !iswhite (*dbp)
-                    && *dbp != ':' && *dbp != '(' && *dbp != ')');
-             if (*dbp == ':')
-               {
-                 do
-                   dbp++;
-                 while (*dbp == ':');
+             while (*dbp == ':');
 
-                 if (L_isdef (dbp - 1))
-                   {
-                     dbp = skip_non_spaces (dbp);
-                     dbp = skip_spaces (dbp);
-                     L_getit ();
-                   }
+             if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
+               {
+                 dbp = skip_non_spaces (dbp);
+                 dbp = skip_spaces (dbp);
+                 L_getit ();
                }
            }
        }
     }
 }
+
 \f
 /*
  * Postscript tag functions
  * Just look for lines where the first character is '/'
- * Richard Mlynarik <mly@adoc.xerox.com>
  * Also look at "defineps" for PSWrap
- * suggested by Masatake YAMATO <masata-y@is.aist-nara.ac.jp>
+ * Ideas by:
+ *   Richard Mlynarik <mly@adoc.xerox.com> (1997)
+ *   Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
  */
 static void
 Postscript_functions (inf)
@@ -4156,12 +4655,8 @@ Postscript_functions (inf)
          pfnote (savenstr (bp, ep-bp), TRUE,
                  lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
        }
-      else if (strneq (bp, "defineps", 8))
-       {
-         bp = skip_non_spaces (bp);
-         bp = skip_spaces (bp);
-         get_tag (bp);
-       }
+      else if (LOOKING_AT (bp, "defineps"))
+       get_tag (bp);
     }
 }
 
@@ -4169,9 +4664,10 @@ Postscript_functions (inf)
 /*
  * Scheme tag functions
  * look for (def... xyzzy
- * look for (def... (xyzzy
- * look for (def ... ((...(xyzzy ....
- * look for (set! xyzzy
+ *          (def... (xyzzy
+ *          (def ... ((...(xyzzy ....
+ *          (set! xyzzy
+ * Original code by Ken Haase (1985?)
  */
 
 static void
@@ -4182,30 +4678,19 @@ Scheme_functions (inf)
 
   LOOP_ON_INPUT_LINES (inf, lb, bp)
     {
-      if (bp[0] == '('
-         && (bp[1] == 'D' || bp[1] == 'd')
-         && (bp[2] == 'E' || bp[2] == 'e')
-         && (bp[3] == 'F' || bp[3] == 'f'))
+      if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
        {
-         bp = skip_non_spaces (bp);
+         bp = skip_non_spaces (bp+4);
          /* Skip over open parens and white space */
-         while (iswhite (*bp) || *bp == '(')
+         while (notinname (*bp))
            bp++;
          get_tag (bp);
        }
-      if (bp[0] == '('
-         && (bp[1] == 'S' || bp[1] == 's')
-         && (bp[2] == 'E' || bp[2] == 'e')
-         && (bp[3] == 'T' || bp[3] == 't')
-         && (bp[4] == '!' || bp[4] == '!')
-         && (iswhite (bp[5])))
-       {
-         bp = skip_non_spaces (bp);
-         bp = skip_spaces (bp);
-         get_tag (bp);
-       }
+      if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
+       get_tag (bp);
     }
 }
+
 \f
 /* Find tags in TeX and LaTeX input files.  */
 
@@ -4218,28 +4703,28 @@ struct TEX_tabent
   int len;
 };
 
-struct TEX_tabent *TEX_toktab = NULL;  /* Table with tag tokens */
+static struct TEX_tabent *TEX_toktab = NULL; /* Table with tag tokens */
 
 /* Default set of control sequences to put into TEX_toktab.
    The value of environment var TEXTAGS is prepended to this.  */
 
-char *TEX_defenv = "\
+static char *TEX_defenv = "\
 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
 :part:appendix:entry:index";
 
-static void TEX_mode P_((FILE *));
-static struct TEX_tabent *TEX_decode_env P_((char *, char *));
-static int TEX_Token P_((char *));
+static void TEX_mode __P((FILE *));
+static struct TEX_tabent *TEX_decode_env __P((char *, char *));
+static int TEX_Token __P((char *));
 
-char TEX_esc = '\\';
-char TEX_opgrp = '{';
-char TEX_clgrp = '}';
+static char TEX_esc = '\\';
+static char TEX_opgrp = '{';
+static char TEX_clgrp = '}';
 
 /*
  * TeX/LaTeX scanning loop.
  */
 static void
-TeX_functions (inf)
+TeX_commands (inf)
      FILE *inf;
 {
   char *cp, *lasthit;
@@ -4265,13 +4750,16 @@ TeX_functions (inf)
          i = TEX_Token (lasthit);
          if (i >= 0)
            {
-             /* We seem to include the TeX command in the tag name.
              register char *p;
-             for (p = lasthit + TEX_toktab[i].len;
-                  *p != '\0' && *p != TEX_clgrp;
+             for (lasthit += TEX_toktab[i].len;
+                  *lasthit == TEX_esc || *lasthit == TEX_opgrp;
+                  lasthit++)
+               continue;
+             for (p = lasthit;
+                  !iswhite (*p) && *p != TEX_opgrp && *p != TEX_clgrp;
                   p++)
-               continue; */
-             pfnote (/*savenstr (lasthit, p-lasthit)*/ (char *)NULL, TRUE,
+               continue;
+             pfnote (savenstr (lasthit, p-lasthit), TRUE,
                      lb.buffer, lb.len, lineno, linecharno);
              break;            /* We only tag a line once */
            }
@@ -4388,38 +4876,37 @@ TEX_Token (cp)
       return i;
   return -1;
 }
+
 \f
 /* Texinfo support.  Dave Love, Mar. 2000.  */
 static void
-Texinfo_functions (inf)
+Texinfo_nodes (inf)
      FILE * inf;
 {
   char *cp, *start;
   LOOP_ON_INPUT_LINES (inf, lb, cp)
-    {
-      if ((*cp++ == '@' && *cp++ == 'n' && *cp++ == 'o' && *cp++ == 'd'
-             && *cp++ == 'e' && iswhite (*cp++)))
-       {
-           while (iswhite (*cp))
-                 cp++;
-             start = cp;
-               while (*cp != '\0' && *cp != ',')
-                     cp++;
-                 pfnote (savenstr (start, cp - start), TRUE,
-                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
-                 }
-    }
+    if (LOOKING_AT (cp, "@node"))
+      {
+       start = cp;
+       while (*cp != '\0' && *cp != ',')
+         cp++;
+       pfnote (savenstr (start, cp - start), TRUE,
+               lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+      }
 }
+
 \f
 /*
- * Prolog support (rewritten) by Anders Lindgren, Mar. 96
+ * Prolog support
  *
- * Assumes that the predicate starts at column 0.
- * Only the first clause of a predicate is added.
+ * Assumes that the predicate or rule starts at column 0.
+ * Only the first clause of a predicate or rule is added.
+ * Original code by Sunichirou Sugou (1989)
+ * Rewritten by Anders Lindgren (1996)
  */
-static int prolog_pred P_((char *, char *));
-static void prolog_skip_comment P_((linebuffer *, FILE *));
-static int prolog_atom P_((char *, int));
+static int prolog_pr __P((char *, char *));
+static void prolog_skip_comment __P((linebuffer *, FILE *));
+static int prolog_atom __P((char *, int));
 
 static void
 Prolog_functions (inf)
@@ -4441,14 +4928,14 @@ Prolog_functions (inf)
        continue;
       else if (cp[0] == '/' && cp[1] == '*')   /* comment. */
        prolog_skip_comment (&lb, inf);
-      else if ((len = prolog_pred (cp, last)) > 0)
+      else if ((len = prolog_pr (cp, last)) > 0)
        {
-         /* Predicate.  Store the function name so that we only
-            generate a tag for the first clause.  */
+         /* Predicate or rule.  Store the function name so that we
+            only generate a tag for the first clause.  */
          if (last == NULL)
            last = xnew(len + 1, char);
          else if (len + 1 > allocated)
-           last = xrnew (last, len + 1, char);
+           xrnew (last, len + 1, char);
          allocated = len + 1;
          strncpy (last, cp, len);
          last[len] = '\0';
@@ -4476,17 +4963,18 @@ prolog_skip_comment (plb, inf)
 }
 
 /*
- * A predicate definition is added if it matches:
+ * A predicate or rule definition is added if it matches:
  *     <beginning of line><Prolog Atom><whitespace>(
+ * or  <beginning of line><Prolog Atom><whitespace>:-
  *
  * It is added to the tags database if it doesn't match the
  * name of the previous clause header.
  *
- * Return the size of the name of the predicate, or 0 if no header
- * was found.
+ * Return the size of the name of the predicate or rule, or 0 if no
+ * header was found.
  */
 static int
-prolog_pred (s, last)
+prolog_pr (s, last)
      char *s;
      char *last;               /* Name of last clause. */
 {
@@ -4500,21 +4988,18 @@ prolog_pred (s, last)
   len = pos;
   pos = skip_spaces (s + pos) - s;
 
-  if ((s[pos] == '(') || (s[pos] == '.'))
-    {
-      if (s[pos] == '(')
-       pos++;
-
-      /* Save only the first clause. */
-      if (last == NULL
-         || len != (int)strlen (last)
-         || !strneq (s, last, len))
+  if ((s[pos] == '.'
+       || (s[pos] == '(' && (pos += 1))
+       || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
+      && (last == NULL         /* save only the first clause */
+         || len != strlen (last)
+         || !strneq (s, last, len)))
        {
          pfnote (savenstr (s, len), TRUE, s, pos, lineno, linecharno);
          return len;
        }
-    }
-  return 0;
+  else
+    return 0;
 }
 
 /*
@@ -4575,17 +5060,18 @@ prolog_atom (s, pos)
   else
     return -1;
 }
+
 \f
 /*
- * Support for Erlang  --  Anders Lindgren, Feb 1996.
+ * Support for Erlang
  *
  * Generates tags for functions, defines, and records.
- *
  * Assumes that Erlang functions start at column 0.
+ * Original code by Anders Lindgren (1996)
  */
-static int erlang_func P_((char *, char *));
-static void erlang_attribute P_((char *));
-static int erlang_atom P_((char *, int));
+static int erlang_func __P((char *, char *));
+static void erlang_attribute __P((char *));
+static int erlang_atom __P((char *, int));
 
 static void
 Erlang_functions (inf)
@@ -4623,7 +5109,7 @@ Erlang_functions (inf)
          if (last == NULL)
            last = xnew (len + 1, char);
          else if (len + 1 > allocated)
-           last = xrnew (last, len + 1, char);
+           xrnew (last, len + 1, char);
          allocated = len + 1;
          strncpy (last, cp, len);
          last[len] = '\0';
@@ -4687,9 +5173,8 @@ erlang_attribute (s)
   int pos;
   int len;
 
-  if (strneq (s, "-define", 7) || strneq (s, "-record", 7))
+  if (LOOKING_AT (s, "-define") || LOOKING_AT (s, "-record"))
     {
-      pos = skip_spaces (s + 7) - s;
       if (s[pos++] == '(')
        {
          pos = skip_spaces (s + pos) - s;
@@ -4752,13 +5237,14 @@ erlang_atom (s, pos)
   else
     return -1;
 }
+
 \f
 #ifdef ETAGS_REGEXPS
 
-static char *scan_separators P_((char *));
-static void analyse_regex P_((char *, bool));
-static void add_regex P_((char *, bool, language *));
-static char *substitute P_((char *, char *, struct re_registers *));
+static char *scan_separators __P((char *));
+static void analyse_regex __P((char *, bool));
+static void add_regex __P((char *, bool, language *));
+static char *substitute __P((char *, char *, struct re_registers *));
 
 /* Take a string like "/blah/" and turn it into "blah", making sure
    that the first and last characters are the same, and handling
@@ -4811,7 +5297,10 @@ analyse_regex (regex_arg, ignore_case)
      bool ignore_case;
 {
   if (regex_arg == NULL)
-    free_patterns ();          /* --no-regex: remove existing regexps */
+    {
+      free_patterns ();                /* --no-regex: remove existing regexps */
+      return;
+    }
 
   /* A real --regexp option or a line in a regexp file. */
   switch (regex_arg[0])
@@ -4859,7 +5348,7 @@ analyse_regex (regex_arg, ignore_case)
              return;
            }
        *cp = '\0';
-       lang = get_language_from_name (lang_name);
+       lang = get_language_from_langname (lang_name);
        if (lang == NULL)
          return;
        add_regex (cp + 1, ignore_case, lang);
@@ -4881,6 +5370,7 @@ add_regex (regexp_pattern, ignore_case, lang)
      bool ignore_case;
      language *lang;
 {
+  static struct re_pattern_buffer zeropattern;
   char *name;
   const char *err;
   struct re_pattern_buffer *patbuf;
@@ -4901,11 +5391,9 @@ add_regex (regexp_pattern, ignore_case, lang)
   (void) scan_separators (name);
 
   patbuf = xnew (1, struct re_pattern_buffer);
-  /* Translation table to fold case if appropriate. */
-  patbuf->translate = (ignore_case) ? lc_trans : NULL;
-  patbuf->fastmap = NULL;
-  patbuf->buffer = NULL;
-  patbuf->allocated = 0;
+  *patbuf = zeropattern;
+  if (ignore_case)
+    patbuf->translate = lc_trans;      /* translation table to fold case  */
 
   err = re_compile_pattern (regexp_pattern, strlen (regexp_pattern), patbuf);
   if (err != NULL)
@@ -4918,10 +5406,11 @@ add_regex (regexp_pattern, ignore_case, lang)
   p_head = xnew (1, pattern);
   p_head->regex = savestr (regexp_pattern);
   p_head->p_next = pp;
-  p_head->language = lang;
-  p_head->pattern = patbuf;
+  p_head->lang = lang;
+  p_head->pat = patbuf;
   p_head->name_pattern = savestr (name);
   p_head->error_signaled = FALSE;
+  p_head->ignore_case = ignore_case;
 }
 
 /*
@@ -4960,7 +5449,6 @@ substitute (in, out, regs)
   for (t = result; *out != '\0'; out++)
     if (*out == '\\' && ISDIGIT (*++out))
       {
-       /* Using "dig2" satisfies my debugger.  Bleah. */
        dig = *out - '0';
        diglen = regs->end[dig] - regs->start[dig];
        strncpy (t, in + regs->start[dig], diglen);
@@ -4970,8 +5458,7 @@ substitute (in, out, regs)
       *t++ = *out;
   *t = '\0';
 
-  if (DEBUG && (t > result + size || t - result != (int)strlen (result)))
-    abort ();
+  assert (t <= result + size && t - result == (int)strlen (result));
 
   return result;
 }
@@ -4991,32 +5478,51 @@ free_patterns ()
     }
   return;
 }
+#endif /* ETAGS_REGEXPS */
+
 \f
-static void
+static bool
+nocase_tail (cp)
+     char *cp;
+{
+  register int len = 0;
+
+  while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
+    cp++, len++;
+  if (*cp == '\0' && !intoken (dbp[len]))
+    {
+      dbp += len;
+      return TRUE;
+    }
+  return FALSE;
+}
+
+static char *
 get_tag (bp)
      register char *bp;
 {
-  register char *cp;
+  register char *cp, *name;
 
   if (*bp == '\0')
-    return;
+    return NULL;
   /* Go till you get to white space or a syntactic break */
-  for (cp = bp + 1;
-       *cp != '\0' && *cp != '(' && *cp != ')' && !iswhite (*cp);
-       cp++)
+  for (cp = bp + 1; !notinname (*cp); cp++)
     continue;
-  pfnote (savenstr (bp, cp-bp), TRUE,
+  name = savenstr (bp, cp-bp);
+  pfnote (name, TRUE,
          lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+  return name;
 }
 
-#endif /* ETAGS_REGEXPS */
 /* Initialize a linebuffer for use */
 static void
 initbuffer (lbp)
      linebuffer *lbp;
 {
-  lbp->size = 200;
-  lbp->buffer = xnew (200, char);
+  lbp->size = (DEBUG) ? 3 : 200;
+  lbp->buffer = xnew (lbp->size, char);
+  lbp->buffer[0] = '\0';
+  lbp->len = 0;
 }
 
 /*
@@ -5048,7 +5554,7 @@ readline_internal (lbp, stream)
        {
          /* We're at the end of linebuffer: expand it. */
          lbp->size *= 2;
-         buffer = xrnew (buffer, lbp->size, char);
+         xrnew (buffer, lbp->size, char);
          p += buffer - lbp->buffer;
          pend = buffer + lbp->size;
          lbp->buffer = buffer;
@@ -5100,55 +5606,173 @@ readline (lbp, stream)
 {
   /* Read new line. */
   long result = readline_internal (lbp, stream);
+
+  /* Honour #line directives. */
+  if (!no_line_directive)
+    {
+      static bool discard_until_line_directive;
+
+      /* Check whether this is a #line directive. */
+      if (result > 12 && strneq (lbp->buffer, "#line ", 6))
+       {
+         int start, lno;
+
+         if (DEBUG) start = 0; /* shut up the compiler */
+         if (sscanf (lbp->buffer, "#line %d \"%n", &lno, &start) == 1)
+           {
+             char *endp = lbp->buffer + start;
+
+             assert (start > 0);
+             while ((endp = etags_strchr (endp, '"')) != NULL
+                    && endp[-1] == '\\')
+               endp++;
+             if (endp != NULL)
+               /* Ok, this is a real #line directive.  Let's deal with it. */
+               {
+                 char *taggedabsname;  /* absolute name of original file */
+                 char *taggedfname;    /* name of original file as given */
+                 char *name;           /* temp var */
+
+                 discard_until_line_directive = FALSE; /* found it */
+                 name = lbp->buffer + start;
+                 *endp = '\0';
+                 canonicalize_filename (name); /* for DOS */
+                 taggedabsname = absolute_filename (name, curfdp->infabsdir);
+                 if (filename_is_absolute (name)
+                     || filename_is_absolute (curfdp->infname))
+                   taggedfname = savestr (taggedabsname);
+                 else
+                   taggedfname = relative_filename (taggedabsname,tagfiledir);
+
+                 if (streq (curfdp->taggedfname, taggedfname))
+                   /* The #line directive is only a line number change.  We
+                      deal with this afterwards. */
+                   free (taggedfname);
+                 else
+                   /* The tags following this #line directive should be
+                      attributed to taggedfname.  In order to do this, set
+                      curfdp accordingly. */
+                   {
+                     fdesc *fdp; /* file description pointer */
+
+                     /* Go look for a file description already set up for the
+                        file indicated in the #line directive.  If there is
+                        one, use it from now until the next #line
+                        directive. */
+                     for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
+                       if (streq (fdp->infname, curfdp->infname)
+                           && streq (fdp->taggedfname, taggedfname))
+                         /* If we remove the second test above (after the &&)
+                            then all entries pertaining to the same file are
+                            coalesced in the tags file.  If we use it, then
+                            entries pertaining to the same file but generated
+                            from different files (via #line directives) will
+                            go into separate sections in the tags file.  These
+                            alternatives look equivalent.  The first one
+                            destroys some apparently useless information. */
+                         {
+                           curfdp = fdp;
+                           free (taggedfname);
+                           break;
+                         }
+                     /* Else, if we already tagged the real file, skip all
+                        input lines until the next #line directive. */
+                     if (fdp == NULL) /* not found */
+                       for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
+                         if (streq (fdp->infabsname, taggedabsname))
+                           {
+                             discard_until_line_directive = TRUE;
+                             free (taggedfname);
+                             break;
+                           }
+                     /* Else create a new file description and use that from
+                        now on, until the next #line directive. */
+                     if (fdp == NULL) /* not found */
+                       {
+                         fdp = fdhead;
+                         fdhead = xnew (1, fdesc);
+                         *fdhead = *curfdp; /* copy curr. file description */
+                         fdhead->next = fdp;
+                         fdhead->infname = savestr (curfdp->infname);
+                         fdhead->infabsname = savestr (curfdp->infabsname);
+                         fdhead->infabsdir = savestr (curfdp->infabsdir);
+                         fdhead->taggedfname = taggedfname;
+                         fdhead->usecharno = FALSE;
+                         curfdp = fdhead;
+                       }
+                   }
+                 free (taggedabsname);
+                 lineno = lno;
+                 return readline (lbp, stream);
+               } /* if a real #line directive */
+           } /* if #line is followed by a a number */
+       } /* if line begins with "#line " */
+
+      /* If we are here, no #line directive was found. */
+      if (discard_until_line_directive)
+       {
+         if (result > 0)
+           /* Do a tail recursion on ourselves, thus discarding the contents
+              of the line buffer. */
+           return readline (lbp, stream);
+         /* End of file. */
+         discard_until_line_directive = FALSE;
+         return 0;
+       }
+    } /* if #line directives should be considered */
+
 #ifdef ETAGS_REGEXPS
-  int match;
-  pattern *pp;
+  {
+    int match;
+    pattern *pp;
 
-  /* Match against relevant patterns. */
-  if (lbp->len > 0)
-    for (pp = p_head; pp != NULL; pp = pp->p_next)
-      {
-       /* Only use generic regexps or those for the current language. */
-       if (pp->language != NULL && pp->language != curlang)
-         continue;
+    /* Match against relevant patterns. */
+    if (lbp->len > 0)
+      for (pp = p_head; pp != NULL; pp = pp->p_next)
+       {
+         /* Only use generic regexps or those for the current language. */
+         if (pp->lang != NULL && pp->lang != fdhead->lang)
+           continue;
 
-       match = re_match (pp->pattern, lbp->buffer, lbp->len, 0, &pp->regs);
-       switch (match)
-         {
-         case -2:
-           /* Some error. */
-           if (!pp->error_signaled)
-             {
-               error ("error while matching \"%s\"", pp->regex);
-               pp->error_signaled = TRUE;
-             }
-           break;
-         case -1:
-           /* No match. */
-           break;
-         default:
-           /* Match occurred.  Construct a tag. */
-           if (pp->name_pattern[0] != '\0')
-             {
-               /* Make a named tag. */
-               char *name = substitute (lbp->buffer,
-                                        pp->name_pattern, &pp->regs);
-               if (name != NULL)
-                 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
-             }
-           else
-             {
-               /* Make an unnamed tag. */
-               pfnote ((char *)NULL, TRUE,
-                       lbp->buffer, match, lineno, linecharno);
-             }
-           break;
-         }
-      }
+         match = re_match (pp->pat, lbp->buffer, lbp->len, 0, &pp->regs);
+         switch (match)
+           {
+           case -2:
+             /* Some error. */
+             if (!pp->error_signaled)
+               {
+                 error ("error while matching \"%s\"", pp->regex);
+                 pp->error_signaled = TRUE;
+               }
+             break;
+           case -1:
+             /* No match. */
+             break;
+           default:
+             /* Match occurred.  Construct a tag. */
+             if (pp->name_pattern[0] != '\0')
+               {
+                 /* Make a named tag. */
+                 char *name = substitute (lbp->buffer,
+                                          pp->name_pattern, &pp->regs);
+                 if (name != NULL)
+                   pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
+               }
+             else
+               {
+                 /* Make an unnamed tag. */
+                 pfnote ((char *)NULL, TRUE,
+                         lbp->buffer, match, lineno, linecharno);
+               }
+             break;
+           }
+       }
+  }
 #endif /* ETAGS_REGEXPS */
 
   return result;
 }
+
 \f
 /*
  * Return a pointer to a space of size strlen(cp)+1 allocated
@@ -5200,7 +5824,6 @@ etags_strrchr (sp, c)
   return (char *)r;
 }
 
-
 /*
  * Return the ptr in sp at which the character c first
  * appears; NULL if not found
@@ -5220,6 +5843,26 @@ etags_strchr (sp, c)
   return NULL;
 }
 
+/*
+ * Return TRUE if the two strings are equal, ignoring case for alphabetic
+ * characters.
+ *
+ * Analogous to BSD's strcasecmp, included for portability.
+ */
+static bool
+strcaseeq (s1, s2)
+     register const char *s1;
+     register const char *s2;
+{
+  while (*s1 != '\0'
+        && (ISALPHA (*s1) && ISALPHA (*s2)
+            ? lowcase (*s1) == lowcase (*s2)
+            : *s1 == *s2))
+    s1++, s2++;
+
+  return (*s1 == *s2);
+}
+
 /* Skip spaces, return new pointer. */
 static char *
 skip_spaces (cp)
@@ -5241,7 +5884,7 @@ skip_non_spaces (cp)
 }
 
 /* Print error message and exit.  */
-static void
+void
 fatal (s1, s2)
      char *s1, *s2;
 {
@@ -5297,6 +5940,7 @@ concat (s1, s2, s3)
 
   return result;
 }
+
 \f
 /* Does the same work as the system V getcwd, but does not need to
    guess the buffer size in advance. */
@@ -5320,7 +5964,8 @@ etags_getcwd ()
   return path;
 
 #else /* not HAVE_GETCWD */
-#ifdef MSDOS
+#if MSDOS
+
   char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS.  */
 
   getwd (path);
@@ -5490,8 +6135,8 @@ canonicalize_filename (fn)
 {
 #ifdef DOS_NT
   /* Canonicalize drive letter case.  */
-  if (fn[0] && fn[1] == ':' && ISLOWER (fn[0]))
-    fn[0] = UPCASE (fn[0]);
+  if (fn[0] != '\0' && fn[1] == ':' && ISLOWER (fn[0]))
+    fn[0] = upcase (fn[0]);
   /* Convert backslashes to slashes.  */
   for (; *fn != '\0'; fn++)
     if (*fn == '\\')
@@ -5502,35 +6147,48 @@ canonicalize_filename (fn)
 #endif
 }
 
-/* Increase the size of a linebuffer. */
+/* Set the minimum size of a string contained in a linebuffer. */
 static void
-grow_linebuffer (lbp, toksize)
+linebuffer_setlen (lbp, toksize)
      linebuffer *lbp;
      int toksize;
 {
-  while (lbp->size < toksize)
-    lbp->size *= 2;
-  lbp->buffer = xrnew (lbp->buffer, lbp->size, char);
+  while (lbp->size <= toksize)
+    {
+      lbp->size *= 2;
+      xrnew (lbp->buffer, lbp->size, char);
+    }
+  lbp->len = toksize;
 }
 
 /* Like malloc but get fatal error if memory is exhausted.  */
-long *
+static PTR
 xmalloc (size)
      unsigned int size;
 {
-  long *result = (long *) malloc (size);
+  PTR result = (PTR) malloc (size);
   if (result == NULL)
     fatal ("virtual memory exhausted", (char *)NULL);
   return result;
 }
 
-long *
+static PTR
 xrealloc (ptr, size)
      char *ptr;
      unsigned int size;
 {
-  long *result =  (long *) realloc (ptr, size);
+  PTR result = (PTR) realloc (ptr, size);
   if (result == NULL)
     fatal ("virtual memory exhausted", (char *)NULL);
   return result;
 }
+
+/*
+ * Local Variables:
+ * c-indentation-style: gnu
+ * indent-tabs-mode: t
+ * tab-width: 8
+ * fill-column: 79
+ * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node")
+ * End:
+ */