view src/termcap.c @ 98644:e1cc41b9282d

2008-10-12 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-edit-fixed-width-region): Exclude final newline from picture area. * org-export-latex.el (org-export-latex-subcontent): Add labels to sections, to make internal links work. (org-export-latex-fontify-headline): Do not remove all text properties, to make sure that target properties survive this process. * org-exp.el (org-export-preprocess-string): Change sequence of modifications, to make sure links are prepared before the LaTeX conversions do happen. * org-attach.el (org-attach-delete-all): Renamed from `org-attch-delete'. Add a security query before deleting the entire directory. New optional argument FORCE can overrule the security query. (org-attach-delete-one): New command. * org-attach.el (org-attach-file-list): Fix bug with directory. * org.el (org-apps-regexp-alist): New function. (org-file-apps): Add auto-mode to the default value. (org-open-file): Use the new structure of org-file-apps. * org-attach.el (org-attach): Support the new keys. (org-attach-method): New option. * org-bbdb.el (org-bbdb-anniversaries): Fix but with 29 Feb/1 March. * org.el (org-remove-uniherited-tags): Fix reverse interpretation of the list value o `org-use-tag-inheritance'. * org-attach.el (org-attach-auto-tag): New option. (org-attach-tag, org-attach-untag): New functions. (org-attach-attach, org-attach-new, org-attach-sync): Call `org-attach-tag'. (org-attach-delete): Call `org-attach-untag'. * org-attach.el: New file. * org-table.el (orgtbl-self-insert-command): Make this work for the keypad as well. * org.el (org-add-log-setup): Limit searc for drawers to entry text, not to subtree. * org-clock.el (org-clock-heading-for-remember): New variable. (org-clock-in): Set `org-clock-heading-for-remember'. 2008-10-12 James TD Smith <ahktenzero@mohorovi.cc> * org-remember.el (org-remember-apply-template): Add new expansions: %k, %K for currently clocked task and a link to the currently clocked task, and %< to file notes in the currently clocked task. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-export-latex.el (org-export-latex-make-header): Also insert the content of the property :latex-header-extra. * org-exp.el (org-infile-export-plist): Put the content of #+LATEX_HEADER: into the property :latex-header-extra. * org-colview.el (org-columns-get-format-and-top-level): Remove resetting the marker. * org-colview-xemacs.el (org-columns-get-format-and-top-level): Remove resetting the marker. * org.el (org-entry-property-inherited-from): Improve docstring. (org-entry-get-with-inheritance): Reset marker before starting the search. * org-exp.el (org-infile-export-plist): Allow multiple STYLE lines. * org.el (org-entry-get-multivalued-property) (org-entry-protect-space, org-entry-restore-space): New functions. (org-file-apps-defaults-macosx): Let postscript files be opened by preview. (org-time-stamp-inactive): Call `org-time-stamp'. (org-time-stamp): New argument `inactive'. Also edit inacive stamps. Convert time stamp type. (org-open-file): Interpret the `default' value for the `command' in `org-file-apps'. * org-id.el (org-id-int-to-b36-one-digit) (org-id-b36-to-int-one-digit, org-id-int-to-b36) (org-id-b36-to-int, org-id-time-to-b36): Modified from b62 to b36. * org-id.el (org-id-reverse-string): New function. (org-id-new): Use `org-id-reverse-string' to make sure the beginning chars of the ID are mutating fast. This allows to use a directory structure to spread things better. (org-id-prefix): Changed default to nil. * org-list.el (org-move-item-down, org-move-item-up): Remember and restore the column of the cursor position. * org-remember.el (org-remember-apply-template): Remove properties from `initial'. * org-wl.el (org-wl-open): Remove useless call to `wl-thread-open-all'. * org-remember.el (org-remember-handler): Fix bug with `bottom' location. * org-bbdb.el (org-bbdb-anniversaries): Require bbdb in `org-bbdb-anniversaries'. * org.el (org-get-next-sibling, org-forward-same-level): New functions, similar to the outline versions, but invisible headings are OK. 2008-10-12 Bastien Guerry <bzg@altern.org> * org.el (org-auto-repeat-maybe): Insert a space between the timestamp's type and the timestamp itself. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-table.el (org-table-sum): Do not format the result with %g, it does rounding when there are too many digits. * org.el (org-map-entries): Protect the keyword-selecting variables. 2008-10-12 Bastien Guerry <bzg@altern.org> * org-agenda.el (org-agenda-to-appt): Make sure the function check against all agenda files. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-list.el: New file, aggregating list functions from org.el and org-export-latex.el. * org.el (org-edit-src-region-extra): New option. * org-agenda.el (org-agenda-to-appt): Fix bug with appointment time before 1am. 2008-10-12 Bastien Guerry <bzg@altern.org> * org-export-latex.el (org-export-latex-keywords-maybe): Bug fix. 2008-10-12 James TA Smith <ahktenzero@mohorovi.cc> * org-plot.el (org-plot/gnuplot): Make tables starting with a hline work correctly. (org-plot/gnuplot-script): Put commas at the end of each script line. * org.el (org-get-refile-targets): Replace links with their descriptions (org-imenu-get-tree): Replace links with their descriptions. * org-remember.el (org-remember-apply-template): Add a new expansion for adding properties to remember items. * org.el (org-add-log-setup): Skip over drawers (properties, clocks etc) when adding notes. * org-agenda.el (org-agenda-get-closed): show durations of clocked items as well as the start and end times. * org-compat.el (org-get-x-clipboard-compat): Add a compat function for fetching the X clipboard on XEmacs and GNU Emacs 21. * org-remember.el (org-get-x-clipboard): Use the compat function to get clipboard values when x-selection-value is unavailable. Use substring-no-properties instead of set-text-properties to remove text properties from the clipboard value. * lisp/org-clock.el (org-update-mode-line): Support limiting the modeline clock string, and display the full todo value in the tooltip. Set a local keymap so mouse-3 on the clock string goes to the currently clocked task. (org-clock-string-limit): Add a custom value for the maximum length of the clock string in the modeline. (org-clock-mode-map): Add a keymap for the modeline string 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-compat.el (org-propertize): New function. 2008-10-12 Bastien Guerry <bzg@altern.org> * org-export-latex.el (org-export-latex-tables): protect exported tables from further special chars conversion. (org-export-latex-preprocess): Preserve LaTeX environments. (org-list-parse-list): Parse descriptive lists. (org-list-to-generic, org-list-to-latex, org-list-to-html) (org-list-to-texinfo): Export descriptive lists. (org-quote-chars): Remove. (org-export-latex-keywords-maybe): Use `replace-regexp-in-string'. (org-export-latex-list-beginning-re): Rename to `org-list-beginning-re' (org-list-item-begin): Rename to `org-list-item-beginning' 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org.el (org-refile): Allow refiling to the last entry in the buffer. (org-get-tags-at): Fix bug when inheritance is turned off. * org.el (org-indent-line-function): No longer check for src regions, this is too much overhead. * org-agenda.el (org-agenda-highlight-todo): Fix bugs with keyword matching. * org.el (org-scan-tags): Make sure that tags matching is not case sensitive. TODO keyword matching is case sensitive, however, to avoid confusion with similar words that are not meant to be keywords. * org.el (org-get-local-tags-at): New function. (org-get-local-tags): New function. * org-exp.el (org-export-get-categories): New function. * org-agenda.el (org-sorting-choice) (org-agenda-sorting-strategy, org-agenda-get-todos) (org-agenda-get-timestamps, org-agenda-get-deadlines) (org-agenda-get-scheduled, org-agenda-get-blocks) (org-entries-lessp): Implement sorting by TODO state. (org-cmp-todo-state): New defsubst. * org-colview.el (org-colview-construct-allowed-dates): New function. (org-columns-next-allowed-value): Use `org-colview-construct-allowed-dates'. * org-colview-xemacs.el (org-colview-construct-allowed-dates): New function. (org-columns-next-allowed-value): Use `org-colview-construct-allowed-dates'. * org.el (org-protect-slash): New function. (org-get-refile-targets): Use `org-protect-slash'. * org-agenda.el (org-global-tags-completion-table): New variable. * org-exp.el (org-export-handle-export-tags): New function. (org-export-preprocess-string): Call `org-export-handle-export-tags'. * org-plot.el: New file. * org-publish.el (org-publish-expand-components): Function removed. (org-publish-expand-projects): Allow components to have components. * org.el (org-indent-line-function): Do not indent in regions that are external source code. (org-yank-and-fold-if-subtree): New function. * org-agenda.el (org-agenda-todayp): New function. (org-agenda-get-deadlines, org-agenda-get-scheduled): Use `org-agenda-todayp'. * org.el (org-insert-heading-respect-content) (org-insert-todo-heading-respect-content): New commands. (org-insert-heading-respect-content): New option. (org-insert-heading): Respect `org-insert-heading-respect-content'. * org-clock.el (org-clock-find-position): Make sure the note after the clock line gets moved into the new clock drawer. * org-id.el (org-id-new): New option. * org-table.el (org-table-copy-down): Avoid overflow during increment. Use prefix argument 0 to temporarily disable the increment. * org-exp.el (org-export-as-html): Do not turn on the major mode if the buffer will be killed anyway. (org-get-current-options): Exclude the #+TEXT field. (org-export-as-html): Make sure text before the first headline is a paragraph. * org-publish.el (org-publish-org-to): Tell the exporter that this buffer will be killed, so it is not necessary to do major mode initialization. * org-archive.el (org-archive-to-archive-sibling): Show empty lines after folding the archive sibling. * org.el (org-log-note-extra): New variable. 2008-10-12 Bastien Guerry <bzg@altern.org> * org.el (org-additional-option-like-keywords): Added keywords for the _QUOTE, _VERSE and _SRC environments. * org-export-latex.el (org-export-latex-preprocess): Fix bug when exporting _QUOTE and _VERSE environments. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-agenda.el (org-agenda-filter-by-tag): New command. * org-exp.el (org-get-current-options): Remove angular brackets from the date entry. * org.el (org-edit-fixed-width-region): New function. (org-edit-fixed-width-region): Also try `org-edit-fixed-width-region'. (org-edit-fixed-width-region-mode): New option. (org-activate-code): Only interprete lines starting with colon plus a space as example lines. * org-remember.el (org-remember-templates): Add nil instead of empty strings to fix the length of remember templates. * org-table.el (org-calc-default-modes): Fix the time format for calc, from 12 hour to 24 hour clock. * org-agenda.el (org-agenda-get-deadlines) (org-agenda-get-scheduled): Avoid `time-of-day' extraction for entries that are pre-warnings of deadlines or reminders. * org.el (org-sort-entries-or-items): Make numeric and alpha comparisons ignore any TODO keyword and priority cookie. * org-remember.el (org-remember-handler): Reinterpretation of the prefix argument. * org-agenda.el (org-agenda-get-scheduled): Use new `org-scheduled' face. * org-faces.el (org-scheduled): New face. * org-wl.el (org-wl-open): Remove incorrect declaration. * org-gnus.el (org-gnus-store-link): Support for :to information in gnus links. * org-exp.el (org-export-as-html): Fixed typo in creator information. (org-export-protect-examples): New parameter indent. Insert extra spaces only when this parameter is specified. (org-export-preprocess-string): Call `org-export-protect-examples' with an indentation parameter when exporting to ASCII. * org-remember.el (org-remember-templates) (org-remember-apply-template): Allow the file component to be a function. * org.el (org-goto-local-search-headings): Renamed from `org-goto-local-search-forward-headings'. Added the possibility to search backwards. * org-export-latex.el (org-export-latex): New customization group. * org-agenda.el (org-write-agenda): Erase buffer for txt export. * org-exp.el (org-html-do-expand): Allow {} to terminate tex macro * org.el (org-buffer-list): Select buffers based on major mode, not on file name. * org-agenda.el (org-agenda-align-tags): Fix bug with malformed face property. * org-colview.el (org-columns-display-here): Use `org-columns-modify-value-for-display-function'. * org-colview-xemacs.el (org-columns-display-here): Use `org-columns-modify-value-for-display-function'. * org.el (org-columns-modify-value-for-display-function): New option. * org-publish.el (org-publish-file): Make sure the directory match for the publishing directory works correctly. * org-agenda.el (org-agenda-execute-calendar-command) (org-agenda-diary-entry): Additional optional argument.
author Carsten Dominik <dominik@science.uva.nl>
date Sun, 12 Oct 2008 06:12:44 +0000
parents c3512b2085a0
children e038c1a8307c
line wrap: on
line source

