-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathconverttoasciidoc.gapps
792 lines (639 loc) · 23.5 KB
/
converttoasciidoc.gapps
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
// vim: set softtabstop=2 shiftwidth=2 expandtab :
var ADOC_MIMETYPE = "text/asciidoc";
// Open handler to add Menu
function onOpen(e) {
var ui = DocumentApp.getUi();
if (e && e.authMode == ScriptApp.AuthMode.NONE) {
ui.createMenu('AsciiDoc')
// .addItem('Latex Equation', 'ConvertEquation')
.addToUi();
} else {
ui.createMenu('AsciiDoc')
.addItem('Export File', 'ConvertToAsciiDocFile')
.addItem('Export Email', 'ConvertToAsciiDocEmail')
// .addItem('Latex Equation', 'ConvertEquation')
.addToUi();
}
}
function onInstall(e) {
onOpen(e);
}
function ConvertEquation() {
var element = DocumentApp.getActiveDocument().getCursor().getElement();
// Scan upwards for an equation
while(element.getType() != DocumentApp.ElementType.EQUATION) {
if(element.getParent() == null)
break;
element = element.getParent();
}
if(element.getType() != DocumentApp.ElementType.EQUATION) {
DocumentApp.getUi().alert("Put cursor into an equation element!");
return;
}
// Covert equation
var latexEquation = handleEquationFunction(element);
var latexEquationText = "$" + latexEquation.trim() + "$";
// Show results
DocumentApp.getUi().alert(latexEquationText);
}
// Convert current document to asciidoc and email it
function ConvertToAsciiDocEmail() {
// Convert to asciidoc
var convertedDoc = asciidoc();
// Add asciidoc document to attachments
convertedDoc.attachments.push({"fileName":DocumentApp.getActiveDocument().getName()+".adoc",
"mimeType": ADOC_MIMETYPE, "content": convertedDoc.text});
// In some cases user email is not accessible
var mail = Session.getActiveUser().getEmail();
if(mail === '') {
DocumentApp.getUi().alert("Could not read your email address");
return;
}
// Send email with asciidoc document
MailApp.sendEmail(mail,
"[gdoc2adoc] "+DocumentApp.getActiveDocument().getName(),
"Your converted AsciiDoc document is attached (converted from "+DocumentApp.getActiveDocument().getUrl()+")",
{ "attachments": convertedDoc.attachments });
}
function getFolder(parent_folder,folder_name){
var folders = parent_folder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
if(folder_name == folder.getName()) {
return folder;
}
}
return false;
}
// Convert current document to file and save it to GDrive
function ConvertToAsciiDocFile() {
// Convert to asciidoc
var convertedDoc = asciidoc();
// Create folder
var id = DocumentApp.getActiveDocument().getId();
var file = DriveApp.getFileById(id);
var parents = file.getParents();
var parent = null;
if(parents.hasNext()) {
parent = parents.next()
if(parents.hasNext()) {
//Logger.log("File has multiple parent directories. Script does not work in this case");
DocumentApp.getUi().alert("Document must not be in multiple directories");
return;
}
} else {
DocumentApp.getUi().alert("Document has to be in a directory for the export");
return;
}
var targetDirName = DocumentApp.getActiveDocument().getName() + ".adoc"
var found = getFolder(parent,targetDirName);
if (found === false){
//Logger.log("Creating output folder...");
found = parent.createFolder(targetDirName);
} else {
//Logger.log("Reusing existing target");
var ui = DocumentApp.getUi();
var result = ui.alert('Existing target folder found!', 'You already have "' + targetDirName + '" in your Drive. Delete folder or Cancel ?',
ui.ButtonSet.OK_CANCEL)
if(result == ui.Button.OK) {
//Logger.log("Trashing target folder...");
found.setTrashed(true);
//Logger.log("Re-Creating output folder...");
found = parent.createFolder(targetDirName);
} else {
//Logger.log("Do not delete target folder, stopping!");
return;
}
}
// Write all files to target folder
for(var file in convertedDoc.files) {
file = convertedDoc.files[file];
var blob = file.blob.copyBlob();
var name = file.name;
blob.setName(name);
found.createFile(blob);
}
// Write mardown file to target folder
// using same nameas folder.
found.createFile(targetDirName, convertedDoc.text, ADOC_MIMETYPE);
}
function processSection(section) {
var state = {
'inSource' : false, // Document read pointer is within a fenced code block
'images' : [], // Image data found in document
'imageCounter' : 0, // Image counter
'prevDoc' : [], // Pointer to the previous element on aparsing tree level
'nextDoc' : [], // Pointer to the next element on a parsing tree level
'size' : [], // Number of elements on a parsing tree level
'listCounters' : [], // List counter
'needToc' : false, // saw a toc reference
'indent' : 0, // indent on current block
'headingPrefix' : '', // Should headings be prefixed by a `=` to make heading1 `==` (see detectHeadingRules)
};
// Detect title, heading1 etc
detectHeadingRules(section, state);
// Process element tree outgoing from the root element
var textElements = processElement(section, state, 0);
return {
'textElements' : textElements,
'state' : state,
};
}
function detectHeadingRulesNested(element, state, headingState) {
Logger.log("detectHeadingRulesNested: " + element.getType());
switch(element.getType()) {
case DocumentApp.ElementType.DOCUMENT:
case DocumentApp.ElementType.BODY_SECTION:
// Iterates over all childs
for(var i=0; i < element.getNumChildren(); i++) {
var child = element.getChild(i);
detectHeadingRulesNested(child, state, headingState);
}
break;
case DocumentApp.ElementType.PARAGRAPH:
switch (element.getHeading()) {
case DocumentApp.ParagraphHeading.HEADING1:
headingState.nbrOfH1 += 1; break;
case DocumentApp.ParagraphHeading.TITLE:
headingState.hasTitle = true;
}
// Iterates over all childs
for(var i=0; i < element.getNumChildren(); i++) {
var child = element.getChild(i);
detectHeadingRulesNested(child, state, headingState);
}
}
}
function detectHeadingRules(element, state) {
var headingState = {
'nbrOfH1': 0,
'hasTitle' : false,
};
detectHeadingRulesNested(element, state, headingState);
Logger.log("Heading detection, nbrOfH1: " + headingState.nbrOfH1 + " and title: " + headingState.hasTitle);
if (headingState.hasTitle == true) {
Logger.log("Heading prefix `=` because there is a title");
state.headingPrefix = '=';
}
else if (headingState.nbrOfH1 == 1) {
// we have a single heading1 so we will pretend it's the title and h2 is for subsections
Logger.log("Heading prefix `` because there is a single h1");
state.headingPrefix = '';
}
else {
// no title and multiple (or no h1) => treat h1 as a Asciidoc subsection (i.e. `==`)
Logger.log("No title and multiple (or no h1) => treat h1 as a Asciidoc subsection (i.e. `==`)");
state.headingPrefix = '=';
}
}
function asciidoc() {
// Text elements
var textElements = [];
// Process header
var head = DocumentApp.getActiveDocument().getHeader();
if(head != null) {
// Do not include empty header sections
var teHead = processSection(head);
if(teHead.textElements.length > 0) {
textElements = textElements.concat(teHead.textElements);
textElements.push('\n\n');
textElements.push('---');
textElements.push('\n\n');
}
}
// Process body
var doc = DocumentApp.getActiveDocument().getBody();
doc = processSection(doc);
textElements = textElements.concat(doc.textElements);
// Process footer
var foot = DocumentApp.getActiveDocument().getFooter();
//Logger.log("foot: " + foot);
if(foot != null) {
var teFoot = processSection(foot);
// Do not include empty footer sections
if(teFoot.textElements.length > 0) {
textElements.push('\n\n');
textElements.push('---');
textElements.push('\n\n');
textElements = textElements.concat(teFoot.textElements);
}
}
// Build final output string
var text = textElements.join('');
// Replace critical chars
text = text.replace('\u201d', '"').replace('\u201c', '"');
// Debug logging
//Logger.log("Result: " + text);
Logger.log("Images: " + doc.state.imageCounter);
// Build attachment and file lists
var attachments = [];
var files = [];
for(var i in doc.state.images) {
var image = doc.state.images[i];
attachments.push( {
"fileName": image.name,
"mimeType": image.type,
"content": image.bytes
} );
files.push( {
"name" : image.name,
"blob" : image.blob
});
}
// Results
return {
'files' : files,
'attachments' : attachments,
'text' : text,
};
}
function escapeHTML(text) {
return text.replace(/</g, '<').replace(/>/g, '>');
}
// Add repeat function to strings
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
function handleTable(element, state, depth) {
var textElements = [];
textElements.push("\n");
textElements.push("|===\n")
function buildTable(size) {
var stack = []
var maxSize = 0;
for(var ir=0; ir<element.getNumRows(); ir++) {
var row = element.getRow(ir);
// Add header seperator
//if(ir == 1) {
// for(var ic=0; ic<row.getNumCells(); ic++) {
// stack.push("|-" + "-".repeat(size));
// }
// stack.push("-|\n");
//}
// Add table data
for(var ic=0; ic<row.getNumCells(); ic++) {
var cell = row.getCell(ic);
// Recursively build cell content
var text = processChilds(cell, state, depth+1).join('');
text = text.replace(/(\r\n|\n|\r)/gm,"");
maxSize = Math.max(text.length, maxSize);
if(size > text.length) {
text += " ".repeat(size - text.length)
}
stack.push("| " + text);
}
stack.push(" \n");
}
stack.push("|===\n")
stack.push("\n");
return {
maxSize : maxSize,
stack : stack,
};
}
var table = buildTable(100);
table = buildTable(Math.max(10, table.maxSize + 1));
textElements = textElements.concat(table.stack);
textElements.push('\n');
return textElements;
}
function formatMd(text, indexLeft, formatLeft, indexRight, formatRight) {
var leftPad = '' + formatLeft;
if(indexLeft > 0) {
if(text[indexLeft - 1] != ' ')
leftPad = ' ' + formatLeft;
}
var rightPad = formatRight + '';
if(indexRight < text.length) {
if(text[indexRight] != ' ') {
rightPad = formatRight + ' ';
}
}
//Note: we do a trim via .replace since asciidoc wont format i.e. * test* with bold.
var formatted = text.substring(0, indexLeft) + leftPad + text.substring(indexLeft, indexRight).replace(/^\s+|\s+$/g,"") + rightPad + text.substring(indexRight);
return formatted;
}
function handleText(doc, state) {
var formatted = doc.getText();
var lastIndex = formatted.length;
var attrs = doc.getTextAttributeIndices();
// Iterate backwards through all attributes
for(var i=attrs.length-1; i >= 0; i--) {
// Current position in text
var index = attrs[i];
// Handle links
if(doc.getLinkUrl(index)) {
var url = doc.getLinkUrl(index);
if (i > 0 && attrs[i-1] == index - 1 && doc.getLinkUrl(attrs[i-1]) === url) {
i -= 1;
index = attrs[i];
url = doc.getLinkUrl(index);
}
formatted = formatted.substring(0, index) + url + '[' + formatted.substring(index, lastIndex) + ']' + formatted.substring(lastIndex);
// Do not handle additional formattings for links
continue;
}
// Handle source code
if(isTextCode(doc, index)) {
if (!state.inSource) {
// Scan left until text without source font is found
while (i > 0 && doc.getFontFamily(attrs[i-1]) && doc.getFontFamily(attrs[i-1]) === sourceFont) {
i -= 1;
off = attrs[i];
}
formatted = formatMd(formatted, index, '`', lastIndex, '`');
// Do not handle additional formattings for code
continue;
}
}
// TODO: does not handle nested formatting well.
// Handle bold and bold italic
if(doc.isBold(index)) {
var dleft, right;
dleft = dright = "*";
if (doc.isItalic(index))
{
// edbacher: changed this to handle bold italic properly.
dleft = "**__";
dright = "__**";
}
formatted = formatMd(formatted, index, dleft, lastIndex, dright);
}
// Handle italic
else if(doc.isItalic(index)) {
formatted = formatMd(formatted, index, '_', lastIndex, '_');
} else if (doc.isUnderline(index)) {
formatted = formatMd(formatted, index, '[.underline]#', lastIndex, '#');
} else if(doc.isStrikethrough(index)) {
formatted = formatMd(formatted, index, '[.line-through]#', lastIndex, '#');
} else if(doc.getTextAlignment(index) == DocumentApp.TextAlignment.SUBSCRIPT) {
formatted = formatMd(formatted, index, '~', lastIndex, '~');
} else if(doc.getTextAlignment(index) == DocumentApp.TextAlignment.SUPERSCRIPT) {
formatted = formatMd(formatted, index, '^', lastIndex, '^');
}
// replace newlines wit any indent requested from higher up formatting.
var haslinebreak = /\r/.exec(formatted);
formatted = formatted.replace(/(?:\r)/g, '\n+\n');
if (haslinebreak) // add extra newline to let list and others continue
formatted += "\n";
// Keep track of last position in text
lastIndex = index;
}
var textElements = [formatted];
return textElements;
}
function handleListItem(item, state, depth) {
var textElements = [];
// Prefix
var prefix = '';
// Add nesting level
for (var i=0; i<item.getNestingLevel(); i++) {
prefix += ' ';
}
var glyphprefix = ''
// Add marker based on glyph type
var glyph = item.getGlyphType();
//Logger.log("Glyph: " + glyph);
switch(glyph) {
case DocumentApp.GlyphType.BULLET:
case DocumentApp.GlyphType.HOLLOW_BULLET:
case DocumentApp.GlyphType.SQUARE_BULLET:
glyphprefix = '*'.repeat(item.getNestingLevel()+1) + ' ';
break;
case DocumentApp.GlyphType.NUMBER:
case DocumentApp.GlyphType.LATIN_LOWER:
case DocumentApp.GlyphType.LATIN_UPPER:
case DocumentApp.GlyphType.ROMAN_LOWER:
case DocumentApp.GlyphType.ROMAN_UPPER:
var key = item.getListId() + '.' + item.getNestingLevel();
//Logger.log("key " + key);
var counter = state.listCounters[key] || 0;
counter++;
state.listCounters[key] = counter;
glyphprefix += '.'.repeat(item.getNestingLevel()+1) + ' ';
break;
default:
glyphprefix += glyph + '*'.repeat(item.getNestingLevel()+1) + ' ';
break;
}
// Add prefix
textElements.push(prefix + glyphprefix);
oldIndent = state.indent
state.indent = glyphprefix.length + prefix.length
children = processChilds(item, state, depth)
state.indent = oldIndent
// Handle all childs
textElements = textElements.concat(children);
return textElements;
}
function handleImage(image, state) {
// Determine file extension based on content type
var contentType = image.getBlob().getContentType();
var fileExtension = '';
if (/\/png$/.test(contentType)) {
fileExtension = ".png";
} else if (/\/gif$/.test(contentType)) {
fileExtension = ".gif";
} else if (/\/jpe?g$/.test(contentType)) {
fileExtension = ".jpg";
} else {
throw "Unsupported image type: " + contentType;
}
// Create filename
var filename = 'img_' + state.imageCounter + fileExtension;
state.imageCounter++;
// Add image
var textElements = []
textElements.push('image:' + filename + '[]'); // TODO: this is inline only
state.images.push( {
"bytes": image.getBlob().getBytes(),
"blob": image.getBlob(),
"type": contentType,
"name": filename,
});
return textElements;
}
// Escape chars with a special meaning in Latex
function latexSanitize(text) {
text = text.replace("\\", "\\\\");
text = text.replace("%", "\\%");
return text;
}
// Converte an Equation or Function element to a Latex expression
function handleEquationFunction(func, state) {
//Logger.log("Equation converter handling: " + func.getType());
var equation = "";
for(var i=0; i<func.getNumChildren(); i++) {
var child = func.getChild(i);
if(child.getType() == DocumentApp.ElementType.EQUATION_FUNCTION) {
equation += child.getCode() + "{" + handleEquationFunction(child, state);
}
else if(child.getType() == DocumentApp.ElementType.EQUATION_FUNCTION_ARGUMENT_SEPARATOR) {
equation = equation.trim() + "}{";
}
else if(child.getType() == DocumentApp.ElementType.EQUATION_SYMBOL) {
equation += child.getCode() + " ";
}
else if(child.getType() == DocumentApp.ElementType.TEXT) {
equation += latexSanitize(child.getText()) + " ";
}
}
if(func.getType() == DocumentApp.ElementType.EQUATION_FUNCTION)
equation = equation.trim() + "}";
//Logger.log("Equation converter result: " + equation);
return equation;
}
function processChilds(doc, state, depth) {
// Text element buffer
var textElements = []
// Keep track of child count on this depth
state.size[depth] = doc.getNumChildren();
// Iterates over all childs
for(var i=0; i < doc.getNumChildren(); i++) {
var child = doc.getChild(i);
// Update pointer on next document
var nextDoc = (i+1 < doc.getNumChildren())?doc.getChild(i+1) : child;
state.nextDoc[depth] = nextDoc;
// Update pointer on prev element
var prevDoc = (i-1 >= 0)?doc.getChild(i-1) : child;
state.prevDoc[depth] = prevDoc;
textElements = textElements.concat(processElement(child, state, depth+1));
}
return textElements;
}
function processElement(element, state, depth) {
// Result
var textElements = [];
switch(element.getType()) {
case DocumentApp.ElementType.DOCUMENT:
Logger.log("this is a document");
break;
case DocumentApp.ElementType.BODY_SECTION:
textElements = textElements.concat(processChilds(element, state, depth));
break;
case DocumentApp.ElementType.PARAGRAPH:
// Determine header prefix
var prefix = '';
switch (element.getHeading()) {
case DocumentApp.ParagraphHeading.HEADING6: prefix = state.headingPrefix + '======'; break;
case DocumentApp.ParagraphHeading.HEADING5: prefix = state.headingPrefix + '====='; break;
case DocumentApp.ParagraphHeading.HEADING4: prefix = state.headingPrefix + '===='; break;
case DocumentApp.ParagraphHeading.HEADING3: prefix = state.headingPrefix + '==='; break;
case DocumentApp.ParagraphHeading.HEADING2: prefix = state.headingPrefix + '=='; break;
case DocumentApp.ParagraphHeading.HEADING1: prefix = state.headingPrefix + '='; break;
case DocumentApp.ParagraphHeading.TITLE:
prefix = '='; state.needToc = true; break;
//default:prefix = element.getHeading(); break;
}
// Add space
if(prefix.length > 0)
prefix += ' ';
// Process childs
var child = processChilds(element, state, depth)
// Only Push prefix if it has kids otherwise it will just be treated as lone =='s
if (child.length > 0) {
textElements.push(prefix);
textElements = textElements.concat(child);
if(state.needToc) {
textElements.push("\n:toc: macro\n")
state.needToc = false;
}
// look for positioned images
var positionedImages = element.getPositionedImages()
for(var image in positionedImages) {
image = positionedImages[image];
textElements.push("\n" + handleImage(image, state) + "\n")
}
}
// Add paragraph break only if its not the last element on this layer
if(state.nextDoc[depth-1] == element)
break;
if(state.inSource)
textElements.push('\n');
else
textElements.push('\n\n');
break;
case DocumentApp.ElementType.LIST_ITEM:
textElements = textElements.concat(handleListItem(element, state, depth));
textElements.push('\n');
if(state.nextDoc[depth-1].getType() != element.getType()) {
textElements.push('\n');
}
break;
case DocumentApp.ElementType.HEADER_SECTION:
textElements = textElements.concat(processChilds(element, state, depth));
break;
case DocumentApp.ElementType.FOOTER_SECTION:
textElements = textElements.concat(processChilds(element, state, depth));
break;
case DocumentApp.ElementType.FOOTNOTE:
//adoced
textElements.push('.footnote:[');
textElements = textElements.concat(processChilds(element.getFootnoteContents(), state, depth));
textElements.push(']');
break;
case DocumentApp.ElementType.HORIZONTAL_RULE:
textElements.push('---\n');
break;
case DocumentApp.ElementType.INLINE_DRAWING:
// Cannot handle this type - there is no export function for rasterized or SVG images...
break;
case DocumentApp.ElementType.TABLE:
textElements = textElements.concat(handleTable(element, state, depth));
break;
case DocumentApp.ElementType.TABLE_OF_CONTENTS:
textElements.push('toc::[]');
state.needToc = true
break;
case DocumentApp.ElementType.TEXT:
var text = handleText(element, state);
// Check for source code delimiter
if(/^```.+$/.test(text.join(''))) {
state.inSource = true;
}
if(text.join('') === '```') {
state.inSource = false;
}
textElements = textElements.concat(text);
break;
case DocumentApp.ElementType.INLINE_IMAGE:
textElements = textElements.concat(handleImage(element, state));
break;
case DocumentApp.ElementType.PAGE_BREAK:
// Ignore page breaks
break;
case DocumentApp.ElementType.EQUATION:
var latexEquation = handleEquationFunction(element, state);
// If equation is the only one in a paragraph - center it
var wrap = '$'
if(state.size[depth-1] == 1) {
wrap = '$$'
}
latexEquation = wrap + latexEquation.trim() + wrap;
textElements.push(latexEquation);
break;
default:
throw("Unknown element type: " + element.getType());
}
return textElements;
}
// from https://github.com/Mogztter/asciidoc-googledocs-addon/blob/master/app/Code.gs
/** Guess if the text is code by looking at the font family. */
function isTextCode(doc, index) {
// Things will be better if Google Fonts can tell us about a font
var i, fontFamily = doc.getFontFamily(index), /* Now it returns a string! */
monospaceFonts = ['Consolas', 'Courier New', 'Source Code Pro'];
if (fontFamily === null) {
return false; // Handle null early.. It means multiple values.
}
// See ES7 Array.prototype.includes(elem, pos)
for (i = 0; i < monospaceFonts.length; i++) {
if (fontFamily === monospaceFonts[i]) {
return true;
}
}
// Last Try: Assume it's mono if it ends with ' Mono'.
// This works for all Google Fonts as of 2016-10-21.
// See ES6 String.prototype.endsWith(str, pos).
return fontFamily.indexOf(' Mono') === fontFamily.length - 5;
}