home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / src / fileio.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-02-14  |  68.4 KB  |  2,549 lines

  1. /* File IO for GNU Emacs.
  2.    Copyright (C) 1985-1993 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. #include "config.h"
  21. #include "lisp.h"
  22. #include "buffer.h"
  23. #include "window.h"
  24. #include "insdel.h"
  25.  
  26. #include <stdio.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <pwd.h>
  30. #include <ctype.h>
  31. #include <errno.h>
  32. #include <sys/param.h>
  33.  
  34. #ifndef VMS
  35. extern int errno;
  36. extern char *sys_errlist[];
  37. extern int sys_nerr;
  38. #endif
  39.  
  40. #include <sys/time.h>
  41.  
  42. #ifdef USG5_4
  43. #include <sys/dirent.h>
  44. #else
  45. #include <sys/dir.h>
  46. #endif
  47.  
  48. #ifdef VMS
  49. #include <perror.h>
  50. #include <file.h>
  51. #include <rmsdef.h>
  52. #include <fab.h>
  53. #include <nam.h>
  54. #endif
  55.  
  56. #ifdef NEED_TIME_H
  57. #include <time.h>
  58. #else /* not NEED_TIME_H */
  59. #ifdef HAVE_TIMEVAL
  60. #include <sys/time.h>
  61. #endif /* HAVE_TIMEVAL */
  62. #endif /* not NEED_TIME_H */
  63.  
  64. #ifdef HPUX_NET
  65. #include <netio.h>
  66. #include <errnet.h>
  67. #endif
  68.  
  69. #define min(a, b) ((a) < (b) ? (a) : (b))
  70. #define max(a, b) ((a) > (b) ? (a) : (b))
  71.  
  72. extern unsigned int lisp_to_word ();
  73. extern Lisp_Object Fcurrent_time_seconds ();
  74.  
  75. /* set by e_write() */
  76. static int e_write_errno;
  77.  
  78. /* Nonzero during writing of auto-save files */
  79. static int auto_saving;
  80.  
  81. /* Set by auto_save_1 to mode of original file so Fwrite_region will create
  82.    a new file with the same mode as the original */
  83. static int auto_save_mode_bits;
  84.  
  85. /* On VMS, nonzero means write new files with record format stmlf.
  86.    Zero means use var format.  */
  87. int vms_stmlf_recfm;
  88.  
  89. Lisp_Object Qfile_error, Qfile_already_exists;
  90.  
  91. void
  92. report_file_error (string, data)
  93.      const char *string;
  94.      Lisp_Object data;
  95. {
  96.   Lisp_Object errstring;
  97.  
  98.   if (errno >= 0 && errno < sys_nerr)
  99.     errstring = build_string (sys_errlist[errno]);
  100.   else
  101.     errstring = build_string ("undocumented error code");
  102.  
  103.   /* System error messages are capitalized.  Downcase the initial
  104.      unless it is followed by a slash.  */
  105.   if (XSTRING (errstring)->data[1] != '/')
  106.     XSTRING (errstring)->data[0] = DOWNCASE (XSTRING (errstring)->data[0]);
  107.  
  108.   while (1)
  109.     Fsignal (Qfile_error,
  110.          Fcons (build_string (string), Fcons (errstring, data)));
  111. }
  112.  
  113. DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
  114.   1, 1, 0,
  115.   "Return the directory component in file name NAME.\n\
  116. Return nil if NAME does not include a directory.\n\
  117. Otherwise return a directory spec.\n\
  118. Given a Unix syntax file name, returns a string ending in slash;\n\
  119. on VMS, perhaps instead a string ending in `:', `]' or `>'.")
  120.   (file)
  121.      Lisp_Object file;
  122. {
  123.   register char *beg;
  124.   register char *p;
  125.  
  126.   CHECK_STRING (file, 0);
  127.  
  128.   beg = (char *) XSTRING (file)->data;
  129.   p = beg + XSTRING (file)->size;
  130.  
  131.   while (p != beg && p[-1] != '/'
  132. #ifdef VMS
  133.      && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
  134. #endif /* VMS */
  135.      ) p--;
  136.  
  137.   if (p == beg)
  138.     return Qnil;
  139.   return make_string (beg, p - beg);
  140. }
  141.  
  142. DEFUN ("file-name-nondirectory", Ffile_name_nondirectory, Sfile_name_nondirectory,
  143.   1, 1, 0,
  144.   "Return file name NAME sans its directory.\n\
  145. For example, in a Unix-syntax file name,\n\
  146. this is everything after the last slash,\n\
  147. or the entire name if it contains no slash.")
  148.   (file)
  149.      Lisp_Object file;
  150. {
  151.   register char *beg, *p, *end;
  152.  
  153.   CHECK_STRING (file, 0);
  154.  
  155.   beg = (char *) XSTRING (file)->data;
  156.   end = p = beg + XSTRING (file)->size;
  157.  
  158.   while (p != beg && p[-1] != '/'
  159. #ifdef VMS
  160.      && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
  161. #endif /* VMS */
  162.      ) p--;
  163.  
  164.   return make_string (p, end - p);
  165. }
  166.  
  167. static char *
  168. file_name_as_directory (out, in)
  169.      char *out, *in;
  170. {
  171.   int size = strlen (in) - 1;
  172.  
  173.   strcpy (out, in);
  174.  
  175. #ifdef VMS
  176.   /* Is it already a directory string? */
  177.   if (in[size] == ':' || in[size] == ']' || in[size] == '>')
  178.     return out;
  179.   /* Is it a VMS directory file name?  If so, hack VMS syntax.  */
  180.   else if (! index (in, '/')
  181.        && ((size > 3 && ! strcmp (&in[size - 3], ".DIR"))
  182.            || (size > 3 && ! strcmp (&in[size - 3], ".dir"))
  183.            || (size > 5 && (! strncmp (&in[size - 5], ".DIR", 4)
  184.                 || ! strncmp (&in[size - 5], ".dir", 4))
  185.            && (in[size - 1] == '.' || in[size - 1] == ';')
  186.            && in[size] == '1')))
  187.     {
  188.       register char *p, *dot;
  189.       char brack;
  190.  
  191.       /* x.dir -> [.x]
  192.      dir:x.dir --> dir:[x]
  193.      dir:[x]y.dir --> dir:[x.y] */
  194.       p = in + size;
  195.       while (p != in && *p != ':' && *p != '>' && *p != ']') p--;
  196.       if (p != in)
  197.     {
  198.       strncpy (out, in, p - in);
  199.       out[p - in] = '\0';
  200.       if (*p == ':')
  201.         {
  202.           brack = ']';
  203.           strcat (out, ":[");
  204.         }
  205.       else
  206.         {
  207.           brack = *p;
  208.           strcat (out, ".");
  209.         }
  210.       p++;
  211.     }
  212.       else
  213.     {
  214.       brack = ']';
  215.       strcpy (out, "[.");
  216.     }
  217.       if (dot = index (p, '.'))
  218.     {
  219.       /* blindly remove any extension */
  220.       size = strlen (out) + (dot - p);
  221.       strncat (out, p, dot - p);
  222.     }
  223.       else
  224.     {
  225.       strcat (out, p);
  226.       size = strlen (out);
  227.     }
  228.       out[size++] = brack;
  229.       out[size] = '\0';
  230.     }
  231. #else /* not VMS */
  232.   /* For Unix syntax, Append a slash if necessary */
  233.   if (out[size] != '/')
  234.     strcat (out, "/");
  235. #endif /* not VMS */
  236.   return out;
  237. }
  238.  
  239. DEFUN ("file-name-as-directory", Ffile_name_as_directory,
  240.        Sfile_name_as_directory, 1, 1, 0,
  241.   "Return a string representing file FILENAME interpreted as a directory.\n\
  242. This operation exists because a directory is also a file, but its name as\n\
  243. a directory is different from its name as a file.\n\
  244. The result can be used as the value of `default-directory'\n\
  245. or passed as second argument to `expand-file-name'.\n\
  246. For a Unix-syntax file name, just appends a slash.\n\
  247. On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc.")
  248.   (file)
  249.      Lisp_Object file;
  250. {
  251.   char *buf;
  252.  
  253.   CHECK_STRING (file, 0);
  254.   if (NILP (file))
  255.     return Qnil;
  256.   buf = (char *) alloca (XSTRING (file)->size + 10);
  257.   return build_string (file_name_as_directory (buf, (char *) XSTRING (file)->data));
  258. }
  259.  
  260. /*
  261.  * Convert from directory name to filename.
  262.  * On VMS:
  263.  *       xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
  264.  *       xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
  265.  * On UNIX, it's simple: just make sure there is a terminating /
  266.  
  267.  * Value is nonzero if the string output is different from the input.
  268.  */
  269.  
  270. static int
  271. directory_file_name (src, dst)
  272.      const char *src;
  273.      char *dst;
  274. {
  275.   long slen;
  276. #ifdef VMS
  277.   long rlen;
  278.   char * ptr, * rptr;
  279.   char bracket;
  280.   struct FAB fab = cc$rms_fab;
  281.   struct NAM nam = cc$rms_nam;
  282.   char esa[NAM$C_MAXRSS];
  283. #endif /* VMS */
  284.  
  285.   slen = strlen (src) - 1;
  286. #ifdef VMS
  287.   if (! index (src, '/')
  288.       && (src[slen] == ']' || src[slen] == ':' || src[slen] == '>'))
  289.     {
  290.       /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
  291.       fab.fab$l_fna = src;
  292.       fab.fab$b_fns = slen + 1;
  293.       fab.fab$l_nam = &nam;
  294.       fab.fab$l_fop = FAB$M_NAM;
  295.  
  296.       nam.nam$l_esa = esa;
  297.       nam.nam$b_ess = sizeof esa;
  298.       nam.nam$b_nop |= NAM$M_SYNCHK;
  299.  
  300.       /* We call SYS$PARSE to handle such things as [--] for us. */
  301.       if (SYS$PARSE(&fab, 0, 0) == RMS$_NORMAL)
  302.     {
  303.       slen = nam.nam$b_esl - 1;
  304.       if (esa[slen] == ';' && esa[slen - 1] == '.')
  305.         slen -= 2;
  306.       esa[slen + 1] = '\0';
  307.       src = esa;
  308.     }
  309.       if (src[slen] != ']' && src[slen] != '>')
  310.     {
  311.       /* what about when we have logical_name:???? */
  312.       if (src[slen] == ':')
  313.         {            /* Xlate logical name and see what we get */
  314.           ptr = strcpy (dst, src); /* upper case for getenv */
  315.           while (*ptr)
  316.         {
  317.           if ('a' <= *ptr && *ptr <= 'z')
  318.             *ptr -= 040;
  319.           ptr++;
  320.         }
  321.           dst[slen] = 0;    /* remove colon */
  322.           if (!(src = egetenv (dst)))
  323.         return 0;
  324.           /* should we jump to the beginning of this procedure?
  325.          Good points: allows us to use logical names that xlate
  326.          to Unix names,
  327.          Bad points: can be a problem if we just translated to a device
  328.          name...
  329.          For now, I'll punt and always expect VMS names, and hope for
  330.          the best! */
  331.           slen = strlen (src) - 1;
  332.           if (src[slen] != ']' && src[slen] != '>')
  333.         { /* no recursion here! */
  334.           strcpy (dst, src);
  335.           return 0;
  336.         }
  337.         }
  338.       else
  339.         {        /* not a directory spec */
  340.           strcpy (dst, src);
  341.           return 0;
  342.         }
  343.     }
  344.       bracket = src[slen];
  345.       if (!(ptr = index (src, bracket - 2)))
  346.     { /* no opening bracket */
  347.       strcpy (dst, src);
  348.       return 0;
  349.     }
  350.       if (!(rptr = rindex (src, '.')))
  351.     rptr = ptr;
  352.       slen = rptr - src;
  353.       strncpy (dst, src, slen);
  354.       dst[slen] = '\0';
  355.       if (*rptr == '.')
  356.     {
  357.       dst[slen++] = bracket;
  358.       dst[slen] = '\0';
  359.     }
  360.       else
  361.     {
  362.       /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
  363.          then translate the device and recurse. */
  364.       if (dst[slen - 1] == ':'
  365.           && dst[slen - 2] != ':'    /* skip decnet nodes */
  366.           && strcmp(src + slen, "[000000]") == 0)
  367.         {
  368.           dst[slen - 1] = '\0';
  369.           if ((ptr = egetenv (dst))
  370.           && (rlen = strlen (ptr) - 1) > 0
  371.           && (ptr[rlen] == ']' || ptr[rlen] == '>')
  372.           && ptr[rlen - 1] == '.')
  373.         {
  374.           ptr[rlen - 1] = ']';
  375.           ptr[rlen] = '\0';
  376.           return directory_file_name (ptr, dst);
  377.         }
  378.           else
  379.         dst[slen - 1] = ':';
  380.         }
  381.       strcat (dst, "[000000]");
  382.       slen += 8;
  383.     }
  384.       rptr++;
  385.       rlen = strlen (rptr) - 1;
  386.       strncat (dst, rptr, rlen);
  387.       dst[slen + rlen] = '\0';
  388.       strcat (dst, ".DIR.1");
  389.       return 1;
  390.     }
  391. #endif /* VMS */
  392.   /* Process as Unix format: just remove any final slash.
  393.      But leave "/" unchanged; do not change it to "".  */
  394.   strcpy (dst, src);
  395.   if (dst[slen] == '/' && slen > 1)
  396.     dst[slen] = 0;
  397.   return 1;
  398. }
  399.  
  400. DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
  401.   1, 1, 0,
  402.   "Returns the file name of the directory named DIR.\n\
  403. This is the name of the file that holds the data for the directory DIR.\n\
  404. This operation exists because a directory is also a file, but its name as\n\
  405. a directory is different from its name as a file.\n\
  406. In Unix-syntax, this function just removes the final slash.\n\
  407. On VMS, given a VMS-syntax directory name such as \"[X.Y]\",\n\
  408. it returns a file name such as \"[X]Y.DIR.1\".")
  409.   (directory)
  410.      Lisp_Object directory;
  411. {
  412.   char *buf;
  413.  
  414.   CHECK_STRING (directory, 0);
  415.  
  416.   if (NILP (directory))
  417.     return Qnil;
  418. #ifdef VMS
  419.   /* 20 extra chars is insufficient for VMS, since we might perform a
  420.      logical name translation. an equivalence string can be up to 255
  421.      chars long, so grab that much extra space...  - sss */
  422.   buf = (char *) alloca (XSTRING (directory)->size + 20 + 255);
  423. #else
  424.   buf = (char *) alloca (XSTRING (directory)->size + 20);
  425. #endif
  426.   directory_file_name ((char *) XSTRING (directory)->data, buf);
  427.   return build_string (buf);
  428. }
  429.  
  430. DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
  431.   "Generate temporary file name (string) starting with PREFIX (a string).\n\
  432. The Emacs process number forms part of the result,\n\
  433. so there is no danger of generating a name being used by another process.")
  434.   (prefix)
  435.      Lisp_Object prefix;
  436. {
  437.   Lisp_Object val;
  438.   val = concat2 (prefix, build_string ("XXXXXX"));
  439.   mktemp ((char *)XSTRING (val)->data);
  440.   return val;
  441. }
  442.  
  443.  
  444. DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
  445.   "Convert FILENAME to absolute, and canonicalize it.\n\
  446. Second arg DEFAULT is directory to start with if FILENAME is relative\n\
  447.  (does not start with slash); if DEFAULT is nil or missing,\n\
  448. the current buffer's value of default-directory is used.\n\
  449. Path components that are `.' are removed, and \n\
  450. path components followed by `..' are removed, along with the `..' itself;\n\
  451. note that these simplifications are done without checking the resulting\n\
  452. paths in the file system.\n\
  453. An initial `~/' expands to your home directory.\n\
  454. An initial `~USER/' expands to USER's home directory.\n\
  455. See also the function `substitute-in-file-name'.")
  456.      (name, defalt)
  457.      Lisp_Object name, defalt;
  458. {
  459.   unsigned char *nm;
  460.   
  461.   register unsigned char *newdir, *p, *o;
  462.   int tlen;
  463.   unsigned char *target;
  464.   struct passwd *pw;
  465.   int lose;
  466. #ifdef VMS
  467.   unsigned char * colon = 0;
  468.   unsigned char * close = 0;
  469.   unsigned char * slash = 0;
  470.   unsigned char * brack = 0;
  471.   int lbrack = 0, rbrack = 0;
  472.   int dots = 0;
  473. #endif /* VMS */
  474.   
  475.   CHECK_STRING (name, 0);
  476.  
  477. #ifdef VMS
  478.   /* Filenames on VMS are always upper case.  */
  479.   name = Fupcase (name);
  480. #endif
  481.  
  482.   nm = XSTRING (name)->data;
  483.   
  484.   /* If nm is absolute, flush ...// and detect /./ and /../.
  485.      If no /./ or /../ we can return right away. */
  486.   if (
  487.       nm[0] == '/'
  488. #ifdef VMS
  489.       || index (nm, ':')
  490. #endif /* VMS */
  491.       )
  492.     {
  493.       p = nm;
  494.       lose = 0;
  495.       while (*p)
  496.     {
  497.       /* Since we know the path is absolute, we can assume that each
  498.          element starts with a "/".  */
  499.  
  500.       /* "//" anywhere isn't necessarily hairy; we just start afresh
  501.          with the second slash.  */
  502.       if (p[0] == '/' && p[1] == '/'
  503. #ifdef APOLLO
  504.           /* // at start of filename is meaningful on Apollo system */
  505.           && nm != p
  506. #endif /* APOLLO */
  507.           )
  508.         nm = p + 1;
  509.  
  510.       /* "~" is hairy as the start of any path element.  */
  511.       if (p[0] == '/' && p[1] == '~')
  512.         nm = p + 1, lose = 1;
  513.  
  514.       /* "." and ".." are hairy.  */
  515.       if (p[0] == '/' && p[1] == '.'
  516.           && (p[2] == '/' || p[2] == 0
  517.           || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
  518.         lose = 1;
  519. #ifdef VMS
  520.       if (p[0] == '\\')
  521.         lose = 1;
  522.       if (p[0] == '/') {
  523.         /* if dev:[dir]/, move nm to / */
  524.         if (!slash && p > nm && (brack || colon)) {
  525.           nm = (brack ? brack + 1 : colon + 1);
  526.           lbrack = rbrack = 0;
  527.           brack = 0;
  528.           colon = 0;
  529.         }
  530.         slash = p;
  531.       }
  532.       if (p[0] == '-')
  533. #ifndef VMS4_4
  534.         /* VMS pre V4.4,convert '-'s in filenames. */
  535.         if (lbrack == rbrack)
  536.           {
  537.         if (dots < 2)    /* this is to allow negative version numbers */
  538.           p[0] = '_';
  539.           }
  540.         else
  541. #endif /* VMS4_4 */
  542.           if (lbrack > rbrack &&
  543.           ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<') &&
  544.            (p[1] == '.' || p[1] == ']' || p[1] == '>')))
  545.         lose = 1;
  546. #ifndef VMS4_4
  547.           else
  548.         p[0] = '_';
  549. #endif /* VMS4_4 */
  550.       /* count open brackets, reset close bracket pointer */
  551.       if (p[0] == '[' || p[0] == '<')
  552.         lbrack++, brack = 0;
  553.       /* count close brackets, set close bracket pointer */
  554.       if (p[0] == ']' || p[0] == '>')
  555.         rbrack++, brack = p;
  556.       /* detect ][ or >< */
  557.       if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
  558.         lose = 1;
  559.       if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
  560.         nm = p + 1, lose = 1;
  561.       if (p[0] == ':' && (colon || slash))
  562.         /* if dev1:[dir]dev2:, move nm to dev2: */
  563.         if (brack)
  564.           {
  565.         nm = brack + 1;
  566.         brack = 0;
  567.           }
  568.         /* if /pathname/dev:, move nm to dev: */
  569.         else if (slash)
  570.           nm = slash + 1;
  571.         /* if node::dev:, move colon following dev */
  572.         else if (colon && colon[-1] == ':')
  573.           colon = p;
  574.         /* if dev1:dev2:, move nm to dev2: */
  575.         else if (colon && colon[-1] != ':')
  576.           {
  577.         nm = colon + 1;
  578.         colon = 0;
  579.           }
  580.       if (p[0] == ':' && !colon)
  581.         {
  582.           if (p[1] == ':')
  583.         p++;
  584.           colon = p;
  585.         }
  586.       if (lbrack == rbrack)
  587.         if (p[0] == ';')
  588.           dots = 2;
  589.         else if (p[0] == '.')
  590.           dots++;
  591. #endif /* VMS */
  592.       p++;
  593.     }
  594.       if (!lose)
  595.     {
  596. #ifdef VMS
  597.       if (index (nm, '/'))
  598.         return build_string (sys_translate_unix (nm));
  599. #endif /* VMS */
  600.       if (nm == XSTRING (name)->data)
  601.         return name;
  602.       return build_string ((char *) nm);
  603.     }
  604.     }
  605.  
  606.   /* Now determine directory to start with and put it in newdir */
  607.  
  608.   newdir = 0;
  609.  
  610.   if (nm[0] == '~')        /* prefix ~ */
  611.     if (nm[1] == '/'
  612. #ifdef VMS
  613.     || nm[1] == ':'
  614. #endif /* VMS */
  615.     || nm[1] == 0)        /* ~ by itself */
  616.       {
  617.     if (!(newdir = (unsigned char *) egetenv ("HOME")))
  618.       newdir = (unsigned char *) "";
  619.     nm++;
  620. #ifdef VMS
  621.     nm++;            /* Don't leave the slash in nm.  */
  622. #endif /* VMS */
  623.       }
  624.     else            /* ~user/filename */
  625.       {
  626.     for (p = nm; *p && (*p != '/'
  627. #ifdef VMS
  628.                 && *p != ':'
  629. #endif /* VMS */
  630.                 ); p++);
  631.     o = (unsigned char *) alloca (p - nm + 1);
  632.     memcpy (o, (char *) nm, p - nm);
  633.     o [p - nm] = 0;
  634.  
  635.     pw = (struct passwd *) getpwnam ((char *) o + 1);
  636.     if (!pw)
  637.       error ("\"%s\" isn't a registered user", o + 1);
  638.  
  639. #ifdef VMS
  640.     nm = p + 1;        /* skip the terminator */
  641. #else
  642.     nm = p;
  643. #endif /* VMS */
  644.     newdir = (unsigned char *) pw -> pw_dir;
  645.       }
  646.  
  647.   if (nm[0] != '/'
  648. #ifdef VMS
  649.       && !index (nm, ':')
  650. #endif /* not VMS */
  651.       && !newdir)
  652.     {
  653.       if (NILP (defalt))
  654.     defalt = current_buffer->directory;
  655.       CHECK_STRING (defalt, 1);
  656.       newdir = XSTRING (defalt)->data;
  657.     }
  658.  
  659.   /* Now concatenate the directory and name to new space in the stack frame */
  660.  
  661.   tlen = ((newdir ? strlen ((char *) newdir) + 1 : 0)
  662.       + strlen ((char *) nm) + 1);
  663.   target = (unsigned char *) alloca (tlen);
  664.   *target = 0;
  665.  
  666.   if (newdir)
  667.     {
  668. #ifndef VMS
  669.       if (nm[0] == 0 || nm[0] == '/')
  670.     strcpy ((char *) target, (char *) newdir);
  671.       else
  672. #endif
  673.       file_name_as_directory ((char *) target, (char *) newdir);
  674.     }
  675.  
  676.   strcat ((char *) target, (char *) nm);
  677. #ifdef VMS
  678.   if (index (target, '/'))
  679.     strcpy (target, sys_translate_unix (target));
  680. #endif /* VMS */
  681.  
  682.   /* Now canonicalize by removing /. and /foo/.. if they appear.  */
  683.  
  684.   p = target;
  685.   o = target;
  686.  
  687.   while (*p)
  688.     {
  689. #ifdef VMS
  690.       if (*p != ']' && *p != '>' && *p != '-')
  691.     {
  692.       if (*p == '\\')
  693.         p++;
  694.       *o++ = *p++;
  695.     }
  696.       else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
  697.     /* brackets are offset from each other by 2 */
  698.     {
  699.       p += 2;
  700.       if (*p != '.' && *p != '-' && o[-1] != '.')
  701.         /* convert [foo][bar] to [bar] */
  702.         while (o[-1] != '[' && o[-1] != '<')
  703.           o--;
  704.       else if (*p == '-' && *o != '.')
  705.         *--p = '.';
  706.     }
  707.       else if (p[0] == '-' && o[-1] == '.' &&
  708.            (p[1] == '.' || p[1] == ']' || p[1] == '>'))
  709.     /* flush .foo.- ; leave - if stopped by '[' or '<' */
  710.     {
  711.       do
  712.         o--;
  713.       while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
  714.       if (p[1] == '.')    /* foo.-.bar ==> bar*/
  715.         p += 2;
  716.       else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
  717.         p++, o--;
  718.       /* else [foo.-] ==> [-] */
  719.     }
  720.       else
  721.     {
  722. #ifndef VMS4_4
  723.       if (*p == '-' &&
  724.           o[-1] != '[' && o[-1] != '<' && o[-1] != '.' &&
  725.           p[1] != ']' && p[1] != '>' && p[1] != '.')
  726.         *p = '_';
  727. #endif /* VMS4_4 */
  728.       *o++ = *p++;
  729.     }
  730. #else /* not VMS */
  731.       if (*p != '/')
  732.      {
  733.       *o++ = *p++;
  734.     }
  735.       else if (!strncmp ((char *) p, "//", 2)
  736. #ifdef APOLLO
  737.            /* // at start of filename is meaningful in Apollo system */
  738.            && o != target
  739. #endif /* APOLLO */
  740.            )
  741.     {
  742.       o = target;
  743.       p++;
  744.     }
  745.       else if (p[0] == '/'
  746.                && p[1] == '.'
  747.                && (p[2] == '/' || p[2] == 0))
  748.     {
  749.       /* If "/." is the entire filename, keep the "/".  Otherwise,
  750.          just delete the whole "/.".  */
  751.       if (o == target && p[2] == '\0')
  752.         *o++ = *p;
  753.       p += 2;
  754.     }
  755.       else if (!strncmp ((char *) p, "/..", 3)
  756.            /* `/../' is the "superroot" on certain file systems.  */
  757.            && o != target
  758.            && (p[3] == '/' || p[3] == 0))
  759.     {
  760.       while (o != target && *--o != '/')
  761.         ;
  762. #ifdef APOLLO
  763.       if (o == target + 1 && o[-1] == '/' && o[0] == '/')
  764.         ++o;
  765.       else
  766. #endif /* APOLLO */
  767.       if (o == target && *o == '/')
  768.         ++o;
  769.       p += 3;
  770.     }
  771.       else
  772.      {
  773.       *o++ = *p++;
  774.     }
  775. #endif /* not VMS */
  776.     }
  777.  
  778.   return make_string ((char *) target, o - target);
  779. }
  780.  
  781. extern char *realpath ();
  782. extern int errno;
  783.  
  784. DEFUN ("truename", Ftruename, Struename, 1, 2, 0,
  785.   "Returns the canonical name of the given FILE.\n\
  786. Second arg DEFAULT is directory to start with if FILE is relative\n\
  787.  (does not start with slash); if DEFAULT is nil or missing,\n\
  788.  the current buffer's value of default-directory is used.\n\
  789. No component of the resulting pathname will be a symbolic link, as\n\
  790.  in the realpath() function.\n\
  791. If the file does not exist, or is otherwise unable to be resolved,\n\
  792.  nil is returned.")
  793.      (name, defalt)
  794.      Lisp_Object name, defalt;
  795. {
  796.   struct gcpro gcpro1, gcpro2;
  797.   char resolved_path[MAXPATHLEN];
  798.   Lisp_Object expanded_name = Qnil;
  799.  
  800.   CHECK_STRING (name, 0);
  801.  
  802.   GCPRO2 (name, expanded_name);
  803.   expanded_name = Fexpand_file_name (name, defalt);
  804.   UNGCPRO;
  805.  
  806.   if (!(STRINGP (expanded_name))) return Qnil;
  807.  
  808.   if (XSTRING (expanded_name)->size >= sizeof (resolved_path))
  809.     while (1)
  810.       Fsignal (Qfile_error,
  811.            Fcons (build_string ("Finding realpath"),
  812.               Fcons (build_string ("pathame too long"),
  813.                  Fcons (expanded_name, Qnil))));
  814.  
  815.   memset (resolved_path, 0, sizeof (resolved_path));
  816.   errno = 0;
  817.  
  818. #ifdef VMS
  819.   if (NILP (Ffile_exists_p (expanded_name)))
  820.     return Qnil;
  821.   strncpy (resolved_path, (char *) XSTRING (expanded_name)->data,
  822.        XSTRING (expanded_name)->size + 1);
  823. #else
  824.   if (! realpath ((char *) XSTRING (expanded_name)->data, resolved_path))
  825.     return Qnil;
  826. #endif
  827.   return build_string (resolved_path);
  828. }
  829.  
  830.  
  831. DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
  832.   Ssubstitute_in_file_name, 1, 1, 0,
  833.   "Substitute environment variables referred to in FILENAME.\n\
  834. `$FOO' where FOO is an environment variable name means to substitute\n\
  835. the value of that variable.  The variable name should be terminated\n\
  836. with a character not a letter, digit or underscore; otherwise, enclose\n\
  837. the entire variable name in braces.\n\
  838. If `/~' appears, all of FILENAME through that `/' is discarded.\n\n\
  839. On VMS, `$' substitution is not done; this function does little and only\n\
  840. duplicates what `expand-file-name' does.")
  841.   (string)
  842.      Lisp_Object string;
  843. {
  844.   unsigned char *nm;
  845.  
  846.   register unsigned char *s, *p, *o, *x, *endp;
  847.   unsigned char *target;
  848.   int total = 0;
  849.   int substituted = 0;
  850.   unsigned char *xnm;
  851.  
  852.   CHECK_STRING (string, 0);
  853.  
  854.   nm = XSTRING (string)->data;
  855.   endp = nm + XSTRING (string)->size;
  856.  
  857.   /* If /~ or // appears, discard everything through first slash. */
  858.  
  859.   for (p = nm; p != endp; p++)
  860.     {
  861.       if ((p[0] == '~' ||
  862. #ifdef APOLLO
  863.        /* // at start of file name is meaningful in Apollo system */
  864.        (p[0] == '/' && p - 1 != nm)
  865. #else /* not APOLLO */
  866.        p[0] == '/'
  867. #endif /* not APOLLO */
  868.        )
  869.       && p != nm &&
  870. #ifdef VMS
  871.       (p[-1] == ':' || p[-1] == ']' || p[-1] == '>' ||
  872. #endif /* VMS */
  873.       p[-1] == '/')
  874. #ifdef VMS
  875.       )
  876. #endif /* VMS */
  877.     {
  878.       nm = p;
  879.       substituted = 1;
  880.     }
  881.     }
  882.  
  883. #ifdef VMS
  884.   return build_string (nm);
  885. #else
  886.  
  887.   /* See if any variables are substituted into the string
  888.      and find the total length of their values in `total' */
  889.  
  890.   for (p = nm; p != endp;)
  891.     if (*p != '$')
  892.       p++;
  893.     else
  894.       {
  895.     p++;
  896.     if (p == endp)
  897.       goto badsubst;
  898.     else if (*p == '$')
  899.       {
  900.         /* "$$" means a single "$" */
  901.         p++;
  902.         total -= 1;
  903.         substituted = 1;
  904.         continue;
  905.       }
  906.     else if (*p == '{')
  907.       {
  908.         o = ++p;
  909.         while (p != endp && *p != '}') p++;
  910.         if (*p != '}') goto missingclose;
  911.         s = p;
  912.       }
  913.     else
  914.       {
  915.         o = p;
  916.         while (p != endp && (isalnum (*p) || *p == '_')) p++;
  917.         s = p;
  918.       }
  919.  
  920.     /* Copy out the variable name */
  921.     target = (unsigned char *) alloca (s - o + 1);
  922.     strncpy ((char *) target, (char *) o, s - o);
  923.     target[s - o] = 0;
  924.  
  925.     /* Get variable value */
  926.     o = (unsigned char *) egetenv ((char *) target);
  927. /* The presence of this code makes vax 5.0 crash, for reasons yet unknown */
  928. #if 0
  929. #ifdef USG
  930.     if (!o && !strcmp (target, "USER"))
  931.       o = egetenv ("LOGNAME");
  932. #endif /* USG */
  933. #endif /* 0 */
  934.     if (!o) goto badvar;
  935.     total += strlen ((char *) o);
  936.     substituted = 1;
  937.       }
  938.  
  939.   if (!substituted)
  940.     return string;
  941.  
  942.   /* If substitution required, recopy the string and do it */
  943.   /* Make space in stack frame for the new copy */
  944.   xnm = (unsigned char *) alloca (XSTRING (string)->size + total + 1);
  945.   x = xnm;
  946.  
  947.   /* Copy the rest of the name through, replacing $ constructs with values */
  948.   for (p = nm; *p;)
  949.     if (*p != '$')
  950.       *x++ = *p++;
  951.     else
  952.       {
  953.     p++;
  954.     if (p == endp)
  955.       goto badsubst;
  956.     else if (*p == '$')
  957.       {
  958.         *x++ = *p++;
  959.         continue;
  960.       }
  961.     else if (*p == '{')
  962.       {
  963.         o = ++p;
  964.         while (p != endp && *p != '}') p++;
  965.         if (*p != '}') goto missingclose;
  966.         s = p++;
  967.       }
  968.     else
  969.       {
  970.         o = p;
  971.         while (p != endp && (isalnum (*p) || *p == '_')) p++;
  972.         s = p;
  973.       }
  974.  
  975.     /* Copy out the variable name */
  976.     target = (unsigned char *) alloca (s - o + 1);
  977.     strncpy ((char *) target, (char *) o, s - o);
  978.     target[s - o] = 0;
  979.  
  980.     /* Get variable value */
  981.     o = (unsigned char *) egetenv ((char *) target);
  982. /* The presence of this code makes vax 5.0 crash, for reasons yet unknown */
  983. #if 0
  984. #ifdef USG
  985.     if (!o && !strcmp (target, "USER"))
  986.       o = egetenv ("LOGNAME");
  987. #endif /* USG */
  988. #endif /* 0 */
  989.     if (!o)
  990.       goto badvar;
  991.  
  992.     strcpy ((char *) x, (char *) o);
  993.     x += strlen ((char *) o);
  994.       }
  995.  
  996.   *x = 0;
  997.  
  998.   /* If /~ or // appears, discard everything through first slash. */
  999.  
  1000.   for (p = xnm; p != x; p++)
  1001.     if ((p[0] == '~' ||
  1002. #ifdef APOLLO
  1003.      /* // at start of file name is meaningful in Apollo system */
  1004.      (p[0] == '/' && p - 1 != xnm)
  1005. #else /* not APOLLO */
  1006.      p[0] == '/'
  1007. #endif /* not APOLLO */
  1008.      )
  1009.     && p != xnm && p[-1] == '/')
  1010.       xnm = p;
  1011.  
  1012.   return make_string ((char *) xnm, x - xnm);
  1013.  
  1014.  badsubst:
  1015.   error ("Bad format environment-variable substitution");
  1016.  missingclose:
  1017.   error ("Missing \"}\" in environment-variable substitution");
  1018.  badvar:
  1019.   error ("Substituting nonexistent environment variable \"%s\"", target);
  1020.  
  1021.   /* NOTREACHED */
  1022.   return Qnil; /* warning suppression */
  1023. #endif /* not VMS */
  1024. }
  1025.  
  1026. /* A slightly faster and more convenient way to get
  1027.    (directory-file-name (expand-file-name FOO)).  The return value may
  1028.    have had its last character zapped with a '\0' character, meaning
  1029.    that it is acceptable to system calls, but not to other lisp
  1030.    functions.  Callers should make sure that the return value doesn't
  1031.    escape.  */
  1032.  
  1033. static Lisp_Object
  1034. expand_and_dir_to_file (filename, defdir)
  1035.      Lisp_Object filename, defdir;
  1036. {
  1037.   register Lisp_Object abspath;
  1038.   struct gcpro gcpro1;
  1039.  
  1040.   GCPRO1 (filename);
  1041.   abspath = Fexpand_file_name (filename, defdir);
  1042. #ifdef VMS
  1043.   {
  1044.     register int c = XSTRING (abspath)->data[XSTRING (abspath)->size - 1];
  1045.     if (c == ':' || c == ']' || c == '>')
  1046.       abspath = Fdirectory_file_name (abspath);
  1047.   }
  1048. #else
  1049.   /* Remove final slash, if any (unless path is root).
  1050.      stat behaves differently depending!  */
  1051.   if (XSTRING (abspath)->size > 1
  1052.       && XSTRING (abspath)->data[XSTRING (abspath)->size - 1] == '/')
  1053.     {
  1054.       if (EQ (abspath, filename))
  1055.     abspath = Fcopy_sequence (abspath);
  1056.       XSTRING (abspath)->data[XSTRING (abspath)->size - 1] = 0;
  1057.     }
  1058. #endif
  1059.   UNGCPRO;
  1060.   return abspath;
  1061. }
  1062.  
  1063. static void
  1064. barf_or_query_if_file_exists (absname, querystring, interactive)
  1065.      Lisp_Object absname;
  1066.      const unsigned char *querystring;
  1067.      int interactive;
  1068. {
  1069.   if (access ((char *) XSTRING (absname)->data, 4) >= 0)
  1070.     {
  1071.       register Lisp_Object tem;
  1072.       struct gcpro gcpro1;
  1073.  
  1074.       GCPRO1 (absname);
  1075.       if (interactive)
  1076.         tem = call1 (Qyes_or_no_p,
  1077.                      (format1 ("File %s already exists; %s anyway? ",
  1078.                                XSTRING (absname)->data, querystring)));
  1079.       else
  1080.         tem = Qt;
  1081.       UNGCPRO;
  1082.       if (NILP (tem))
  1083.     Fsignal (Qfile_already_exists,
  1084.          list2 (build_string ("File already exists"), absname));
  1085.     }
  1086.   return;
  1087. }
  1088.  
  1089. static int retrying_write (int, char *, int);
  1090.  
  1091. #if defined(HAVE_TIMEVAL) && !defined(USE_UTIME)
  1092. #if !defined(IRIX) && !defined(NeXT)
  1093. extern int utimes (const char *, struct timeval *);
  1094. #endif
  1095. #endif
  1096.  
  1097. DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 4,
  1098.   "fCopy file: \nFCopy %s to file: \np\nP",
  1099.   "Copy FILE to NEWNAME.  Both args must be strings.\n\
  1100. Signals a `file-already-exists' error if file NEWNAME already exists,\n\
  1101. unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.\n\
  1102. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1103. This is what happens in interactive use with M-x.\n\
  1104. Fourth arg KEEP-TIME non-nil means give the new file the same\n\
  1105. last-modified time as the old one.  (This works on only some systems.)\n\
  1106. A prefix arg makes KEEP-TIME non-nil.")
  1107.   (filename, newname, ok_if_already_exists, keep_date)
  1108.      Lisp_Object filename, newname, ok_if_already_exists, keep_date;
  1109. {
  1110.   int ifd, ofd, n;
  1111.   char buf[16 * 1024];
  1112.   struct stat st;
  1113.  
  1114.   CHECK_STRING (filename, 0);
  1115.   CHECK_STRING (newname, 1);
  1116.   filename = Fexpand_file_name (filename, Qnil);
  1117.   newname = Fexpand_file_name (newname, Qnil);
  1118.  
  1119.   /* When second argument is a directory, copy the file into it.
  1120.      (copy-file "foo" "bar/") == (copy-file "foo" "bar/foo")
  1121.    */
  1122.   if (!NILP (Ffile_directory_p (newname)))
  1123.     {
  1124.       Lisp_Object args[3];
  1125.       int i = 0;
  1126.       args[i++] = newname;
  1127.       if (XSTRING (newname)->data [XSTRING (newname)->size - 1] != '/')
  1128.         args[i++] = build_string ("/");
  1129.       args[i++] = Ffile_name_nondirectory (filename);
  1130.       newname = Fconcat (i, args);
  1131.     }
  1132.  
  1133.   if (NILP (ok_if_already_exists)
  1134.       || FIXNUMP (ok_if_already_exists))
  1135.     barf_or_query_if_file_exists (newname, (unsigned char *) "copy to it",
  1136.                   FIXNUMP (ok_if_already_exists));
  1137.  
  1138.   ifd = open ((char *) XSTRING (filename)->data, 0);
  1139.   if (ifd < 0)
  1140.     report_file_error ("Opening input file", Fcons (filename, Qnil));
  1141.  
  1142. #ifdef VMS
  1143.   /* Create the copy file with the same record format as the input file */
  1144.   ofd = sys_creat (XSTRING (newname)->data, 0666, ifd);
  1145. #else
  1146.   ofd = creat ((char *) XSTRING (newname)->data, 0666);
  1147. #endif /* VMS */
  1148.   if (ofd < 0)
  1149.     {
  1150.       close (ifd);
  1151.       report_file_error ("Opening output file", Fcons (newname, Qnil));
  1152.     }
  1153.  
  1154.   while ((n = read (ifd, buf, sizeof buf)) > 0)
  1155.     if (retrying_write (ofd, buf, n) != 0)
  1156.       report_file_error ("I/O error", Fcons (newname, Qnil));
  1157.  
  1158.   if (fstat (ifd, &st) >= 0)
  1159.     {
  1160. #ifdef HAVE_TIMEVAL
  1161.       if (!NILP (keep_date))
  1162.     {
  1163. #ifdef USE_UTIME
  1164. /* AIX has utimes() in compatibility package, but it dies.  So use good old
  1165.    utime interface instead. */
  1166.       struct {
  1167.         time_t atime;
  1168.         time_t mtime;
  1169.       } tv;
  1170.       tv.atime = st.st_atime;
  1171.       tv.mtime = st.st_mtime;
  1172.       utime (XSTRING (newname)->data, &tv);
  1173. #else /* not USE_UTIME */
  1174.       struct timeval timevals[2];
  1175.       timevals[0].tv_sec = st.st_atime;
  1176.       timevals[1].tv_sec = st.st_mtime;
  1177.       timevals[0].tv_usec = timevals[1].tv_usec = 0;
  1178.       utimes ((char *) XSTRING (newname)->data, timevals);
  1179. #endif /* not USE_UTIME */
  1180.     }
  1181. #endif /* HAVE_TIMEVALS */
  1182.  
  1183. #ifdef APOLLO
  1184.       if (!egetenv ("USE_DOMAIN_ACLS"))
  1185. #endif
  1186.       chmod ((char *)XSTRING (newname)->data, st.st_mode & 07777);
  1187.     }
  1188.  
  1189.   close (ifd);
  1190.   if (close (ofd) < 0)
  1191.     report_file_error ("I/O error", Fcons (newname, Qnil));
  1192.  
  1193.   return Qnil;
  1194. }
  1195.  
  1196. DEFUN ("make-directory", Fmake_directory, Smake_directory, 1, 1, "FMake directory: ",
  1197.   "Create a directory.  One argument, a file name string.")
  1198.   (dirname)
  1199.      Lisp_Object dirname;
  1200. {
  1201.   char dir [MAXPATHLEN];
  1202.   CHECK_STRING (dirname, 0);
  1203.   dirname = Fexpand_file_name (dirname, Qnil);
  1204.   if (XSTRING (dirname)->size > (sizeof (dir) - 1))
  1205.     while (1)
  1206.       Fsignal (Qfile_error,
  1207.            Fcons (build_string ("Creating directory"),
  1208.               Fcons (build_string ("pathame too long"),
  1209.                  Flist (1, &dirname))));
  1210.   strncpy (dir, (char *) XSTRING (dirname)->data, XSTRING (dirname)->size + 1);
  1211. #ifndef VMS
  1212.   if (dir [XSTRING (dirname)->size - 1] == '/')
  1213.     dir [XSTRING (dirname)->size - 1] = 0;
  1214. #endif
  1215.   if (mkdir (dir, 0777) != 0)
  1216.     report_file_error ("Creating directory", Flist (1, &dirname));
  1217.  
  1218.     return Qnil;
  1219. }
  1220.  
  1221. DEFUN ("remove-directory", Fremove_directory, Sremove_directory, 1, 1, "FRemove directory: ",
  1222.   "Remove a directory.  One argument, a file name string.")
  1223.   (dirname)
  1224.      Lisp_Object dirname;
  1225. {
  1226.   unsigned char *dir;
  1227.  
  1228.   CHECK_STRING (dirname, 0);
  1229.   dirname = Fexpand_file_name (dirname, Qnil);
  1230.   dir = XSTRING (dirname)->data;
  1231.  
  1232.   if (rmdir ((char *) dir) != 0)
  1233.     report_file_error ("Removing directory", Flist (1, &dirname));
  1234.  
  1235.   return Qnil;
  1236. }
  1237.  
  1238. DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
  1239.   "Delete specified file.  One argument, a file name string.\n\
  1240. If file has multiple names, it continues to exist with the other names.")
  1241.   (filename)
  1242.      Lisp_Object filename;
  1243. {
  1244.   CHECK_STRING (filename, 0);
  1245.   filename = Fexpand_file_name (filename, Qnil);
  1246.   if (0 > unlink ((char *) XSTRING (filename)->data))
  1247.     report_file_error ("Removing old name", Flist (1, &filename));
  1248.   return Qnil;
  1249. }
  1250.  
  1251. DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
  1252.   "fRename file: \nFRename %s to file: \np",
  1253.   "Rename FILE as NEWNAME.  Both args strings.\n\
  1254. If file has names other than FILE, it continues to have those names.\n\
  1255. Signals a `file-already-exists' error if a file NEWNAME already exists\n\
  1256. unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
  1257. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1258. This is what happens in interactive use with M-x.")
  1259.   (filename, newname, ok_if_already_exists)
  1260.      Lisp_Object filename, newname, ok_if_already_exists;
  1261. {
  1262. #ifdef NO_ARG_ARRAY
  1263.   Lisp_Object args[2];
  1264. #endif
  1265.  
  1266.   CHECK_STRING (filename, 0);
  1267.   CHECK_STRING (newname, 1);
  1268.   filename = Fexpand_file_name (filename, Qnil);
  1269.   newname = Fexpand_file_name (newname, Qnil);
  1270.   if (NILP (ok_if_already_exists)
  1271.       || FIXNUMP (ok_if_already_exists))
  1272.     barf_or_query_if_file_exists (newname, (unsigned char *) "rename to it",
  1273.                   FIXNUMP (ok_if_already_exists));
  1274. #ifndef BSD4_1
  1275.   if (0 > rename ((char *) XSTRING (filename)->data,
  1276.           (char *) XSTRING (newname)->data))
  1277. #else
  1278.   if (0 > link ((char *) XSTRING (filename)->data, XSTRING (newname)->data)
  1279.       || 0 > unlink ((char *) XSTRING (filename)->data))
  1280. #endif
  1281.     {
  1282.       if (errno == EXDEV)
  1283.     {
  1284.       Fcopy_file (filename, newname, ok_if_already_exists, Qt);
  1285.       Fdelete_file (filename);
  1286.     }
  1287.       else
  1288. #ifdef NO_ARG_ARRAY
  1289.     {
  1290.       args[0] = filename;
  1291.       args[1] = newname;
  1292.       report_file_error ("Renaming", Flist (2, args));
  1293.     }
  1294. #else
  1295.     report_file_error ("Renaming", Flist (2, &filename));
  1296. #endif
  1297.     }
  1298.   return Qnil;
  1299. }
  1300.  
  1301. DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
  1302.   "fAdd name to file: \nFName to add to %s: \np",
  1303.   "Give FILE additional name NEWNAME.  Both args strings.\n\
  1304. Signals a `file-already-exists' error if a file NEWNAME already exists\n\
  1305. unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
  1306. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1307. This is what happens in interactive use with M-x.")
  1308.   (filename, newname, ok_if_already_exists)
  1309.      Lisp_Object filename, newname, ok_if_already_exists;
  1310. {
  1311. #ifdef NO_ARG_ARRAY
  1312.   Lisp_Object args[2];
  1313. #endif
  1314.  
  1315.   CHECK_STRING (filename, 0);
  1316.   CHECK_STRING (newname, 1);
  1317.   filename = Fexpand_file_name (filename, Qnil);
  1318.   newname = Fexpand_file_name (newname, Qnil);
  1319.   if (NILP (ok_if_already_exists)
  1320.       || FIXNUMP (ok_if_already_exists))
  1321.     barf_or_query_if_file_exists (newname,
  1322.                   (unsigned char *) "make it a new name",
  1323.                   FIXNUMP (ok_if_already_exists));
  1324.   unlink ((char *) XSTRING (newname)->data);
  1325.   if (0 > link ((char *) XSTRING (filename)->data,
  1326.         (char *) XSTRING (newname)->data))
  1327.     {
  1328. #ifdef NO_ARG_ARRAY
  1329.       args[0] = filename;
  1330.       args[1] = newname;
  1331.       report_file_error ("Adding new name", Flist (2, args));
  1332. #else
  1333.       report_file_error ("Adding new name", Flist (2, &filename));
  1334. #endif
  1335.     }
  1336.  
  1337.   return Qnil;
  1338. }
  1339.  
  1340. #ifdef S_IFLNK
  1341. DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
  1342.   "FMake symbolic link to file: \nFMake symbolic link to file %s: \np",
  1343.   "Make a symbolic link to FILENAME, named LINKNAME.  Both args strings.\n\
  1344. Signals a `file-already-exists' error if a file NEWNAME already exists\n\
  1345. unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
  1346. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1347. This happens for interactive use with M-x.")
  1348.   (filename, newname, ok_if_already_exists)
  1349.      Lisp_Object filename, newname, ok_if_already_exists;
  1350. {
  1351. #ifdef NO_ARG_ARRAY
  1352.   Lisp_Object args[2];
  1353. #endif
  1354.  
  1355.   CHECK_STRING (filename, 0);
  1356.   CHECK_STRING (newname, 1);
  1357.   filename = Fexpand_file_name (filename, Qnil);
  1358.   newname = Fexpand_file_name (newname, Qnil);
  1359.   if (NILP (ok_if_already_exists)
  1360.       || FIXNUMP (ok_if_already_exists))
  1361.     barf_or_query_if_file_exists (newname, (unsigned char *) "make it a link",
  1362.                   FIXNUMP (ok_if_already_exists));
  1363.   if (0 > symlink ((char *) XSTRING (filename)->data,
  1364.            (char *) XSTRING (newname)->data))
  1365.     {
  1366.       /* If we didn't complain already, silently delete existing file.  */
  1367.       if (errno == EEXIST)
  1368.     {
  1369.       unlink ((char *) XSTRING (filename)->data);
  1370.       if (0 <= symlink ((char *) XSTRING (filename)->data,
  1371.                 (char *) XSTRING (newname)->data))
  1372.         return Qnil;
  1373.     }
  1374.  
  1375. #ifdef NO_ARG_ARRAY
  1376.       args[0] = filename;
  1377.       args[1] = newname;
  1378.       report_file_error ("Making symbolic link", Flist (2, args));
  1379. #else
  1380.       report_file_error ("Making symbolic link", Flist (2, &filename));
  1381. #endif
  1382.     }
  1383.   return Qnil;
  1384. }
  1385. #endif /* S_IFLNK */
  1386.  
  1387. #ifdef VMS
  1388.  
  1389. DEFUN ("define-logical-name", Fdefine_logical_name, Sdefine_logical_name,
  1390.        2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
  1391.   "Define the job-wide logical name NAME to have the value STRING.\n\
  1392. If STRING is nil or a null string, the logical name NAME is deleted.")
  1393.   (varname, string)
  1394.      Lisp_Object varname;
  1395.      Lisp_Object string;
  1396. {
  1397.   CHECK_STRING (varname, 0);
  1398.   if (NILP (string))
  1399.     delete_logical_name (XSTRING (varname)->data);
  1400.   else
  1401.     {
  1402.       CHECK_STRING (string, 1);
  1403.  
  1404.       if (XSTRING (string)->size == 0)
  1405.         delete_logical_name (XSTRING (varname)->data);
  1406.       else
  1407.         define_logical_name (XSTRING (varname)->data, XSTRING (string)->data);
  1408.     }
  1409.  
  1410.   return string;
  1411. }
  1412. #endif /* VMS */
  1413.  
  1414. #ifdef HPUX_NET
  1415.  
  1416. DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
  1417.        "Open a network connection to PATH using LOGIN as the login string.")
  1418.      (path, login)
  1419.      Lisp_Object path, login;
  1420. {
  1421.   int netresult;
  1422.   
  1423.   CHECK_STRING (path, 0);
  1424.   CHECK_STRING (login, 0);  
  1425.   
  1426.   netresult = netunam (XSTRING (path)->data, XSTRING (login)->data);
  1427.  
  1428.   if (netresult == -1)
  1429.     return Qnil;
  1430.   else
  1431.     return Qt;
  1432. }
  1433. #endif /* HPUX_NET */
  1434.  
  1435. DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
  1436.        1, 1, 0,
  1437.        "Return t if file FILENAME specifies an absolute path name.\n\
  1438. On Unix, this is a name starting with a `/' or a `~'.")
  1439.      (filename)
  1440.      Lisp_Object filename;
  1441. {
  1442.   unsigned char *ptr;
  1443.  
  1444.   CHECK_STRING (filename, 0);
  1445.   ptr = XSTRING (filename)->data;
  1446.   if (*ptr == '/' || *ptr == '~'
  1447. #ifdef VMS
  1448. /* ??? This criterion is probably wrong for '<'.  */
  1449.       || index (ptr, ':') || index (ptr, '<')
  1450.       || (*ptr == '[' && (ptr[1] != '-' || (ptr[2] != '.' && ptr[2] != ']'))
  1451.       && ptr[1] != '.')
  1452. #endif /* VMS */
  1453.       )
  1454.     return Qt;
  1455.   else
  1456.     return Qnil;
  1457. }
  1458.  
  1459. DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
  1460.   "Return t if file FILENAME exists.  (This does not mean you can read it.)\n\
  1461. See also `file-readable-p' and `file-attributes'.")
  1462.   (filename)
  1463.      Lisp_Object filename;
  1464. {
  1465.   Lisp_Object abspath;
  1466.  
  1467.   CHECK_STRING (filename, 0);
  1468.   abspath = Fexpand_file_name (filename, Qnil);
  1469.   return (access ((char *) XSTRING (abspath)->data, 0) >= 0) ? Qt : Qnil;
  1470. }
  1471.  
  1472. DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
  1473.   "Return t if FILENAME can be executed by you.\n\
  1474. For directories this means you can change to that directory.")
  1475.   (filename)
  1476.     Lisp_Object filename;
  1477.  
  1478. {
  1479.   Lisp_Object abspath;
  1480.  
  1481.   CHECK_STRING (filename, 0);
  1482.   abspath = Fexpand_file_name (filename, Qnil);
  1483.   return (access ((char *) XSTRING (abspath)->data, 1) >= 0) ? Qt : Qnil;
  1484. }
  1485.  
  1486. DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
  1487.   "Return t if file FILENAME exists and you can read it.\n\
  1488. See also `file-exists-p' and `file-attributes'.")
  1489.   (filename)
  1490.      Lisp_Object filename;
  1491. {
  1492.   Lisp_Object abspath;
  1493.  
  1494.   CHECK_STRING (filename, 0);
  1495.   abspath = Fexpand_file_name (filename, Qnil);
  1496.   return (access ((char *) XSTRING (abspath)->data, 4) >= 0) ? Qt : Qnil;
  1497. }
  1498.  
  1499. DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
  1500.   "If file FILENAME is the name of a symbolic link\n\
  1501. returns the name of the file to which it is linked.\n\
  1502. Otherwise returns NIL.")
  1503.   (filename)
  1504.      Lisp_Object filename;
  1505. {
  1506. #ifdef S_IFLNK
  1507.   char *buf;
  1508.   int bufsize;
  1509.   int valsize;
  1510.   Lisp_Object val;
  1511.  
  1512.   CHECK_STRING (filename, 0);
  1513.   filename = Fexpand_file_name (filename, Qnil);
  1514.  
  1515.   bufsize = 100;
  1516.   while (1)
  1517.     {
  1518.       buf = (char *) xmalloc (bufsize);
  1519.       memset (buf, 0, bufsize);
  1520.       valsize = readlink ((char *) XSTRING (filename)->data, buf, bufsize);
  1521.       if (valsize < bufsize) break;
  1522.       /* Buffer was not long enough */
  1523.       xfree (buf);
  1524.       bufsize *= 2;
  1525.     }
  1526.   if (valsize == -1)
  1527.     {
  1528.       xfree (buf);
  1529.       return Qnil;
  1530.     }
  1531.   val = make_string (buf, valsize);
  1532.   xfree (buf);
  1533.   return val;
  1534. #else /* not S_IFLNK */
  1535.   return Qnil;
  1536. #endif /* not S_IFLNK */
  1537. }
  1538.  
  1539. /* Having this before file-symlink-p mysteriously caused it to be forgotten
  1540.    on the RT/PC.  */
  1541. DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
  1542.   "Return t if file FILENAME can be written or created by you.")
  1543.   (filename)
  1544.      Lisp_Object filename;
  1545. {
  1546.   Lisp_Object abspath, dir;
  1547.  
  1548.   CHECK_STRING (filename, 0);
  1549.   abspath = Fexpand_file_name (filename, Qnil);
  1550.   if (access ((char *) XSTRING (abspath)->data, 0) >= 0)
  1551.     return (access ((char *) XSTRING (abspath)->data, 2) >= 0) ? Qt : Qnil;
  1552.   dir = Ffile_name_directory (abspath);
  1553. #ifdef VMS
  1554.   if (!NILP (dir))
  1555.     dir = Fdirectory_file_name (dir);
  1556. #endif /* VMS */
  1557.   return (access (!NILP (dir) ? (char *) XSTRING (dir)->data : "", 2) >= 0
  1558.       ? Qt : Qnil);
  1559. }
  1560.  
  1561. DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
  1562.   "Return t if file FILENAME is the name of a directory as a file.\n\
  1563. A directory name spec may be given instead; then the value is t\n\
  1564. if the directory so specified exists and really is a directory.")
  1565.   (filename)
  1566.      Lisp_Object filename;
  1567. {
  1568.   register Lisp_Object abspath;
  1569.   struct stat st;
  1570.  
  1571.   abspath = expand_and_dir_to_file (filename, current_buffer->directory);
  1572.  
  1573.   if (stat ((char *)XSTRING (abspath)->data, &st) < 0)
  1574.     return Qnil;
  1575.   return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
  1576. }
  1577.  
  1578. DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
  1579.   "Return mode bits of FILE, as an integer.")
  1580.   (filename)
  1581.      Lisp_Object filename;
  1582. {
  1583.   Lisp_Object abspath;
  1584.   struct stat st;
  1585.  
  1586.   abspath = expand_and_dir_to_file (filename, current_buffer->directory);
  1587.  
  1588.   if (stat ((char *)XSTRING (abspath)->data, &st) < 0)
  1589.     return Qnil;
  1590.   return make_number (st.st_mode & 07777);
  1591. }
  1592.  
  1593. DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2, 0,
  1594.   "Set mode bits of FILE to MODE (an integer).\n\
  1595. Only the 12 low bits of MODE are used.")
  1596.   (filename, mode)
  1597.      Lisp_Object filename, mode;
  1598. {
  1599.   Lisp_Object abspath;
  1600.  
  1601.   abspath = Fexpand_file_name (filename, current_buffer->directory);
  1602.   CHECK_FIXNUM (mode, 1);
  1603.  
  1604. #ifndef APOLLO
  1605.   if (chmod ((char *)XSTRING (abspath)->data, XINT (mode)) < 0)
  1606.     report_file_error ("Doing chmod", Fcons (abspath, Qnil));
  1607. #else /* APOLLO */
  1608.   if (!egetenv ("USE_DOMAIN_ACLS"))
  1609.     {
  1610.       struct stat st;
  1611.       struct timeval tvp[2];
  1612.  
  1613.       /* chmod on apollo also change the file's modtime; need to save the
  1614.      modtime and then restore it. */
  1615.       if (stat (XSTRING (abspath)->data, &st) < 0)
  1616.     {
  1617.       report_file_error ("Doing chmod", Fcons (abspath, Qnil));
  1618.       return (Qnil);
  1619.     }
  1620.  
  1621.       if (chmod (XSTRING (abspath)->data, XINT (mode)) < 0)
  1622.      report_file_error ("Doing chmod", Fcons (abspath, Qnil));
  1623.  
  1624.       /* reset the old accessed and modified times.  */
  1625.       tvp[0].tv_sec = st.st_atime + 1; /* +1 due to an Apollo roundoff bug */
  1626.       tvp[0].tv_usec = 0;
  1627.       tvp[1].tv_sec = st.st_mtime + 1; /* +1 due to an Apollo roundoff bug */
  1628.       tvp[1].tv_usec = 0;
  1629.  
  1630.       if (utimes (XSTRING (abspath)->data, tvp) < 0)
  1631.      report_file_error ("Doing utimes", Fcons (abspath, Qnil));
  1632.     }
  1633. #endif /* APOLLO */
  1634.  
  1635.   return Qnil;
  1636. }
  1637.  
  1638. DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
  1639.   "Return t if file FILE1 is newer than file FILE2.\n\
  1640. If FILE1 does not exist, the answer is nil;\n\
  1641. otherwise, if FILE2 does not exist, the answer is t.")
  1642.   (file1, file2)
  1643.      Lisp_Object file1, file2;
  1644. {
  1645.   Lisp_Object abspath;
  1646.   struct stat st;
  1647.   int mtime1;
  1648.  
  1649.   CHECK_STRING (file1, 0);
  1650.   CHECK_STRING (file2, 0);
  1651.  
  1652.   abspath = expand_and_dir_to_file (file1, current_buffer->directory);
  1653.  
  1654.   if (stat ((char *)XSTRING (abspath)->data, &st) < 0)
  1655.     return Qnil;
  1656.  
  1657.   mtime1 = st.st_mtime;
  1658.  
  1659.   abspath = expand_and_dir_to_file (file2, current_buffer->directory);
  1660.  
  1661.   if (stat ((char *)XSTRING (abspath)->data, &st) < 0)
  1662.     return Qt;
  1663.  
  1664.   return (mtime1 > st.st_mtime) ? Qt : Qnil;
  1665. }
  1666.  
  1667. static Lisp_Object
  1668. close_file_unwind (fd)
  1669.      Lisp_Object fd;
  1670. {
  1671.   close (XFASTINT (fd));
  1672.   return Qnil;
  1673. }
  1674.  
  1675. DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
  1676.   1, 2, 0,
  1677.   "Insert contents of file FILENAME after point.\n\
  1678. Returns list of absolute pathname and length of data inserted.\n\
  1679. If second argument VISIT is non-nil, the buffer's visited filename\n\
  1680. and last save file modtime are set, and it is marked unmodified.\n\
  1681. If visiting and the file does not exist, visiting is completed\n\
  1682. before the error is signaled.")
  1683.   (filename, visit)
  1684.      Lisp_Object filename, visit;
  1685. {
  1686.   struct stat st;
  1687.   register int fd;
  1688.   register int inserted = 0;
  1689.   register int how_much;
  1690.   int count = specpdl_depth;
  1691.  
  1692.   if (!NILP (current_buffer->read_only))
  1693.     Fbarf_if_buffer_read_only();
  1694.  
  1695.   CHECK_STRING (filename, 0);
  1696.   filename = Fexpand_file_name (filename, Qnil);
  1697.  
  1698.   fd = -1;
  1699.  
  1700. #ifndef APOLLO
  1701.   if (stat ((char *)XSTRING (filename)->data, &st) < 0
  1702.     || (fd = open ((char *) XSTRING (filename)->data, 0)) < 0)
  1703. #else
  1704.   if ((fd = open (XSTRING (filename)->data, 0)) < 0
  1705.       || fstat (fd, &st) < 0)
  1706. #endif /* not APOLLO */
  1707.     {
  1708.       if (fd >= 0) close (fd);
  1709.       if (NILP (visit))
  1710.     report_file_error ("Opening input file", Fcons (filename, Qnil));
  1711.       st.st_mtime = -1;
  1712.       how_much = 0;
  1713.       goto notfound;
  1714.     }
  1715.  
  1716.   record_unwind_protect (close_file_unwind, make_number (fd));
  1717.  
  1718.   /* Supposedly happens on VMS.  */
  1719.   if (st.st_size < 0)
  1720.     error ("File size is negative");
  1721.   {
  1722.     register Lisp_Object temp;
  1723.  
  1724.     /* Make sure point-max won't overflow after this insertion.  */
  1725.     XSET (temp, Lisp_Int, st.st_size + Z);
  1726.     if (st.st_size + Z != XINT (temp))
  1727.       error ("maximum buffer size exceeded");
  1728.   }
  1729.  
  1730.   if (NILP (visit))
  1731.     prepare_to_modify_buffer (point, point);
  1732.  
  1733.   move_gap (point);
  1734.   if (GAP_SIZE < st.st_size)
  1735.     make_gap (st.st_size - GAP_SIZE);
  1736.     
  1737.   while (1)
  1738.     {
  1739.       int try = min (st.st_size - inserted, 64 << 10);
  1740.       int this = read (fd, (char *) CHAR_ADDRESS (point + inserted - 1) + 1,
  1741.                try);
  1742.  
  1743.       if (this <= 0)
  1744.     {
  1745.       how_much = this;
  1746.       break;
  1747.     }
  1748.  
  1749.       GPT += this;
  1750.       GAP_SIZE -= this;
  1751.       ZV += this;
  1752.       Z += this;
  1753.       inserted += this;
  1754.     }
  1755.  
  1756.   if (inserted > 0)
  1757.     MODIFF++;
  1758.   record_insert (point, inserted);
  1759.  
  1760.   close (fd);
  1761.  
  1762.   /* Discard the unwind protect >>>> Kludge! */
  1763.   specpdl_ptr = specpdl + count;
  1764.   specpdl_depth = count;
  1765.  
  1766.   if (how_much < 0)
  1767.     error ("IO error reading %s", XSTRING (filename)->data);
  1768.  
  1769.  notfound:
  1770.  
  1771.   if (!NILP (visit))
  1772.     {
  1773.       current_buffer->undo_list = Qnil;
  1774. #ifdef APOLLO
  1775.       stat (XSTRING (filename)->data, &st);
  1776. #endif
  1777.       current_buffer->modtime = st.st_mtime;
  1778.       current_buffer->save_modified = MODIFF;
  1779.       current_buffer->auto_save_modified = MODIFF;
  1780.       XFASTINT (current_buffer->save_length) = Z - BEG;
  1781. #ifdef CLASH_DETECTION
  1782.       if (!NILP (current_buffer->filename))
  1783.     unlock_file (current_buffer->filename);
  1784.       unlock_file (filename);
  1785. #endif /* CLASH_DETECTION */
  1786.       current_buffer->filename = filename;
  1787.       call0 (intern ("compute-buffer-file-truename"));
  1788.       /* If visiting nonexistent file, return nil.  */
  1789.       if (st.st_mtime == -1)
  1790.     report_file_error ("Opening input file", Fcons (filename, Qnil));
  1791.     }
  1792.  
  1793.   signal_after_change (point, 0, inserted);
  1794.   return Fcons (filename, Fcons (make_number (inserted), Qnil));
  1795. }
  1796.  
  1797. static int e_write (int, char *, int);
  1798.  
  1799. DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 5,
  1800.   "r\nFWrite region to file: ",
  1801.   "Write current region into specified file.\n\
  1802. When called from a program, takes three arguments:\n\
  1803. START, END and FILENAME.  START and END are buffer positions.\n\
  1804. Optional fourth argument APPEND if non-nil means\n\
  1805.   append to existing file contents (if any).\n\
  1806. Optional fifth argument VISIT if t means\n\
  1807.   set the last-save-file-modtime of buffer to this file's modtime\n\
  1808.   and mark buffer not modified.\n\
  1809. If VISIT is neither t nor nil, it means do not print\n\
  1810.   the \"Wrote file\" message.\n\
  1811. Kludgy feature: if START is a string, then that string is written\n\
  1812. to the file, instead of any buffer contents, and END is ignored.")
  1813.   (start, end, filename, append, visit)
  1814.      Lisp_Object start, end, filename, append, visit;
  1815. {
  1816.   register int fd;
  1817.   int failure;
  1818.   char *fn;
  1819.   struct stat st;
  1820.   int tem;
  1821.   int count = specpdl_depth;
  1822. #ifdef VMS
  1823.   unsigned char *fname = 0;    /* If non-0, original filename (must rename) */
  1824. #endif /* VMS */
  1825.  
  1826.   /* Special kludge to simplify auto-saving */
  1827.   if (NILP (start))
  1828.     {
  1829.       XFASTINT (start) = BEG;
  1830.       XFASTINT (end) = Z;
  1831.     }
  1832.   else if (!STRINGP (start))
  1833.     validate_region (&start, &end);
  1834.  
  1835.   filename = Fexpand_file_name (filename, Qnil);
  1836.   fn = (char *)XSTRING (filename)->data;
  1837.  
  1838. #ifdef CLASH_DETECTION
  1839.   if (!auto_saving)
  1840.     lock_file (filename);
  1841. #endif /* CLASH_DETECTION */
  1842.  
  1843.   fd = -1;
  1844.   if (!NILP (append))
  1845.     fd = open (fn, 1);
  1846.  
  1847.   if (fd < 0)
  1848. #ifdef VMS
  1849.     if (auto_saving)    /* Overwrite any previous version of autosave file */
  1850.       {
  1851.     vms_truncate (fn);    /* if fn exists, truncate to zero length */
  1852.     fd = open (fn, O_RDWR);
  1853.     if (fd < 0)
  1854.       fd = creat_copy_attrs (STRINGP (current_buffer->filename)
  1855.                  ? XSTRING (current_buffer->filename)->data : 0,
  1856.                  fn);
  1857.       }
  1858.     else        /* Write to temporary name and rename if no errors */
  1859.       {
  1860.     Lisp_Object temp_name;
  1861.     temp_name = Ffile_name_directory (filename);
  1862.  
  1863.     if (!NILP (temp_name))
  1864.       {
  1865.         temp_name = Fmake_temp_name (concat2 (temp_name,
  1866.                           build_string ("$$SAVE$$")));
  1867.         fname = XSTRING (filename)->data;
  1868.         fn = XSTRING (temp_name)->data;
  1869.         fd = creat_copy_attrs (fname, fn);
  1870.         if (fd < 0)
  1871.           {
  1872.         /* If we can't open the temporary file, try creating a new
  1873.            version of the original file.  VMS "creat" creates a
  1874.            new version rather than truncating an existing file. */
  1875.         fn = fname;
  1876.         fname = 0;
  1877.         fd = creat (fn, 0666);
  1878.         if (fd < 0)
  1879.           {
  1880.             /* We can't make a new version;
  1881.                try to truncate and rewrite existing version if any.  */
  1882.             vms_truncate (fn);
  1883.             fd = open (fn, O_RDWR);
  1884.           }
  1885.           }
  1886.       }
  1887.     else
  1888.       fd = creat (fn, 0666);
  1889.       }
  1890. #else /* not VMS */
  1891.   fd = creat (fn, auto_saving ? auto_save_mode_bits : 0666);
  1892. #endif /* not VMS */
  1893.  
  1894.   if (fd < 0)
  1895.     {
  1896. #ifdef CLASH_DETECTION
  1897.       if (!auto_saving) unlock_file (filename);
  1898. #endif /* CLASH_DETECTION */
  1899.       report_file_error ("Opening output file", Fcons (filename, Qnil));
  1900.     }
  1901.  
  1902.   record_unwind_protect (close_file_unwind, make_number (fd));
  1903.  
  1904.   if (!NILP (append))
  1905.     if (lseek (fd, 0, 2) < 0)
  1906.       {
  1907. #ifdef CLASH_DETECTION
  1908.     if (!auto_saving) unlock_file (filename);
  1909. #endif /* CLASH_DETECTION */
  1910.     report_file_error ("Lseek error", Fcons (filename, Qnil));
  1911.       }
  1912.  
  1913. #ifdef VMS
  1914. /*
  1915.  * Kludge Warning: The VMS C RTL likes to insert carriage returns
  1916.  * if we do writes that don't end with a carriage return. Furthermore
  1917.  * it cannot handle writes of more then 16K. The modified
  1918.  * version of "sys_write" in SYSDEP.C (see comment there) copes with
  1919.  * this EXCEPT for the last record (iff it doesn't end with a carriage
  1920.  * return). This implies that if your buffer doesn't end with a carriage
  1921.  * return, you get one free... tough. However it also means that if
  1922.  * we make two calls to sys_write (a la the following code) you can
  1923.  * get one at the gap as well. The easiest way to fix this (honest)
  1924.  * is to move the gap to the next newline (or the end of the buffer).
  1925.  * Thus this change.
  1926.  *
  1927.  * Yech!
  1928.  */
  1929.   if (GPT > BEG && *GPT_ADDR[-1] != '\n')
  1930.     move_gap (find_next_newline (GPT, 1));
  1931. #endif
  1932.  
  1933.   failure = 0;
  1934.   immediate_quit = 1;
  1935.  
  1936.   if (STRINGP (start))
  1937.     {
  1938.       failure = 0 > e_write (fd, (char *) XSTRING (start)->data,
  1939.                  XSTRING (start)->size);
  1940.     }
  1941.   else if (XINT (start) != XINT (end))
  1942.     {
  1943.       if (XINT (start) < GPT)
  1944.     {
  1945.       register int end1 = XINT (end);
  1946.       tem = XINT (start);
  1947.       failure = 0 > e_write (fd, (char *) CHAR_ADDRESS (tem),
  1948.                  min (GPT, end1) - tem);
  1949.     }
  1950.  
  1951.       if (XINT (end) > GPT && !failure)
  1952.     {
  1953.       tem = XINT (start);
  1954.       tem = max (tem, GPT);
  1955.       failure = 0 > e_write (fd, (char *) CHAR_ADDRESS (tem),
  1956.                  XINT (end) - tem);
  1957.     }
  1958.     }
  1959.  
  1960.   immediate_quit = 0;
  1961.  
  1962. #ifndef USG
  1963. #ifndef VMS
  1964. #ifndef BSD4_1
  1965. #ifndef alliant /* trinkle@cs.purdue.edu says fsync can return EBUSY
  1966.            on alliant, for no visible reason.  */
  1967.   /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
  1968.      Disk full in NFS may be reported here.  */
  1969.   if (fsync (fd) < 0) {
  1970.     failure = 1;
  1971.     e_write_errno = errno;
  1972.   }
  1973. #endif
  1974. #endif
  1975. #endif
  1976. #endif
  1977.  
  1978.   /* Spurious "file has changed on disk" warnings have been 
  1979.      observed on Suns as well.
  1980.      It seems that `close' can change the modtime, under nfs.
  1981.  
  1982.      (This has supposedly been fixed in Sunos 4,
  1983.      but who knows about all the other machines with NFS?)  */
  1984. #if 0
  1985.  
  1986.   /* On VMS and APOLLO, must do the stat after the close
  1987.      since closing changes the modtime.  */
  1988. #ifndef VMS
  1989. #ifndef APOLLO
  1990.   /* Recall that #if defined does not work on VMS.  */
  1991. #define FOO
  1992.   fstat (fd, &st);
  1993. #endif
  1994. #endif
  1995. #endif
  1996.  
  1997.   /* NFS can report a write failure now.  */
  1998.   if (close (fd) < 0) {
  1999.     failure = 1;
  2000.     e_write_errno = errno;
  2001.   }
  2002.  
  2003. #ifdef VMS
  2004.   /* If we wrote to a temporary name and had no errors, rename to real name. */
  2005.   if (fname)
  2006.     {
  2007.       if (!failure)
  2008.     failure = (rename (fn, fname) != 0);
  2009.       fn = fname;
  2010.     }
  2011. #endif /* VMS */
  2012.  
  2013. #ifndef FOO
  2014.   stat (fn, &st);
  2015. #endif
  2016.   /* Discard the unwind protect >>>> Kludge! */
  2017.   specpdl_ptr = specpdl + count;
  2018.   specpdl_depth = count;
  2019.  
  2020. #ifdef CLASH_DETECTION
  2021.   if (!auto_saving)
  2022.     unlock_file (filename);
  2023. #endif /* CLASH_DETECTION */
  2024.  
  2025.   /* Do this before reporting IO error
  2026.      to avoid a "file has changed on disk" warning on
  2027.      next attempt to save.  */
  2028.   if (EQ (visit, Qt))
  2029.     current_buffer->modtime = st.st_mtime;
  2030.  
  2031.   if (failure) {
  2032.     errno = e_write_errno;
  2033.     report_file_error ("I/O error", Fcons (filename, Qnil));
  2034.   }
  2035.  
  2036.   if (EQ (visit, Qt))
  2037.     {
  2038.       current_buffer->save_modified = MODIFF;
  2039.       XFASTINT (current_buffer->save_length) = Z - BEG;
  2040.       current_buffer->filename = filename;
  2041.     }
  2042.   else if (!NILP (visit))
  2043.     return Qnil;
  2044.  
  2045.   if (!auto_saving)
  2046.     {
  2047.       Lisp_Object fsp = Ffile_symlink_p (build_string (fn));
  2048.       if (NILP (fsp))
  2049.     message ("Wrote %s", fn);
  2050.       else
  2051.     message ("Wrote %s (symlink to %s)", fn, (char *) XSTRING (fsp)->data);
  2052.     }
  2053.   return Qnil;
  2054. }
  2055.  
  2056.  
  2057. /* a version of write that will correctly retry when an interrupt arrives 
  2058.    down inside the syscall.  Returns 0 for success, something else for failure.
  2059.    If it fails, e_write_error is set to the error number.
  2060.  */
  2061. static int 
  2062. retrying_write (fd, addr, len)
  2063.      int fd;
  2064.      register char *addr;
  2065.      register int len;
  2066. {
  2067.   int nbytes;
  2068.   /* When you tell write() to write N bytes, it doesn't necessarily do so.
  2069.      If it writes some, and then gets in interrupt, it just stops, and tells
  2070.      you how many it did write, and the right thing to do is to immediately
  2071.      call write() again to dump the rest.  If write() returns -1, then that
  2072.      means that no output was written, and the reason is in errno.
  2073.    */
  2074.   while (0 < (nbytes = write (fd, addr, len))) {
  2075.     addr += nbytes;
  2076.     len -= nbytes;
  2077.   }
  2078.  
  2079.   if (nbytes) {
  2080.     if (errno == EINTR) {
  2081.       /* This means an interrupt arrived before any data was actually written,
  2082.      so the kernel punted, and the right thing to do is simply try again.
  2083.      ## Do we have to pussyfoot around EAGAIN as well?
  2084.        */
  2085.       return retrying_write (fd, addr, len);
  2086.     }
  2087.     /* else, it's a real error of some kind, not just unix stupidity.
  2088.        Cache the current value of errno in case something else set it before
  2089.        we get around to reporting the error to the user.
  2090.      */
  2091.     e_write_errno = errno;
  2092.     return nbytes;
  2093.   }
  2094.   /* else, everything went fine. */
  2095.   return 0;
  2096. }
  2097.  
  2098.  
  2099. /* Write LEN bytes starting at ADDR to FD.
  2100.    Returns 0 for success, something else for failure.
  2101.    If it fails, e_write_error is set to the error number.
  2102.  */
  2103. static int
  2104. e_write (fd, addr, len)
  2105.      int fd;
  2106.      register char *addr;
  2107.      register int len;
  2108. {
  2109.   char buf[16 * 1024];
  2110.   register char *p, *end;
  2111.  
  2112.   if (!EQ (current_buffer->selective_display, Qt))
  2113.     return retrying_write (fd, addr, len);
  2114.   else
  2115.     {
  2116.       int write_error;
  2117.       p = buf;
  2118.       end = p + sizeof buf;
  2119.       while (len--)
  2120.     {
  2121.       if (p == end)
  2122.         {
  2123.           if (0 != (write_error = retrying_write (fd, buf, sizeof buf)))
  2124.         return write_error;
  2125.           p = buf;
  2126.         }
  2127.       *p = *addr++;
  2128.       if (*p++ == '\015')
  2129.         p[-1] = '\n';
  2130.     }
  2131.       if (p != buf)
  2132.     if (0 != (write_error = retrying_write (fd, buf, p - buf)))
  2133.       return write_error;
  2134.     }
  2135.   return 0;
  2136. }
  2137.  
  2138.  
  2139. #if 0
  2140. #include <des_crypt.h>
  2141.  
  2142. #define CRYPT_BLOCK_SIZE 8    /* bytes */
  2143. #define CRYPT_KEY_SIZE 8    /* bytes */
  2144.  
  2145. DEFUN ("encrypt-string", Fencrypt_string, Sencrypt_string, 2, 2, 0,
  2146. "Encrypt STRING using KEY.")
  2147.   (string, key)
  2148.      Lisp_Object string, key;
  2149. {
  2150.   char *encrypted_string, *raw_key;
  2151.   int rounded_size, extra, key_size;
  2152.  
  2153.   CHECK_STRING (string, 0);
  2154.   CHECK_STRING (key, 1);
  2155.  
  2156.   extra = XSTRING (string)->size % CRYPT_BLOCK_SIZE;
  2157.   rounded_size = XSTRING (string)->size + extra;
  2158.   encrypted_string = alloca (rounded_size + 1);
  2159.   bcopy (XSTRING (string)->data, encrypted_string, XSTRING (string)->size);
  2160.   memset (encrypted_string + rounded_size - extra, 0, extra + 1);
  2161.  
  2162.   if (XSTRING (key)->size > CRYPT_KEY_SIZE)
  2163.     key_size = CRYPT_KEY_SIZE;
  2164.   else
  2165.     key_size = XSTRING (key)->size;
  2166.  
  2167.   raw_key = alloca (CRYPT_KEY_SIZE + 1);
  2168.   bcopy (XSTRING (key)->data, raw_key, key_size);
  2169.   memset (raw_key + key_size, 0, (CRYPT_KEY_SIZE + 1) - key_size);
  2170.  
  2171.   (void) ecb_crypt (raw_key, encrypted_string, rounded_size,
  2172.             DES_ENCRYPT | DES_SW);
  2173.   return make_string (encrypted_string, rounded_size);
  2174. }
  2175.  
  2176. DEFUN ("decrypt-string", Fdecrypt_string, Sdecrypt_string, 2, 2, 0,
  2177. "Decrypt STRING using KEY.")
  2178.   (string, key)
  2179.      Lisp_Object string, key;
  2180. {
  2181.   char *decrypted_string, *raw_key;
  2182.   int string_size, key_size;
  2183.  
  2184.   CHECK_STRING (string, 0);
  2185.   CHECK_STRING (key, 1);
  2186.  
  2187.   string_size = XSTRING (string)->size + 1;
  2188.   decrypted_string = alloca (string_size);
  2189.   bcopy (XSTRING (string)->data, decrypted_string, string_size);
  2190.   decrypted_string[string_size - 1] = '\0';
  2191.  
  2192.   if (XSTRING (key)->size > CRYPT_KEY_SIZE)
  2193.     key_size = CRYPT_KEY_SIZE;
  2194.   else
  2195.     key_size = XSTRING (key)->size;
  2196.  
  2197.   raw_key = alloca (CRYPT_KEY_SIZE + 1);
  2198.   bcopy (XSTRING (key)->data, raw_key, key_size);
  2199.   memset (raw_key + key_size, 0, (CRYPT_KEY_SIZE + 1) - key_size);
  2200.  
  2201.  
  2202.   (void) ecb_crypt (raw_key, decrypted_string, string_size,
  2203.             DES_DECRYPT | DES_SW);
  2204.   return make_string (decrypted_string, string_size - 1);
  2205. }
  2206. #endif
  2207.  
  2208. DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
  2209.   Sverify_visited_file_modtime, 1, 1, 0,
  2210.   "Return t if last mod time of BUF's visited file matches what BUF records.\n\
  2211. This means that the file has not been changed since it was visited or saved.")
  2212.   (buf)
  2213.      Lisp_Object buf;
  2214. {
  2215.   struct buffer *b;
  2216.   struct stat st;
  2217.  
  2218.   CHECK_BUFFER (buf, 0);
  2219.   b = XBUFFER (buf);
  2220.  
  2221.   if (!STRINGP (b->filename)) return Qt;
  2222.   if (b->modtime == 0) return Qt;
  2223.  
  2224.   if (stat ((char *)XSTRING (b->filename)->data, &st) < 0)
  2225.     {
  2226.       /* If the file doesn't exist now and didn't exist before,
  2227.      we say that it isn't modified, provided the error is a tame one.  */
  2228.       if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
  2229.     st.st_mtime = -1;
  2230.       else
  2231.     st.st_mtime = 0;
  2232.     }
  2233.   if (st.st_mtime == b->modtime
  2234.       /* If both are positive, accept them if they are off by one second.  */
  2235.       || (st.st_mtime > 0 && b->modtime > 0
  2236.       && (st.st_mtime == b->modtime + 1
  2237.           || st.st_mtime == b->modtime - 1)))
  2238.     return Qt;
  2239.   return Qnil;
  2240. }
  2241.  
  2242. DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
  2243.   Sclear_visited_file_modtime, 0, 0, 0,
  2244.   "Clear out records of last mod time of visited file.\n\
  2245. Next attempt to save will certainly not complain of a discrepancy.")
  2246.   ()
  2247. {
  2248.   current_buffer->modtime = 0;
  2249.   return Qnil;
  2250. }
  2251.  
  2252. DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
  2253.   Sset_visited_file_modtime, 0, 0, 0,
  2254.   "Update buffer's recorded modification time from the visited file's time.\n\
  2255. Useful if the buffer was not read from the file normally\n\
  2256. or if the file itself has been changed for some known benign reason.")
  2257.    ()
  2258. {
  2259.   register Lisp_Object filename;
  2260.   struct stat st;
  2261.  
  2262.   filename = Fexpand_file_name (current_buffer->filename, Qnil);
  2263.   
  2264.   if (stat ((char *)XSTRING (filename)->data, &st) >= 0)
  2265.     current_buffer->modtime = st.st_mtime;
  2266.  
  2267.   return Qnil;
  2268. }
  2269.  
  2270. DEFUN ("set-buffer-modtime", Fset_buffer_modtime,
  2271.   Sset_buffer_modtime, 1, 2, 0,
  2272.   "Update BUFFER's recorded modification time from the associated \n\
  2273. file's modtime, if there is an associated file. If not, use the \n\
  2274. current time. In either case, if the optional arg TIME is supplied, use \n\
  2275. that is it is either an integer or a cons of two integers.")
  2276.   (buf, in_time)
  2277. Lisp_Object buf, in_time;
  2278. {
  2279.   struct buffer *b = XBUFFER (buf);
  2280.   unsigned long time_to_use = 0;
  2281.   int set_time_to_use = 0;
  2282.   Lisp_Object filename;
  2283.   struct stat st;
  2284.  
  2285.   CHECK_BUFFER (buf, 0);
  2286.  
  2287.   if (!NILP (in_time))
  2288.     {
  2289.       if (FIXNUMP (in_time))
  2290.         {
  2291.           CHECK_FIXNUM (in_time, 1);
  2292.           time_to_use = XINT (in_time);
  2293.           set_time_to_use = 1;
  2294.         }
  2295.       else if ((CONSP (in_time)) &&
  2296.                (FIXNUMP (Fcar (in_time))) && 
  2297.                (FIXNUMP (Fcdr (in_time))))
  2298.         {
  2299.           time_to_use = lisp_to_word (in_time);
  2300.           set_time_to_use = 1;
  2301.         }
  2302.     }
  2303.  
  2304.   if (!set_time_to_use)
  2305.     {
  2306.       if (STRINGP (b->filename))
  2307.         filename = Fexpand_file_name (b->filename, Qnil);
  2308.       else
  2309.         filename = Qnil;
  2310.   
  2311.       if (!NILP (filename) && !NILP (Ffile_exists_p (filename)))
  2312.         {
  2313.           if (stat ((char *)XSTRING (filename)->data, &st) >= 0)
  2314.             time_to_use = st.st_mtime;
  2315.           else
  2316.             time_to_use = time ((long *)0);
  2317.         }
  2318.       else
  2319.     time_to_use = time ((long *)0);
  2320.     }
  2321.  
  2322.   b->modtime = time_to_use;
  2323.  
  2324.   return Qnil;
  2325. }
  2326.  
  2327.  
  2328. static Lisp_Object
  2329. auto_save_error ()
  2330. {
  2331.   unsigned char *name = XSTRING (current_buffer->name)->data;
  2332.  
  2333.   ring_bell (intern("auto-save-error"));  /* Lucid sound change */
  2334.   message ("Autosaving...error for %s", name);
  2335.   Fsleep_for (make_number (1));
  2336.   message ("Autosaving...error!for %s", name);
  2337.   Fsleep_for (make_number (1));
  2338.   message ("Autosaving...error for %s", name);
  2339.   Fsleep_for (make_number (1));
  2340.   return Qnil;
  2341. }
  2342.  
  2343. static Lisp_Object
  2344. auto_save_1 ()
  2345. {
  2346.   struct stat st;
  2347.  
  2348.   /* Get visited file's mode to become the auto save file's mode.  */
  2349.   if (!NILP (current_buffer->filename) &&
  2350.       stat ((char *)XSTRING (current_buffer->filename)->data, &st) >= 0)
  2351.     /* But make sure we can overwrite it later!  */
  2352.     auto_save_mode_bits = st.st_mode | 0600;
  2353.   else
  2354.     auto_save_mode_bits = 0666;
  2355.  
  2356.   return
  2357.     Fwrite_region (Qnil, Qnil,
  2358.            current_buffer->auto_save_file_name,
  2359.            Qnil, Qlambda);
  2360. }
  2361.  
  2362.  
  2363. /* Fdo_auto_save() checks whether a GC is in progress when it is called,
  2364.    and if so, tries to avoid touching lisp objects.
  2365.  
  2366.    The only time that Fdo_auto_save() is called while GC is in progress
  2367.    is if we're going down, as a result of an abort() or a kill signal.
  2368.    It's fairly important that we generate autosave files in that case!
  2369.  */
  2370. extern int gc_in_progress;
  2371.  
  2372.  
  2373. extern int minibuf_level;
  2374.  
  2375. DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 1, "",
  2376.   "Auto-save all buffers that need it.\n\
  2377. This is all buffers that have auto-saving enabled\n\
  2378. and are changed since last auto-saved.\n\
  2379. Auto-saving writes the buffer into a file\n\
  2380. so that your editing is not lost if the system crashes.\n\
  2381. This file is not the file you visited; that changes only when you save.\n\n\
  2382. Non-nil first argument means do not print any message if successful."
  2383. /* Nice idea but not yet implemented */
  2384. /* "Non-nil second argument means save only current buffer." */
  2385. )
  2386.   (nomsg)
  2387.      Lisp_Object nomsg;
  2388. {
  2389.   struct buffer *old = current_buffer, *b;
  2390.   Lisp_Object tail, buf;
  2391.   int auto_saved = 0;
  2392.   char *omessage = echo_area_glyphs;
  2393.  
  2394.   auto_saving = 1;
  2395.   if (minibuf_level || gc_in_progress)
  2396.     nomsg = Qt;
  2397.  
  2398.   /* Vrun_hooks is nil before emacs is dumped, and inc-vers.el will
  2399.      eventually call do-auto-save, so don't err here in that case. */
  2400.   if (!NILP (Vrun_hooks) && !gc_in_progress)
  2401.     call1 (Vrun_hooks, intern ("auto-save-hook"));
  2402.  
  2403.   for (tail = Vbuffer_alist;
  2404.        XGCTYPE (tail) == Lisp_Cons;
  2405.        tail = XCONS (tail)->cdr)
  2406.     {
  2407.       buf = XCONS (XCONS (tail)->car)->cdr;
  2408.       b = XBUFFER (buf);
  2409.       /* Check for auto save enabled
  2410.      and file changed since last auto save
  2411.      and file changed since last real save.  */
  2412.       if (XGCTYPE (b->auto_save_file_name) == Lisp_String
  2413.       && b->save_modified < BUF_MODIFF (b)
  2414.       && b->auto_save_modified < BUF_MODIFF (b))
  2415.     {
  2416.       if (!gc_in_progress &&
  2417.           (XFASTINT (b->save_length) * 10
  2418.            > (BUF_Z (b) - BUF_BEG (b)) * 13)
  2419.           /* A short file is likely to change a large fraction;
  2420.          spare the user annoying messages.  */
  2421.           && XFASTINT (b->save_length) > 5000
  2422.           /* These messages are frequent and annoying for `*mail*'.  */
  2423.           && !EQ (b->filename, Qnil))
  2424.         {
  2425.           /* It has shrunk too much; turn off auto-saving here.
  2426.          Unless we're about to crash, in which case auto-save it
  2427.          anyway.
  2428.            */
  2429.           message ("Buffer %s has shrunk a lot; auto save turned off there",
  2430.                XSTRING (b->name)->data);
  2431.           /* User can reenable saving with M-x auto-save.  */
  2432.           b->auto_save_file_name = Qnil;
  2433.           /* Prevent warning from repeating if user does so.  */
  2434.           XFASTINT (b->save_length) = 0;
  2435.           Fsleep_for (make_number (1));
  2436.           continue;
  2437.         }
  2438.       internal_set_buffer (b);
  2439.       if (!auto_saved && NILP (nomsg))
  2440.         message ("Auto-saving...");
  2441.       condition_case_1 (Qt,
  2442.                             auto_save_1, Qnil,
  2443.                             auto_save_error, Qnil);
  2444.       auto_saved++;
  2445.       b->auto_save_modified = BUF_MODIFF (b);
  2446.       XFASTINT (current_buffer->save_length) = Z - BEG;
  2447.       internal_set_buffer (old);
  2448.     }
  2449.     }
  2450.  
  2451.   if (auto_saved && NILP (nomsg))
  2452.     message ("%s", omessage ? omessage : "Auto-saving...done");
  2453.  
  2454.   auto_saving = 0;
  2455.   return Qnil;
  2456. }
  2457.  
  2458. DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
  2459.   Sset_buffer_auto_saved, 0, 0, 0,
  2460.   "Mark current buffer as auto-saved with its current text.\n\
  2461. No auto-save file will be written until the buffer changes again.")
  2462.   ()
  2463. {
  2464.   current_buffer->auto_save_modified = MODIFF;
  2465.   XFASTINT (current_buffer->save_length) = Z - BEG;
  2466.   return Qnil;
  2467. }
  2468.  
  2469. DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
  2470.   0, 0, 0,
  2471.   "Return t if buffer has been auto-saved since last read in or saved.")
  2472.   ()
  2473. {
  2474.   return (current_buffer->save_modified < current_buffer->auto_save_modified) ? Qt : Qnil;
  2475. }
  2476.  
  2477. void
  2478. syms_of_fileio ()
  2479. {
  2480.   Qfile_error = intern ("file-error");
  2481.   staticpro (&Qfile_error);
  2482.   Qfile_already_exists = intern("file-already-exists");
  2483.   staticpro (&Qfile_already_exists);
  2484.  
  2485.   Fput (Qfile_error, Qerror_conditions,
  2486.     Fcons (Qfile_error, Fcons (Qerror, Qnil)));
  2487.   Fput (Qfile_error, Qerror_message,
  2488.     build_string ("File error"));
  2489.  
  2490.   Fput (Qfile_already_exists, Qerror_conditions,
  2491.     Fcons (Qfile_already_exists,
  2492.            Fcons (Qfile_error, Fcons (Qerror, Qnil))));
  2493.   Fput (Qfile_already_exists, Qerror_message,
  2494.     build_string ("File already exists"));
  2495.  
  2496.   DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm,
  2497.     "*Non-nil means write new files with record format `stmlf'.\n\
  2498. nil means use format `var'.  This variable is meaningful only on VMS.");
  2499.   vms_stmlf_recfm = 0;
  2500.  
  2501.   defsubr (&Sfile_name_directory);
  2502.   defsubr (&Sfile_name_nondirectory);
  2503.   defsubr (&Sfile_name_as_directory);
  2504.   defsubr (&Sdirectory_file_name);
  2505.   defsubr (&Smake_temp_name);
  2506.   defsubr (&Sexpand_file_name);
  2507.   defsubr (&Struename);
  2508.   defsubr (&Ssubstitute_in_file_name);
  2509.   defsubr (&Scopy_file);
  2510.   defsubr (&Smake_directory);
  2511.   defsubr (&Sremove_directory);
  2512.   defsubr (&Sdelete_file);
  2513.   defsubr (&Srename_file);
  2514.   defsubr (&Sadd_name_to_file);
  2515. #ifdef S_IFLNK
  2516.   defsubr (&Smake_symbolic_link);
  2517. #endif /* S_IFLNK */
  2518. #ifdef VMS
  2519.   defsubr (&Sdefine_logical_name);
  2520. #endif /* VMS */
  2521. #ifdef HPUX_NET
  2522.   defsubr (&Ssysnetunam);
  2523. #endif /* HPUX_NET */
  2524.   defsubr (&Sfile_name_absolute_p);
  2525.   defsubr (&Sfile_exists_p);
  2526.   defsubr (&Sfile_executable_p);
  2527.   defsubr (&Sfile_readable_p);
  2528.   defsubr (&Sfile_writable_p);
  2529.   defsubr (&Sfile_symlink_p);
  2530.   defsubr (&Sfile_directory_p);
  2531.   defsubr (&Sfile_modes);
  2532.   defsubr (&Sset_file_modes);
  2533.   defsubr (&Sfile_newer_than_file_p);
  2534.   defsubr (&Sinsert_file_contents);
  2535.   defsubr (&Swrite_region);
  2536. #if 0
  2537.   defsubr (&Sencrypt_string);
  2538.   defsubr (&Sdecrypt_string);
  2539. #endif
  2540.   defsubr (&Sverify_visited_file_modtime);
  2541.   defsubr (&Sclear_visited_file_modtime);
  2542.   defsubr (&Sset_visited_file_modtime);
  2543.   defsubr (&Sset_buffer_modtime);
  2544.  
  2545.   defsubr (&Sdo_auto_save);
  2546.   defsubr (&Sset_buffer_auto_saved);
  2547.   defsubr (&Srecent_auto_save_p);
  2548. }
  2549.