/* Work-alike for termcap, plus extra features.
   Copyright (C) 1985, 1986, 1993, 1994, 1995, 2000, 2001, 2002, 2003,
                 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
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; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.  */

/* Emacs config.h may rename various library functions such as malloc.  */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef emacs

#include <lisp.h>		/* xmalloc is here */
/* Get the O_* definitions for open et al.  */
#include <sys/file.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#else /* not emacs */

#ifdef STDC_HEADERS
#include <stdlib.h>
#include <string.h>
#else
char *getenv ();
char *malloc ();
char *realloc ();
#endif

/* Do this after the include, in case string.h prototypes bcopy.  */
#if (defined(HAVE_STRING_H) || defined(STDC_HEADERS)) && !defined(bcopy)
#define bcopy(s, d, n) memcpy ((d), (s), (n))
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#endif /* not emacs */

#ifndef NULL
#define NULL (char *) 0
#endif

#ifndef O_RDONLY
#define O_RDONLY 0
#endif

/* BUFSIZE is the initial size allocated for the buffer
   for reading the termcap file.
   It is not a limit.
   Make it large normally for speed.
   Make it variable when debugging, so can exercise
   increasing the space dynamically.  */

#ifndef BUFSIZE
#ifdef DEBUG
#define BUFSIZE bufsize

