Win32: move environment block creation to a helper method
[git/mingw/4msysgit/kblees.git] / pager.c
blob975955ba82a0dbb128d6733090cd74c2b509ea81
1 #include "cache.h"
2 #include "run-command.h"
3 #include "sigchain.h"
5 #ifndef DEFAULT_PAGER
6 #define DEFAULT_PAGER "less"
7 #endif
9 /*
10 * This is split up from the rest of git so that we can do
11 * something different on Windows.
14 #ifndef WIN32
15 static void pager_preexec(void)
18 * Work around bug in "less" by not starting it until we
19 * have real input
21 fd_set in;
23 FD_ZERO(&in);
24 FD_SET(0, &in);
25 select(1, &in, NULL, &in, NULL);
27 #endif
29 static const char *pager_argv[] = { NULL, NULL };
30 static struct child_process pager_process;
32 static void wait_for_pager(void)
34 fflush(stdout);
35 fflush(stderr);
36 /* signal EOF to pager */
37 close(1);
38 close(2);
39 finish_command(&pager_process);
42 static void wait_for_pager_signal(int signo)
44 wait_for_pager();
45 sigchain_pop(signo);
46 raise(signo);
49 const char *git_pager(int stdout_is_tty)
51 const char *pager;
53 if (!stdout_is_tty)
54 return NULL;
56 pager = getenv("GIT_PAGER");
57 if (!pager) {
58 if (!pager_program)
59 git_config(git_default_config, NULL);
60 pager = pager_program;
62 if (!pager)
63 pager = getenv("PAGER");
64 if (!pager)
65 pager = DEFAULT_PAGER;
66 else if (!*pager || !strcmp(pager, "cat"))
67 pager = NULL;
69 return pager;
72 void setup_pager(void)
74 const char *pager = git_pager(isatty(1));
76 if (!pager)
77 return;
79 setenv("GIT_PAGER_IN_USE", "true", 1);
81 /* spawn the pager */
82 pager_argv[0] = pager;
83 pager_process.use_shell = 1;
84 pager_process.argv = pager_argv;
85 pager_process.in = -1;
86 if (!getenv("LESS")) {
87 static const char *env[] = { "LESS=FRSX", NULL };
88 pager_process.env = env;
90 #ifndef WIN32
91 pager_process.preexec_cb = pager_preexec;
92 #endif
93 if (start_command(&pager_process))
94 return;
96 /* original process continues, but writes to the pipe */
97 dup2(pager_process.in, 1);
98 if (isatty(2))
99 dup2(pager_process.in, 2);
100 close(pager_process.in);
102 /* this makes sure that the parent terminates after the pager */
103 sigchain_push_common(wait_for_pager_signal);
104 atexit(wait_for_pager);
107 int pager_in_use(void)
109 const char *env;
110 env = getenv("GIT_PAGER_IN_USE");
111 return env ? git_config_bool("GIT_PAGER_IN_USE", env) : 0;