Tue Apr 15 16:09:15 1997 Francesco Potorti` <F.Potorti@cnuce.cnr.it>
[bpt/emacs.git] / lib-src / etags.c
index 80f7893..8b21906 100644 (file)
@@ -1,5 +1,7 @@
 /* Tags file maker to go with GNU Emacs
-   Copyright (C) 1984,87,88,89,93,94 Free Software Foundation, Inc. and Ken Arnold
+   Copyright (C) 1984, 87, 88, 89, 93, 94, 95
+   Free Software Foundation, Inc. and Ken Arnold
+
 This file is not considered part of GNU Emacs.
 
 This program is free software; you can redistribute it and/or modify
@@ -13,8 +15,8 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
+along with this program; if not, write to the Free Software Foundation,
+Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
 
 /*
  * Authors:
@@ -24,32 +26,44 @@ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  *     Gnu Emacs TAGS format and modifications by RMS?
  *     Sam Kendall added C++.
  *     Francesco Potorti` reorganised C and C++ based on work by Joe Wells.
-#ifdef ETAGS_REGEXPS
  *     Regexp tags by Tom Tromey.
-#endif
  *
- *     Francesco Potorti` (pot@cnuce.cnr.it) is the current maintainer.
+ *     Francesco Potorti` (F.Potorti@cnuce.cnr.it) is the current maintainer.
  */
 
-char pot_etags_version[] = "@(#) pot revision number is 11.24";
+char pot_etags_version[] = "@(#) pot revision number is $Revision: 11.84 $";
+
+#define        TRUE    1
+#define        FALSE   0
+
+#ifndef DEBUG
+# define DEBUG FALSE
+#endif
 
 #ifdef MSDOS
-#include <fcntl.h>
-#include <sys/param.h>
+# include <string.h>
+# include <fcntl.h>
+# include <sys/param.h>
 #endif /* MSDOS */
 
 #ifdef WINDOWSNT
+# include <stdlib.h>
+# include <fcntl.h>
+# include <string.h>
+# include <io.h>
+# define MAXPATHLEN _MAX_PATH
+#endif
+
+#if !defined (MSDOS) && !defined (WINDOWSNT) && defined (STDC_HEADERS)
 #include <stdlib.h>
-#include <fcntl.h>
 #include <string.h>
-#define MAXPATHLEN _MAX_PATH
 #endif
 
 #ifdef HAVE_CONFIG_H
-#include <config.h>
-/* On some systems, Emacs defines static as nothing for the sake
-   of unexec.  We don't want that here since we don't use unexec. */
-#undef static
+# include <config.h>
+  /* On some systems, Emacs defines static as nothing for the sake
+     of unexec.  We don't want that here since we don't use unexec. */
+# undef static
 #endif
 
 #include <stdio.h>
@@ -68,14 +82,11 @@ extern int errno;
 #include <getopt.h>
 
 #ifdef ETAGS_REGEXPS
-#include <regex.h>
+# include <regex.h>
 #endif /* ETAGS_REGEXPS */
 
-#define        TRUE    1
-#define        FALSE   0
-
 /* Define CTAGS to make the program "ctags" compatible with the usual one.
- Let it undefined to make the program "etags", which makes emacs-style
+ Leave it undefined to make the program "etags", which makes emacs-style
  tag tables and tags typedefs, #defines and struct/union/enum by default. */
 #ifdef CTAGS
 # undef  CTAGS
@@ -86,11 +97,11 @@ extern int errno;
 
 /* Exit codes for success and failure.  */
 #ifdef VMS
-#define        GOOD    1
-#define BAD    0
+# define       GOOD    1
+# define       BAD     0
 #else
-#define        GOOD    0
-#define        BAD     1
+# define       GOOD    0
+# define       BAD     1
 #endif
 
 /* C extensions. */
@@ -98,29 +109,46 @@ extern int errno;
 #define C_STAR 0x00003         /* C* */
 #define YACC   0x10000         /* yacc file */
 
-#define streq(s,t)     (strcmp (s, t) == 0)
-#define strneq(s,t,n)  (strncmp (s, t, n) == 0)
+#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 ((char)c)
 
 #define        iswhite(arg)    (_wht[arg])     /* T if char is white           */
 #define        begtoken(arg)   (_btk[arg])     /* T if char can start token    */
 #define        intoken(arg)    (_itk[arg])     /* T if char can be in token    */
 #define        endtoken(arg)   (_etk[arg])     /* T if char ends tokens        */
 
+#ifdef DOS_NT
+# define absolutefn(fn) (fn[0] == '/' \
+                        || (fn[1] == ':' && fn[2] == '/'))
+#else
+# define absolutefn(fn) (fn[0] == '/')
+#endif
+
+
 /*
  *     xnew -- allocate storage
  *
  * SYNOPSIS:   Type *xnew (int n, Type);
  */
-#define xnew(n,Type)   ((Type *) xmalloc ((n) * sizeof (Type)))
+#ifdef chkmalloc
+# include "chkmalloc.h"
+# define xnew(n,Type)  ((Type *) trace_xmalloc (__FILE__, __LINE__, \
+                                                (n) * sizeof (Type)))
+#else
+# define xnew(n,Type)  ((Type *) xmalloc ((n) * sizeof (Type)))
+#endif
 
 typedef int logical;
 
 typedef struct nd_st
