blob: ca002f9f791b6cdb8257836be9e13fe648afa1cc [file] [log] [blame]
Linus Torvaldsf67b45f2006-02-28 11:26:21 -08001#include "cache.h"
2
3/*
4 * This is split up from the rest of git so that we might do
5 * something different on Windows, for example.
6 */
7
Jeff King6e9af862007-12-11 01:27:33 -05008static int spawned_pager;
9
Johannes Schindelin402461a2006-04-16 04:44:25 +020010static void run_pager(const char *pager)
Linus Torvaldsf67b45f2006-02-28 11:26:21 -080011{
Linus Torvalds35ce8622007-01-24 11:21:10 -080012 /*
13 * Work around bug in "less" by not starting it until we
14 * have real input
15 */
16 fd_set in;
17
18 FD_ZERO(&in);
19 FD_SET(0, &in);
20 select(1, &in, NULL, &in, NULL);
21
Johannes Schindelin402461a2006-04-16 04:44:25 +020022 execlp(pager, pager, NULL);
Linus Torvalds34fd1c92006-04-21 12:25:13 -070023 execl("/bin/sh", "sh", "-c", pager, NULL);
Linus Torvaldsf67b45f2006-02-28 11:26:21 -080024}
25
26void setup_pager(void)
27{
28 pid_t pid;
29 int fd[2];
Matthias Lederhoferc27d2052006-07-31 15:27:00 +020030 const char *pager = getenv("GIT_PAGER");
Linus Torvaldsf67b45f2006-02-28 11:26:21 -080031
32 if (!isatty(1))
33 return;
Junio C Hamanocad3a202007-08-06 21:08:43 -070034 if (!pager) {
35 if (!pager_program)
36 git_config(git_default_config);
Brian Gernhardt54adf372007-07-03 14:18:11 -040037 pager = pager_program;
Junio C Hamanocad3a202007-08-06 21:08:43 -070038 }
Brian Gernhardt54adf372007-07-03 14:18:11 -040039 if (!pager)
Matthias Lederhoferc27d2052006-07-31 15:27:00 +020040 pager = getenv("PAGER");
41 if (!pager)
Johannes Schindelin402461a2006-04-16 04:44:25 +020042 pager = "less";
Junio C Hamanocaef71a2006-04-16 01:46:08 -070043 else if (!*pager || !strcmp(pager, "cat"))
Johannes Schindelin402461a2006-04-16 04:44:25 +020044 return;
45
Jeff King6e9af862007-12-11 01:27:33 -050046 spawned_pager = 1; /* means we are emitting to terminal */
Junio C Hamano85fb65e2006-06-06 16:58:40 -070047
Linus Torvaldsf67b45f2006-02-28 11:26:21 -080048 if (pipe(fd) < 0)
49 return;
50 pid = fork();
51 if (pid < 0) {
52 close(fd[0]);
53 close(fd[1]);
54 return;
55 }
56
57 /* return in the child */
58 if (!pid) {
59 dup2(fd[1], 1);
Junio C Hamano61b80502008-02-16 11:15:41 -080060 dup2(fd[1], 2);
Linus Torvaldsf67b45f2006-02-28 11:26:21 -080061 close(fd[0]);
62 close(fd[1]);
63 return;
64 }
65
66 /* The original process turns into the PAGER */
67 dup2(fd[0], 0);
68 close(fd[0]);
69 close(fd[1]);
70
Junio C Hamano0abc0262006-10-22 20:28:10 -070071 setenv("LESS", "FRSX", 0);
Johannes Schindelin402461a2006-04-16 04:44:25 +020072 run_pager(pager);
Linus Torvalds34fd1c92006-04-21 12:25:13 -070073 die("unable to execute pager '%s'", pager);
Linus Torvaldsf67b45f2006-02-28 11:26:21 -080074 exit(255);
75}
Jeff King6e9af862007-12-11 01:27:33 -050076
77int pager_in_use(void)
78{
79 const char *env;
80
81 if (spawned_pager)
82 return 1;
83
84 env = getenv("GIT_PAGER_IN_USE");
85 return env ? git_config_bool("GIT_PAGER_IN_USE", env) : 0;
86}