int bufsize = 128;
#else
#define BUFSIZE 2048
#endif
#endif

#ifndef TERMCAP_FILE
#define TERMCAP_FILE "/etc/termcap"
#endif

#ifndef emacs
static void
memory_out ()
{
  write (2, "virtual memory exhausted\n", 25);
  exit (1);
}

static char *
xmalloc (size)
     unsigned size;
{
  register char *tem = malloc (size);

  if (!tem)
    memory_out ();
  return tem;
}

static char *
xrealloc (ptr, size)
     char *ptr;
     unsigned size;
{
  register char *tem = realloc (ptr, size);

  if (!tem)
    memory_out ();
  return tem;
}
#endif /* not emacs */

/* Looking up capabilities in the entry already found.  */

/* The pointer to the data made by tgetent is left here
   for tgetnum, tgetflag and tgetstr to find.  */
static char *term_entry;

static char *tgetst1 ();

/* Search entry BP for capability CAP.
   Return a pointer to the capability (in BP) if found,
   0 if not found.  */

static char *
find_capability (bp, cap)
     register char *bp, *cap;
{
  for (; *bp; bp++)
    if (bp[0] == ':'
	&& bp[1] == cap[0]
	&& bp[2] == cap[1])
      return &bp[4];
  return NULL;
}

