-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.go
556 lines (522 loc) · 11.7 KB
/
main.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package main
import (
"archive/zip"
"bytes"
"encoding/base64"
"encoding/xml"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/mattn/go-runewidth"
)
type Relationship struct {
Text string `xml:",chardata"`
ID string `xml:"Id,attr"`
Type string `xml:"Type,attr"`
Target string `xml:"Target,attr"`
TargetMode string `xml:"TargetMode,attr"`
}
type Relationships struct {
XMLName xml.Name `xml:"Relationships"`
Text string `xml:",chardata"`
Xmlns string `xml:"xmlns,attr"`
Relationship []Relationship `xml:"Relationship"`
}
type TextVal struct {
Text string `xml:",chardata"`
Val string `xml:"val,attr"`
}
type NumberingLvl struct {
Text string `xml:",chardata"`
Ilvl string `xml:"ilvl,attr"`
Tplc string `xml:"tplc,attr"`
Tentative string `xml:"tentative,attr"`
Start TextVal `xml:"start"`
NumFmt TextVal `xml:"numFmt"`
LvlText TextVal `xml:"lvlText"`
LvlJc TextVal `xml:"lvlJc"`
PPr struct {
Text string `xml:",chardata"`
Ind struct {
Text string `xml:",chardata"`
Left string `xml:"left,attr"`
Hanging string `xml:"hanging,attr"`
} `xml:"ind"`
} `xml:"pPr"`
RPr struct {
Text string `xml:",chardata"`
U struct {
Text string `xml:",chardata"`
Val string `xml:"val,attr"`
} `xml:"u"`
RFonts struct {
Text string `xml:",chardata"`
Hint string `xml:"hint,attr"`
} `xml:"rFonts"`
} `xml:"rPr"`
}
type Numbering struct {
XMLName xml.Name `xml:"numbering"`
Text string `xml:",chardata"`
Wpc string `xml:"wpc,attr"`
Cx string `xml:"cx,attr"`
Cx1 string `xml:"cx1,attr"`
Mc string `xml:"mc,attr"`
O string `xml:"o,attr"`
R string `xml:"r,attr"`
M string `xml:"m,attr"`
V string `xml:"v,attr"`
Wp14 string `xml:"wp14,attr"`
Wp string `xml:"wp,attr"`
W10 string `xml:"w10,attr"`
W string `xml:"w,attr"`
W14 string `xml:"w14,attr"`
W15 string `xml:"w15,attr"`
W16se string `xml:"w16se,attr"`
Wpg string `xml:"wpg,attr"`
Wpi string `xml:"wpi,attr"`
Wne string `xml:"wne,attr"`
Wps string `xml:"wps,attr"`
Ignorable string `xml:"Ignorable,attr"`
AbstractNum []struct {
Text string `xml:",chardata"`
AbstractNumId string `xml:"abstractNumId,attr"`
RestartNumberingAfterBreak string `xml:"restartNumberingAfterBreak,attr"`
Nsid TextVal `xml:"nsid"`
MultiLevelType TextVal `xml:"multiLevelType"`
Tmpl TextVal `xml:"tmpl"`
Lvl []NumberingLvl `xml:"lvl"`
} `xml:"abstractNum"`
Num []struct {
Text string `xml:",chardata"`
NumId string `xml:"numId,attr"`
AbstractNumId TextVal `xml:"abstractNumId"`
} `xml:"num"`
}
type file struct {
rels Relationships
num Numbering
r *zip.ReadCloser
embed bool
list map[string]int
}
type Node struct {
XMLName xml.Name
Attrs []xml.Attr `xml:"-"`
Content []byte `xml:",innerxml"`
Nodes []Node `xml:",any"`
}
func (n *Node) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
n.Attrs = start.Attr
type node Node
return d.DecodeElement((*node)(n), &start)
}
func escape(s, set string) string {
replacer := []string{}
for _, r := range []rune(set) {
rs := string(r)
replacer = append(replacer, rs, `\`+rs)
}
return strings.NewReplacer(replacer...).Replace(s)
}
func (zf *file) extract(rel *Relationship, w io.Writer) error {
err := os.MkdirAll(filepath.Dir(rel.Target), 0755)
if err != nil {
return err
}
for _, f := range zf.r.File {
if f.Name != "word/"+rel.Target {
continue
}
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
b := make([]byte, f.UncompressedSize64)
n, err := rc.Read(b)
if err != nil && err != io.EOF {
return err
}
if zf.embed {
fmt.Fprintf(w, "![](data:image/png;base64,%s)",
base64.StdEncoding.EncodeToString(b[:n]))
} else {
err = ioutil.WriteFile(rel.Target, b, 0644)
if err != nil {
return err
}
fmt.Fprintf(w, "![](%s)", escape(rel.Target, "()"))
}
break
}
return nil
}
func attr(attrs []xml.Attr, name string) (string, bool) {
for _, attr := range attrs {
if attr.Name.Local == name {
return attr.Value, true
}
}
return "", false
}
func (zf *file) walk(node *Node, w io.Writer) error {
switch node.XMLName.Local {
case "hyperlink":
fmt.Fprint(w, "[")
var cbuf bytes.Buffer
for _, n := range node.Nodes {
if err := zf.walk(&n, &cbuf); err != nil {
return err
}
}
fmt.Fprint(w, escape(cbuf.String(), "[]"))
fmt.Fprint(w, "]")
fmt.Fprint(w, "(")
if id, ok := attr(node.Attrs, "id"); ok {
for _, rel := range zf.rels.Relationship {
if id == rel.ID {
fmt.Fprint(w, escape(rel.Target, "()"))
break
}
}
}
fmt.Fprint(w, ")")
case "t":
fmt.Fprint(w, string(node.Content))
case "pPr":
code := false
for _, n := range node.Nodes {
switch n.XMLName.Local {
case "ind":
if left, ok := attr(n.Attrs, "left"); ok {
if i, err := strconv.Atoi(left); err == nil {
fmt.Fprint(w, strings.Repeat(" ", i/360))
}
}
case "pStyle":
if val, ok := attr(n.Attrs, "val"); ok {
if strings.HasPrefix(val, "Heading") {
if i, err := strconv.Atoi(val[7:]); err == nil {
fmt.Fprint(w, strings.Repeat("#", i)+" ")
}
} else if val == "Code" {
code = true
} else {
if i, err := strconv.Atoi(val); err == nil {
fmt.Fprint(w, strings.Repeat("#", i)+" ")
}
}
}
case "numPr":
numId := ""
ilvl := ""
numFmt := ""
start := 1
ind := 0
for _, nn := range n.Nodes {
if nn.XMLName.Local == "numId" {
if val, ok := attr(nn.Attrs, "val"); ok {
numId = val
}
}
if nn.XMLName.Local == "ilvl" {
if val, ok := attr(nn.Attrs, "val"); ok {
ilvl = val
}
}
}
for _, num := range zf.num.Num {
if numId != num.NumId {
continue
}
for _, abnum := range zf.num.AbstractNum {
if abnum.AbstractNumId != num.AbstractNumId.Val {
continue
}
for _, ablvl := range abnum.Lvl {
if ablvl.Ilvl != ilvl {
continue
}
if i, err := strconv.Atoi(ablvl.Start.Val); err == nil {
start = i
}
if i, err := strconv.Atoi(ablvl.PPr.Ind.Left); err == nil {
ind = i / 360
}
numFmt = ablvl.NumFmt.Val
break
}
break
}
break
}
fmt.Fprint(w, strings.Repeat(" ", ind))
switch numFmt {
case "decimal", "aiueoFullWidth":
key := fmt.Sprint("%s:%d", numId, ind)
cur, ok := zf.list[key]
if !ok {
zf.list[key] = start
} else {
zf.list[key] = cur + 1
}
fmt.Fprintf(w, "%d. ", zf.list[key])
case "bullet":
fmt.Fprint(w, "* ")
}
}
}
if code {
fmt.Fprint(w, "`")
}
for _, n := range node.Nodes {
if err := zf.walk(&n, w); err != nil {
return err
}
}
if code {
fmt.Fprint(w, "`")
}
case "tbl":
var rows [][]string
for _, tr := range node.Nodes {
if tr.XMLName.Local != "tr" {
continue
}
var cols []string
for _, tc := range tr.Nodes {
if tc.XMLName.Local != "tc" {
continue
}
var cbuf bytes.Buffer
if err := zf.walk(&tc, &cbuf); err != nil {
return err
}
cols = append(cols, strings.Replace(cbuf.String(), "\n", "", -1))
}
rows = append(rows, cols)
}
maxcol := 0
for _, cols := range rows {
if len(cols) > maxcol {
maxcol = len(cols)
}
}
widths := make([]int, maxcol)
for _, row := range rows {
for i := 0; i < maxcol; i++ {
if i < len(row) {
width := runewidth.StringWidth(row[i])
if widths[i] < width {
widths[i] = width
}
}
}
}
for i, row := range rows {
if i == 0 {
for j := 0; j < maxcol; j++ {
fmt.Fprint(w, "|")
fmt.Fprint(w, strings.Repeat(" ", widths[j]))
}
fmt.Fprint(w, "|\n")
for j := 0; j < maxcol; j++ {
fmt.Fprint(w, "|")
fmt.Fprint(w, strings.Repeat("-", widths[j]))
}
fmt.Fprint(w, "|\n")
}
for j := 0; j < maxcol; j++ {
fmt.Fprint(w, "|")
if j < len(row) {
width := runewidth.StringWidth(row[j])
fmt.Fprint(w, escape(row[j], "|"))
fmt.Fprint(w, strings.Repeat(" ", widths[j]-width))
} else {
fmt.Fprint(w, strings.Repeat(" ", widths[j]))
}
}
fmt.Fprint(w, "|\n")
}
fmt.Fprint(w, "\n")
case "r":
bold := false
italic := false
strike := false
for _, n := range node.Nodes {
if n.XMLName.Local != "rPr" {
continue
}
for _, nn := range n.Nodes {
switch nn.XMLName.Local {
case "b":
bold = true
case "i":
italic = true
case "strike":
strike = true
}
}
}
if strike {
fmt.Fprint(w, "~~")
}
if bold {
fmt.Fprint(w, "**")
}
if italic {
fmt.Fprint(w, "*")
}
var cbuf bytes.Buffer
for _, n := range node.Nodes {
if err := zf.walk(&n, &cbuf); err != nil {
return err
}
}
fmt.Fprint(w, escape(cbuf.String(), `*~\`))
if italic {
fmt.Fprint(w, "*")
}
if bold {
fmt.Fprint(w, "**")
}
if strike {
fmt.Fprint(w, "~~")
}
case "p":
for _, n := range node.Nodes {
if err := zf.walk(&n, w); err != nil {
return err
}
}
fmt.Fprintln(w)
case "blip":
if id, ok := attr(node.Attrs, "embed"); ok {
for _, rel := range zf.rels.Relationship {
if id != rel.ID {
continue
}
if err := zf.extract(&rel, w); err != nil {
return err
}
}
}
case "Fallback":
case "txbxContent":
var cbuf bytes.Buffer
for _, n := range node.Nodes {
if err := zf.walk(&n, &cbuf); err != nil {
return err
}
}
fmt.Fprintln(w, "\n```\n"+cbuf.String()+"```")
default:
for _, n := range node.Nodes {
if err := zf.walk(&n, w); err != nil {
return err
}
}
}
return nil
}
func readFile(f *zip.File) (*Node, error) {
rc, err := f.Open()
defer rc.Close()
b, _ := ioutil.ReadAll(rc)
if err != nil {
return nil, err
}
var node Node
err = xml.Unmarshal(b, &node)
if err != nil {
return nil, err
}
return &node, nil
}
func findFile(files []*zip.File, target string) *zip.File {
for _, f := range files {
if f.Name == target {
return f
}
}
return nil
}
func docx2md(arg string, embed bool) error {
r, err := zip.OpenReader(arg)
if err != nil {
return err
}
defer r.Close()
var rels Relationships
var num Numbering
for _, f := range r.File {
switch f.Name {
case "word/_rels/document.xml.rels":
rc, err := f.Open()
defer rc.Close()
b, _ := ioutil.ReadAll(rc)
if err != nil {
return err
}
err = xml.Unmarshal(b, &rels)
if err != nil {
return err
}
case "word/numbering.xml":
rc, err := f.Open()
defer rc.Close()
b, _ := ioutil.ReadAll(rc)
if err != nil {
return err
}
err = xml.Unmarshal(b, &num)
if err != nil {
return err
}
}
}
f := findFile(r.File, "word/document.xml")
if f == nil {
return errors.New("incorrect document")
}
node, err := readFile(f)
if err != nil {
return err
}
var buf bytes.Buffer
zf := &file{
r: r,
rels: rels,
num: num,
embed: embed,
list: make(map[string]int),
}
err = zf.walk(node, &buf)
if err != nil {
return err
}
fmt.Print(buf.String())
return nil
}
func main() {
var embed bool
flag.BoolVar(&embed, "embed", false, "embed resources")
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
os.Exit(1)
}
for _, arg := range flag.Args() {
if err := docx2md(arg, embed); err != nil {
log.Fatal(err)
}
}
}