summaryrefslogtreecommitdiff
path: root/.local/bin/open_man
blob: b37d94bd3625f6a4e511761cb8b805721a6d73fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env bash

MENU_CMD=dmenu "$@"

if [ "$XDG_SESSION_TYPE" = "wayland" ]; then
  MENU_CMD=bemenu "$@"
  TERM=$TERM -d none
else
  MENU_CMD=dmenu "$@"
fi

cachedir=${XDG_CACHE_HOME:-"$HOME/.cache"}
if [ -d "$cachedir" ]; then
	cache=$cachedir/dmenu_run_man
	historyfile=$cachedir/dmenu_man_history
else  # if no xdg dir, fall back to dotfiles in ~
	cache=$HOME/.dmenu_cache_man
	historyfile=$HOME/.dmenu_man_history
fi

# Generate a new cache if necessary
if stest -dqr -n "$cache" /usr/share/man/**/*; then
	ls /usr/share/man/**/* \
	  | sed -Ee 's/^.*\///g;s/(\.gz)?//g;/:$/d;/^ *$/d;s/(.*)\.([0-9].*)$/\1 (\2)/g' \
	  | sort -u > $cache
fi

awk -v histfile=$historyfile '
	BEGIN {
		while( (getline < histfile) > 0 ) {
			sub("^[0-9]+\t","")
			print
			x[$0]=1
		}
	} !x[$0]++ ' "$cache" \
	| $MENU_CMD \
	| awk -v histfile=$historyfile '
		BEGIN {
			FS=OFS="\t"
			while ( (getline < histfile) > 0 ) {
				count=$1
				sub("^[0-9]+\t","")
				fname=$0
				history[fname]=count
			}
			close(histfile)
		}

		{
			history[$0]++
			print
		}

		END {
			if(!NR) exit
			for (f in history)
				print history[f],f | "sort -t '\t' -k1rn >" histfile
		}
	' \
	| while read MAN; do
		VERSION=$(echo $MAN | sed -Ee 's/.* \(([0-9].*)\)/\1/g')
		PAGE=$(echo $MAN | sed -Ee 's/(.*) \([0-9].*\)/\1/g')
		## Uncomment for debugging
		#echo "Man: $VERSION $PAGE"
		$TERM man $VERSION $PAGE
	done