int
tgetnum (cap)
     char *cap;
{
  register char *ptr = find_capability (term_entry, cap);
  if (!ptr || ptr[-1] != '#')
    return -1;
  return atoi (ptr);
}

int
tgetflag (cap)
     char *cap;
{
  register char *ptr = find_capability (term_entry, cap);
  return ptr && ptr[-1] == ':';
}

/* Look up a string-valued capability CAP.
   If AREA is non-null, it points to a pointer to a block in which
   to store the string.  That pointer is advanced over the space used.
   If AREA is null, space is allocated with `malloc'.  */

char *
tgetstr (cap, area)
     char *cap;
     char **area;
{
  register char *ptr = find_capability (term_entry, cap);
  if (!ptr || (ptr[-1] != '=' && ptr[-1] != '~'))
    return NULL;
  return tgetst1 (ptr, area);
}

#ifdef IS_EBCDIC_HOST
/* Table, indexed by a character in range 0200 to 0300 with 0200 subtracted,
   gives meaning of character following \, or a space if no special meaning.
   Sixteen characters per line within the string.  */

static char esctab[]
  = " \057\026  \047\014         \
     \025   \015      \
   \005 \013          \
                ";
#else
/* Table, indexed by a character in range 0100 to 0140 with 0100 subtracted,
   gives meaning of character following \, or a space if no special meaning.
   Eight characters per line within the string.  */

