1 // SPDX-License-Identifier: GPL-2.0
2 #include <sys/select.h>
9 #include "run-command.h"
11 #include "subcmd-config.h"
14 * This is split up from the rest of git so that we can do
15 * something different on Windows.
18 static int spawned_pager;
19 static int pager_columns;
21 void pager_init(const char *pager_env)
23 subcmd_config.pager_env = pager_env;
26 static void pager_preexec(void)
29 * Work around bug in "less" by not starting it until we
36 select(1, &in, NULL, &in, NULL);
38 setenv("LESS", "FRSX", 0);
41 static const char *pager_argv[] = { "sh", "-c", NULL, NULL };
42 static struct child_process pager_process;
44 static void wait_for_pager(void)
48 /* signal EOF to pager */
51 finish_command(&pager_process);
54 static void wait_for_pager_signal(int signo)
61 void setup_pager(void)
63 const char *pager = getenv(subcmd_config.pager_env);
68 if (ioctl(1, TIOCGWINSZ, &sz) == 0)
69 pager_columns = sz.ws_col;
71 pager = getenv("PAGER");
72 if (!(pager || access("/usr/bin/pager", X_OK)))
73 pager = "/usr/bin/pager";
74 if (!(pager || access("/usr/bin/less", X_OK)))
75 pager = "/usr/bin/less";
78 if (!*pager || !strcmp(pager, "cat"))
81 spawned_pager = 1; /* means we are emitting to terminal */
84 pager_argv[2] = pager;
85 pager_process.argv = pager_argv;
86 pager_process.in = -1;
87 pager_process.preexec_cb = pager_preexec;
89 if (start_command(&pager_process))
92 /* original process continues, but writes to the pipe */
93 dup2(pager_process.in, 1);
95 dup2(pager_process.in, 2);
96 close(pager_process.in);
98 /* this makes sure that the parent terminates after the pager */
99 sigchain_push_common(wait_for_pager_signal);
100 atexit(wait_for_pager);
103 int pager_in_use(void)
105 return spawned_pager;
108 int pager_get_columns(void)
112 s = getenv("COLUMNS");
116 return (pager_columns ? pager_columns : 80) - 2;