forked from DARIAH-DE/dwp-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dwp.py
executable file
·139 lines (113 loc) · 3.75 KB
/
dwp.py
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3
from subprocess import call
try:
from readchar import readkey
except ImportError:
readkey = input
import sys
import os
import platform
import re
def yn(*prompt, default=True):
"""
Prompts the user to answer a yes/no question.
Args:
*prompt: List of arguments that form a prompt. Passed on to `print`.
default (bool): Yes or no when the user hits enter?
Returns:
(bool) The user's choice.
Raises:
`KeyboardInterrupt` when the user has pressed Ctrl+C
"""
if default:
options = " [Y/n]? "
else:
options = " [y/N]? "
accept = "yYjJ"
reject = "nN\x1b\x07" # Esc, ^G
default_keys = " \r" # Space, Return
print(*prompt, end=options, flush=True)
while True:
inp = readkey()
key = inp[0] if inp else default_keys[0]
if key in accept or default and key in default_keys:
print(accept[0])
return True
elif key in reject or not default and key in default_keys:
print(reject[0])
return False
elif key == "\x03": # ^C
raise KeyboardInterrupt()
else:
print(key, "\x08", sep="", end="", flush=True)
def run_file(filename):
if platform.system() == 'Linux':
call(["xdg-open", filename])
elif platform.system() == 'Windows':
os.startfile(filename)
else:
call(["open", filename])
def run_pandoc(filename, args):
"""
Runs pandoc with appropriate arguments.
Args:
filename (str): The input file to run pandoc on
args: Iterable with additional arguments to pass to pandoc.
Returns:
(int) pandoc's exit code
"""
args = ["pandoc"] + args
argnames = [arg.split('=')[0] for arg in args]
basename, extension = os.path.splitext(filename)
pdfname = basename + '.pdf'
if "-o" not in argnames:
args.extend(["-o", pdfname])
if "--latex-engine" not in argnames:
args.append("--latex-engine=lualatex")
if "--template" not in argnames:
args.append("--template=DWP")
args.append("--filter=pandoc-citeproc")
if os.path.exists(basename + ".bib"):
args.append("--bibliography="+basename+".bib")
# find language & csl
if "--csl" not in argnames:
with open(filename, encoding="utf8") as f:
langtag = re.search(r'^lang:\s*(\w+)\s*$', f.read(), re.M)
if langtag:
if langtag.group(1) == 'de':
csl = os.path.expanduser('~/.pandoc/templates/chicago-author-date-de.csl')
else:
csl = os.path.expanduser('~/.pandoc/templates/chicago-author-date.csl')
if os.path.exists(csl):
args.append("--csl="+csl)
else:
print("Not found:", csl)
else:
print("Warning: No lang entry found")
args.append('--metadata=link-citations:true')
args.append(filename)
print(" ".join(args))
result = call(args)
return result
def main(argv):
if argv is None:
argv = []
if len(argv) < 2:
print("Usage: {} filename".format(argv[0]))
sys.exit(1)
filename = argv[-1]
basename, extension = os.path.splitext(filename)
if extension == "":
filename = filename + ".md"
extension = ".md"
if os.path.exists(filename):
if run_pandoc(filename, argv[1:-1]) == 0:
if yn("Show PDF?"):
run_file(basename + ".pdf")
elif yn("Generate .tex for debugging?"):
run_pandoc(filename, ["-o", basename + ".tex"] + argv[1:-1])
else:
print("ERROR:", filename, "not found.")
sys.exit(1)
if __name__ == "__main__":
main(sys.argv)