2 * Copyright (C) 1984-2011 Mark Nudelman
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Less License, as specified in the README file.
7 * For more information about less, or for information on how to
8 * contact the author, see the README file.
13 * Routines to mess around with filenames (and files).
14 * Much of this is very OS dependent.
21 #if MSDOS_COMPILER==WIN32C && defined(__BORLANDC__)
24 #if MSDOS_COMPILER==DJGPPC
27 #define _MAX_PATH PATH_MAX
43 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
46 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
51 extern int force_open;
53 extern int use_lessopen;
56 extern IFILE curr_ifile;
57 extern IFILE old_ifile;
58 #if SPACES_IN_FILENAMES
59 extern char openquote;
60 extern char closequote;
64 * Remove quotes around a filename.
73 name = p = (char *) ecalloc(strlen(str)+1, sizeof(char));
74 if (*str == openquote)
79 if (*str == closequote)
81 if (str[1] != closequote)
89 char *esc = get_meta_escape();
90 int esclen = strlen(esc);
93 if (esclen > 0 && strncmp(str, esc, esclen) == 0)
103 * Get the shell's escape character.
110 s = lgetenv("LESSMETAESCAPE");
117 * Get the characters which the shell considers to be "metacharacters".
122 static char *mchars = NULL;
126 mchars = lgetenv("LESSMETACHARS");
128 mchars = DEF_METACHARS;
134 * Is this a shell metacharacter?
140 return (strchr(metachars(), c) != NULL);
144 * Insert a backslash before each metacharacter in a string.
153 char *esc = get_meta_escape();
154 int esclen = strlen(esc);
159 * Determine how big a string we need to allocate.
161 len = 1; /* Trailing null byte */
162 for (p = s; *p != '\0'; p++)
165 if (*p == openquote || *p == closequote)
172 * We've got a metachar, but this shell
173 * doesn't support escape chars. Use quotes.
179 * Allow space for the escape char.
189 * We can't quote a string that contains quotes.
195 * Allocate and construct the new string.
197 newstr = p = (char *) ecalloc(len, sizeof(char));
200 SNPRINTF3(newstr, len, "%c%s%c", openquote, s, closequote);
208 * Add the escape char.
221 * Return a pathname that points to a specified file in a specified directory.
222 * Return NULL if the file does not exist in the directory.
225 dirfile(dirname, filename)
234 if (dirname == NULL || *dirname == '\0')
237 * Construct the full pathname.
239 len= strlen(dirname) + strlen(filename) + 2;
240 pathname = (char *) calloc(len, sizeof(char));
241 if (pathname == NULL)
243 SNPRINTF3(pathname, len, "%s%s%s", dirname, PATHNAME_SEP, filename);
245 * Make sure the file exists.
247 qpathname = shell_unquote(pathname);
248 f = open(qpathname, OPEN_READ);
262 * Return the full pathname of the given file in the "home directory".
268 register char *pathname;
271 * Try $HOME/filename.
273 pathname = dirfile(lgetenv("HOME"), filename);
274 if (pathname != NULL)
278 * Try $INIT/filename.
280 pathname = dirfile(lgetenv("INIT"), filename);
281 if (pathname != NULL)
284 #if MSDOS_COMPILER || OS2
286 * Look for the file anywhere on search path.
288 pathname = (char *) calloc(_MAX_PATH, sizeof(char));
289 #if MSDOS_COMPILER==DJGPPC
291 char *res = searchpath(filename);
295 strcpy(pathname, res);
298 _searchenv(filename, "PATH", pathname);
300 if (*pathname != '\0')
308 * Expand a string, substituting any "%" with the current filename,
309 * and any "#" with the previous filename.
310 * But a string of N "%"s is just replaced with N-1 "%"s.
311 * Likewise for a string of N "#"s.
312 * {{ This is a lot of work just to support % and #. }}
318 register char *fr, *to;
323 #define fchar_ifile(c) \
324 ((c) == '%' ? curr_ifile : \
325 (c) == '#' ? old_ifile : NULL_IFILE)
328 * Make one pass to see how big a buffer we
329 * need to allocate for the expanded string.
332 for (fr = s; *fr != '\0'; fr++)
338 if (fr > s && fr[-1] == *fr)
341 * Second (or later) char in a string
342 * of identical chars. Treat as normal.
345 } else if (fr[1] != *fr)
348 * Single char (not repeated). Treat specially.
350 ifile = fchar_ifile(*fr);
351 if (ifile == NULL_IFILE)
354 n += strlen(get_filename(ifile));
357 * Else it is the first char in a string of
358 * identical chars. Just discard it.
367 e = (char *) ecalloc(n+1, sizeof(char));
370 * Now copy the string, expanding any "%" or "#".
373 for (fr = s; *fr != '\0'; fr++)
379 if (fr > s && fr[-1] == *fr)
382 } else if (fr[1] != *fr)
384 ifile = fchar_ifile(*fr);
385 if (ifile == NULL_IFILE)
389 strcpy(to, get_filename(ifile));
404 #if TAB_COMPLETE_FILENAME
407 * Return a blank-separated list of filenames which "complete"
420 * Complete the filename "s" by globbing "s*".
422 #if MSDOS_COMPILER && (MSDOS_COMPILER == MSOFTC || MSDOS_COMPILER == BORLANDC)
424 * But in DOS, we have to glob "s*.*".
425 * But if the final component of the filename already has
426 * a dot in it, just do "s*".
427 * (Thus, "FILE" is globbed as "FILE*.*",
428 * but "FILE.A" is globbed as "FILE.A*").
433 for (slash = s+strlen(s)-1; slash > s; slash--)
434 if (*slash == *PATHNAME_SEP || *slash == '/')
437 fpat = (char *) ecalloc(len, sizeof(char));
438 if (strchr(slash, '.') == NULL)
439 SNPRINTF1(fpat, len, "%s*.*", s);
441 SNPRINTF1(fpat, len, "%s*", s);
445 int len = strlen(s) + 2;
446 fpat = (char *) ecalloc(len, sizeof(char));
447 SNPRINTF1(fpat, len, "%s*", s);
451 s = shell_unquote(qs);
452 if (strcmp(s,fpat) == 0)
455 * The filename didn't expand.
467 * Try to determine if a file is "binary".
468 * This is just a guess, and we need not try too hard to make it accurate.
482 if (lseek(f, (off_t)0, SEEK_SET) == BAD_LSEEK)
484 n = read(f, data, sizeof(data));
486 for (p = data; p < pend; )
488 LWCHAR c = step_char(&p, +1, pend);
489 if (ctldisp == OPT_ONPLUS && IS_CSI_START(c))
492 c = step_char(&p, +1, pend);
493 } while (p < pend && is_ansi_middle(c));
494 } else if (binary_char(c))
498 * Call it a binary file if there are more than 5 binary characters
499 * in the first 256 bytes of the file.
501 return (bin_count > 5);
505 * Try to determine the size of a file by seeking to the end.
513 spos = lseek(f, (off_t)0, SEEK_END);
514 if (spos == BAD_LSEEK)
515 return (NULL_POSITION);
516 return ((POSITION) spos);
520 * Read a string from a file.
521 * Return a pointer to the string in memory.
533 * Make a guess about how many chars in the string
534 * and allocate a buffer to hold it.
537 buf = (char *) ecalloc(len, sizeof(char));
540 if ((ch = getc(fd)) == '\n' || ch == EOF)
542 if (p - buf >= len-1)
545 * The string is too big to fit in the buffer we have.
546 * Allocate a new buffer, twice as big.
550 p = (char *) ecalloc(len, sizeof(char));
554 p = buf + strlen(buf);
566 #if MSDOS_COMPILER && MSDOS_COMPILER!=WIN32C
571 * Execute a shell command.
572 * Return a pointer to a pipe connected to the shell command's standard output.
583 shell = lgetenv("SHELL");
584 if (shell != NULL && *shell != '\0')
590 * Read the output of <$SHELL -c cmd>.
591 * Escape any metacharacters in the command.
593 esccmd = shell_quote(cmd);
596 fd = popen(cmd, "r");
599 int len = strlen(shell) + strlen(esccmd) + 5;
600 scmd = (char *) ecalloc(len, sizeof(char));
601 SNPRINTF3(scmd, len, "%s %s %s", shell, shell_coption(), esccmd);
603 fd = popen(scmd, "r");
609 fd = popen(cmd, "r");
612 * Redirection in `popen' might have messed with the
613 * standard devices. Restore binary input mode.
619 #endif /* HAVE_POPEN */
623 * Expand a filename, doing any system-specific metacharacter substitutions.
632 ofilename = fexpand(filename);
635 filename = shell_unquote(ofilename);
637 #ifdef DECL_GLOB_LIST
640 * The globbing function returns a list of names.
647 GLOB_LIST(filename, list);
648 if (GLOB_LIST_FAILED(list))
653 length = 1; /* Room for trailing null byte */
654 for (SCAN_GLOB_LIST(list, p))
656 INIT_GLOB_LIST(list, p);
657 qfilename = shell_quote(p);
658 if (qfilename != NULL)
660 length += strlen(qfilename) + 1;
664 gfilename = (char *) ecalloc(length, sizeof(char));
665 for (SCAN_GLOB_LIST(list, p))
667 INIT_GLOB_LIST(list, p);
668 qfilename = shell_quote(p);
669 if (qfilename != NULL)
671 sprintf(gfilename + strlen(gfilename), "%s ", qfilename);
676 * Overwrite the final trailing space with a null terminator.
679 GLOB_LIST_DONE(list);
682 #ifdef DECL_GLOB_NAME
685 * The globbing function returns a single name, and
686 * is called multiple times to walk thru all names.
693 DECL_GLOB_NAME(fnd,drive,dir,fname,ext,handle)
695 GLOB_FIRST_NAME(filename, &fnd, handle);
696 if (GLOB_FIRST_FAILED(handle))
702 _splitpath(filename, drive, dir, fname, ext);
704 gfilename = (char *) ecalloc(len, sizeof(char));
707 n = strlen(drive) + strlen(dir) + strlen(fnd.GLOB_NAME) + 1;
708 pathname = (char *) ecalloc(n, sizeof(char));
709 SNPRINTF3(pathname, n, "%s%s%s", drive, dir, fnd.GLOB_NAME);
710 qpathname = shell_quote(pathname);
712 if (qpathname != NULL)
714 n = strlen(qpathname);
715 while (p - gfilename + n + 2 >= len)
718 * No room in current buffer.
719 * Allocate a bigger one.
723 p = (char *) ecalloc(len, sizeof(char));
724 strcpy(p, gfilename);
727 p = gfilename + strlen(gfilename);
729 strcpy(p, qpathname);
734 } while (GLOB_NEXT_NAME(handle, &fnd) == 0);
737 * Overwrite the final trailing space with a null terminator.
740 GLOB_NAME_DONE(handle);
746 * We get the shell to glob the filename for us by passing
747 * an "echo" command to the shell and reading its output.
756 esc = get_meta_escape();
757 if (strlen(esc) == 0)
759 esc = shell_quote(esc);
765 lessecho = lgetenv("LESSECHO");
766 if (lessecho == NULL || *lessecho == '\0')
767 lessecho = "lessecho";
769 * Invoke lessecho, and read its output (a globbed list of filenames).
771 len = strlen(lessecho) + strlen(ofilename) + (7*strlen(metachars())) + 24;
772 cmd = (char *) ecalloc(len, sizeof(char));
773 SNPRINTF4(cmd, len, "%s -p0x%x -d0x%x -e%s ", lessecho, openquote, closequote, esc);
775 for (s = metachars(); *s != '\0'; s++)
776 sprintf(cmd + strlen(cmd), "-n0x%x ", *s);
777 sprintf(cmd + strlen(cmd), "-- %s", ofilename);
783 * Cannot create the pipe.
784 * Just return the original (fexpanded) filename.
789 gfilename = readfd(fd);
791 if (*gfilename == '\0')
800 * No globbing functions at all. Just use the fexpanded filename.
802 gfilename = save(filename);
812 * See if we should open a "replacement file"
813 * instead of the file we're about to open.
816 open_altfile(filename, pf, pfd)
832 if (!use_lessopen || secure)
835 if ((lessopen = lgetenv("LESSOPEN")) == NULL)
837 if (*lessopen == '|')
840 * If LESSOPEN starts with a |, it indicates
841 * a "pipe preprocessor".
844 error("LESSOPEN pipe is not supported", NULL_PARG);
851 if (*lessopen == '-') {
853 * Lessopen preprocessor will accept "-" as a filename.
857 if (strcmp(filename, "-") == 0)
861 len = strlen(lessopen) + strlen(filename) + 2;
862 cmd = (char *) ecalloc(len, sizeof(char));
863 SNPRINTF1(cmd, len, lessopen, filename);
869 * Cannot create the pipe.
880 * Read one char to see if the pipe will produce any data.
881 * If it does, push the char back on the pipe.
885 if (read(f, &c, 1) != 1)
888 * Pipe is empty. This means there is no alt file.
903 * Pipe is empty. This means there is no alt file.
907 #endif /* HAVE_POPEN */
911 * Close a replacement file.
914 close_altfile(altfilename, filename, pipefd)
931 * The pclose function of OS/2 emx sometimes fails.
932 * Send SIGINT to the piped process before closing it.
934 kill(((FILE*)pipefd)->_pid, SIGINT);
936 pclose((FILE*) pipefd);
938 if ((lessclose = lgetenv("LESSCLOSE")) == NULL)
940 len = strlen(lessclose) + strlen(filename) + strlen(altfilename) + 2;
941 cmd = (char *) ecalloc(len, sizeof(char));
942 SNPRINTF2(cmd, len, lessclose, filename, altfilename);
951 * Is the specified file a directory?
959 filename = shell_unquote(filename);
965 r = stat(filename, &statbuf);
966 isdir = (r >= 0 && S_ISDIR(statbuf.st_mode));
973 f = open(filename, S_IREAD | S_IFDIR);
985 * Returns NULL if the file can be opened and
986 * is an ordinary file, otherwise an error message
987 * (if it cannot be opened or is a directory, etc.)
993 register char *m = NULL;
995 filename = shell_unquote(filename);
996 if (!force_open && is_dir(filename))
998 static char is_a_dir[] = " is a directory";
1000 m = (char *) ecalloc(strlen(filename) + sizeof(is_a_dir),
1002 strcpy(m, filename);
1003 strcat(m, is_a_dir);
1008 struct stat statbuf;
1010 r = stat(filename, &statbuf);
1013 m = errno_message(filename);
1014 } else if (force_open)
1017 } else if (!S_ISREG(statbuf.st_mode))
1019 static char not_reg[] = " is not a regular file (use -f to see it)";
1020 m = (char *) ecalloc(strlen(filename) + sizeof(not_reg),
1022 strcpy(m, filename);
1032 * Return the size of a file, as cheaply as possible.
1033 * In Unix, we can stat the file.
1040 struct stat statbuf;
1042 if (fstat(f, &statbuf) >= 0)
1043 return ((POSITION) statbuf.st_size);
1048 if ((size = (long) _gs_size(f)) >= 0)
1049 return ((POSITION) size);
1052 return (seek_filesize(f));
1065 * Return last component of a pathname.
1068 last_component(name)
1073 for (slash = name + strlen(name); slash > name; )
1076 if (*slash == *PATHNAME_SEP || *slash == '/')