static char esctab[]
  = " \007\010  \033\014 \
      \012 \
  \015 \011 \013 \
        ";
#endif

/* PTR points to a string value inside a termcap entry.
   Copy that value, processing \ and ^ abbreviations,
   into the block that *AREA points to,
   or to newly allocated storage if AREA is NULL.
   Return the address to which we copied the value,
   or NULL if PTR is NULL.  */

static char *
tgetst1 (ptr, area)
     char *ptr;
     char **area;
{
  register char *p, *r;
  register int c;
  register int size;
  char *ret;
  register int c1;

  if (!ptr)
    return NULL;

  /* `ret' gets address of where to store the string.  */
  if (!area)
    {
      /* Compute size of block needed (may overestimate).  */
      p = ptr;
      while ((c = *p++) && c != ':' && c != '\n')
	;
      ret = (char *) xmalloc (p - ptr + 1);
    }
  else
    ret = *area;

  /* Copy the string value, stopping at null or colon.
     Also process ^ and \ abbreviations.  */
  p = ptr;
  r = ret;
  while ((c = *p++) && c != ':' && c != '\n')
    {
      if (c == '^')
	{
	  c = *p++;
	  if (c == '?')
	    c = 0177;
	  else
	    c &= 037;
	}
      else if (c == '\\')
	{
	  c = *p++;
	  if (c >= '0' && c <= '7')
	    {
	      c -= '0';
	      size = 0;

	      while (++size < 3 && (c1 = *p) >= '0' && c1 <= '7')
		{
		  c *= 8;
		  c += c1 - '0';
		  p++;
		}
	    }
#ifdef IS_EBCDIC_HOST
	  else if (c >= 0200 && c < 0360)
	    {
	      c1 = esctab[(c & ~0100) - 0200];
	      if (c1 != ' ')
		c = c1;
	    }
#else
	  else if (c >= 0100 && c < 0200)
	    {
	      c1 = esctab[(c & ~040) - 0100];
	      if (c1 != ' ')
		c = c1;
	    }
#endif
	}
      *r++ = c;
    }

  /* Sometimes entries have "%pN" which means use parameter N in the
     next %-substitution.  If all such N are continuous in the range
     [1,9] we can remove each "%pN" because they are redundant, thus
     reducing bandwidth requirements.  True, Emacs is well beyond the
     days of 150baud teletypes, but some of its users aren't much so.

     This pass could probably be integrated into the one above but
     abbreviation expansion makes that effort a little more hairy than
     its worth; this is cleaner.  */
  {
    register int last_p_param = 0;
    int remove_p_params = 1;
    struct { char *beg; int len; } cut[11];

    for (cut[0].beg = p = ret; p < r - 3; p++)
      {
	if (!remove_p_params)
	  break;
	if (*p == '%' && *(p + 1) == 'p')
	  {
	    if (*(p + 2) - '0' == 1 + last_p_param)
	      {
		cut[last_p_param].len = p - cut[last_p_param].beg;
		last_p_param++;
		p += 3;
		cut[last_p_param].beg = p;
	      }
	    else				/* not continuous: bail */
	      remove_p_params = 0;
	    if (last_p_param > 10)		/* too many: bail */
	      remove_p_params = 0;
	  }
      }
    if (remove_p_params && last_p_param)
      {
	register int i;
	char *wp;

	cut[last_p_param].len = r - cut[last_p_param].beg;
	for (i = 0, wp = ret; i <= last_p_param; wp += cut[i++].len)
	  bcopy (cut[i].beg, wp, cut[i].len);
	r = wp;
      }
  }

  *r = '\0';
  /* Update *AREA.  */
  if (area)
    *area = r + 1;
  return ret;
}

/* Outputting a string with padding.  */

#ifndef emacs
short ospeed;
/* If OSPEED is 0, we use this as the actual baud rate.  */
int tputs_baud_rate;
#endif

char PC;

