Skip to content

Commit 2791a30

Browse files
committed
F1 shows man page for current query
1 parent c6c5f04 commit 2791a30

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

pgcli/key_bindings.py

+17
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import logging
2+
import click
3+
import re
24
from prompt_toolkit.enums import EditingMode
35
from prompt_toolkit.key_binding import KeyBindings
46
from prompt_toolkit.filters import (
@@ -8,6 +10,7 @@
810
has_selection,
911
vi_mode,
1012
)
13+
from .man import man
1114

1215
from .pgbuffer import buffer_should_be_handled, safe_multi_line_mode
1316

@@ -20,6 +23,20 @@ def pgcli_bindings(pgcli):
2023

2124
tab_insert_text = " " * 4
2225

26+
@kb.add("f1")
27+
def _(event):
28+
"""Show man page for current command."""
29+
_logger.debug("Detected <F1> key.")
30+
31+
m = re.match(r"^[\w\s]+", event.app.current_buffer.text)
32+
if not m:
33+
return
34+
click.clear()
35+
text = m.group()
36+
_logger.debug(f"Launching man page for {text}")
37+
if not man(text):
38+
_logger.debug("Failed to show man page")
39+
2340
@kb.add("f2")
2441
def _(event):
2542
"""Enable/Disable SmartCompletion Mode."""

pgcli/man.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import subprocess
2+
3+
IGNORED = [
4+
"OR",
5+
"REPLACE",
6+
"DEFAULT",
7+
"UNIQUE",
8+
"TRUSTED",
9+
"PROCEDURAL",
10+
"TEMP",
11+
"TEMPORARY",
12+
"UNLOGGED",
13+
"GLOBAL",
14+
"LOCAL",
15+
"CONSTRAINT",
16+
"RECURSIVE",
17+
"WORK",
18+
"TRANSACTION",
19+
"SESSION",
20+
]
21+
22+
23+
def try_man(page):
24+
try:
25+
subprocess.run(
26+
f"man -I 7 {page}", shell=True, check=True, universal_newlines=True
27+
)
28+
return True
29+
except subprocess.CalledProcessError:
30+
return False
31+
32+
33+
def man(query):
34+
words = query.strip().split()[:6]
35+
words = map(lambda e: e.upper(), words)
36+
words = list(filter(lambda e: e not in IGNORED, words))
37+
if not words:
38+
return True
39+
if words[0] == "RELEASE":
40+
words.insert(1, "SAVEPOINT")
41+
for i in [2, 1, 3, 4]:
42+
if try_man("_".join(words[0 : i + 1])):
43+
return True
44+
return False

0 commit comments

Comments
 (0)