-{                              /* sorting structure                    */
+{                              /* sorting structure            */
   char *name;                  /* function or type name        */
   char *file;                  /* file name                    */
   logical is_func;             /* use pattern or line no       */
-  logical named;               /* list name separately         */
   logical been_warned;         /* set if noticed dup           */
   int lno;                     /* line number tag is on        */
   long cno;                    /* character number line starts on */
@@ -135,7 +163,8 @@ char *savenstr (), *savestr ();
 char *etags_strchr (), *etags_strrchr ();
 char *etags_getcwd ();
 char *relative_filename (), *absolute_filename (), *absolute_dirname ();
-char *xmalloc (), *xrealloc ();
+void grow_linebuffer ();
+long *xmalloc (), *xrealloc ();
 
 typedef void Lang_function ();
 #if FALSE                              /* many compilers barf on this */
@@ -144,31 +173,38 @@ Lang_function default_C_entries;
 Lang_function C_entries;
 Lang_function Cplusplus_entries;
 Lang_function Cstar_entries;
+Lang_function Erlang_functions;
 Lang_function Fortran_functions;
 Lang_function Yacc_entries;
 Lang_function Lisp_functions;
 Lang_function Pascal_functions;
+Lang_function Perl_functions;
 Lang_function Prolog_functions;
 Lang_function Scheme_functions;
 Lang_function TeX_functions;
 Lang_function just_read_file;
 #else                          /* so let's write it this way */
 void Asm_labels ();
-void default_C_entries ();
 void C_entries ();
+void default_C_entries ();
+void plain_C_entries ();
 void Cplusplus_entries ();
 void Cstar_entries ();
+void Erlang_functions ();
 void Fortran_functions ();
 void Yacc_entries ();
 void Lisp_functions ();
 void Pascal_functions ();
+void Perl_functions ();
 void Prolog_functions ();
 void Scheme_functions ();
 void TeX_functions ();
 void just_read_file ();
 #endif
 
-logical get_language ();
+Lang_function *get_language_from_name ();
+Lang_function *get_language_from_interpreter ();
+Lang_function *get_language_from_suffix ();
 int total_size_of_entries ();
 long readline ();
 long readline_internal ();
@@ -177,6 +213,7 @@ void add_regex ();
 #endif
 void add_node ();
 void error ();
+void suggest_asking_for_help ();
 void fatal (), pfatal ();
 void find_entries ();
 void free_tree ();
@@ -193,9 +230,7 @@ char searchar = '/';                /* use /.../ searches */
 
 int lineno;                    /* line number of current line */
 long charno;                   /* current character number */
-
-long linecharno;               /* charno of start of line; not used by C,
-                                  but by every other language. */
+long linecharno;               /* charno of start of line */
 
 char *curfile;                 /* current input file name */
 char *tagfile;                 /* output file */
@@ -218,7 +253,7 @@ struct linebuffer
 };
 
 struct linebuffer lb;          /* the current line */
-struct linebuffer token_str;   /* used by C_entries as temporary area */
+struct linebuffer token_name;  /* used by C_entries as a temporary area */
 struct
 {
   long linepos;
@@ -228,12 +263,14 @@ struct
 /* boolean "functions" (see init)      */
 logical _wht[0177], _etk[0177], _itk[0177], _btk[0177];
 char
- *white = " \f\t\n\013",       /* white chars                          */
- *endtk = " \t\n\013\"'#()[]{}=-+%*/&|^~!<>;,.:?", /* token ending chars */
-                               /* token starting chars                 */
- *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~",
-                               /* valid in-token chars                 */
- *intk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
+  /* white chars */
+  *white = " \f\t\n\013",
+  /* token ending chars */
+  *endtk = " \t\n\013\"'#()[]{}=-+%*/&|^~!<>;,.:?",
+  /* token starting chars */
+  *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
+  /* valid in-token chars */
+  *intk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
 
 logical append_to_tagfile;     /* -a: append to tags */
 /* The following three default to TRUE for etags, but to FALSE for ctags.  */
@@ -242,7 +279,7 @@ logical typedefs_and_cplusplus;     /* -T: create tags for typedefs, level */
                                /* 0 struct/enum/union decls, and C++ */
                                /* member functions. */
 logical constantypedefs;       /* -d: create tags for C #define and enum */
-                               /* constants.  Enum consts not implemented. */
+                               /* constants. */
                                /* -D: opposite of -d.  Default under ctags. */
 logical update;                        /* -u: update tags */
 logical vgrind_style;          /* -v: create vgrind style index output */
@@ -250,12 +287,11 @@ logical no_warnings;              /* -w: suppress warnings */
 logical cxref_style;           /* -x: create cxref style output */
 logical cplusplus;             /* .[hc] means C++, not C */
 logical noindentypedefs;       /* -I: ignore indentation in C */
-#define permit_duplicates TRUE /* allow duplicate tags */
 
 struct option longopts[] =
 {
   { "append",                  no_argument,       NULL, 'a' },
-  { "backward-search",         no_argument,       NULL, 'B' }, 
+  { "backward-search",         no_argument,       NULL, 'B' },
   { "c++",                     no_argument,       NULL, 'C' },
   { "cxref",                   no_argument,       NULL, 'x' },
   { "defines",                 no_argument,       NULL, 'd' },
@@ -271,14 +307,14 @@ struct option longopts[] =
   { "regex",                   required_argument, NULL, 'r' },
   { "typedefs",                        no_argument,       NULL, 't' },
   { "typedefs-and-c++",                no_argument,       NULL, 'T' },
-  { "update",                  no_argument,       NULL, 'u' }, 
+  { "update",                  no_argument,       NULL, 'u' },
   { "version",                 no_argument,       NULL, 'V' },
-  { "vgrind",                  no_argument,       NULL, 'v' }, 
+  { "vgrind",                  no_argument,       NULL, 'v' },
   { 0 }
 };
 
 #ifdef ETAGS_REGEXPS
-/* Structure defining a regular expression.  Elements are 
+/* Structure defining a regular expression.  Elements are
    the compiled pattern, and the name string. */
 struct pattern
 {
@@ -295,147 +331,139 @@ int num_patterns = 0;
 struct pattern *patterns = NULL;
 #endif /* ETAGS_REGEXPS */
 
-/* Language stuff. */
+/*
+ * Language stuff.
+ */
+
+/* Non-NULL if language fixed. */
+Lang_function *lang_func = 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 */
+                         "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 [] =
+  { "c", "h", NULL };
+
+/* .M is for Objective C++ files. */
+char *Cplusplus_suffixes [] =
+  { "C", "H", "c++", "cc", "cpp", "cxx", "h++", "hh", "hpp", "hxx", "M", NULL};
+
+char *Cstar_suffixes [] =
+  { "cs", "hs", NULL };
+
+char *Erlang_suffixes [] =
+  { "erl", "hrl", NULL };
+
+char *Fortran_suffixes [] =
+  { "F", "f", "f90", "for", NULL };
+
+char *Lisp_suffixes [] =
+  { "cl", "clisp", "el", "l", "lisp", "lsp", "ml", NULL };
+
+char *Pascal_suffixes [] =
+  { "p", "pas", NULL };
+
+char *Perl_suffixes [] =
+  { "pl", "pm", NULL };
+char *Perl_interpreters [] =
+  { "perl", "@PERL@", NULL };
+
+char *plain_C_suffixes [] =
+  { "pc",                      /* Pro*C file */
+    "m",                       /* Objective C file */
+    "lm",                      /* Objective lex file */
+     NULL };
+
+char *Prolog_suffixes [] =
+  { "prolog", NULL };
+
+/* Can't do the `SCM' or `scm' prefix with a version number. */
+char *Scheme_suffixes [] =
+  { "SCM", "SM", "oak", "sch", "scheme", "scm", "sm", "t", NULL };
+
+char *TeX_suffixes [] =
+  { "TeX", "bib", "clo", "cls", "ltx", "sty", "tex", NULL };
+
+char *Yacc_suffixes [] =
+  { "y", "ym", NULL };         /* .ym is Objective yacc file */
+
+/* Table of language names and corresponding functions, file suffixes
+   and interpreter names.
+   It is ok for a given function to be listed under more than one
+   name.  I just didn't. */
 struct lang_entry
 {
-  char *extension;
+  char *name;
   Lang_function *function;
+  char **suffixes;
+  char **interpreters;
 };
 
-/* Table of language names and corresponding functions. */
-/* It is ok for a given function to be listed under more than one
-   name.  I just didn't. */
-/* "auto" language reverts to default behavior. */
-struct lang_entry lang_names[] =
-{
-  { "asm", Asm_labels },
-  { "c", default_C_entries },
-  { "c++", Cplusplus_entries },
-  { "c*", Cstar_entries },
-  { "fortran", Fortran_functions },
-  { "lisp", Lisp_functions },
-  { "none", just_read_file },
-  { "pascal", Pascal_functions },
-  { "scheme" , Scheme_functions },
-  { "tex", TeX_functions },
-  { "auto", NULL },
-  { NULL, NULL }
-};
-
-/* Table of file extensions and corresponding language functions. */
-struct lang_entry lang_extensions[] =
-{
-  /* Assume that ".s" or ".a" is assembly code. -wolfgang.
-     Or even ".sa". */
-  { "a", Asm_labels },         /* Unix assembler */
-  { "asm", Asm_labels },       /* Microcontroller assembly */
-  { "def", Asm_labels },       /* BSO/Tasking definition includes  */
-  { "inc", Asm_labels },       /* Microcontroller include files */
-  { "ins", Asm_labels },       /* Microcontroller include files */
-  { "s", Asm_labels },
-  { "sa", Asm_labels },                /* Unix assembler */
-  { "src", Asm_labels },       /* BSO/Tasking C compiler output */
-
-  /* .aux, .bbl, .clo, .cls, .dtx or .tex implies LaTeX source code. */
-  { "aux", TeX_functions },
-  { "bbl", TeX_functions },
-  { "clo", TeX_functions },
-  { "cls", TeX_functions },
-  { "dtx", TeX_functions },
-  { "sty", TeX_functions },
-  { "tex", TeX_functions },
-
-  /* .l or .el or .lisp (or .cl or .clisp or ...) implies lisp source code */
-  { "cl", Lisp_functions },
-  { "clisp", Lisp_functions },
-  { "el", Lisp_functions },
-  { "l", Lisp_functions },
-  { "lisp", Lisp_functions },
-  { "lsp", Lisp_functions },
-
-  /* .scm or .sm or .scheme implies scheme source code */
-  { "SCM", Scheme_functions },
-  { "SM", Scheme_functions },
-  { "oak", Scheme_functions },
-  { "sch", Scheme_functions },
-  { "scheme", Scheme_functions },
-  { "scm", Scheme_functions },
-  { "sm", Scheme_functions },
-  { "t", Scheme_functions },
-  /* FIXME Can't do the `SCM' or `scm' prefix with a version number */
-
-  /* Note that ".c" and ".h" can be considered C++, if the --c++
-     flag was given.  That is why default_C_entries is called here. */
-  { "c", default_C_entries },
-  { "h", default_C_entries },
-
-  /* .C or .H or .c++ or .cc or .cpp or .cxx or .h++ or .hh or .hxx:
-     a C++ file */
-  { "C", Cplusplus_entries },
-  { "H", Cplusplus_entries },
-  { "c++", Cplusplus_entries },
-  { "cc", Cplusplus_entries },
-  { "cpp", Cplusplus_entries },
-  { "cxx", Cplusplus_entries },
-  { "h++", Cplusplus_entries },
-  { "hh", Cplusplus_entries },
-  { "hxx", Cplusplus_entries },
-
-  /* .y: a yacc file */
-  { "y", Yacc_entries },
-
-  /* .cs or .hs: a C* file */
-  { "cs", Cstar_entries },
-  { "hs", Cstar_entries },
-
-  /* .f and .for are FORTRAN. */
-  { "F", Fortran_functions },
-  { "f", Fortran_functions },
-  { "for", Fortran_functions },
-
-  /* .pl implies prolog source code */
-  { "pl", Prolog_functions },
-
-  /* .p or .pas: a Pascal file */
-  { "p", Pascal_functions },
-  { "pas", Pascal_functions },
-
-  { NULL, NULL }
+struct lang_entry lang_names [] =
+{
+  { "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              },
+  { "erlang",  Erlang_functions,    Erlang_suffixes,     NULL              },
+  { "fortran", Fortran_functions,   Fortran_suffixes,    NULL              },
+  { "lisp",    Lisp_functions,     Lisp_suffixes,        NULL              },
+  { "pascal",  Pascal_functions,    Pascal_suffixes,     NULL              },
+  { "perl",    Perl_functions,     Perl_suffixes,        Perl_interpreters },
+  { "proc",    plain_C_entries,            plain_C_suffixes,     NULL              },
+  { "prolog",  Prolog_functions,    Prolog_suffixes,     NULL              },
+  { "scheme",  Scheme_functions,    Scheme_suffixes,     NULL              },
+  { "tex",     TeX_functions,      TeX_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 */
 };
 
-/* Non-NULL if language fixed. */
-Lang_function *lang_func = NULL;
-
 \f
 void
 print_language_names ()
 {
-  struct lang_entry *name, *ext;
+  struct lang_entry *lang;
+  char **ext;
 
   puts ("\nThese are the currently supported languages, along with the\n\
-default extensions for files:");
-  for (name = lang_names; name->extension; ++name)
+default file name suffixes:");
+  for (lang = lang_names; lang->name != NULL; lang++)
     {
-      printf ("\t%s\t", name->extension);
-      for (ext = lang_extensions; ext->extension; ++ext)
-       if (name->function == ext->function)
-         printf (" .%s", ext->extension);
+      printf ("\t%s\t", lang->name);
+      if (lang->suffixes != NULL)
+       for (ext = lang->suffixes; *ext != NULL; ext++)
+         printf (" .%s", *ext);
       puts ("");
     }
-  puts ("Where `auto' means use default language for files based on filename\n\
-extension, and `none' means only do regexp processing on files.\n\
-If no language is specified and no extension is found for some file,\n\
+  puts ("Where `auto' means use default language for files based on file\n\
+name suffix, and `none' means only do regexp processing on files.\n\
+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.");
 }
 
+#ifndef VERSION
+# define VERSION "19"
+#endif
 void
 print_version ()
 {
-#ifdef VERSION
-  printf ("%s for Emacs version %s.\n", (CTAGS) ? "CTAGS" : "ETAGS", VERSION);
-#else
-  printf ("%s for Emacs version 19.\n", (CTAGS) ? "CTAGS" : "ETAGS");
-#endif  
+  printf ("%s (GNU Emacs %s)\n", (CTAGS) ? "ctags" : "etags", VERSION);
+  puts ("Copyright (C) 1996 Free Software Foundation, Inc. and Ken Arnold");
+  puts ("This program is distributed under the same terms as Emacs");
 
   exit (GOOD);
 }
@@ -445,7 +473,11 @@ print_help ()
 {
   printf ("These are the options accepted by %s.  You may use unambiguous\n\
 abbreviations for the long option names.  A - as file name means read\n\
-names from stdin.\n\n", progname);
+names from stdin.", progname);
+  if (!CTAGS)
+    printf ("  Absolute names are stored in the output file as they\n\
+are.  Relative ones are stored relative to the output file's directory.");
+  puts ("\n");
 
   puts ("-a, --append\n\
         Append tag entries to existing tags file.");
@@ -456,15 +488,15 @@ names from stdin.\n\n", progname);
         backward-search command instead of '/', the forward-search command.");
 
   puts ("-C, --c++\n\
-        Treat files whose extension defaults to C language as C++ files.");
+        Treat files whose name suffix defaults to C language as C++ files.");
 
   if (CTAGS)
     puts ("-d, --defines\n\
-        Create tag entries for constant C #defines, too.");
+        Create tag entries for C #define constants and enum constants, too.");
   else
     puts ("-D, --no-defines\n\
-        Don't create tag entries for constant C #defines.  This makes\n\
-       the tags file smaller.");
+        Don't create tag entries for C #define constants and enum constants.\n\
+       This makes the tags file smaller.");
 
   if (!CTAGS)
     {
@@ -530,6 +562,9 @@ names from stdin.\n\n", progname);
 
   print_language_names ();
 
+  puts ("");
+  puts ("Report bugs to bug-gnu-emacs@prep.ai.mit.edu");
+
   exit (GOOD);
 }
 
@@ -541,13 +576,13 @@ enum argument_type
   at_filename
 };
 
-/* This structure helps us allow mixing of --lang and filenames. */
+/* This structure helps us allow mixing of --lang and file names. */
 typedef struct
 {
   enum argument_type arg_type;
   char *what;
   Lang_function *function;
-} ARGUMENT;
+} argument;
 
 #ifdef VMS                     /* VMS specific functions */
 
@@ -563,19 +598,19 @@ typedef struct    {
 
 /*
  v1.05 nmm 26-Jun-86 fn_exp - expand specification of list of file names
- returning in each successive call the next filename matching the input
+ returning in each successive call the next file name matching the input
  spec. The function expects that each in_spec passed
  to it will be processed to completion; in particular, up to and
  including the call following that in which the last matching name
  is returned, the function ignores the value of in_spec, and will
- only start processing a new spec with the following call. 
+ only start processing a new spec with the following call.
  If an error occurs, on return out_spec contains the value
  of in_spec when the error occurred.
 
- With each successive filename returned in out_spec, the
+ With each successive file name returned in out_spec, the
  function's return value is one. When there are no more matching
  names the function returns zero. If on the first call no file
- matches in_spec, or there is any other error, -1 is returned. 
+ matches in_spec, or there is any other error, -1 is returned.
 */
 
 #include       <rmsdef.h>
@@ -620,10 +655,10 @@ fn_exp (out, in)
   lib$find_file_end(&context);
   pass1 = TRUE;
   return retval;
-}      
+}
 
 /*
-  v1.01 nmm 19-Aug-85 gfnames - return in successive calls the 
+  v1.01 nmm 19-Aug-85 gfnames - return in successive calls the
   name of each file specified by the provided arg expanding wildcards.
 */
 char *
@@ -651,7 +686,7 @@ gfnames (arg, p_error)
 system (cmd)
      char *cmd;
 {
-  fprintf (stderr, "system() function not implemented under VMS\n");
+  error ("%s", "system() function not implemented under VMS");
 }
 #endif
 
@@ -659,7 +694,7 @@ system (cmd)
 char *massage_name (s)
      char *s;
 {
-  char *start = s;     
+  char *start = s;
 
   for ( ; *s; s++)
     if (*s == VERSION_DELIM)
@@ -668,37 +703,41 @@ char *massage_name (s)
        break;
       }
     else
-      *s = tolower(*s);
+      *s = lowcase (*s);
   return start;
 }
 #endif /* VMS */
 
 \f
-void
+int
 main (argc, argv)
      int argc;
      char *argv[];
 {
   int i;
-  unsigned int nincluded_files = 0;
-  char **included_files = xnew (argc, char *);
+  unsigned int nincluded_files;
+  char **included_files;
   char *this_file;
-  ARGUMENT *argbuffer;
-  int current_arg = 0, file_count = 0;
+  argument *argbuffer;
+  int current_arg, file_count;
   struct linebuffer filename_lb;
 #ifdef VMS
   logical got_err;
 #endif
+
 #ifdef DOS_NT
   _fmode = O_BINARY;   /* all of files are treated as binary files */
 #endif /* DOS_NT */
 
   progname = argv[0];
+  nincluded_files = 0;
+  included_files = xnew (argc, char *);
+  current_arg = 0;
+  file_count = 0;
 
   /* Allocate enough no matter what happens.  Overkill, but each one
      is small. */
-  argbuffer = xnew (argc, ARGUMENT);
+  argbuffer = xnew (argc, argument);
 
 #ifdef ETAGS_REGEXPS
   /* Set syntax for regular expression routines. */
@@ -707,7 +746,7 @@ main (argc, argv)
 
   /*
    * If etags, always find typedefs and structure tags.  Why not?
-   * Also default is to find macro constants.
+   * Also default is to find macro constants and enum constants.
    */
   if (!CTAGS)
     typedefs = typedefs_and_cplusplus = constantypedefs = TRUE;
@@ -728,7 +767,7 @@ main (argc, argv)
          break;
 
        case 1:
-         /* This means that a filename has been seen.  Record it. */
+         /* This means that a file name has been seen.  Record it. */
          argbuffer[current_arg].arg_type = at_filename;
          argbuffer[current_arg].what = optarg;
          ++current_arg;
@@ -752,9 +791,8 @@ main (argc, argv)
        case 'o':
          if (tagfile)
            {
-             fprintf (stderr, "%s: -%c option may only be given once.\n",
-                      progname, opt);
-             goto usage;
+             error ("-%c option may only be given once.", opt);
+             suggest_asking_for_help ();
            }
          tagfile = optarg;
          break;
@@ -763,12 +801,7 @@ main (argc, argv)
          noindentypedefs = TRUE;
          break;
        case 'l':
-         if (!get_language (optarg, &argbuffer[current_arg].function))
-           {
-             fprintf (stderr, "%s: language \"%s\" not recognized.\n",
-                      progname, optarg);
-             goto usage;
-           }
+         argbuffer[current_arg].function = get_language_from_name (optarg);
          argbuffer[current_arg].arg_type = at_language;
          ++current_arg;
          break;
@@ -821,7 +854,7 @@ main (argc, argv)
          break;
 #endif /* CTAGS */
        default:
-         goto usage;
+         suggest_asking_for_help ();
        }
     }
 
@@ -835,33 +868,24 @@ main (argc, argv)
 
   if (nincluded_files == 0 && file_count == 0)
     {
-      fprintf (stderr, "%s: No input files specified.\n", progname);
-
-    usage:
-      fprintf (stderr, "\tTry `%s --help' for a complete list of options.\n",
-              progname);
-      exit (BAD);
+      error ("%s", "No input files specified.");
+      suggest_asking_for_help ();
     }
 
   if (tagfile == NULL)
-    {
-      tagfile = CTAGS ? "tags" : "TAGS";
-    }
+    tagfile = CTAGS ? "tags" : "TAGS";
   cwd = etags_getcwd ();       /* the current working directory */
-  strcat (cwd, "/");
+  if (cwd[strlen (cwd) - 1] != '/')
+    cwd = concat (cwd, "/", "");
   if (streq (tagfile, "-"))
-    {
-      tagfiledir = cwd;
-    }
+    tagfiledir = cwd;
   else
-    {
-      tagfiledir = absolute_dirname (tagfile, cwd);
-    }
+    tagfiledir = absolute_dirname (tagfile, cwd);
 
   init ();                     /* set up boolean "functions" */
 
   initbuffer (&lb);
-  initbuffer (&token_str);
+  initbuffer (&token_name);
   initbuffer (&lbs[0].lb);
   initbuffer (&lbs[1].lb);
   initbuffer (&filename_lb);
@@ -869,7 +893,15 @@ main (argc, argv)
   if (!CTAGS)
     {
       if (streq (tagfile, "-"))
-       tagf = stdout;
+       {
+         tagf = stdout;
+#ifdef DOS_NT
+         /* Switch redirected `stdout' to binary mode (setting `_fmode'
+            doesn't take effect until after `stdout' is already open). */
+         if (!isatty (fileno (stdout)))
+           setmode (fileno (stdout), O_BINARY);
+#endif /* DOS_NT */
+       }
       else
        tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
       if (tagf == NULL)
@@ -934,9 +966,6 @@ main (argc, argv)
      because we want them ordered.  Let's do it now. */
   if (cxref_style)
     {
-      tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
-      if (tagf == NULL)
-       pfatal (tagfile);
       put_entries (head);
       exit (GOOD);
     }
@@ -952,7 +981,7 @@ main (argc, argv)
                   "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
                   tagfile, argbuffer[i].what, tagfile);
          if (system (cmd) != GOOD)
-           fatal ("failed to execute shell command");
+           fatal ("failed to execute shell command", (char *)NULL);
        }
       append_to_tagfile = TRUE;
     }
@@ -969,30 +998,79 @@ main (argc, argv)
       sprintf (cmd, "sort %s -o %s", tagfile, tagfile);
       exit (system (cmd));
     }