#ifndef emacs
/* Actual baud rate if positive;
   - baud rate / 100 if negative.  */

static int speeds[] =
  {
    0, 50, 75, 110, 135, 150, -2, -3, -6, -12,
    -18, -24, -48, -96, -192, -288, -384, -576, -1152
  };

#endif /* not emacs */

void
tputs (str, nlines, outfun)
     register char *str;
     int nlines;
     register int (*outfun) ();
{
  register int padcount = 0;
  register int speed;

#ifdef emacs
  extern EMACS_INT baud_rate;
  speed = baud_rate;
  /* For quite high speeds, convert to the smaller
     units to avoid overflow.  */
  if (speed > 10000)
    speed = - speed / 100;
#else
  if (ospeed == 0)
    speed = tputs_baud_rate;
  else
    speed = speeds[ospeed];
#endif

  if (!str)
    return;

  while (*str >= '0' && *str <= '9')
    {
      padcount += *str++ - '0';
      padcount *= 10;
    }
  if (*str == '.')
    {
      str++;
      padcount += *str++ - '0';
    }
  if (*str == '*')
    {
      str++;
      padcount *= nlines;
    }
  while (*str)
    (*outfun) (*str++);

  /* PADCOUNT is now in units of tenths of msec.
     SPEED is measured in characters per 10 seconds
     or in characters per .1 seconds (if negative).
     We use the smaller units for larger speeds to avoid overflow.  */
  padcount *= speed;
  padcount += 500;
  padcount /= 1000;
  if (speed < 0)
    padcount = -padcount;
  else
    {
      padcount += 50;
      padcount /= 100;
    }

  while (padcount-- > 0)
    (*outfun) (PC);
}

/* Finding the termcap entry in the termcap data base.  */

struct termcap_buffer
  {
    char *beg;
    int size;
    char *ptr;
    int ateof;
    int full;
  };

/* Forward declarations of static functions.  */

static int scan_file ();
static char *gobble_line ();
static int compare_contin ();
static int name_match ();

#ifdef MSDOS /* MW, May 1993 */
static int
valid_filename_p (fn)
     char *fn;
{
  return *fn == '/' || fn[1] == ':';
}
#else
#define valid_filename_p(fn) (*(fn) == '/')
#endif

/* Find the termcap entry data for terminal type NAME
   and store it in the block that BP points to.
   Record its address for future use.

   If BP is null, space is dynamically allocated.

   Return -1 if there is some difficulty accessing the data base
   of terminal types,
   0 if the data base is accessible but the type NAME is not defined
   in it, and some other value otherwise.  */

