/
latex.go
400 lines (352 loc) · 9.79 KB
/
latex.go
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package latex
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/jojomi/go-script"
)
// CompileTask holds the configuration of a compilation
// task
type CompileTask struct {
scriptContext *script.Context
sourceDir string
compileDir string
compileFilename string
resolveSymlinks bool
verbosity VerbosityLevel
}
type VerbosityLevel uint
const (
VerbosityNone = iota
VerbosityDefault
VerbosityMore
VerbosityAll
)
// NewCompileTask returns a default (empty) CompileTask
func NewCompileTask() CompileTask {
return CompileTask{
verbosity: VerbosityDefault,
}
}
func (t *CompileTask) context() *script.Context {
// lazy initialize script context
if t.scriptContext == nil {
t.scriptContext = script.NewContext()
}
return t.scriptContext
}
// ResolveSymlinks determines if symlinks will be resolved
func (t *CompileTask) ResolveSymlinks() bool {
return t.resolveSymlinks
}
// SetResolveSymlinks sets if symlinks will be resolved
func (t *CompileTask) SetResolveSymlinks(resolveSymlinks bool) {
t.resolveSymlinks = resolveSymlinks
}
// SetVerbosity is used to change the verbosity level
func (t *CompileTask) SetVerbosity(verbosity VerbosityLevel) {
t.verbosity = verbosity
}
// SourceDir returns the source directory for compilation
func (t *CompileTask) SourceDir() string {
return t.sourceDir
}
// SetSourceDir sets the source directory for compilation
func (t *CompileTask) SetSourceDir(sourceDir string) {
t.sourceDir = sourceDir
}
// CompileFilename returns the filename to be compiled.
// Makes sure the filename is ending with .tex.
func (t *CompileTask) CompileFilename() string {
filename := t.compileFilename
if !strings.HasSuffix(filename, ".tex") {
return filename + ".tex"
}
return filename
}
// CompileFilenamePdf returns the filename of the pdf file
// to be expected after a pdflatex run.
func (t *CompileTask) CompileFilenamePdf() string {
filename := t.CompileFilename()
return t.texFilenameToPdf(filename)
}
// SetCompileFilename sets the name of the TeX file to be compiled.
func (t *CompileTask) SetCompileFilename(compileFilename string) {
t.compileFilename = compileFilename
}
// SetCompileDir sets the directory used for compilation. If no parameter is
// supplied a random and unique temporary directory is used for compilation.
// Usually this is the preferable mode of operation because it ensures clean
// building state.
func (t *CompileTask) SetCompileDir(CompileDir string) {
var err error
if CompileDir == "" {
CompileDir, err = t.context().TempDir()
}
if err == nil {
t.compileDir = CompileDir
}
t.context().SetWorkingDir(t.CompileDirInternal())
}
// CopyToCompileDir copies the source files to the compilation directory.
func (t *CompileTask) CopyToCompileDir(CompileDir string) {
t.SetCompileDir(CompileDir)
os.RemoveAll(CompileDir)
os.MkdirAll(CompileDir, 0700)
sc := t.context()
err := sc.CopyDir(t.SourceDir(), t.CompileDirInternal())
if err != nil {
panic(err)
}
if t.ResolveSymlinks() {
sc.ResolveSymlinks(t.CompileDirInternal())
}
}
// ClearCompileDir removes the compilation directory. Suitable to call using
// defer after CopyToCompileDir. Be careful not to remove your source directory
// when building there.
func (t *CompileTask) ClearCompileDir() {
err := os.RemoveAll(t.CompileDir())
if err != nil {
panic(err)
}
}
func (t *CompileTask) defaultCompileFilename(filename string) (file string) {
if file == "" {
file = t.CompileFilename()
}
return
}
func (t *CompileTask) texFilenameToPdf(filename string) string {
return filename[0:len(filename)-4] + ".pdf"
}
func (t *CompileTask) defaultCompilePdfFilename(filename string) (file string) {
file = t.defaultCompileFilename(filename)
// replace .tex by .pdf
file = t.texFilenameToPdf(file)
return
}
func (t *CompileTask) latextool(toolname, file string, args ...string) error {
sc := t.context()
file = t.defaultCompileFilename(file)
args = append(args, file)
//fmt.Println(sc.CommandPath("lualatex"))
sc.MustCommandExist(toolname)
var execFunction func(script.Command) (*script.ProcessResult, error)
switch t.verbosity {
case VerbosityNone:
execFunction = sc.ExecuteFullySilent
case VerbosityMore:
fallthrough
case VerbosityAll:
execFunction = sc.ExecuteDebug
case VerbosityDefault:
fallthrough
default:
execFunction = sc.ExecuteSilent
}
command := &script.LocalCommand{}
command.Add(toolname)
command.AddAll(args...)
result, err := execFunction(command)
if err != nil {
fmt.Print(result.Output())
fmt.Print(result.Error())
os.Exit(1)
}
return nil
}
// Pdflatex calls pdflatex with the file and arguments supplied. For standard
// invokation no arguments are needed.
func (t *CompileTask) Pdflatex(file string, args ...string) error {
return t.latextool("pdflatex", file, args...)
}
// Xelatex calls xelatex with the file and arguments supplied. For standard
// invokation no arguments are needed.
func (t *CompileTask) Xelatex(file string, args ...string) error {
return t.latextool("xelatex", file, args...)
}
// Lualatex calls lualatex with the file and arguments supplied. For standard
// invokation no arguments are needed.
func (t *CompileTask) Lualatex(file string, args ...string) error {
return t.latextool("lualatex", file, args...)
}
// LillypondBook calls lillypond-book.
func (t *CompileTask) LillypondBook(latexToolname, file string, args ...string) error {
binName := "lilypond-book"
sc := t.context()
file = sc.AbsPath(t.defaultCompileFilename(file))
tempDir, err := t.context().TempDir()
if err != nil {
return err
}
args = append(args, "--pdf")
args = append(args, fmt.Sprintf("--output=%s", tempDir))
args = append(args, file)
defer os.RemoveAll(tempDir)
sc.MustCommandExist(binName)
command := &script.LocalCommand{}
command.Add(binName)
command.AddAll(args...)
_, err = sc.ExecuteFullySilent(command)
if err != nil {
return err
}
matches, err := filepath.Glob(filepath.Join(tempDir, "*"))
if err != nil {
return err
}
for _, match := range matches {
fi, err := os.Stat(match)
if err != nil {
return err
}
from := match
to := path.Join(t.CompileDirInternal(), filepath.Base(match))
//fmt.Println(from, to)
if fi.IsDir() {
err := sc.CopyDir(from, to)
if err != nil {
return err
}
} else {
err := sc.CopyFile(from, to)
if err != nil {
return err
}
}
}
return nil
}
// Optimize modifies a given PDF to reduce filesize for a certain output type.
// Valid values for channel are "screen", "printer", "prepress", "ebook",
// "default".
func (t *CompileTask) Optimize(file string, channel string) error {
// minify pdf: http://tex.stackexchange.com/a/41273
// http://stackoverflow.com/a/27454451
// http://blog.rot13.org/2011/05/optimize-pdf-file-size-using-ghostscript.html
if !contains([]string{"screen", "printer", "prepress", "ebook", "default"}, channel) {
// TODO err?
return nil
}
sc := t.context()
if !sc.CommandExists("gs") {
return nil
}
file = t.defaultCompilePdfFilename(file)
tempFile, err := sc.TempFile()
if err != nil {
return err
}
params := []string{
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
fmt.Sprintf("-dPDFSETTINGS=/%s", channel),
"-o",
tempFile.Name(),
file,
}
sc.SetWorkingDir(t.CompileDirInternal())
command := &script.LocalCommand{}
command.Add("gs")
command.AddAll(params...)
_, err = sc.ExecuteSilent(command)
if err != nil {
return err
}
sc.MoveFile(tempFile.Name(), file)
return nil
}
// MoveToDest moves a file from compilation directory.
func (t *CompileTask) MoveToDest(from, to string) error {
from = t.defaultCompilePdfFilename(from)
from = path.Join(t.CompileDirInternal(), from)
to, err := filepath.Abs(to)
if err != nil {
panic(err)
}
return t.context().MoveFile(from, to)
}
// CompileDir returns the current compilation directory.
func (t *CompileTask) CompileDir() string {
if t.compileDir == "" {
return t.sourceDir
}
return t.compileDir
}
// CompileDirInternal returns the current internal compilation directory.
func (t *CompileTask) CompileDirInternal() string {
if t.CompileDir() == t.SourceDir() {
return t.CompileDir()
}
return path.Join(t.CompileDir(), "input")
}
// ClearLatexTempFiles removes common temprary LaTeX files in a directory.
func (t *CompileTask) ClearLatexTempFiles(dir string) {
// remove temp files
extensions := []string{"aux", "log", "toc", "nav", "ind", "ilg", "idx"}
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
for _, ext := range extensions {
if strings.HasSuffix(path, "."+ext) {
os.Remove(path)
return nil
}
}
return nil
})
}
// Template returns a text/template to base templating off.
func (t *CompileTask) Template(baseFilename string) (*template.Template, string) {
sc := t.context()
baseFilename = sc.AbsPath(t.defaultCompileFilename(baseFilename))
templ := template.New("latex")
return templ, baseFilename
}
// ExecuteTemplate executes a template on the source TeX files.
func (t *CompileTask) ExecuteTemplate(templ *template.Template, data interface{}, inputFilename string, outputFilename string) error {
sc := t.context()
useTempFile := outputFilename == ""
if useTempFile {
tempFile, err := sc.TempFile()
if err != nil {
return err
}
outputFilename = tempFile.Name()
}
inputFilename = sc.AbsPath(t.defaultCompileFilename(inputFilename))
f, err := os.Create(sc.AbsPath(outputFilename))
if err != nil {
return err
}
w := io.Writer(f)
err = templ.ExecuteTemplate(w, filepath.Base(inputFilename), data)
if err != nil {
return err
}
f.Close()
if useTempFile {
// copy back, remove temp
err = os.Remove(inputFilename)
if err != nil {
return err
}
err = sc.CopyFile(outputFilename, inputFilename)
if err != nil {
return err
}
}
return nil
}
// auxiliary
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}