xref: /freebsd/usr.bin/man/man.sh (revision f5463265955b829775bbb32e1fd0bc11dafc36ce)
1#! /bin/sh
2#
3# SPDX-License-Identifier: BSD-2-Clause
4#
5#  Copyright (c) 2010 Gordon Tetlow
6#  All rights reserved.
7#
8#  Redistribution and use in source and binary forms, with or without
9#  modification, are permitted provided that the following conditions
10#  are met:
11#  1. Redistributions of source code must retain the above copyright
12#     notice, this list of conditions and the following disclaimer.
13#  2. Redistributions in binary form must reproduce the above copyright
14#     notice, this list of conditions and the following disclaimer in the
15#     documentation and/or other materials provided with the distribution.
16#
17#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23#  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24#  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27#  SUCH DAMAGE.
28#
29
30# Rendering a manual page is fast. Even a manual page several 100k in size
31# takes less than a CPU second. If it takes much longer, it is very likely
32# that a tool like mandoc(1) is running in an infinite loop. In this case
33# it is better to terminate it.
34ulimit -t 20
35
36# Usage: add_to_manpath path
37# Adds a variable to manpath while ensuring we don't have duplicates.
38# Returns true if we were able to add something. False otherwise.
39add_to_manpath() {
40	case "$manpath" in
41	*:$1)	decho "  Skipping duplicate manpath entry $1" 2 ;;
42	$1:*)	decho "  Skipping duplicate manpath entry $1" 2 ;;
43	*:$1:*)	decho "  Skipping duplicate manpath entry $1" 2 ;;
44	*)	if [ -d "$1" ]; then
45			decho "  Adding $1 to manpath"
46			manpath="$manpath:$1"
47			return 0
48		fi
49		;;
50	esac
51
52	return 1
53}
54
55# Usage: build_manlocales
56# Builds a correct MANLOCALES variable.
57build_manlocales() {
58	# If the user has set manlocales, who are we to argue.
59	if [ -n "$MANLOCALES" ]; then
60		return
61	fi
62
63	parse_configs
64
65	# Trim leading colon
66	MANLOCALES=${manlocales#:}
67
68	decho "Available manual locales: $MANLOCALES"
69}
70
71# Usage: build_mansect
72# Builds a correct MANSECT variable.
73build_mansect() {
74	# If the user has set mansect, who are we to argue.
75	if [ -n "$MANSECT" ]; then
76		return
77	fi
78
79	parse_configs
80
81	# Trim leading colon
82	MANSECT=${mansect#:}
83
84	if [ -z "$MANSECT" ]; then
85		MANSECT=$man_default_sections
86	fi
87	decho "Using manual sections: $MANSECT"
88}
89
90# Usage: build_manpath
91# Builds a correct MANPATH variable.
92build_manpath() {
93	local IFS
94
95	# If the user has set a manpath, who are we to argue.
96	if [ -n "$MANPATH" ]; then
97		case "$MANPATH" in
98		*:) PREPEND_MANPATH=${MANPATH} ;;
99		:*) APPEND_MANPATH=${MANPATH} ;;
100		*::*)
101			PREPEND_MANPATH=${MANPATH%%::*}
102			APPEND_MANPATH=${MANPATH#*::}
103			;;
104		*) return ;;
105		esac
106	fi
107
108	if [ -n "$PREPEND_MANPATH" ]; then
109		IFS=:
110		for path in $PREPEND_MANPATH; do
111			add_to_manpath "$path"
112		done
113		unset IFS
114	fi
115
116	search_path
117
118	decho "Adding default manpath entries"
119	IFS=:
120	for path in $man_default_path; do
121		add_to_manpath "$path"
122	done
123	unset IFS
124
125	parse_configs
126
127	if [ -n "$APPEND_MANPATH" ]; then
128		IFS=:
129		for path in $APPEND_MANPATH; do
130			add_to_manpath "$path"
131		done
132		unset IFS
133	fi
134	# Trim leading colon
135	MANPATH=${manpath#:}
136
137	decho "Using manual path: $MANPATH"
138}
139
140# Usage: check_cat catglob
141# Checks to see if a cat glob is available.
142check_cat() {
143	if exists "$1"; then
144		use_cat=yes
145		catpage=$found
146		setup_cattool "$catpage"
147		decho "    Found catpage \"$catpage\""
148		return 0
149	else
150		return 1
151	fi
152}
153
154# Usage: check_man manglob catglob
155# Given 2 globs, figures out if the manglob is available, if so, check to
156# see if the catglob is also available and up to date.
157check_man() {
158	if exists "$1"; then
159		# We have a match, check for a cat page
160		manpage=$found
161		setup_cattool "$manpage"
162		decho "    Found manpage \"$manpage\""
163
164		if [ -n "${use_width}" ]; then
165			# non-standard width
166			unset use_cat
167			decho "    Skipping catpage: non-standard page width"
168		elif exists "$2" && is_newer $found "$manpage"; then
169			# cat page found and is newer, use that
170			use_cat=yes
171			catpage=$found
172			setup_cattool "$catpage"
173			decho "    Using catpage \"$catpage\""
174		else
175			# no cat page or is older
176			unset use_cat
177			decho "    Skipping catpage: not found or old"
178		fi
179		return 0
180	fi
181
182	return 1
183}
184
185# Usage: decho "string" [debuglevel]
186# Echoes to stderr string prefaced with -- if high enough debuglevel.
187decho() {
188	if [ $debug -ge ${2:-1} ]; then
189		echo "-- $1" >&2
190	fi
191}
192
193# Usage: exists glob
194#
195# Returns true if glob resolves to a real file and store the first
196# found filename in the variable $found
197exists() {
198	local IFS
199
200	# Don't accidentally inherit callers IFS (breaks perl manpages)
201	unset IFS
202
203	# Use some globbing tricks in the shell to determine if a file
204	# exists or not.
205	set +f
206	for file in "$1"*
207	do
208		if [ -r "$file" ]; then
209			found="$file"
210			set -f
211			return 0
212		fi
213	done
214	set -f
215
216	return 1
217}
218
219# Usage: find_file path section subdir pagename
220# Returns: true if something is matched and found.
221# Search the given path/section combo for a given page.
222find_file() {
223	local manroot catroot mann man0 catn cat0
224
225	manroot="$1/man$2"
226	catroot="$1/cat$2"
227	if [ -n "$3" ]; then
228		manroot="$manroot/$3"
229		catroot="$catroot/$3"
230	fi
231
232	if [ ! -d "$manroot" -a ! -d "$catroot" ]; then
233		return 1
234	fi
235	decho "  Searching directory $manroot" 2
236
237	mann="$manroot/$4.$2"
238	man0="$manroot/$4.0"
239	catn="$catroot/$4.$2"
240	cat0="$catroot/$4.0"
241
242	# This is the behavior as seen by the original man utility.
243	# Let's not change that which doesn't seem broken.
244	if check_man "$mann" "$catn"; then
245		return 0
246	elif check_man "$man0" "$cat0"; then
247		return 0
248	elif check_cat "$catn"; then
249		return 0
250	elif check_cat "$cat0"; then
251		return 0
252	fi
253
254	return 1
255}
256
257# Usage: is_newer file1 file2
258# Returns true if file1 is newer than file2 as calculated by mtime.
259is_newer() {
260	if ! [ "$1" -ot "$2" ]; then
261		decho "    mtime: $1 not older than $2" 3
262		return 0
263	else
264		decho "    mtime: $1 older than $2" 3
265		return 1
266	fi
267}
268
269# Usage: manpath_parse_args "$@"
270# Parses commandline options for manpath.
271manpath_parse_args() {
272	local cmd_arg
273
274	OPTIND=1
275	while getopts 'Ldq' cmd_arg; do
276		case "${cmd_arg}" in
277		L)	Lflag=Lflag ;;
278		d)	debug=$(( $debug + 1 )) ;;
279		q)	qflag=qflag ;;
280		*)	manpath_usage ;;
281		esac
282	done >&2
283}
284
285# Usage: manpath_usage
286# Display usage for the manpath(1) utility.
287manpath_usage() {
288	echo 'usage: manpath [-Ldq]' >&2
289	exit 1
290}
291
292# Usage: manpath_warnings
293# Display some warnings to stderr.
294manpath_warnings() {
295	if [ -n "$Lflag" -a -n "$MANLOCALES" ]; then
296		echo "(Warning: MANLOCALES environment variable set)" >&2
297	fi
298}
299
300# Usage: man_check_for_so page path
301# Returns: True if able to resolve the file, false if it ended in tears.
302# Detects the presence of the .so directive and causes the file to be
303# redirected to another source file.
304man_check_for_so() {
305	local IFS line tstr
306
307	unset IFS
308	if [ -n "$catpage" ]; then
309		return 0
310	fi
311
312	# We need to loop to accommodate multiple .so directives.
313	while true
314	do
315		line=$($cattool "$manpage" | head -n1)
316		case "$line" in
317		.so*)	trim "${line#.so}"
318			decho "$manpage includes $tstr"
319			# Glob and check for the file.
320			if ! check_man "$path/$tstr" ""; then
321				decho "  Unable to find $tstr"
322				return 1
323			fi
324			;;
325		*)	break ;;
326		esac
327	done
328
329	return 0
330}
331
332# Usage: man_display_page
333# Display either the manpage or catpage depending on the use_cat variable
334man_display_page() {
335	local IFS pipeline testline
336
337	# We are called with IFS set to colon. This causes really weird
338	# things to happen for the variables that have spaces in them.
339	unset IFS
340
341	# If we are supposed to use a catpage and we aren't using troff(1)
342	# just zcat the catpage and we are done.
343	if [ -z "$tflag" -a -n "$use_cat" ]; then
344		if [ -n "$wflag" ]; then
345			echo "$catpage (source: \"$manpage\")"
346			ret=0
347		else
348			if [ $debug -gt 0 ]; then
349				decho "Command: $cattool \"$catpage\" | $MANPAGER"
350				ret=0
351			else
352				$cattool "$catpage" | $MANPAGER
353				ret=$?
354			fi
355		fi
356		return
357	fi
358
359	# Okay, we are using the manpage, do we just need to output the
360	# name of the manpage?
361	if [ -n "$wflag" ]; then
362		echo "$manpage"
363		ret=0
364		return
365	fi
366
367	if [ -n "$use_width" ]; then
368		mandoc_args="-O width=${use_width}"
369	fi
370	testline="mandoc -Tlint -Wunsupp >/dev/null 2>&1"
371	if [ -n "$tflag" ]; then
372		pipeline="mandoc -Tps $mandoc_args"
373	else
374		pipeline="mandoc $mandoc_args | $MANPAGER"
375	fi
376
377	if ! $cattool "$manpage" | eval "$testline"; then
378		if which -s groff; then
379			man_display_page_groff
380		else
381			echo "This manpage needs groff(1) to be rendered" >&2
382			echo "First install groff(1): " >&2
383			echo "pkg install groff " >&2
384			ret=1
385		fi
386		return
387	fi
388
389	if [ $debug -gt 0 ]; then
390		decho "Command: $cattool \"$manpage\" | eval \"$pipeline\""
391		ret=0
392	else
393		$cattool "$manpage" | eval "$pipeline"
394		ret=$?
395	fi
396}
397
398# Usage: man_display_page_groff
399# Display the manpage using groff
400man_display_page_groff() {
401	local EQN NROFF PIC TBL TROFF REFER VGRIND
402	local IFS l nroff_dev pipeline preproc_arg tool
403
404	# So, we really do need to parse the manpage. First, figure out the
405	# device flag (-T) we have to pass to eqn(1) and groff(1). Then,
406	# setup the pipeline of commands based on the user's request.
407
408	# If the manpage is from a particular charset, we need to setup nroff
409	# to properly output for the correct device.
410	case "${manpage}" in
411	*.${man_charset}/*)
412		# I don't pretend to know this; I'm just copying from the
413		# previous version of man(1).
414		case "$man_charset" in
415		KOI8-R)		nroff_dev="koi8-r" ;;
416		ISO8859-1)	nroff_dev="latin1" ;;
417		ISO8859-15)	nroff_dev="latin1" ;;
418		UTF-8)		nroff_dev="utf8" ;;
419		*)		nroff_dev="ascii" ;;
420		esac
421
422		NROFF="$NROFF -T$nroff_dev"
423		EQN="$EQN -T$nroff_dev"
424
425		# Iff the manpage is from the locale and not just the charset,
426		# then we need to define the locale string.
427		case "${manpage}" in
428		*/${man_lang}_${man_country}.${man_charset}/*)
429			NROFF="$NROFF -dlocale=$man_lang.$man_charset"
430			;;
431		*/${man_lang}.${man_charset}/*)
432			NROFF="$NROFF -dlocale=$man_lang.$man_charset"
433			;;
434		esac
435
436		# Allow language specific calls to override the default
437		# set of utilities.
438		l=$(echo $man_lang | tr [:lower:] [:upper:])
439		for tool in EQN NROFF PIC TBL TROFF REFER VGRIND; do
440			eval "$tool=\${${tool}_$l:-\$$tool}"
441		done
442		;;
443	*)	NROFF="$NROFF -Tascii"
444		EQN="$EQN -Tascii"
445		;;
446	esac
447
448	if [ -z "$MANCOLOR" ]; then
449		NROFF="$NROFF -P-c"
450	fi
451
452	if [ -n "${use_width}" ]; then
453		NROFF="$NROFF -rLL=${use_width}n -rLT=${use_width}n"
454	fi
455
456	if [ -n "$MANROFFSEQ" ]; then
457		set -- -$MANROFFSEQ
458		OPTIND=1
459		while getopts 'egprtv' preproc_arg; do
460			case "${preproc_arg}" in
461			e)	pipeline="$pipeline | $EQN" ;;
462			g)	;; # Ignore for compatibility.
463			p)	pipeline="$pipeline | $PIC" ;;
464			r)	pipeline="$pipeline | $REFER" ;;
465			t)	pipeline="$pipeline | $TBL" ;;
466			v)	pipeline="$pipeline | $VGRIND" ;;
467			*)	usage ;;
468			esac
469		done
470		# Strip the leading " | " from the resulting pipeline.
471		pipeline="${pipeline#" | "}"
472	else
473		pipeline="$TBL"
474	fi
475
476	if [ -n "$tflag" ]; then
477		pipeline="$pipeline | $TROFF"
478	else
479		pipeline="$pipeline | $NROFF | $MANPAGER"
480	fi
481
482	if [ $debug -gt 0 ]; then
483		decho "Command: $cattool \"$manpage\" | eval \"$pipeline\""
484		ret=0
485	else
486		$cattool "$manpage" | eval "$pipeline"
487		ret=$?
488	fi
489}
490
491# Usage: man_find_and_display page
492# Search through the manpaths looking for the given page.
493man_find_and_display() {
494	local found_page locpath p path sect
495
496	# Check to see if it's a file. But only if it has a '/' in
497	# the filename.
498	case "$1" in
499	*/*)	if [ -f "$1" -a -r "$1" ]; then
500			decho "Found a usable page, displaying that"
501			unset use_cat
502			manpage="$1"
503			setup_cattool "$manpage"
504			if man_check_for_so "$manpage" "$(dirname \"$manpage"")"; then
505				found_page=yes
506				man_display_page
507			fi
508			return
509		fi
510		;;
511	esac
512
513	IFS=:
514	for sect in $MANSECT; do
515		decho "Searching section $sect" 2
516		for path in $MANPATH; do
517			for locpath in $locpaths; do
518				p=$path/$locpath
519				p=${p%/.} # Rid ourselves of the trailing /.
520
521				# Check if there is a MACHINE specific manpath.
522				if find_file $p $sect $MACHINE "$1"; then
523					if man_check_for_so "$manpage" $p; then
524						found_page=yes
525						man_display_page
526						if [ -n "$aflag" ]; then
527							continue 2
528						else
529							return
530						fi
531					fi
532				fi
533
534				# Check if there is a MACHINE_ARCH
535				# specific manpath.
536				if find_file $p $sect $MACHINE_ARCH "$1"; then
537					if man_check_for_so "$manpage" $p; then
538						found_page=yes
539						man_display_page
540						if [ -n "$aflag" ]; then
541							continue 2
542						else
543							return
544						fi
545					fi
546				fi
547
548				# Check plain old manpath.
549				if find_file $p $sect '' "$1"; then
550					if man_check_for_so "$manpage" $p; then
551						found_page=yes
552						man_display_page
553						if [ -n "$aflag" ]; then
554							continue 2
555						else
556							return
557						fi
558					fi
559				fi
560			done
561		done
562	done
563	unset IFS
564
565	# Nothing? Well, we are done then.
566	if [ -z "$found_page" ]; then
567		echo "No manual entry for \"$1\"" >&2
568		ret=1
569		return
570	fi
571}
572
573# Usage: man_parse_opts "$@"
574# Parses commandline options for man.
575man_parse_opts() {
576	local cmd_arg
577
578	OPTIND=1
579	while getopts 'K:M:P:S:adfhkm:op:tw' cmd_arg; do
580		case "${cmd_arg}" in
581		K)	Kflag=Kflag
582			REGEXP=$OPTARG ;;
583		M)	MANPATH=$OPTARG ;;
584		P)	MANPAGER=$OPTARG ;;
585		S)	MANSECT=$OPTARG ;;
586		a)	aflag=aflag ;;
587		d)	debug=$(( $debug + 1 )) ;;
588		f)	fflag=fflag ;;
589		h)	man_usage 0 ;;
590		k)	kflag=kflag ;;
591		m)	mflag=$OPTARG ;;
592		o)	oflag=oflag ;;
593		p)	MANROFFSEQ=$OPTARG ;;
594		t)	tflag=tflag ;;
595		w)	wflag=wflag ;;
596		*)	man_usage ;;
597		esac
598	done >&2
599
600	shift $(( $OPTIND - 1 ))
601
602	# Check the args for incompatible options.
603
604	case "${Kflag}${fflag}${kflag}${tflag}${wflag}" in
605	Kflagfflag*)	echo "Incompatible options: -K and -f"; man_usage ;;
606	Kflag*kflag*)	echo "Incompatible options: -K and -k"; man_usage ;;
607	Kflag*tflag)	echo "Incompatible options: -K and -t"; man_usage ;;
608	fflagkflag*)	echo "Incompatible options: -f and -k"; man_usage ;;
609	fflag*tflag*)	echo "Incompatible options: -f and -t"; man_usage ;;
610	fflag*wflag)	echo "Incompatible options: -f and -w"; man_usage ;;
611	*kflagtflag*)	echo "Incompatible options: -k and -t"; man_usage ;;
612	*kflag*wflag)	echo "Incompatible options: -k and -w"; man_usage ;;
613	*tflagwflag)	echo "Incompatible options: -t and -w"; man_usage ;;
614	esac
615
616	# Short circuit for whatis(1) and apropos(1)
617	if [ -n "$fflag" ]; then
618		do_whatis "$@"
619		exit
620	fi
621
622	if [ -n "$kflag" ]; then
623		do_apropos "$@"
624		exit
625	fi
626}
627
628# Usage: man_setup
629# Setup various trivial but essential variables.
630man_setup() {
631	# Setup machine and architecture variables.
632	if [ -n "$mflag" ]; then
633		MACHINE_ARCH=${mflag%%:*}
634		MACHINE=${mflag##*:}
635	fi
636	if [ -z "$MACHINE_ARCH" ]; then
637		MACHINE_ARCH=$($SYSCTL -n hw.machine_arch)
638	fi
639	if [ -z "$MACHINE" ]; then
640		MACHINE=$($SYSCTL -n hw.machine)
641	fi
642	decho "Using architecture: $MACHINE_ARCH:$MACHINE"
643
644	setup_pager
645	build_manpath
646	build_mansect
647	man_setup_locale
648	man_setup_width
649}
650
651# Usage: man_setup_width
652# Set up page width.
653man_setup_width() {
654	local sizes
655
656	unset use_width
657	case "$MANWIDTH" in
658	[0-9]*)
659		if [ "$MANWIDTH" -gt 0 2>/dev/null ]; then
660			use_width=$MANWIDTH
661		fi
662		;;
663	[Tt][Tt][Yy])
664		if { sizes=$($STTY size 0>&3 2>/dev/null); } 3>&1; then
665			set -- $sizes
666			if [ $2 -gt 80 ]; then
667				use_width=$(($2-2))
668			fi
669		fi
670		;;
671	esac
672	if [ -n "$use_width" ]; then
673		decho "Using non-standard page width: ${use_width}"
674	else
675		decho 'Using standard page width'
676	fi
677}
678
679# Usage: man_setup_locale
680# Setup necessary locale variables.
681man_setup_locale() {
682	local lang_cc
683	local locstr
684
685	locpaths='.'
686	man_charset='US-ASCII'
687
688	# Setup locale information.
689	if [ -n "$oflag" ]; then
690		decho 'Using non-localized manpages'
691	else
692		# Use the locale tool to give us proper locale information
693		eval $( $LOCALE )
694
695		if [ -n "$LANG" ]; then
696			locstr=$LANG
697		else
698			locstr=$LC_CTYPE
699		fi
700
701		case "$locstr" in
702		C)		;;
703		C.UTF-8)	;;
704		POSIX)		;;
705		[a-z][a-z]_[A-Z][A-Z]\.*)
706				lang_cc="${locstr%.*}"
707				man_lang="${locstr%_*}"
708				man_country="${lang_cc#*_}"
709				man_charset="${locstr#*.}"
710				locpaths="$locstr"
711				locpaths="$locpaths:$man_lang.$man_charset"
712				if [ "$man_lang" != "en" ]; then
713					locpaths="$locpaths:en.$man_charset"
714				fi
715				locpaths="$locpaths:."
716				;;
717		*)		echo 'Unknown locale, assuming C' >&2
718				;;
719		esac
720	fi
721
722	decho "Using locale paths: $locpaths"
723}
724
725# Usage: man_usage [exitcode]
726# Display usage for the man utility.
727man_usage() {
728	echo 'Usage:'
729	echo ' man [-adho] [-t | -w] [-K regexp] [-M manpath] [-P pager] [-S mansect]'
730	echo '     [-m arch[:machine]] [-p [eprtv]] [mansect] page [...]'
731	echo ' man -f page [...] -- Emulates whatis(1)'
732	echo ' man -k page [...] -- Emulates apropos(1)'
733
734	# When exit'ing with -h, it's not an error.
735	exit ${1:-1}
736}
737
738# Usage: parse_configs
739# Reads the end-user adjustable config files.
740parse_configs() {
741	local IFS file files
742
743	if [ -n "$parsed_configs" ]; then
744		return
745	fi
746
747	unset IFS
748
749	# Read the global config first in case the user wants
750	# to override config_local.
751	if [ -r "$config_global" ]; then
752		parse_file "$config_global"
753	fi
754
755	# Glob the list of files to parse.
756	set +f
757	files=$(echo $config_local)
758	set -f
759
760	for file in $files; do
761		if [ -r "$file" ]; then
762			parse_file "$file"
763		fi
764	done
765
766	parsed_configs='yes'
767}
768
769# Usage: parse_file file
770# Reads the specified config files.
771parse_file() {
772	local file line tstr var
773
774	file="$1"
775	decho "Parsing config file: $file"
776	while read line; do
777		decho "  $line" 2
778		case "$line" in
779		\#*)		decho "    Comment" 3
780				;;
781		MANPATH*)	decho "    MANPATH" 3
782				trim "${line#MANPATH}"
783				add_to_manpath "$tstr"
784				;;
785		MANLOCALE*)	decho "    MANLOCALE" 3
786				trim "${line#MANLOCALE}"
787				manlocales="$manlocales:$tstr"
788				;;
789		MANCONFIG*)	decho "    MANCONFIG" 3
790				trim "${line#MANCONFIG}"
791				config_local="$tstr"
792				;;
793		MANSECT*)	decho "    MANSECT" 3
794				trim "${line#MANSECT}"
795				mansect="$mansect:$tstr"
796				;;
797		# Set variables in the form of FOO_BAR
798		*_*[\ \	]*)	var="${line%%[\ \	]*}"
799				trim "${line#$var}"
800				eval "$var=\"$tstr\""
801				decho "    Parsed $var" 3
802				;;
803		esac
804	done < "$file"
805}
806
807# Usage: search_path
808# Traverse $PATH looking for manpaths.
809search_path() {
810	local IFS p path
811
812	decho "Searching PATH for man directories"
813
814	IFS=:
815	for path in $PATH; do
816		if add_to_manpath "$path/man"; then
817			:
818		elif add_to_manpath "$path/MAN"; then
819			:
820		else
821			case "$path" in
822			*/bin)	p="${path%/bin}/share/man"
823				add_to_manpath "$p"
824				p="${path%/bin}/man"
825				add_to_manpath "$p"
826				;;
827			esac
828		fi
829	done
830	unset IFS
831
832	if [ -z "$manpath" ]; then
833		decho '  Unable to find any manpaths, using default'
834		manpath=$man_default_path
835	fi
836}
837
838# Usage: search_whatis cmd [arglist]
839# Do the heavy lifting for apropos/whatis
840search_whatis() {
841	local IFS bad cmd f good key keywords loc opt out path rval wlist
842
843	cmd="$1"
844	shift
845
846	whatis_parse_args "$@"
847
848	build_manpath
849	build_manlocales
850	setup_pager
851
852	if [ "$cmd" = "whatis" ]; then
853		opt="-w"
854	fi
855
856	f='whatis'
857
858	IFS=:
859	for path in $MANPATH; do
860		if [ \! -d "$path" ]; then
861			decho "Skipping non-existent path: $path" 2
862			continue
863		fi
864
865		if [ -f "$path/$f" -a -r "$path/$f" ]; then
866			decho "Found whatis: $path/$f"
867			wlist="$wlist $path/$f"
868		fi
869
870		for loc in $MANLOCALES; do
871			if [ -f "$path/$loc/$f" -a -r "$path/$loc/$f" ]; then
872				decho "Found whatis: $path/$loc/$f"
873				wlist="$wlist $path/$loc/$f"
874			fi
875		done
876	done
877	unset IFS
878
879	if [ -z "$wlist" ]; then
880		echo "$cmd: no whatis databases in $MANPATH" >&2
881		exit 1
882	fi
883
884	rval=0
885	for key in $keywords; do
886		out=$(grep -Ehi $opt -- "$key" $wlist)
887		if [ -n "$out" ]; then
888			good="$good\\n$out"
889		else
890			bad="$bad\\n$key: nothing appropriate"
891			rval=1
892		fi
893	done
894
895	# Strip leading carriage return.
896	good=${good#\\n}
897	bad=${bad#\\n}
898
899	if [ -n "$good" ]; then
900		printf '%b\n' "$good" | $MANPAGER
901	fi
902
903	if [ -n "$bad" ]; then
904		printf '%b\n' "$bad" >&2
905	fi
906
907	exit $rval
908}
909
910# Usage: setup_cattool page
911# Finds an appropriate decompressor based on extension
912setup_cattool() {
913	case "$1" in
914	*.bz)	cattool='/usr/bin/bzcat' ;;
915	*.bz2)	cattool='/usr/bin/bzcat' ;;
916	*.gz)	cattool='/usr/bin/gzcat' ;;
917	*.lzma)	cattool='/usr/bin/lzcat' ;;
918	*.xz)	cattool='/usr/bin/xzcat' ;;
919	*.zst)	cattool='/usr/bin/zstdcat' ;;
920	*)	cattool='/usr/bin/zcat -f' ;;
921	esac
922}
923
924# Usage: setup_pager
925# Correctly sets $MANPAGER
926setup_pager() {
927	# Setup pager.
928	if [ -z "$MANPAGER" ]; then
929		if [ -n "$MANCOLOR" ]; then
930			MANPAGER="less -sR"
931		else
932			if [ -n "$PAGER" ]; then
933				MANPAGER="$PAGER"
934			else
935				MANPAGER="less -s"
936			fi
937		fi
938	fi
939	decho "Using pager: $MANPAGER"
940}
941
942# Usage: trim string
943# Trims whitespace from beginning and end of a variable
944trim() {
945	tstr=$1
946	while true; do
947		case "$tstr" in
948		[\ \	]*)	tstr="${tstr##[\ \	]}" ;;
949		*[\ \	])	tstr="${tstr%%[\ \	]}" ;;
950		*)		break ;;
951		esac
952	done
953}
954
955# Usage: whatis_parse_args "$@"
956# Parse commandline args for whatis and apropos.
957whatis_parse_args() {
958	local cmd_arg
959	OPTIND=1
960	while getopts 'd' cmd_arg; do
961		case "${cmd_arg}" in
962		d)	debug=$(( $debug + 1 )) ;;
963		*)	whatis_usage ;;
964		esac
965	done >&2
966
967	shift $(( $OPTIND - 1 ))
968
969	keywords="$*"
970}
971
972# Usage: whatis_usage
973# Display usage for the whatis/apropos utility.
974whatis_usage() {
975	echo "usage: $cmd [-d] keyword [...]"
976	exit 1
977}
978
979
980
981# Supported commands
982do_apropos() {
983	[ $(stat -f %i /usr/bin/man) -ne $(stat -f %i /usr/bin/apropos) ] && \
984		exec apropos "$@"
985	search_whatis apropos "$@"
986}
987
988# Usage: do_full_search reg_exp
989# Do a full search of the regular expression passed
990# as parameter in all man pages
991do_full_search() {
992	local gflags re
993	re=${1}
994
995	# Build grep(1) flags
996	gflags="-H"
997
998	# wflag implies -l for grep(1)
999	if [ -n "$wflag" ]; then
1000		gflags="${gflags} -l"
1001	fi
1002
1003	gflags="${gflags} --label"
1004
1005	set +f
1006	for mpath in $(echo "${MANPATH}" | tr : '[:blank:]'); do
1007		for section in $(echo "${MANSECT}" | tr : '[:blank:]'); do
1008			for manfile in ${mpath}/man${section}/*.${section}*; do
1009				mandoc "${manfile}" 2>/dev/null |
1010					grep -E ${gflags} "${manfile}" -e "${re}"
1011			done
1012		done
1013	done
1014	set -f
1015}
1016
1017do_man() {
1018	local IFS
1019
1020	man_parse_opts "$@"
1021	man_setup
1022
1023	shift $(( $OPTIND - 1 ))
1024	IFS=:
1025	for sect in $MANSECT; do
1026		if [ "$sect" = "$1" ]; then
1027			decho "Detected manual section as first arg: $1"
1028			MANSECT="$1"
1029			shift
1030			break
1031		fi
1032	done
1033	unset IFS
1034	pages="$*"
1035
1036	if [ -z "$pages" -a -z "${Kflag}" ]; then
1037		echo 'What manual page do you want?' >&2
1038		exit 1
1039	fi
1040
1041	if [ ! -z "${Kflag}" ]; then
1042		# Short circuit because -K flag does a sufficiently
1043		# different thing like not showing the man page at all
1044		do_full_search "${REGEXP}"
1045	fi
1046
1047	for page in "$@"; do
1048		decho "Searching for \"$page\""
1049		man_find_and_display "$page"
1050	done
1051
1052	exit ${ret:-0}
1053}
1054
1055do_manpath() {
1056	manpath_parse_args "$@"
1057	if [ -z "$qflag" ]; then
1058		manpath_warnings
1059	fi
1060	if [ -n "$Lflag" ]; then
1061		build_manlocales
1062		echo $MANLOCALES
1063	else
1064		build_manpath
1065		echo $MANPATH
1066	fi
1067	exit 0
1068}
1069
1070do_whatis() {
1071	[ $(stat -f %i /usr/bin/man) -ne $(stat -f %i /usr/bin/whatis) ] && \
1072		exec whatis "$@"
1073	search_whatis whatis "$@"
1074}
1075
1076# User's PATH setting decides on the groff-suite to pick up.
1077EQN=eqn
1078NROFF='groff -S -P-h -Wall -mtty-char -mandoc'
1079PIC=pic
1080REFER=refer
1081TBL=tbl
1082TROFF='groff -S -mandoc'
1083VGRIND=vgrind
1084
1085LOCALE=/usr/bin/locale
1086STTY=/bin/stty
1087SYSCTL=/sbin/sysctl
1088
1089debug=0
1090man_default_sections='1:8:2:3:3lua:n:4:5:6:7:9:l'
1091man_default_path='/usr/share/man:/usr/share/openssl/man:/usr/local/share/man:/usr/local/man'
1092cattool='/usr/bin/zcat -f'
1093
1094config_global='/etc/man.conf'
1095
1096# This can be overridden via a setting in /etc/man.conf.
1097config_local='/usr/local/etc/man.d/*.conf'
1098
1099# Set noglobbing for now. I don't want spurious globbing.
1100set -f
1101
1102case "$0" in
1103*apropos)	do_apropos "$@" ;;
1104*manpath)	do_manpath "$@" ;;
1105*whatis)	do_whatis "$@" ;;
1106*)		do_man "$@" ;;
1107esac
1108