int
tgetent (bp, name)
     char *bp, *name;
{
  register char *termcap_name;
  register int fd;
  struct termcap_buffer buf;
  register char *bp1;
  char *tc_search_point;
  char *term;
  int malloc_size = 0;
  register int c;
  char *tcenv = NULL;		/* TERMCAP value, if it contains :tc=.  */
  char *indirect = NULL;	/* Terminal type in :tc= in TERMCAP value.  */
  int filep;

#ifdef INTERNAL_TERMINAL
  /* For the internal terminal we don't want to read any termcap file,
     so fake it.  */
  if (!strcmp (name, "internal"))
    {
      term = INTERNAL_TERMINAL;
      if (!bp)
	{
	  malloc_size = 1 + strlen (term);
	  bp = (char *) xmalloc (malloc_size);
	}
      strcpy (bp, term);
      goto ret;
    }
#endif /* INTERNAL_TERMINAL */

  /* For compatibility with programs like `less' that want to
     put data in the termcap buffer themselves as a fallback.  */
  if (bp)
    term_entry = bp;

  termcap_name = getenv ("TERMCAP");
  if (termcap_name && *termcap_name == '\0')
    termcap_name = NULL;
#if defined (MSDOS) && !defined (TEST)
  if (termcap_name && (*termcap_name == '\\'
		       || *termcap_name == '/'
		       || termcap_name[1] == ':'))
    dostounix_filename(termcap_name);
#endif

  filep = termcap_name && valid_filename_p (termcap_name);

  /* If termcap_name is non-null and starts with / (in the un*x case, that is),
     it is a file name to use instead of /etc/termcap.
     If it is non-null and does not start with /,
     it is the entry itself, but only if
     the name the caller requested matches the TERM variable.  */

  if (termcap_name && !filep && !strcmp (name, getenv ("TERM")))
    {
      indirect = tgetst1 (find_capability (termcap_name, "tc"), (char **) 0);
      if (!indirect)
	{
	  if (!bp)
	    bp = termcap_name;
	  else
	    strcpy (bp, termcap_name);
	  goto ret;
	}
      else
	{			/* It has tc=.  Need to read /etc/termcap.  */
	  tcenv = termcap_name;
 	  termcap_name = NULL;
	}
    }

  if (!termcap_name || !filep)
    termcap_name = TERMCAP_FILE;

  /* Here we know we must search a file and termcap_name has its name.  */

#ifdef MSDOS
  fd = open (termcap_name, O_RDONLY|O_TEXT, 0);
#else
  fd = open (termcap_name, O_RDONLY, 0);
#endif
  if (fd < 0)
    return -1;

  buf.size = BUFSIZE;
  /* Add 1 to size to ensure room for terminating null.  */
  buf.beg = (char *) xmalloc (buf.size + 1);
  term = indirect ? indirect : name;

  if (!bp)
    {
      malloc_size = indirect ? strlen (tcenv) + 1 : buf.size;
      bp = (char *) xmalloc (malloc_size);
    }
  tc_search_point = bp1 = bp;

  if (indirect)
    /* Copy the data from the environment variable.  */
    {
      strcpy (bp, tcenv);
      bp1 += strlen (tcenv);
    }

  while (term)
    {
      /* Scan the file, reading it via buf, till find start of main entry.  */
      if (scan_file (term, fd, &buf) == 0)
	{
	  close (fd);
	  free (buf.beg);
	  if (malloc_size)
	    free (bp);
	  return 0;
	}

      /* Free old `term' if appropriate.  */
      if (term != name)
	free (term);

      /* If BP is malloc'd by us, make sure it is big enough.  */
      if (malloc_size)
	{
	  int offset1 = bp1 - bp, offset2 = tc_search_point - bp;
	  malloc_size = offset1 + buf.size;
	  bp = termcap_name = (char *) xrealloc (bp, malloc_size);
	  bp1 = termcap_name + offset1;
	  tc_search_point = termcap_name + offset2;
	}

      /* Copy the line of the entry from buf into bp.  */
      termcap_name = buf.ptr;
      while ((*bp1++ = c = *termcap_name++) && c != '\n')
	/* Drop out any \ newline sequence.  */
	if (c == '\\' && *termcap_name == '\n')
	  {
	    bp1--;
	    termcap_name++;
	  }
      *bp1 = '\0';

      /* Does this entry refer to another terminal type's entry?
	 If something is found, copy it into heap and null-terminate it.  */
      tc_search_point = find_capability (tc_search_point, "tc");
      term = tgetst1 (tc_search_point, (char **) 0);
    }

  close (fd);
  free (buf.beg);

  if (malloc_size)
    bp = (char *) xrealloc (bp, bp1 - bp + 1);

 ret:
  term_entry = bp;
  return 1;
}

/* Given file open on FD and buffer BUFP,
   scan the file from the beginning until a line is found
   that starts the entry for terminal type STR.
   Return 1 if successful, with that line in BUFP,
   or 0 if no entry is found in the file.  */

static int
scan_file (str, fd, bufp)
     char *str;
     int fd;
     register struct termcap_buffer *bufp;
{
  register char *end;

  bufp->ptr = bufp->beg;
  bufp->full = 0;
  bufp->ateof = 0;
  *bufp->ptr = '\0';

  lseek (fd, 0L, 0);

  while (!bufp->ateof)
    {
      /* Read a line into the buffer.  */
      end = NULL;
      do
	{
	  /* if it is continued, append another line to it,
	     until a non-continued line ends.  */
	  end = gobble_line (fd, bufp, end);
	}
      while (!bufp->ateof && end[-2] == '\\');

      if (*bufp->ptr != '#'
	  && name_match (bufp->ptr, str))
	return 1;

      /* Discard the line just processed.  */
      bufp->ptr = end;
    }
  return 0;
}