-  exit (GOOD);
+  return GOOD;
 }
 
 
 /*
- * Set the language, given the name.
+ * Return a Lang_function given the name.
  */
-logical
-get_language (language, func)
-     char *language;
-     Lang_function **func;
+Lang_function *
+get_language_from_name (name)
+     char *name;
 {
   struct lang_entry *lang;
 
-  for (lang = lang_names; lang->extension; ++lang)
-    {
-      if (streq (language, lang->extension))
-       {
-         *func = lang->function;
-         return TRUE;
-       }
-    }
+  if (name != NULL)
+    for (lang = lang_names; lang->name != NULL; lang++)
+      {
+       if (streq (name, lang->name))
+         return lang->function;
+      }
 
-  return FALSE;
+  error ("language \"%s\" not recognized.", optarg);
+  suggest_asking_for_help ();
+
+  /* This point should never be reached.  The function should either
+     return a function pointer  or never return.  Note that a NULL
+     pointer cannot be considered as an error, as it means that the
+     language has not been explicitely imposed by the user ("auto"). */
+  return NULL;                 /* avoid warnings from compiler */
+}
+
+
+/*
+ * Return a Lang_function given the interpreter name.
+ */
+Lang_function *
+get_language_from_interpreter (interpreter)
+     char *interpreter;
+{
+  struct lang_entry *lang;
+  char **iname;
+
+  if (interpreter == NULL)
+    return NULL;
+  for (lang = lang_names; lang->name != NULL; lang++)
+    if (lang->interpreters != NULL)
+      for (iname = lang->interpreters; *iname != NULL; iname++)
+       if (streq (*iname, interpreter))
+           return lang->function;
+
+  return NULL;
+}
+
+
+
+/*
+ * Return a Lang_function given the file suffix.
+ */
+Lang_function *
+get_language_from_suffix (suffix)
+     char *suffix;
+{
+  struct lang_entry *lang;
+  char **ext;
+
+  if (suffix == NULL)
+    return NULL;
+  for (lang = lang_names; lang->name != NULL; lang++)
+    if (lang->suffixes != NULL)
+      for (ext = lang->suffixes; *ext != NULL; ext++)
+       if (streq (*ext, suffix))
+           return lang->function;
+
+  return NULL;
 }
 
 
