12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152externalcapture_stdout:unit->unit="wax_pager_capture_stdout"externalflush_captured:unit->unit="wax_pager_flush_captured"letshould_use_pager()=Unix.isattyUnix.stdout&&Sys.getenv_opt"TERM"<>Some"dumb"&&Sys.getenv_opt"NOPAGER"=None(* [more] is the only pager present on every Windows system. *)letdefault_pager=ifSys.win32then"more"else"less -RFX"letallows_color()=(not(should_use_pager()))||Sys.getenv_opt"PAGER"<>None||notSys.win32letuse_nativef=flushstdout;letpager=matchSys.getenv_opt"PAGER"withSomep->p|None->default_pagerin(* [open_process_out] runs the command through the system shell ([/bin/sh
-c] on Unix, [cmd /d /c] on Windows) with our terminal as its
stdout/stderr, and returns a channel onto its stdin; [f] writes there,
leaving the process's own stdout untouched. *)letoc=Unix.open_process_outpagerin(* Closing [oc] gives the pager end-of-file; wait for the user to quit it
before exiting, whether [f] returned or exited through a diagnostic. *)at_exit(fun()->tryignore(Unix.close_process_outoc)withSys_error_->());(* A pager that quits early makes further writes fail; ignoring SIGPIPE
turns the lethal signal into the [Sys_error] handled below. Windows has
no SIGPIPE (the write simply fails). *)ifnotSys.win32thenSys.set_signalSys.sigpipeSys.Signal_ignore;tryfoc;exit0withSys_errormsgwhenmsg="Broken pipe"->exit0letuse_nodef=flushstdout;capture_stdout();Fun.protect~finally:(fun()->flushstdout;flush_captured())(fun()->fstdout)letusef=ifnot(should_use_pager())thenfstdoutelsematchSys.backend_typewith|Native|Bytecode->use_nativef|Other_->use_nodef