/* Return nonzero if NAME is one of the names specified
   by termcap entry LINE.  */

static int
name_match (line, name)
     char *line, *name;
{
  register char *tem;

  if (!compare_contin (line, name))
    return 1;
  /* This line starts an entry.  Is it the right one?  */
  for (tem = line; *tem && *tem != '\n' && *tem != ':'; tem++)
    if (*tem == '|' && !compare_contin (tem + 1, name))
      return 1;

  return 0;
}

static int
compare_contin (str1, str2)
     register char *str1, *str2;
{
  register int c1, c2;
  while (1)
    {
      c1 = *str1++;
      c2 = *str2++;
      while (c1 == '\\' && *str1 == '\n')
	{
	  str1++;
	  while ((c1 = *str1++) == ' ' || c1 == '\t');
	}
      if (c2 == '\0')
	{
	  /* End of type being looked up.  */
	  if (c1 == '|' || c1 == ':')
	    /* If end of name in data base, we win.  */
	    return 0;
	  else
	    return 1;
        }
      else if (c1 != c2)
	return 1;
    }
}

/* Make sure that the buffer <- BUFP contains a full line
   of the file open on FD, starting at the place BUFP->ptr
   points to.  Can read more of the file, discard stuff before
   BUFP->ptr, or make the buffer bigger.

   Return the pointer to after the newline ending the line,
   or to the end of the file, if there is no newline to end it.

   Can also merge on continuation lines.  If APPEND_END is
   non-null, it points past the newline of a line that is
   continued; we add another line onto it and regard the whole
   thing as one line.  The caller decides when a line is continued.  */

static char *
gobble_line (fd, bufp, append_end)
     int fd;
     register struct termcap_buffer *bufp;
     char *append_end;
{
  register char *end;
  register int nread;
  register char *buf = bufp->beg;
  register char *tem;

  if (!append_end)
    append_end = bufp->ptr;

  while (1)
    {
      end = append_end;
      while (*end && *end != '\n') end++;
      if (*end)
        break;
      if (bufp->ateof)
	return buf + bufp->full;
      if (bufp->ptr == buf)
	{
	  if (bufp->full == bufp->size)
	    {
	      bufp->size *= 2;
	      /* Add 1 to size to ensure room for terminating null.  */
	      tem = (char *) xrealloc (buf, bufp->size + 1);
	      bufp->ptr = (bufp->ptr - buf) + tem;
	      append_end = (append_end - buf) + tem;
	      bufp->beg = buf = tem;
	    }
	}
      else
	{
	  append_end -= bufp->ptr - buf;
	  bcopy (bufp->ptr, buf, bufp->full -= bufp->ptr - buf);
	  bufp->ptr = buf;
	}
      if (!(nread = read (fd, buf + bufp->full, bufp->size - bufp->full)))
	bufp->ateof = 1;
      bufp->full += nread;
      buf[bufp->full] = '\0';
    }
  return end + 1;
}

#ifdef TEST

#ifdef NULL
#undef NULL
#endif

#include <stdio.h>

main (argc, argv)
     int argc;
     char **argv;
{
  char *term;
  char *buf;

  term = argv[1];
  printf ("TERM: %s\n", term);

  buf = (char *) tgetent (0, term);
  if ((int) buf <= 0)
    {
      printf ("No entry.\n");
      return 0;
    }

  printf ("Entry: %s\n", buf);

  tprint ("cm");
  tprint ("AL");

  printf ("co: %d\n", tgetnum ("co"));
  printf ("am: %d\n", tgetflag ("am"));
}

tprint (cap)
     char *cap;
{
  char *x = tgetstr (cap, 0);
  register char *y;

  printf ("%s: ", cap);
  if (x)
    {
      for (y = x; *y; y++)
	if (*y <= ' ' || *y == 0177)
	  printf ("\\%0o", *y);
	else
	  putchar (*y);
      free (x);
    }
  else
    printf ("none");
  putchar ('\n');
}

#endif /* TEST */

/* arch-tag: c2e8d427-2271-4fac-95fe-411857238b80
   (do not change this comment) */