@@ -1005,15 +1083,22 @@ process_file (file)
 {
   struct stat stat_buf;
   FILE *inf;
+#ifdef DOS_NT
+  char *p;
+
+  for (p = file; *p != '\0'; p++)
+    if (*p == '\\')
+      *p = '/';
+#endif
 
   if (stat (file, &stat_buf) == 0 && !S_ISREG (stat_buf.st_mode))
     {
-      fprintf (stderr, "Skipping %s: it is not a regular file.\n", file);
+      error ("Skipping %s: it is not a regular file.", file);
       return;
     }
   if (streq (file, tagfile) && !streq (tagfile, "-"))
     {
-      fprintf (stderr, "Skipping inclusion of %s in self.\n", file);
+      error ("Skipping inclusion of %s in self.", file);
       return;
     }
   inf = fopen (file, "r");
@@ -1029,18 +1114,19 @@ process_file (file)
     {
       char *filename;
 
-      if (file[0] == '/')
+      if (absolutefn (file))
        {
-         /* file is an absolute filename.  Canonicalise it. */
+         /* file is an absolute file name.  Canonicalise it. */
          filename = absolute_filename (file, cwd);
        }
       else
        {
-         /* file is a filename relative to cwd.  Make it relative
+         /* file is a file name relative to cwd.  Make it relative
             to the directory of the tags file. */
          filename = relative_filename (file, tagfiledir);
        }
       fprintf (tagf, "\f\n%s,%d\n", filename, total_size_of_entries (head));
+      free (filename);
       put_entries (head);
       free_tree (head);
       head = NULL;
@@ -1087,34 +1173,70 @@ find_entries (file, inf)
      FILE *inf;
 {
   char *cp;
-  struct lang_entry *lang;
+  Lang_function *function;
   NODE *old_last_node;
   extern NODE *last_node;
 
+
+  /* Memory leakage here: the memory block pointed by curfile is never
+     released.  The amount of memory leaked here is the sum of the
+     lengths of the input file names. */
   curfile = savestr (file);
-  cp = etags_strrchr (file, '.');
 
   /* If user specified a language, use it. */
-  if (lang_func != NULL)
+  function = lang_func;
+  if (function != NULL)
     {
-      lang_func (inf);
+      function (inf);
       fclose (inf);
       return;
     }
 
-  if (cp)
+  cp = etags_strrchr (file, '.');
+  if (cp != NULL)
+    {
+      cp += 1;
+      function = get_language_from_suffix (cp);
+      if (function != NULL)
+       {
+         function (inf);
+         fclose (inf);
+         return;
+       }
+    }
+
+  /* Look for sharp-bang as the first two characters. */
+  if (readline_internal (&lb, inf) > 2
+      && lb.buffer[0] == '#'
+      && lb.buffer[1] == '!')
     {
-      ++cp;
-      for (lang = lang_extensions; lang->extension; ++lang)
+      char *lp;
+
+      /* Set lp to point at the first char after the last slash in the
+         line or, if no slashes, at the first nonblank.  Then set cp to
+        the first successive blank and terminate the string. */
+      lp = etags_strrchr (lb.buffer+2, '/');
+      if (lp != NULL)
+       lp += 1;
+      else
+       for (lp = lb.buffer+2; *lp != '\0' && isspace (*lp); lp++)
+         continue;
+      for (cp = lp; *cp != '\0' && !isspace (*cp); cp++)
+       continue;
+      *cp = '\0';
+
+      if (strlen (lp) > 0)
        {
-         if (streq (cp, lang->extension))
+         function = get_language_from_interpreter (lp);
+         if (function != NULL)
            {
-             lang->function (inf);
+             function (inf);
              fclose (inf);
              return;
            }
        }
     }
+  rewind (inf);
 
   /* Try Fortran. */
   old_last_node = last_node;
@@ -1122,51 +1244,62 @@ find_entries (file, inf)
 
   /* No Fortran entries found.  Try C. */
   if (old_last_node == last_node)
-    default_C_entries (inf);
+    {
+      rewind (inf);
+      default_C_entries (inf);
+    }
   fclose (inf);
+  return;
 }
 \f
 /* Record a tag. */
 void
-pfnote (name, is_func, named, linestart, linelen, lno, cno)
-     char *name;               /* tag name */
+pfnote (name, is_func, linestart, linelen, lno, cno)
+     char *name;               /* tag name, or NULL if unnamed */
      logical is_func;          /* tag is a function */
-     logical named;            /* tag different from text of definition */
      char *linestart;          /* start of the line where tag is */
      int linelen;              /* length of the line where tag is */
      int lno;                  /* line number */
      long cno;                 /* character number */
 {
-  register NODE *np = xnew (1, NODE);
-  register char *fp;
+  register NODE *np;
+
+  if (CTAGS && name == NULL)
+    return;
+
+  np = xnew (1, NODE);
 
   /* If ctags mode, change name "main" to M<thisfilename>. */
   if (CTAGS && !cxref_style && streq (name, "main"))
     {
-      fp = etags_strrchr (curfile, '/');
+      register char *fp = etags_strrchr (curfile, '/');
       np->name = concat ("M", fp == 0 ? curfile : fp + 1, "");
       fp = etags_strrchr (np->name, '.');
       if (fp && fp[1] != '\0' && fp[2] == '\0')
        fp[0] = 0;
-      np->named = TRUE;
     }
   else
-    {
-      np->name = name;
-      np->named = named;
-    }
+    np->name = name;
   np->been_warned = FALSE;
   np->file = curfile;
   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 espect etags.el to take care
+     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 */ ;
   np->left = np->right = NULL;
-  np->pat = savenstr (linestart, ((CTAGS && !cxref_style) ? 50 : linelen));
+  if (CTAGS && !cxref_style)
+    {
+      if (strlen (linestart) < 50)
+       np->pat = concat (linestart, "$", "");
+      else
+       np->pat = savenstr (linestart, 50);
+    }
+  else
+    np->pat = savenstr (linestart, linelen);
 
   add_node (np, &head);
 }
@@ -1183,7 +1316,7 @@ free_tree (node)
     {
       register NODE *node_right = node->right;
       free_tree (node->left);
-      if (node->named)
+      if (node->name != NULL)
        free (node->name);
       free (node->pat);
       free ((char *) node);
@@ -1219,7 +1352,7 @@ add_node (node, cur_node_p)
     {
       /* Etags Mode */
       if (last_node == NULL)
-       fatal ("internal error in add_node", 0);
+       fatal ("internal error in add_node", (char *)NULL);
       last_node->right = node;
       last_node = node;
     }
@@ -1234,7 +1367,7 @@ add_node (node, cur_node_p)
        */
       if (!dif)
        {
-         if (node->file == cur_node->file)
+         if (streq (node->file, cur_node->file))
            {
              if (!no_warnings)
                {
@@ -1242,26 +1375,18 @@ add_node (node, cur_node_p)
                           node->file, lineno, node->name);
                  fprintf (stderr, "Second entry ignored\n");
                }
-             return;
            }
-         if (!cur_node->been_warned && !no_warnings)
+         else if (!cur_node->been_warned && !no_warnings)
            {
-             fprintf (stderr,
-                 "Duplicate entry in files %s and %s: %s (Warning only)\n",
-                      node->file, cur_node->file, node->name);
+             fprintf
+               (stderr,
+                "Duplicate entry in files %s and %s: %s (Warning only)\n",
+                node->file, cur_node->file, node->name);
+             cur_node->been_warned = TRUE;
            }
-         cur_node->been_warned = TRUE;
          return;
        }
 
-      /* Maybe refuse to add duplicate nodes.  */
-      if (!permit_duplicates)
-       {
-         if (streq (node->name, cur_node->name)
-             && streq (node->file, cur_node->file))
-           return;
-       }
-
       /* Actually add the node */
       add_node (node, dif < 0 ? &cur_node->left : &cur_node->right);
     }
@@ -1283,49 +1408,51 @@ put_entries (node)
 
   if (!CTAGS)
     {
-      if (node->named)
+      if (node->name != NULL)
+       fprintf (tagf, "%s\177%s\001%d,%d\n",
+                node->pat, node->name, node->lno, node->cno);
+      else
+       fprintf (tagf, "%s\177%d,%d\n",
+                node->pat, node->lno, node->cno);
+    }
+  else
+    {
+      if (node->name == NULL)
+       error ("internal error: NULL name in ctags mode.", (char *)NULL);
+
+      if (cxref_style)
        {
-         fprintf (tagf, "%s\177%s\001%d,%d\n",
-                  node->pat, node->name,
-                  node->lno, node->cno);
+         if (vgrind_style)
+           fprintf (stdout, "%s %s %d\n",
+                    node->name, node->file, (node->lno + 63) / 64);
+         else
+           fprintf (stdout, "%-16s %3d %-16s %s\n",
+                    node->name, node->lno, node->file, node->pat);
        }
       else
        {
-         fprintf (tagf, "%s\177%d,%d\n",
-                  node->pat,
-                  node->lno, node->cno);
-       }
-    }
-  else if (!cxref_style)
-    {
-      fprintf (tagf, "%s\t%s\t",
-              node->name, node->file);
+         fprintf (tagf, "%s\t%s\t", node->name, node->file);
 
-      if (node->is_func)
-       {                       /* a function */
-         putc (searchar, tagf);
-         putc ('^', tagf);
+         if (node->is_func)
+           {                   /* a function */
+             putc (searchar, tagf);
+             putc ('^', tagf);
 
-         for (sp = node->pat; *sp; sp++)
-           {
-             if (*sp == '\\' || *sp == searchar)
-               putc ('\\', tagf);
-             putc (*sp, tagf);
+             for (sp = node->pat; *sp; sp++)
+               {
+                 if (*sp == '\\' || *sp == searchar)
+                   putc ('\\', tagf);
+                 putc (*sp, tagf);
+               }
+             putc (searchar, tagf);
            }
-         putc (searchar, tagf);
-       }
-      else
-       {                       /* a typedef; text pattern inadequate */
-         fprintf (tagf, "%d", node->lno);
+         else
+           {                   /* a typedef; text pattern inadequate */
+             fprintf (tagf, "%d", node->lno);
+           }
+         putc ('\n', tagf);
        }
-      putc ('\n', tagf);
     }
-  else if (vgrind_style)
-    fprintf (stdout, "%s %s %d\n",
-            node->name, node->file, (node->lno + 63) / 64);
-  else
-    fprintf (stdout, "%-16s %3d %-16s %s\n",
-            node->name, node->lno, node->file, node->pat);
 
   /* Output subentries that follow this one */
   put_entries (node->right);
@@ -1369,7 +1496,7 @@ total_size_of_entries (node)
       /* Count this entry */
       total += strlen (node->pat) + 1;
       total += number_len ((long) node->lno) + 1 + number_len (node->cno) + 1;
-      if (node->named)
+      if (node->name != NULL)
        total += 1 + strlen (node->name);       /* \001name */
     }
 
@@ -1381,21 +1508,28 @@ total_size_of_entries (node)
  */
 enum sym_type
 {
-  st_none, st_C_struct, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
+  st_none, st_C_objprot, st_C_objimpl, st_C_objend, st_C_gnumacro,
+  st_C_struct, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
 };
 
 /* Feed stuff between (but not including) %[ and %] lines to:
-      gperf -c -k1,3 -o -p -r -t
+      gperf -c -k 1,3 -o -p -r -t
 %[
 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
 %%
+@interface,    0,      st_C_objprot
+@protocol,     0,      st_C_objprot
+@implementation,0,     st_C_objimpl
+@end,          0,      st_C_objend
 class,         C_PLPL, st_C_struct
+namespace,     C_PLPL, st_C_struct
 domain,        C_STAR, st_C_struct
 union,         0,      st_C_struct
 struct,        0,      st_C_struct
 enum,          0,      st_C_enum
 typedef,       0,      st_C_typedef
 define,        0,      st_C_define
+bool,          C_PLPL, st_C_typespec
 long,          0,      st_C_typespec
 short,         0,      st_C_typespec
 int,           0,      st_C_typespec
@@ -1410,93 +1544,122 @@ extern,        0,      st_C_typespec
 static,        0,      st_C_typespec
 const,         0,      st_C_typespec
 volatile,      0,      st_C_typespec
+explicit,      C_PLPL, st_C_typespec
+mutable,       C_PLPL, st_C_typespec
+typename,      C_PLPL, st_C_typespec
+# DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
+DEFUN,         0,      st_C_gnumacro
+SYSCALL,       0,      st_C_gnumacro
+ENTRY,         0,      st_C_gnumacro
+PSEUDO,                0,      st_C_gnumacro
+# These are defined inside C functions, so currently they are not met.
+# EXFUN used in glibc, DEFVAR_* in emacs.
+#EXFUN,                0,      st_C_gnumacro
+#DEFVAR_,      0,      st_C_gnumacro
 %]
 and replace lines between %< and %> with its output. */
 /*%<*/
-/* C code produced by gperf version 1.8.1 (K&R C version) */
-/* Command-line: gperf -c -k1,3 -o -p -r -t  */
+/* C code produced by gperf version 2.1 (K&R C version) */
+/* 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 MIN_WORD_LENGTH 3
-#define MAX_WORD_LENGTH 8
-#define MIN_HASH_VALUE 10
-#define MAX_HASH_VALUE 62
+#define MAX_WORD_LENGTH 15
+#define MIN_HASH_VALUE 34
+#define MAX_HASH_VALUE 121
 /*
-   21 keywords
-   53 is the maximum key range
+   34 keywords
+   88 is the maximum key range
 */
 
 static int
 hash (str, len)
-     register char  *str;
-     register int  len;
+     register char *str;
+     register unsigned int  len;
 {
   static unsigned char hash_table[] =
     {
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
-     62, 62, 62, 62, 62, 62, 62,  2, 62,  7,
-      6,  9, 15, 30, 62, 24, 62, 62,  1, 24,
-      7, 27, 13, 62, 19, 26, 18, 27,  1, 62,
-     62, 62, 62, 62, 62, 62, 62, 62,
+     121, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+     121, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+     121, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+     121, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+     121, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+     121, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+     121, 121, 121, 121,  45, 121, 121, 121,  16,  19,
+      61, 121, 121, 121, 121, 121, 121, 121, 121, 121,
+      10, 121, 121,  20,  53, 121, 121, 121, 121, 121,
+     121, 121, 121, 121, 121, 121, 121,  41,  45,  22,
+      60,  47,  37,  28, 121,  55, 121, 121,  20,  14,
+      29,  30,   5, 121,  50,  59,  30,  54,   6, 121,
+     121, 121, 121, 121, 121, 121, 121, 121,
   };
   return len + hash_table[str[2]] + hash_table[str[0]];
 }
 
 struct C_stab_entry *
-in_word_set  (str, len)
+in_word_set (str, len)
      register char *str;
-     register int len;
+     register unsigned int len;
 {
 
   static struct C_stab_entry  wordlist[] =
     {
       {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
-      {"",}, 
+      {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
+      {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
+      {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
       {"volatile",     0,      st_C_typespec},
-      {"",}, 
+      {"PSEUDO",               0,      st_C_gnumacro},
+      {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
+      {"typedef",      0,      st_C_typedef},
+      {"typename",     C_PLPL, st_C_typespec},
+      {"",}, {"",}, {"",}, 
+      {"SYSCALL",      0,      st_C_gnumacro},
+      {"",}, {"",}, {"",}, 
+      {"mutable",      C_PLPL, st_C_typespec},
+      {"namespace",    C_PLPL, st_C_struct},
       {"long",         0,      st_C_typespec},
-      {"char",         0,      st_C_typespec},
-      {"class",        C_PLPL, st_C_struct},
-      {"",}, {"",}, {"",}, {"",}, 
+      {"",}, {"",}, 
       {"const",        0,      st_C_typespec},
+      {"",}, {"",}, {"",}, 
+      {"explicit",     C_PLPL, st_C_typespec},
       {"",}, {"",}, {"",}, {"",}, 
-      {"auto",         0,      st_C_typespec},
-      {"",}, {"",}, 
-      {"define",       0,      st_C_define},
-      {"",}, 
       {"void",         0,      st_C_typespec},
+      {"",}, 
+      {"char",         0,      st_C_typespec},
+      {"class",        C_PLPL, st_C_struct},
       {"",}, {"",}, {"",}, 
-      {"extern",       0,      st_C_typespec},
-      {"static",       0,      st_C_typespec},
+      {"float",        0,      st_C_typespec},
       {"",}, 
-      {"domain",       C_STAR, st_C_struct},
+      {"@implementation", 0,   st_C_objimpl},
+      {"auto",         0,      st_C_typespec},
       {"",}, 
-      {"typedef",      0,      st_C_typedef},
-      {"double",       0,      st_C_typespec},
-      {"enum",         0,      st_C_enum},
-      {"",}, {"",}, {"",}, {"",}, 
-      {"int",          0,      st_C_typespec},
+      {"ENTRY",                0,      st_C_gnumacro},
+      {"@end",                 0,      st_C_objend},
+      {"bool",                 C_PLPL, st_C_typespec},
+      {"domain",       C_STAR, st_C_struct},
       {"",}, 
-      {"float",        0,      st_C_typespec},
+      {"DEFUN",                0,      st_C_gnumacro},
+      {"extern",       0,      st_C_typespec},
+      {"@interface",   0,      st_C_objprot},
       {"",}, {"",}, {"",}, 
-      {"struct",       0,      st_C_struct},
+      {"int",          0,      st_C_typespec},
       {"",}, {"",}, {"",}, {"",}, 
-      {"union",        0,      st_C_struct},
-      {"",}, 
+      {"signed",       0,      st_C_typespec},
       {"short",        0,      st_C_typespec},
-      {"",}, {"",}, 
+      {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
+      {"define",       0,      st_C_define},
+      {"@protocol",    0,      st_C_objprot},
+      {"enum",         0,      st_C_enum},
+      {"static",       0,      st_C_typespec},
+      {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, 
+      {"union",        0,      st_C_struct},
+      {"struct",       0,      st_C_struct},
+      {"",}, {"",}, {"",}, {"",}, 
+      {"double",       0,      st_C_typespec},
       {"unsigned",     0,      st_C_typespec},
-      {"signed",       0,      st_C_typespec},
     };
 
   if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
@@ -1507,7 +1670,7 @@ in_word_set  (str, len)
         {
           register char *s = wordlist[key].name;
 
-          if (*s == *str && strneq (str + 1, s + 1, len - 1))
+          if (*s == *str && !strncmp (str + 1, s + 1, len - 1))
             return &wordlist[key];
         }
     }
@@ -1516,12 +1679,12 @@ in_word_set  (str, len)
 /*%>*/
 
 enum sym_type
-C_symtype(str, len, c_ext)
+C_symtype (str, len, c_ext)
      char *str;
      int len;
      int c_ext;
 {
-  register struct C_stab_entry *se = in_word_set(str, len);
+  register struct C_stab_entry *se = in_word_set (str, len);
 
   if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
     return st_none;
@@ -1532,7 +1695,7 @@ C_symtype(str, len, c_ext)
   * C functions are recognized using a simple finite automaton.
   * funcdef is its state variable.
   */
-typedef enum
+enum
 {
   fnone,                       /* nothing seen */
   ftagseen,                    /* function-like tag seen */
@@ -1540,59 +1703,79 @@ typedef enum
   finlist,                     /* in parameter list */
   flistseen,                   /* after parameter list */
   fignore                      /* before open brace */
-} FUNCST;
-FUNCST funcdef;
+} funcdef;
 
 
  /*
   * typedefs are recognized using a simple finite automaton.
-  * typeddef is its state variable.
+  * typdef is its state variable.
   */
-typedef enum
+enum
 {
   tnone,                       /* nothing seen */
   ttypedseen,                  /* typedef keyword seen */
   tinbody,                     /* inside typedef body */
   tend,                                /* just before typedef tag */
   tignore                      /* junk after typedef tag */
-} TYPEDST;
-TYPEDST typdef;
+} typdef;
 
 
- /* 
+ /*
   * struct-like structures (enum, struct and union) are recognized
   * using another simple finite automaton.  `structdef' is its state
   * variable.
   */
-typedef enum
+enum
 {
   snone,                       /* nothing seen yet */
   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*/
-} STRUCTST;
-STRUCTST structdef;
+} structdef;
 
 /*
  * When structdef is stagseen, scolonseen, or sinbody, structtag is the
- * struct tag, and structtype is the type of the preceding struct-like  
+ * 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>";
+
 /*
  * Yet another little state machine to deal with preprocessor lines.
  */
-typedef enum
+enum
 {
   dnone,                       /* nothing seen */
   dsharpseen,                  /* '#' seen as first char on line */
   ddefineseen,                 /* '#' and 'define' seen */
   dignorerest                  /* ignore rest of line */
-} DEFINEST;
-DEFINEST definedef;
+} definedef;
+
+/*
+ * State machine for Objective C protocols and implementations.
+ */
+enum
+{
+  onone,                       /* nothing seen */
+  oprotocol,                   /* @interface or @protocol seen */
+  oimplementation,             /* @implementations seen */
+  otagseen,                    /* class name seen */
+  oparenseen,                  /* parenthesis before category seen */
+  ocatseen,                    /* category name seen */
+  oinbody,                     /* in @implementation body */
+  omethodsign,                 /* in @implementation body, after +/- */
+  omethodtag,                  /* after method name */
+  omethodcolon,                        /* after method colon */
+  omethodparm,                 /* after method parameter */
+  oignore                      /* wait for @end */
+} objdef;
 
 /*
  * Set this to TRUE, and the next token considered is called a function.
@@ -1605,14 +1788,19 @@ logical next_token_is_func;
  */
 logical yacc_rules;
 
+/*
+ * methodlen is the length of the method name stored in token_name.
+ */
+int methodlen;
+
 /*
  * consider_token ()
  *     checks to see if the current token is at the start of a
  *     function, or corresponds to a typedef, or is a struct/union/enum
- *     tag.
+ *     tag, or #define, or an enum constant.
  *
- *     *IS_FUNC gets TRUE iff the token is a function or macro with args.
- *     C_EXT is which language we are looking at.
+ *     *IS_FUNC gets TRUE iff the token is a function or #define macro
+ *     with args.  C_EXT is which language we are looking at.
  *
  *     In the future we will need some way to adjust where the end of
  *     the token is; for instance, implementing the C++ keyword
@@ -1624,16 +1812,18 @@ logical yacc_rules;
  *     structdef               IN OUT
  *     definedef               IN OUT
  *     typdef                  IN OUT
+ *     objdef                  IN OUT
  *     next_token_is_func      IN OUT
  */
 
 logical
-consider_token (str, len, c, c_ext, cblev, is_func)
+consider_token (str, len, c, c_ext, cblev, parlev, is_func)
      register char *str;       /* IN: token pointer */
      register int len;         /* IN: token length */
      register char c;          /* IN: first char after the token */
      int c_ext;                        /* IN: C extensions mask */
      int cblev;                        /* IN: curly brace level */
+     int parlev;               /* IN: parenthesis level */
      logical *is_func;         /* OUT: function found */
 {
   enum sym_type toktype = C_symtype (str, len, c_ext);
@@ -1670,7 +1860,7 @@ consider_token (str, len, c, c_ext, cblev, is_func)
     case dignorerest:
       return FALSE;
     default:
-      error ("internal error: definedef value.", 0);
+      error ("internal error: definedef value.", (char *)NULL);
     }
 
   /*
@@ -1720,11 +1910,6 @@ consider_token (str, len, c, c_ext, cblev, is_func)
    * 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.
-   *
-   * This if statement deals with the typdef state machine as 
-   * follows: if typdef==ttypedseen and token is struct/union/class/enum,
-   * return FALSE.  All the other code here is for the structdef 
-   * state machine.
    */
   switch (toktype)
     {
@@ -1738,6 +1923,7 @@ consider_token (str, len, c, c_ext, cblev, is_func)
        }
       return FALSE;
     }
+
   if (structdef == skeyseen)
     {
       /* Save the tag for struct/union/class, for functions that may be
@@ -1757,23 +1943,25 @@ consider_token (str, len, c, c_ext, cblev, is_func)
       return FALSE;
     }
 
-  /* Detect GNU macros. */
-  if (definedef == dnone)
-    if (strneq (str, "DEFUN", 5) /* Used in emacs */
-#if FALSE      
-          These are defined inside C functions, so currently they
-          are not met anyway.
-       || strneq (str, "EXFUN", 5) /* Used in glibc */
-       || strneq (str, "DEFVAR_", 7) /* Used in emacs */
-#endif
-       || strneq (str, "SYSCALL", 7) /* Used in glibc (mach) */
-       || strneq (str, "ENTRY", 5) /* Used in glibc */
-       || strneq (str, "PSEUDO", 6)) /* Used in glibc */
-
-      {
-       next_token_is_func = TRUE;
-       return FALSE;
-      }
+  /* Detect GNU macros.
+
+     DEFUN note for writers of emacs C code:
+      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, so writers of emacs code are recommended to put the
+     first two args of a DEFUN on the same line. */
+  if (definedef == dnone && toktype == st_C_gnumacro)
+    {
+      next_token_is_func = TRUE;
+      return FALSE;
+    }
   if (next_token_is_func)
     {
       next_token_is_func = FALSE;
@@ -1782,33 +1970,106 @@ consider_token (str, len, c, c_ext, cblev, is_func)
       return TRUE;
     }
 
-  /* A function? */
-  switch (toktype)
+  /* Detect Objective C constructs. */
+  switch (objdef)
     {
-    case st_C_typespec:
-      if (funcdef != finlist && funcdef != fignore)
-        funcdef = fnone;               /* should be useless */
+    case onone:
+      switch (toktype)
+       {
+       case st_C_objprot:
+         objdef = oprotocol;
+         return FALSE;
+       case st_C_objimpl:
+         objdef = oimplementation;
+         return FALSE;
+       }
+      break;
+    case oimplementation:
+      /* Save the class tag for functions that may be defined inside. */
+      objtag = savenstr (str, len);
+      objdef = oinbody;
       return FALSE;
-    default:
-      if (funcdef == fnone)
+    case oprotocol:
+      /* Save the class tag for categories. */
+      objtag = savenstr (str, len);
+      objdef = otagseen;
+      *is_func = TRUE;
+      return TRUE;
+    case oparenseen:
+      objdef = ocatseen;
+      *is_func = TRUE;
+      return TRUE;
+    case oinbody:
+      break;
+    case omethodsign:
+      if (parlev == 0)
        {
-         funcdef = ftagseen;
-         *is_func = TRUE;
+         objdef = omethodtag;
+         methodlen = len;
+         grow_linebuffer (&token_name, methodlen+1);
+         strncpy (token_name.buffer, str, len);
+         token_name.buffer[methodlen] = '\0';
          return TRUE;
        }
-    }
-
-  return FALSE;
-}
-
-/*
- * C_entries ()
- *     This routine finds functions, typedefs, #define's and
- *     struct/union/enum definitions in C syntax and adds them
- *     to the list.
+      return FALSE;
+    case omethodcolon:
+      if (parlev == 0)
+       objdef = omethodparm;
+      return FALSE;
+    case omethodparm:
+      if (parlev == 0)
+       {
+         objdef = omethodtag;
+         methodlen += len;
+         grow_linebuffer (&token_name, methodlen+1);
+         strncat (token_name.buffer, str, len);
+         return TRUE;
+       }
+      return FALSE;
+    case oignore:
+      if (toktype == st_C_objend)
+       {
+         /* Memory leakage here: the string pointed by objtag is
+            never released, because many tests would be needed to
+            avoid breaking on incorrect input code.  The amount of
+            memory leaked here is the sum of the lengths of the
+            class tags.
+         free (objtag); */
+         objdef = onone;
+       }
+      return FALSE;
+    }
+
+  /* A function or enum constant? */
+  switch (toktype)
+    {
+    case st_C_typespec:
+      if (funcdef != finlist && funcdef != fignore)
+        funcdef = fnone;               /* should be useless */
+      return FALSE;
+    case st_none:
+      if (constantypedefs && structdef == sinbody && structtype == st_C_enum)
+       return TRUE;
+      if (funcdef == fnone)
+       {
+         funcdef = ftagseen;
+         *is_func = TRUE;
+         return TRUE;
+       }
+    }
+
+  return FALSE;
+}
+
+/*
+ * C_entries ()
+ *     This routine finds functions, typedefs, #define's, enum
+ *     constants and struct/union/enum definitions in C syntax
+ *     and adds them to the list.
  */
 typedef struct
 {
+  logical valid;
   char *str;
   logical named;
   int linelen;
@@ -1831,6 +2092,7 @@ typedef struct
 do {                                                                   \
   curlinepos = charno;                                                 \
   lineno++;                                                            \
+  linecharno = charno;                                                 \
   charno += readline (&curlb, inf);                                    \
   lp = curlb.buffer;                                                   \
   quotednl = FALSE;                                                    \
@@ -1840,16 +2102,36 @@ do {                                                                    \
 #define CNL                                                            \
 do {                                                                   \
   CNL_SAVE_DEFINEDEF;                                                  \
-  if (token_saved)                                                     \
+  if (savetok.valid)                                                   \
     {                                                                  \
       tok = savetok;                                                   \
-      token_saved = FALSE;                                             \
+      savetok.valid = FALSE;                                           \
     }                                                                  \
   definedef = dnone;                                                   \
 } while (0)
 
-#define make_tag(isfun)  pfnote (savestr (token_str.buffer), isfun, \
-  tok.named, tok.buffer, tok.linelen, tok.lineno, tok.linepos)
+
+void
+make_C_tag (isfun, tokp)
+     logical isfun;
+     TOKEN *tokp;
+{
+  char *name = NULL;
+
+  /* This function should never be called when tok.valid is FALSE, but
+     we must protect against invalid input or internal errors. */
+  if (tokp->valid)
+    {
+      if (CTAGS || tokp->named)
+       name = savestr (token_name.buffer);
+      pfnote (name, isfun,
+             tokp->buffer, tokp->linelen, tokp->lineno, tokp->linepos);
+      tokp->valid = FALSE;
+    }
+  else if (DEBUG)
+    abort ();
+}
+
 
 void
 C_entries (c_ext, inf)
@@ -1866,18 +2148,20 @@ C_entries (c_ext, inf)
   int parlev;                  /* current parenthesis level */
   logical incomm, inquote, inchar, quotednl, midtoken;
   logical cplpl;
-  logical token_saved;         /* token saved */
   TOKEN savetok;               /* token saved during preprocessor handling */
 
+
   curndx = newndx = 0;
   lineno = 0;
   charno = 0;
   lp = curlb.buffer;
   *lp = 0;
 
-  definedef = dnone; funcdef = fnone; typdef = tnone; structdef = snone;
-  next_token_is_func = yacc_rules = token_saved = FALSE;
+  funcdef = fnone; typdef = tnone; structdef = snone;
+  definedef = dnone; objdef = onone;
+  next_token_is_func = yacc_rules = FALSE;
   midtoken = inquote = inchar = incomm = quotednl = FALSE;
+  tok.valid = savetok.valid = FALSE;
   cblev = 0;
   parlev = 0;
   cplpl = c_ext & C_PLPL;
@@ -1947,7 +2231,7 @@ C_entries (c_ext, inf)
            }
          continue;
        }
-      else 
+      else
        switch (c)
          {
          case '"':
@@ -1967,9 +2251,9 @@ C_entries (c_ext, inf)
                incomm = TRUE;
                continue;
              }
-           else if (cplpl && *lp == '/')
+           else if (/* cplpl && */ *lp == '/')
              {
-               c = 0;
+               c = '\0';
                break;
              }
            else
@@ -2020,7 +2304,8 @@ C_entries (c_ext, inf)
       /* Consider token only if some complicated conditions are satisfied. */
       if ((definedef != dnone
           || (cblev == 0 && structdef != scolonseen)
-          || (cblev == 1 && cplpl && structdef == sinbody))
+          || (cblev == 1 && cplpl && structdef == sinbody)
+          || (structdef == sinbody && structtype == st_C_enum))
          && typdef != tignore
          && definedef != dignorerest
          && funcdef != finlist)
@@ -2029,7 +2314,7 @@ C_entries (c_ext, inf)
            {
              if (endtoken (c))
                {
-                 if (cplpl && c == ':' && *lp == ':' && begtoken(*(lp + 1)))
+                 if (c == ':' && cplpl && *lp == ':' && begtoken(*(lp + 1)))
                    {
                      /*
                       * This handles :: in the middle, but not at the
@@ -2043,38 +2328,46 @@ C_entries (c_ext, inf)
                      logical is_func = FALSE;
 
                      if (yacc_rules
-                         || consider_token (newlb.buffer + tokoff, toklen,
-                                            c, c_ext, cblev, &is_func))
+                         || consider_token (newlb.buffer + tokoff, toklen, c,
+                                            c_ext, cblev, parlev, &is_func))
                        {
                          if (structdef == sinbody
                              && definedef == dnone
                              && is_func)
                            /* function defined in C++ class body */
                            {
-                             int strsize = strlen(structtag) + 2 + toklen + 1;
-                             while (token_str.size < strsize)
-                               {
-                                 token_str.size *= 2;
-                                 token_str.buffer = xrealloc(token_str.buffer,
-                                                             token_str.size);
-                               }
-                             strcpy (token_str.buffer, structtag);
-                             strcat (token_str.buffer, "::");
-                             strncat (token_str.buffer,
+                             grow_linebuffer (&token_name,
+                                              strlen(structtag)+2+toklen+1);
+                             strcpy (token_name.buffer, structtag);
+                             strcat (token_name.buffer, "::");
+                             strncat (token_name.buffer,
+                                      newlb.buffer+tokoff, toklen);
+                             tok.named = TRUE;
+                           }
+                         else if (objdef == ocatseen)
+                           /* Objective C category */
+                           {
+                             grow_linebuffer (&token_name,
+                                              strlen(objtag)+2+toklen+1);
+                             strcpy (token_name.buffer, objtag);
+                             strcat (token_name.buffer, "(");
+                             strncat (token_name.buffer,
                                       newlb.buffer+tokoff, toklen);
+                             strcat (token_name.buffer, ")");
+                             tok.named = TRUE;
+                           }
+                         else if (objdef == omethodtag
+                                  || objdef == omethodparm)
+                           /* Objective C method */
+                           {
                              tok.named = TRUE;
                            }
                          else
                            {
-                             while (token_str.size < toklen + 1)
-                               {
-                                 token_str.size *= 2;
-                                 token_str.buffer = xrealloc(token_str.buffer,
-                                                             token_str.size);
-                               }
-                             strncpy (token_str.buffer,
+                             grow_linebuffer (&token_name, toklen+1);
+                             strncpy (token_name.buffer,
                                       newlb.buffer+tokoff, toklen);
-                             token_str.buffer[toklen] = '\0';
+                             token_name.buffer[toklen] = '\0';
                              if (structdef == stagseen
                                  || typdef == tend
                                  || (is_func
@@ -2087,17 +2380,19 @@ C_entries (c_ext, inf)
                          tok.linelen = tokoff + toklen + 1;
                          tok.buffer = newlb.buffer;
                          tok.linepos = newlinepos;
+                         tok.valid = TRUE;
 
                          if (definedef == dnone
                              && (funcdef == ftagseen
                                  || structdef == stagseen
-                                 || typdef == tend))
+                                 || typdef == tend
+                                 || objdef != onone))
                            {
                              if (current_lb_is_new)
                                switch_line_buffers ();
                            }
                          else
-                           make_tag (is_func);
+                           make_C_tag (is_func, &tok);
                        }
                      midtoken = FALSE;
                    }
@@ -2119,7 +2414,7 @@ C_entries (c_ext, inf)
                      funcdef = finlist;
                      continue;
                    case flistseen:
-                     make_tag (TRUE);
+                     make_C_tag (TRUE, &tok);
                      funcdef = fignore;
                      break;
                    case ftagseen:
@@ -2131,7 +2426,6 @@ C_entries (c_ext, inf)
                  break;
                case dsharpseen:
                  savetok = tok;
-                 token_saved = TRUE;
                }
              if (!yacc_rules || lp == newlb.buffer + 1)
                {
@@ -2151,6 +2445,20 @@ C_entries (c_ext, inf)
        case ':':
          if (definedef != dnone)
            break;
+         switch (objdef)
+           {
+           case  otagseen:
+             objdef = oignore;
+             make_C_tag (TRUE, &tok);
+             break;
+           case omethodtag:
+           case omethodparm:
+             objdef = omethodcolon;
+             methodlen += 1;
+             grow_linebuffer (&token_name, methodlen+1);
+             strcat (token_name.buffer, ":");
+             break;
+           }
          if (structdef == stagseen)
            structdef = scolonseen;
          else
@@ -2159,7 +2467,7 @@ C_entries (c_ext, inf)
              case ftagseen:
                if (yacc_rules)
                  {
-                   make_tag (FALSE);
+                   make_C_tag (FALSE, &tok);
                    funcdef = fignore;
                  }
                break;
@@ -2175,19 +2483,33 @@ C_entries (c_ext, inf)
            switch (typdef)
              {
              case tend:
-               make_tag (FALSE);
+               make_C_tag (FALSE, &tok);
                /* FALLTHRU */
              default:
                typdef = tnone;
              }
          if (funcdef != fignore)
-           funcdef = fnone;
+           {
+             funcdef = fnone;
+             /* 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 (structdef == stagseen)
            structdef = snone;
          break;
        case ',':
          if (definedef != dnone)
            break;
+         switch (objdef)
+           {
+           case omethodtag:
+           case omethodparm:
+             make_C_tag (TRUE, &tok);
+             objdef = oinbody;
+             break;
+           }
          if (funcdef != finlist && funcdef != fignore)
            funcdef = fnone;
          if (structdef == stagseen)
@@ -2199,7 +2521,7 @@ C_entries (c_ext, inf)
          if (cblev == 0 && typdef == tend)
            {
              typdef = tignore;
-             make_tag (FALSE);
+             make_C_tag (FALSE, &tok);
              break;
            }
          if (funcdef != finlist && funcdef != fignore)
@@ -2210,6 +2532,8 @@ C_entries (c_ext, inf)
        case '(':
          if (definedef != dnone)
            break;
+         if (objdef == otagseen && parlev == 0)
+           objdef = oparenseen;
          switch (funcdef)
            {
            case fnone:
@@ -2220,10 +2544,10 @@ C_entries (c_ext, inf)
                  /* Make sure that the next char is not a '*'.
                     This handles constructs like:
                     typedef void OperatorFun (int fun); */
-                 if (*lp != '*')
+                 if (tok.valid && *lp != '*')
                    {
                      typdef = tignore;
-                     make_tag (FALSE);
+                     make_C_tag (FALSE, &tok);
                    }
                  break;
                } /* switch (typdef) */
@@ -2240,6 +2564,11 @@ C_entries (c_ext, inf)
        case ')':
          if (definedef != dnone)
            break;
+         if (objdef == ocatseen && parlev == 1)
+           {
+             make_C_tag (TRUE, &tok);
+             objdef = oignore;
+           }
          if (--parlev == 0)
            {
              switch (funcdef)
@@ -2252,7 +2581,7 @@ C_entries (c_ext, inf)
              if (cblev == 0 && typdef == tend)
                {
                  typdef = tignore;
-                 make_tag (FALSE);
+                 make_C_tag (FALSE, &tok);
                }
            }
          else if (parlev < 0)  /* can happen due to ill-conceived #if's. */
@@ -2266,27 +2595,40 @@ C_entries (c_ext, inf)
          switch (structdef)
            {
            case skeyseen:      /* unnamed struct */
-             structtag = "_anonymous_";
              structdef = sinbody;
+             structtag = "_anonymous_";
              break;
            case stagseen:
            case scolonseen:    /* named struct */
              structdef = sinbody;
-             make_tag (FALSE);
+             make_C_tag (FALSE, &tok);
              break;
            }
          switch (funcdef)
            {
            case flistseen:
-             make_tag (TRUE);
+             make_C_tag (TRUE, &tok);
              /* FALLTHRU */
            case fignore:
              funcdef = fnone;
              break;
            case fnone:
-             /* Neutralize `extern "C" {' grot and look inside structs. */
-             if (cblev == 0 && structdef == snone && typdef == tnone)
-               cblev = -1;
+             switch (objdef)
+               {
+               case otagseen:
+                 make_C_tag (TRUE, &tok);
+                 objdef = oignore;
+                 break;
+               case omethodtag:
+               case omethodparm:
+                 make_C_tag (TRUE, &tok);
+                 objdef = oinbody;
+                 break;
+               default:
+                 /* Neutralize `extern "C" {' grot. */
+                 if (cblev == 0 && structdef == snone && typdef == tnone)
+                   cblev = -1;
+               }
            }
          cblev++;
          break;
@@ -2310,17 +2652,27 @@ C_entries (c_ext, inf)
            {
              if (typdef == tinbody)
                typdef = tend;
-#if FALSE                      /* too risky */
+             /* 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);
-#endif
+               free (structtag); */
 
              structdef = snone;
              structtag = "<error>";
            }
          break;
-       case '=':
-       case '#': case '+': case '-': case '~': case '&': case '%': case '/':
+       case '+':
+       case '-':
+         if (objdef == oinbody && cblev == 0)
+           {
+             objdef = omethodsign;
+             break;
+           }
+         /* FALLTHRU */
+       case '=': case '#': case '~': case '&': case '%': case '/':
        case '|': case '^': case '!': case '<': case '>': case '.': case '?':
          if (definedef != dnone)
            break;
@@ -2329,6 +2681,11 @@ C_entries (c_ext, inf)
            funcdef = fnone;
          break;
        case '\0':
+         if (objdef == otagseen)
+           {
+             make_C_tag (TRUE, &tok);
+             objdef = oignore;
+           }
          /* If a macro spans multiple lines don't reset its state. */
          if (quotednl)
            CNL_SAVE_DEFINEDEF;
@@ -2351,6 +2708,14 @@ default_C_entries (inf)
   C_entries (cplusplus ? C_PLPL : 0, inf);
 }
 
+/* Always do plain ANSI C. */
+void
+plain_C_entries (inf)
+     FILE *inf;
+{
+  C_entries (0, inf);
+}
+
 /* Always do C++. */
 void
 Cplusplus_entries (inf)
@@ -2385,9 +2750,9 @@ tail (cp)
 {
   register int len = 0;
 
-  while (*cp && (*cp | ' ') == (dbp[len] | ' '))
+  while (*cp && lowcase(*cp) == lowcase(dbp[len]))
     cp++, len++;
-  if (*cp == 0)
+  if (*cp == '\0' && !intoken(dbp[len]))
     {
       dbp += len;
       return TRUE;
@@ -2405,8 +2770,11 @@ takeprec ()
   dbp++;
   while (isspace (*dbp))
     dbp++;
-  if (tail ("(*)"))
-    return;
+  if (strneq (dbp, "(*)", 3))
+    {
+      dbp += 3;
+      return;
+    }
   if (!isdigit (*dbp))
     {
       --dbp;                   /* force failure */
@@ -2446,8 +2814,8 @@ getit (inf)
        && (isalpha (*cp) || isdigit (*cp) || (*cp == '_') || (*cp == '$')));
        cp++)
     continue;
-  pfnote (savenstr (dbp, cp-dbp), TRUE, FALSE, lb.buffer,
-         cp - lb.buffer + 1, lineno, linecharno);
+  pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
+         lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
 }
 
 void
@@ -2467,9 +2835,9 @@ Fortran_functions (inf)
        dbp++;                  /* Ratfor escape to fortran */
       while (isspace (*dbp))
        dbp++;
-      if (*dbp == 0)
+      if (*dbp == '\0')
        continue;
-      switch (*dbp | ' ')
+      switch (lowcase (*dbp))
        {
        case 'i':
          if (tail ("integer"))
@@ -2492,7 +2860,7 @@ Fortran_functions (inf)
            {
              while (isspace (*dbp))
                dbp++;
-             if (*dbp == 0)
+             if (*dbp == '\0')
                continue;
              if (tail ("precision"))
                break;
@@ -2502,9 +2870,9 @@ Fortran_functions (inf)
        }
       while (isspace (*dbp))
        dbp++;
-      if (*dbp == 0)
+      if (*dbp == '\0')
        continue;
-      switch (*dbp | ' ')
+      switch (lowcase (*dbp))
        {
        case 'f':
          if (tail ("function"))
@@ -2563,22 +2931,47 @@ Asm_labels (inf)
          if (*cp == ':' || isspace (*cp))
            {
              /* Found end of label, so copy it and add it to the table. */
-             pfnote (savenstr (lb.buffer, cp-lb.buffer), TRUE, FALSE,
+             pfnote ((CTAGS) ? savenstr(lb.buffer, cp-lb.buffer) : NULL, TRUE,
                      lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
            }
        }
     }
 }
 \f
-/* Added by Mosur Mohan, 4/22/88 */
-/* Pascal parsing                */
+/*
+ * Perl support by Bart Robinson <lomew@cs.utah.edu>
+ * Perl sub names: look for /^sub[ \t\n]+[^ \t\n{]+/
+ */
+void
+Perl_functions (inf)
+     FILE *inf;
+{
+  register char *cp;
+
+  lineno = 0;
+  charno = 0;
+
+  while (!feof (inf))
+    {
+      lineno++;
+      linecharno = charno;
+      charno += readline (&lb, inf);
+      cp = lb.buffer;
 
-#define GET_NEW_LINE \
-{ \
-  linecharno = charno; lineno++; \
-  charno += 1 + readline (&lb, inf); \
-  dbp = lb.buffer; \
+      if (*cp++ == 's' && *cp++ == 'u' && *cp++ == 'b' && isspace(*cp++))
+       {
+         while (*cp && isspace(*cp))
+           cp++;
+         while (*cp && ! isspace(*cp) && *cp != '{')
+           cp++;
+         pfnote ((CTAGS) ? savenstr (lb.buffer, cp-lb.buffer) : NULL, TRUE,
+                 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
+       }
+    }
 }
+\f
+/* Added by Mosur Mohan, 4/22/88 */
+/* Pascal parsing                */
 
 /*
  *  Locates tags for procedures & functions.  Doesn't do any type- or
@@ -2592,26 +2985,26 @@ Pascal_functions (inf)
 {
   struct linebuffer tline;     /* mostly copied from C_entries */
   long save_lcno;
-  int save_lineno;
-  char c, *cp;
-  char *nambuf;
+  int save_lineno, save_len;
+  char c, *cp, *namebuf;
 
   logical                      /* each of these flags is TRUE iff: */
     incomment,                 /* point is inside a comment */
     inquote,                   /* point is inside '..' string */
-    get_tagname,               /* point is after PROCEDURE/FUNCTION */
-  /*   keyword, so next item = potential tag */
+    get_tagname,               /* point is after PROCEDURE/FUNCTION
+                                  keyword, so next item = potential tag */
     found_tag,                 /* point is after a potential tag */
     inparms,                   /* point is within parameter-list */
-    verify_tag;                        /* point has passed the parm-list, so the */
-  /*   next token will determine whether    */
-  /*   this is a FORWARD/EXTERN to be       */
-  /*   ignored, or whether it is a real tag */
+    verify_tag;                        /* point has passed the parm-list, so the
+                                  next token will determine whether this
+                                  is a FORWARD/EXTERN to be ignored, or
+                                  whether it is a real tag */
 
   lineno = 0;
   charno = 0;
   dbp = lb.buffer;
-  *dbp = 0;
+  *dbp = '\0';
+  save_len = 0;
   initbuffer (&tline);
 
   incomment = inquote = FALSE;
@@ -2626,20 +3019,23 @@ Pascal_functions (inf)
       c = *dbp++;
       if (c == '\0')           /* if end of line */
        {
-         GET_NEW_LINE;
+         lineno++;
+         linecharno = charno;
+         charno += readline (&lb, inf);
+         dbp = lb.buffer;
          if (*dbp == '\0')
            continue;
          if (!((found_tag && verify_tag) ||
                get_tagname))
-           c = *dbp++;         /* only if don't need *dbp pointing */
-                               /* to the beginning of the name of  */
-                               /* the procedure or function        */
+           c = *dbp++;         /* only if don't need *dbp pointing
+                                  to the beginning of the name of
+                                  the procedure or function */
        }
       if (incomment)
        {
-         if (c == '}')         /* within { } comments */
+         if (c == '}')         /* within { } comments */
            incomment = FALSE;
-         else if (c == '*' && dbp[1] == ')') /* within (* - *) comments */
+         else if (c == '*' && *dbp == ')') /* within (* *) comments */
            {
              dbp++;
              incomment = FALSE;
@@ -2658,11 +3054,11 @@ Pascal_functions (inf)
          case '\'':
            inquote = TRUE;     /* found first quote */
            continue;
-         case '{':             /* found open-{-comment */
+         case '{':             /* found open { comment */
            incomment = TRUE;
            continue;
          case '(':
-           if (*dbp == '*')    /* found open-(*-comment */
+           if (*dbp == '*')    /* found open (* comment */
              {
                incomment = TRUE;
                dbp++;
@@ -2675,19 +3071,19 @@ Pascal_functions (inf)
              inparms = FALSE;
            continue;
          case ';':
-           if ((found_tag) && (!inparms))      /* end of proc or fn stmt */
+           if (found_tag && !inparms) /* end of proc or fn stmt */
              {
                verify_tag = TRUE;
                break;
              }
            continue;
          }
-      if ((found_tag) && (verify_tag) && (*dbp != ' '))
+      if (found_tag && verify_tag && (*dbp != ' '))
        {
          /* check if this is an "extern" declaration */
-         if (*dbp == 0)
+         if (*dbp == '\0')
            continue;
-         if ((*dbp == 'e') || (*dbp == 'E'))
+         if (lowcase (*dbp == 'e'))
            {
              if (tail ("extern"))      /* superfluous, really! */
                {
@@ -2695,7 +3091,7 @@ Pascal_functions (inf)
                  verify_tag = FALSE;
                }
            }
-         else if ((*dbp == 'f') || (*dbp == 'F'))
+         else if (lowcase (*dbp) == 'f')
            {
              if (tail ("forward"))     /*  check for forward reference */
                {
@@ -2703,22 +3099,22 @@ Pascal_functions (inf)
                  verify_tag = FALSE;
                }
            }
-         if ((found_tag) && (verify_tag)) /* not external proc, so make tag */
+         if (found_tag && verify_tag) /* not external proc, so make tag */
            {
              found_tag = FALSE;
              verify_tag = FALSE;
-             pfnote (nambuf, TRUE, FALSE, tline.buffer,
-                     cp - tline.buffer + 1, save_lineno, save_lcno);
+             pfnote (namebuf, TRUE,
+                     tline.buffer, save_len, save_lineno, save_lcno);
              continue;
            }
        }
       if (get_tagname)         /* grab name of proc or fn */
        {
-         if (*dbp == 0)
+         if (*dbp == '\0')
            continue;
 
          /* save all values for later tagging */
-         tline.size = lb.size;
+         grow_linebuffer (&tline, strlen (lb.buffer) + 1);
          strcpy (tline.buffer, lb.buffer);
          save_lineno = lineno;
          save_lcno = linecharno;
@@ -2726,8 +3122,9 @@ Pascal_functions (inf)
          /* grab block name */
          for (cp = dbp + 1; *cp && (!endtoken (*cp)); cp++)
            continue;
-         nambuf = savenstr (dbp, cp-dbp);
-         dbp = cp;             /* restore dbp to e-o-token */
+         namebuf = (CTAGS) ? savenstr (dbp, cp-dbp) : NULL;
+         dbp = cp;             /* set dbp to e-o-token */
+         save_len = dbp - lb.buffer + 1;
          get_tagname = FALSE;
          found_tag = TRUE;
          continue;
@@ -2737,7 +3134,7 @@ Pascal_functions (inf)
       else if (!incomment && !inquote && !found_tag)
        {
          /* check for proc/fn keywords */
-         switch (c | ' ')
+         switch (lowcase (c))
            {
            case 'p':
              if (tail ("rocedure"))    /* c = 'p', dbp has advanced */
@@ -2750,6 +3147,8 @@ Pascal_functions (inf)
            }
        }
     }                          /* while not eof */
+
+  free (tline.buffer);
 }
 \f
 /*
@@ -2796,9 +3195,9 @@ L_getit ()
     continue;
   if (cp == dbp)
     return;
-  
-  pfnote (savenstr (dbp, cp-dbp), TRUE, FALSE, lb.buffer,
-         cp - lb.buffer + 1, lineno, linecharno);
+
+  pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
+         lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
 }
 
 void
@@ -2908,14 +3307,14 @@ get_scheme ()
 {
   register char *cp;
 
-  if (*dbp == 0)
+  if (*dbp == '\0')
     return;
   /* Go till you get to white space or a syntactic break */
   for (cp = dbp + 1;
        *cp && *cp != '(' && *cp != ')' && !isspace (*cp);
        cp++)
     continue;
-  pfnote (savenstr (dbp, cp-dbp), TRUE, FALSE,
+  pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
          lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
 }
 \f
@@ -2936,12 +3335,15 @@ struct TEX_tabent *TEX_toktab = NULL;   /* Table with tag tokens */
    The value of environment var TEXTAGS is prepended to this.  */
 
 char *TEX_defenv = "\
-:chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem:typeout";
+:chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
+:part:appendix:entry:index";
 
 void TEX_mode ();
 struct TEX_tabent *TEX_decode_env ();
-void TEX_getit ();
 int TEX_Token ();
+#if TeX_named_tokens
+void TEX_getit ();
+#endif
 
 char TEX_esc = '\\';
 char TEX_opgrp = '{';
@@ -2984,7 +3386,11 @@ TeX_functions (inf)
          i = TEX_Token (lasthit);
          if (0 <= i)
            {
+             pfnote ((char *)NULL, TRUE,
+                     lb.buffer, strlen (lb.buffer), lineno, linecharno);
+#if TeX_named_tokens
              TEX_getit (lasthit, TEX_toktab[i].len);
+#endif
              break;            /* We only save a line once */
            }
        }
@@ -3079,6 +3485,7 @@ TEX_decode_env (evarname, defenv)
   return tab;
 }
 
+#if TeX_named_tokens
 /* Record a tag defined by a TeX command of length LEN and starting at NAME.
    The name being defined actually starts at (NAME + LEN + 1).
    But we seem to include the TeX command in the tag name.  */
@@ -3089,15 +3496,16 @@ TEX_getit (name, len)
 {
   char *p = name + len;
 
-  if (*name == 0)
+  if (*name == '\0')
     return;
 
   /* Let tag name extend to next group close (or end of line) */
   while (*p && *p != TEX_clgrp)
     p++;
-  pfnote (savenstr (name, p-name), TRUE, FALSE, lb.buffer,
-         strlen (lb.buffer), lineno, linecharno);
+  pfnote (savenstr (name, p-name), TRUE,
+         lb.buffer, strlen (lb.buffer), lineno, linecharno);
 }
+#endif
 
 /* If the text at CP matches one of the tag-defining TeX command names,
    return the pointer to the first occurrence of that command in TEX_toktab.
@@ -3116,109 +3524,415 @@ TEX_Token (cp)
   return -1;
 }
 \f
-/* Support for Prolog.  */
+/*
+ * Prolog support (rewritten) by Anders Lindgren, Mar. 96
+ *
+ * Assumes that the predicate starts at column 0.
+ * Only the first clause of a predicate is added. 
+ */
+void
+Prolog_functions (inf)
+     FILE *inf;
+{
+  int prolog_pred ();
+  void prolog_skip_comment ();
+
+  char * last;
+  int len;
+  int allocated;
+
+  allocated = 0;
+  len = 0;
+  last = NULL;
+
+  lineno = 0;
+  linecharno = 0;
+  charno = 0;
+
+  while (!feof (inf))
+    {
+      lineno++;
+      linecharno += charno;
+      charno = readline (&lb, inf);
+      dbp = lb.buffer;
+      if (dbp[0] == '\0')      /* Empty line */
+       continue;
+      else if (isspace (dbp[0])) /* Not a predicate */
+       continue;
+      else if (dbp[0] == '/' && dbp[1] == '*') /* comment. */
+       prolog_skip_comment (&lb, inf);
+      else if (len = prolog_pred (dbp, last)) 
+       {
+         /* Predicate.  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 = (char *) xrealloc(last, len + 1);
+         allocated = len + 1;
+         strncpy (last, dbp, len);
+         last[len] = '\0';
+       }
+    }
+}
+
 
-/* Whole head (not only functor, but also arguments)
-   is gotten in compound term. */
 void
-prolog_getit (s)
+prolog_skip_comment (plb, inf)
+     struct linebuffer *plb;
+     FILE *inf;
+{
+  char *cp;
+
+  do
+    {
+      for (cp = plb->buffer; *cp != '\0'; cp++)
+       if (cp[0] == '*' && cp[1] == '/')
+         return;
+      lineno++;
+      linecharno += readline (plb, inf);
+    }
+  while (!feof(inf));
+}
+
+/*
+ * A predicate definition is added if it matches:
+ *     <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.
+ */
+int
+prolog_pred (s, last)
      char *s;
+     char *last;               /* Name of last clause. */
 {
-  char *save_s;
-  int insquote, npar;
+  int prolog_atom();
+  int prolog_white();
 
-  save_s = s;
-  insquote = FALSE;
-  npar = 0;
-  while (1)
+  int pos;
+  int len;
+
+  pos = prolog_atom(s, 0);
+  if (pos < 1)
+    return 0;
+
+  len = pos;
+  pos += prolog_white(s, pos);
+
+  if ((s[pos] == '(') || (s[pos] == '.'))
     {
-      if (s[0] == '\0')                /* syntax error. */
-       return;
-      else if (insquote && s[0] == '\'' && s[1] == '\'')
-       s += 2;
-      else if (s[0] == '\'')
+      if (s[pos] == '(')
+       pos++;
+
+      /* Save only the first clause. */
+      if ((last == NULL) ||
+         (len != strlen(last)) ||
+         (strncmp(s, last, len) != 0))
        {
-         insquote = !insquote;
-         s++;
+         pfnote ((CTAGS) ? savenstr (s, len) : NULL, TRUE,
+                 s, pos, lineno, linecharno);
+         return len;
        }
-      else if (!insquote && s[0] == '(')
+    }
+  return 0;
+}
+
+/*
+ * Consume a Prolog atom.
+ * Return the number of bytes consumed, or -1 if there was an error.
+ *
+ * A prolog atom, in this context, could be one of:
+ * - An alphanumeric sequence, starting with a lower case letter.
+ * - A quoted arbitrary string. Single quotes can escape themselves.
+ *   Backslash quotes everything.
+ */
+int
+prolog_atom (s, pos)
+     char *s;
+     int pos;
+{
+  int origpos;
+
+  origpos = pos;
+
+  if (islower(s[pos]) || (s[pos] == '_'))
+    {
+      /* The atom is unquoted. */
+      pos++;
+      while (isalnum(s[pos]) || (s[pos] == '_'))
        {
-         npar++;
-         s++;
+         pos++;
        }
-      else if (!insquote && s[0] == ')')
+      return pos - origpos;
+    }
+  else if (s[pos] == '\'')
+    {
+      pos++;
+
+      while (1) 
        {
-         npar--;
-         s++;
-         if (npar == 0)
-           break;
-         else if (npar < 0)    /* syntax error. */
-           return;
-       }
-      else if (!insquote && s[0] == '.'
-              && (isspace (s[1]) || s[1] == '\0'))
-       {                       /* fullstop. */
-         if (npar != 0)        /* syntax error. */
-           return;
-         s++;
-         break;
+         if (s[pos] == '\'')
+           {
+             pos++;
+             if (s[pos] != '\'')
+               break;
+             pos++;            /* A double quote */
+           }
+         else if (s[pos] == '\0')
+           /* Multiline quoted atoms are ignored. */
+           return -1;
+         else if (s[pos] == '\\')
+           {
+             if (s[pos+1] == '\0')
+               return -1;
+             pos += 2;
+           }
+         else
+           pos++;
        }
-      else
-       s++;
+      return pos - origpos;
     }
-  pfnote (savenstr (save_s, s-save_s), TRUE, FALSE,
-         save_s, s-save_s, lineno, linecharno);
+  else
+    return -1;
 }
 
-/* It is assumed that prolog predicate starts from column 0. */
+/* Consume whitespace.  Return the number of bytes eaten. */
+int
+prolog_white (s, pos)
+     char *s;
+     int pos;
+{
+  int origpos;
+
+  origpos = pos;
+
+  while (isspace(s[pos]))
+    pos++;
+
+  return pos - origpos;
+}
+\f
+/* 
+ * Support for Erlang  --  Anders Lindgren, Feb 1996.
+ *
+ * Generates tags for functions, defines, and records.
+ *
+ * Assumes that Erlang functions start at column 0.
+ */
 void
-Prolog_functions (inf)
+Erlang_functions (inf)
      FILE *inf;
 {
-  void skip_comment (), prolog_getit ();
+  int erlang_func ();
+  void erlang_attribute ();
+
+  char * last;
+  int len;
+  int allocated;
+
+  allocated = 0;
+  len = 0;
+  last = NULL;
+
+  lineno = 0;
+  linecharno = 0;
+  charno = 0;
 
-  lineno = linecharno = charno = 0;
   while (!feof (inf))
     {
       lineno++;
       linecharno += charno;
-      charno = readline (&lb, inf) + 1;        /* 1 for newline. */
+      charno = readline (&lb, inf);
       dbp = lb.buffer;
-      if (isspace (dbp[0]))    /* not predicate header. */
+      if (dbp[0] == '\0')      /* Empty line */
        continue;
-      else if (dbp[0] == '%')  /* comment. */
+      else if (isspace (dbp[0])) /* Not function nor attribute */
        continue;
-      else if (dbp[0] == '/' && dbp[1] == '*') /* comment. */
-       skip_comment (&lb, inf, &lineno, &linecharno);
-      else                     /* found. */
-       prolog_getit (dbp);
+      else if (dbp[0] == '%')  /* comment */
+       continue;
+      else if (dbp[0] == '"')  /* Sometimes, strings start in column one */
+       continue;
+      else if (dbp[0] == '-')  /* attribute, e.g. "-define" */
+       {
+         erlang_attribute(dbp);
+         last = NULL;
+       }
+      else if (len = erlang_func (dbp, last)) 
+       {
+         /* 
+          * Function.  Store the function name so that we only
+          * generates a tag for the first clause.
+          */
+         if (last == NULL)
+           last = xnew(len + 1, char);
+         else if (len + 1 > allocated)
+           last = (char *) xrealloc(last, len + 1);
+         allocated = len + 1;
+         strncpy (last, dbp, len);
+         last[len] = '\0';
+       }
     }
 }
 
+
+/*
+ * A function definition is added if it matches:
+ *     <beginning of line><Erlang 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 function, or 0 if no function
+ * was found.
+ */
+int
+erlang_func (s, last)
+     char *s;
+     char *last;               /* Name of last clause. */
+{
+  int erlang_atom ();
+  int erlang_white ();
+
+  int pos;
+  int len;
+
+  pos = erlang_atom(s, 0);
+  if (pos < 1)
+    return 0;
+
+  len = pos;
+  pos += erlang_white(s, pos);
+
+  if (s[pos++] == '(')
+    {
+      /* Save only the first clause. */
+      if ((last == NULL) ||
+         (len != strlen(last)) ||
+         (strncmp(s, last, len) != 0))
+       {
+         pfnote ((CTAGS) ? savenstr (s, len) : NULL, TRUE,
+                 s, pos, lineno, linecharno);
+         return len;
+       }
+    }
+  return 0;
+}
+
+
+/*
+ * Handle attributes.  Currently, tags are generated for defines 
+ * and records.
+ *
+ * They are on the form:
+ * -define(foo, bar).
+ * -define(Foo(M, N), M+N).
+ * -record(graph, {vtab = notable, cyclic = true}).
+ */
 void
-skip_comment (plb, inf, plineno, plinecharno)
-     struct linebuffer *plb;
-     FILE *inf;
-     int *plineno;             /* result */
-     long *plinecharno;                /* result */
+erlang_attribute (s)
+     char *s;
 {
-  char *cp;
+  int erlang_atom ();
+  int erlang_white ();
 
-  do
+  int pos;
+  int len;
+
+  if ((strncmp(s, "-define", 7) == 0) ||
+      (strncmp(s, "-record", 7) == 0))
     {
-      for (cp = plb->buffer; *cp != '\0'; cp++)
-       if (cp[0] == '*' && cp[1] == '/')
-         return;
-      (*plineno)++;
-      *plinecharno += readline (plb, inf) + 1; /* 1 for newline. */
+      pos = 7;
+      pos += erlang_white(s, pos);
+
+      if (s[pos++] == '(') 
+       {
+         pos += erlang_white(s, pos);
+       
+         if (len = erlang_atom(s, pos))
+           {
+             pfnote ((CTAGS) ? savenstr (& s[pos], len) : NULL, TRUE,
+                     s, pos + len, lineno, linecharno);
+           }
+       }
     }
-  while (!feof(inf));
+  return;
+}
+
+
+/*
+ * Consume an Erlang atom (or variable).
+ * Return the number of bytes consumed, or -1 if there was an error.
+ */
+int
+erlang_atom (s, pos)
+     char *s;
+     int pos;
+{
+  int origpos;
+
+  origpos = pos;
+
+  if (isalpha (s[pos]) || s[pos] == '_')
+    {
+      /* The atom is unquoted. */
+      pos++;
+      while (isalnum (s[pos]) || s[pos] == '_')
+       pos++;
+      return pos - origpos;
+    }
+  else if (s[pos] == '\'')
+    {
+      pos++;
+
+      while (1) 
+       {
+         if (s[pos] == '\'')
+           {
+             pos++;
+             break;
+           }
+         else if (s[pos] == '\0')
+           /* Multiline quoted atoms are ignored. */
+           return -1;
+         else if (s[pos] == '\\')
+           {
+             if (s[pos+1] == '\0')
+               return -1;
+             pos += 2;
+           }
+         else
+           pos++;
+       }
+      return pos - origpos;
+    }
+  else
+    return -1;
+}
+
+/* Consume whitespace.  Return the number of bytes eaten */
+int
+erlang_white (s, pos)
+     char *s;
+     int pos;
+{
+  int origpos;
+
+  origpos = pos;
+
+  while (isspace (s[pos]))
+    pos++;
+
+  return pos - origpos;
 }
 \f
 #ifdef ETAGS_REGEXPS
 /* Take a string like "/blah/" and turn it into "blah", making sure
    that the first and last characters are the same, and handling
-   quoted separator characters.  Actually, stops on the occurence of
+   quoted separator characters.  Actually, stops on the occurrence of
    an unquoted separator.  Also turns "\t" into a Tab character.
    Returns pointer to terminating separator.  Works in place.  Null
    terminates name string. */
@@ -3279,7 +3993,7 @@ add_regex (regexp_pattern)
 
   if (regexp_pattern[0] == '\0')
     {
-      error ("missing regexp", 0);
+      error ("missing regexp", (char *)NULL);
       return;
     }
   if (regexp_pattern[strlen(regexp_pattern)-1] != regexp_pattern[0])
@@ -3290,7 +4004,7 @@ add_regex (regexp_pattern)
   name = scan_separators (regexp_pattern);
   if (regexp_pattern[0] == '\0')
     {
-      error ("null regexp", 0);
+      error ("null regexp", (char *)NULL);
       return;
     }
   (void) scan_separators (name);
@@ -3321,7 +4035,7 @@ add_regex (regexp_pattern)
 }
 
 /*
- * Do the subtitutions indicated by the regular expression and
+ * Do the substitutions indicated by the regular expression and
  * arguments.
  */
 char *
@@ -3329,65 +4043,40 @@ substitute (in, out, regs)
      char *in, *out;
      struct re_registers *regs;
 {
-  char *result = NULL, *t;
-  int size = 0;
+  char *result, *t;
+  int size, i;
+
+  result = NULL;
+  size = strlen (out);
 
   /* Pass 1: figure out how much size to allocate. */
-  for (t = out; *t; ++t)
-    {
-      if (*t == '\\')
-       {
-         ++t;
-         if (!*t)
-           {
-             fprintf (stderr, "%s: pattern subtitution ends prematurely\n",
-                      progname);
-             return NULL;
-           }
-         if (isdigit (*t))
-           {
-             int dig = *t - '0';
-             size += regs->end[dig] - regs->start[dig];
-           }
-       }
-    }
+  if (out[strlen (out) - 1] == '\\')
+    fatal ("pattern error in %s", out);
+  for (t = out; *t != '\0'; ++t)
+    if (*t == '\\' && isdigit (*++t))
+      {
+       int dig = *t - '0';
+       size += regs->end[dig] - regs->start[dig] - 2;
+      }
 
   /* Allocate space and do the substitutions. */
   result = xnew (size + 1, char);
-  size = 0;
-  for (; *out; ++out)
+  for (i = 0; *out != '\0'; ++out)
     {
-      if (*out == '\\')
+      if (*out == '\\' && isdigit (*++out))
        {
-         ++out;
-         if (isdigit (*out))
-           {
-             /* Using "dig2" satisfies my debugger.  Bleah. */
-             int dig2 = *out - '0';
-             strncpy (result + size, in + regs->start[dig2],
-                      regs->end[dig2] - regs->start[dig2]);
-             size += regs->end[dig2] - regs->start[dig2];
-           }
-         else
-           {
-             switch (*out)
-               {
-               case '\t':
-                 result[size++] = '\t';
-                 break;
-               case '\\':
-                 *out = '\\';
-                 break;
-               default:
-                 result[size++] = *out;
-                 break;
-               }
-           }
+         /* Using "dig2" satisfies my debugger.  Bleah. */
+         int dig2 = *out - '0';
+         int diglen = regs->end[dig2] - regs->start[dig2];
+         strncpy (result + i, in + regs->start[dig2], diglen);
+         i += diglen;
        }
       else
-       result[size++] = *out;
+       result[i++] = *out;
     }
-  result[size] = '\0';
+  result[i] = '\0';
+  if (DEBUG && i > size)
+    abort ();
 
   return result;
 }
@@ -3432,15 +4121,25 @@ readline_internal (linebuffer, stream)
        }
       if (c == EOF)
        {
+         *p = '\0';
          chars_deleted = 0;
          break;
        }
       if (c == '\n')
        {
-         if (p[-1] == '\r' && p > buffer)
+         if (p > buffer && p[-1] == '\r')
            {
              *--p = '\0';
+#ifdef DOS_NT
+            /* Assume CRLF->LF translation will be performed by Emacs
+               when loading this file, so CRs won't appear in the buffer.
+               It would be cleaner to compensate within Emacs;
+               however, Emacs does not know how many CRs were deleted
+               before any given point in the file.  */
+             chars_deleted = 1;
+#else
              chars_deleted = 2;
+#endif
            }
          else
            {
@@ -3465,10 +4164,10 @@ readline (linebuffer, stream)
      FILE *stream;
 {
   /* Read new line. */
-  int i;
   long result = readline_internal (linebuffer, stream);
-
 #ifdef ETAGS_REGEXPS
+  int i;
+
   /* Match against all listed patterns. */
   for (i = 0; i < num_patterns; ++i)
     {
@@ -3496,14 +4195,14 @@ readline (linebuffer, stream)
                                       patterns[i].name_pattern,
                                       &patterns[i].regs);
              if (name != NULL)
-               pfnote (name, TRUE, TRUE, linebuffer->buffer,
-                       match, lineno, linecharno);
+               pfnote (name, TRUE,
+                       linebuffer->buffer, match, lineno, linecharno);
            }
          else
            {
              /* Make an unnamed tag. */
-             pfnote (NULL, TRUE, FALSE, linebuffer->buffer,
-                     match, lineno, linecharno);
+             pfnote ((char *)NULL, TRUE,
+                     linebuffer->buffer, match, lineno, linecharno);
            }
          break;
        }
@@ -3521,6 +4220,9 @@ void
 just_read_file (inf)
      FILE *inf;
 {
+  lineno = 0;
+  charno = 0;
+
   while (!feof (inf))
     {
       ++lineno;
@@ -3615,6 +4317,14 @@ pfatal (s1)
   exit (BAD);
 }
 
+void
+suggest_asking_for_help ()
+{
+  fprintf (stderr, "\tTry `%s --help' for a complete list of options.\n",
+          progname);
+  exit (BAD);
+}
+
 /* Print error message.  `s1' is printf control string, `s2' is arg for it. */
 void
 error (s1, s2)
@@ -3643,40 +4353,48 @@ concat (s1, s2, s3)
 }
 \f
 /* Does the same work as the system V getcwd, but does not need to
-   guess buffer size in advance. */
+   guess the buffer size in advance. */
 char *
 etags_getcwd ()
-#ifdef DOS_NT
-{
-  char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS.  */
-
-  getwd (path);
-  p = path;
-  while (*p)
-    if (*p == '\\')
-      *p++ = '/';
-    else
-      *p++ = tolower (*p);
-
-  return strdup (path);
-}
-#elif HAVE_GETCWD /* not DOS_NT */
 {
+#ifdef HAVE_GETCWD
   int bufsize = 200;
   char *path = xnew (bufsize, char);
 
   while (getcwd (path, bufsize) == NULL)
     {
       if (errno != ERANGE)
-       pfatal ("pwd");
+       pfatal ("getcwd");
       bufsize *= 2;
       path = xnew (bufsize, char);
     }
 
+#if WINDOWSNT
+  {
+    /* Convert backslashes to slashes.  */
+    char *p;
+    for (p = path; *p != '\0'; p++)
+      if (*p == '\\')
+       *p = '/';
+  }
+#endif
+
   return path;
-}
-#else /* not DOS_NT and not HAVE_GETCWD */
-{
+
+#else /* not HAVE_GETCWD */
+#ifdef MSDOS
+  char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS.  */
+
+  getwd (path);
+
+  for (p = path; *p != '\0'; p++)
+    if (*p == '\\')
+      *p = '/';
+    else
+      *p = lowcase (*p);
+
+  return strdup (path);
+#else /* not MSDOS */
   struct linebuffer path;
   FILE *pipe;
 
@@ -3687,46 +4405,49 @@ etags_getcwd ()
   pclose (pipe);
 
   return path.buffer;
+#endif /* not MSDOS */
+#endif /* not HAVE_GETCWD */
 }
-#endif /* not DOS_NT and not HAVE_GETCWD */
 
-/* Return a newly allocated string containing the filename
+/* Return a newly allocated string containing the file name
    of FILE relative to the absolute directory DIR (which
    should end with a slash). */
 char *
 relative_filename (file, dir)
      char *file, *dir;
 {
-  char *fp, *dp, *res;
+  char *fp, *dp, *abs, *res;
+  int i;
 
-  /* Find the common root of file and dir. */
-  fp = absolute_filename (file, cwd);
+  /* Find the common root of file and dir (with a trailing slash). */
+  abs = absolute_filename (file, cwd);
+  fp = abs;
   dp = dir;
   while (*fp++ == *dp++)
     continue;
-  do
-    {
-      fp--;
-      dp--;
-    }
+  fp--, dp--;                  /* back to the first differing char */
+  do                           /* look at the equal chars until '/' */
+    fp--, dp--;
   while (*fp != '/');
 
-  /* Build a sequence of "../" strings for the resulting relative filename. */
-  for (dp = etags_strchr (dp + 1, '/'), res = "";
-       dp != NULL;
-       dp = etags_strchr (dp + 1, '/'))
-    {
-      res = concat (res, "../", "");
-    }
+  /* Build a sequence of "../" strings for the resulting relative file name. */
+  i = 0;
+  while ((dp = etags_strchr (dp + 1, '/')) != NULL)
+    i += 1;
+  res = xnew (3*i + strlen (fp + 1) + 1, char);
+  res[0] = '\0';
+  while (i-- > 0)
+    strcat (res, "../");
 
-  /* Add the filename relative to the common root of file and dir. */
-  res = concat (res, fp + 1, "");
+  /* Add the file name relative to the common root of file and dir. */
+  strcat (res, fp + 1);
+  free (abs);
 
-  return res;                  /* temporary stub */
+  return res;
 }
 
 /* Return a newly allocated string containing the
-   absolute filename of FILE given CWD (which should
+   absolute file name of FILE given CWD (which should
    end with a slash). */
 char *
 absolute_filename (file, cwd)
@@ -3734,8 +4455,14 @@ absolute_filename (file, cwd)
 {
   char *slashp, *cp, *res;
 
-  if (file[0] == '/')
-    res = concat (file, "", "");
+  if (absolutefn (file))
+    res = savestr (file);
+#ifdef DOS_NT
+  /* We don't support non-absolute file names with a drive
+     letter, like `d:NAME' (it's too much hassle).  */
+  else if (file[1] == ':')
+    fatal ("%s: relative file names with drive letters not supported", file);
+#endif
   else
     res = concat (cwd, file, "");
 
@@ -3751,18 +4478,17 @@ absolute_filename (file, cwd)
              cp = slashp;
              do
                cp--;
-             while (cp >= res && *cp != '/');
-             if (*cp == '/')
-               {
-                 strcpy (cp, slashp + 3);
-               }
-             else              /* else (cp == res) */
-               {
-                 if (slashp[3] != '\0')
-                   strcpy (cp, slashp + 4);
-                 else
-                   return ".";
-               }
+             while (cp >= res && !absolutefn (cp));
+             if (cp < res)
+               cp = slashp;    /* the absolute name begins with "/.." */
+#ifdef DOS_NT
+             /* Under MSDOS and NT we get `d:/NAME' as absolute
+                file name, so the luser could say `d:/../NAME'.
+                We silently treat this as `d:/NAME'.  */
+             else if (cp[0] != '/')
+               cp = slashp;
+#endif
+             strcpy (cp, slashp + 3);
              slashp = cp;
              continue;
            }
@@ -3775,12 +4501,15 @@ absolute_filename (file, cwd)
 
       slashp = etags_strchr (slashp + 1, '/');
     }
-
-  return res;
+  
+  if (res[0] == '\0')
+    return savestr ("/");
+  else
+    return res;
 }
 
 /* Return a newly allocated string containing the absolute
-   filename of dir where FILE resides given CWD (which should
+   file name of dir where FILE resides given CWD (which should
    end with a slash). */
 char *
 absolute_dirname (file, cwd)
@@ -3788,10 +4517,17 @@ absolute_dirname (file, cwd)
 {
   char *slashp, *res;
   char save;
+#ifdef DOS_NT
+  char *p;
+
+  for (p = file; *p != '\0'; p++)
+    if (*p == '\\')
+      *p = '/';
+#endif
 
   slashp = etags_strrchr (file, '/');
   if (slashp == NULL)
-    return cwd;
+    return savestr (cwd);
   save = slashp[1];
   slashp[1] = '\0';
   res = absolute_filename (file, cwd);
@@ -3800,24 +4536,35 @@ absolute_dirname (file, cwd)
   return res;
 }
 
+/* Increase the size of a linebuffer. */
+void
+grow_linebuffer (bufp, toksize)
+     struct linebuffer *bufp;
+     int toksize;
+{
+  while (bufp->size < toksize)
+    bufp->size *= 2;
+  bufp->buffer = (char *) xrealloc (bufp->buffer, bufp->size);
+}
+
 /* Like malloc but get fatal error if memory is exhausted.  */
-char *
+long *
 xmalloc (size)
      unsigned int size;
 {
-  char *result = (char *) malloc (size);
+  long *result = (long *) malloc (size);
   if (result == NULL)
-    fatal ("virtual memory exhausted", 0);
+    fatal ("virtual memory exhausted", (char *)NULL);
   return result;
 }
 
-char *
+long *
 xrealloc (ptr, size)
      char *ptr;
      unsigned int size;
 {
-  char *result = (char *) realloc (ptr, size);
+  long *result =  (long *) realloc (ptr, size);
   if (result == NULL)
-    fatal ("virtual memory exhausted");
+    fatal ("virtual memory exhausted", (char *)NULL);
   return result;
 }