forked from asciidoctor/asciidoctor-vscode
/
text-parser.ts
318 lines (283 loc) · 13.8 KB
/
text-parser.ts
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
import * as vscode from 'vscode';
import * as path from "path";
import { spawn } from "child_process";
import { isNullOrUndefined } from 'util';
const fileUrl = require('file-url');
const asciidoctor = require('@asciidoctor/core')()
const docbook = require('@asciidoctor/docbook-converter')
const kroki = require('asciidoctor-kroki')
const use_kroki = vscode.workspace.getConfiguration('asciidoc', null).get('use_kroki');
if (use_kroki)
kroki.register(asciidoctor.Extensions);
export class AsciidocParser {
public html: string = '';
public document = null;
private ext_path = vscode.extensions.getExtension('joaompinto.asciidoctor-vscode').extensionPath;
private stylesdir = path.join(this.ext_path, 'media')
constructor(private readonly filename: string, private errorCollection: vscode.DiagnosticCollection = null) {
}
public getAttribute(name: string) {
return isNullOrUndefined(this.document) ? null : this.document.getAttribute(name);
}
public async getMediaDir(text) {
const match = text.match(new RegExp("^\\s*:mediadir:"));
return match;
}
private async convert_using_javascript(text: string, forHTMLSave: boolean, backend: string) {
return new Promise<string>((resolve) => {
const editor = vscode.window.activeTextEditor;
const doc = editor.document;
const documentPath = path.dirname(path.resolve(doc.fileName));
const workspacePath = vscode.workspace.workspaceFolders
const contains_style = !isNullOrUndefined(text.match(new RegExp("^\\s*:(stylesheet|stylesdir):", "img")));
const use_editor_stylesheet = vscode.workspace.getConfiguration('asciidoc', null).get('preview.useEditorStyle', false);
const preview_attributes = vscode.workspace.getConfiguration('asciidoc', null).get('preview.attributes', {});
const preview_style = vscode.workspace.getConfiguration('asciidoc', null).get('preview.style', "");
const useWorkspaceAsBaseDir = vscode.workspace.getConfiguration('asciidoc', null).get('useWorkspaceRoot');
const enableErrorDiagnostics = vscode.workspace.getConfiguration('asciidoc', null).get('enableErrorDiagnostics');
let base_dir = documentPath;
if (useWorkspaceAsBaseDir && typeof vscode.workspace.rootPath !== 'undefined') {
base_dir = vscode.workspace.rootPath;
}
if(this.errorCollection) {
this.errorCollection.clear();
}
const memoryLogger = asciidoctor.MemoryLogger.create();
asciidoctor.LoggerManager.setLogger(memoryLogger);
var attributes = {};
if (contains_style) {
attributes = { 'copycss': true }
} else if (preview_style != "") {
var stylesdir: string, stylesheet: string
if (path.isAbsolute(preview_style)) {
stylesdir = path.dirname(preview_style)
stylesheet = path.basename(preview_style)
} else {
if (workspacePath == undefined) {
stylesdir = documentPath
} else if (workspacePath.length > 0) {
stylesdir = workspacePath[0].uri.path
}
stylesdir = path.dirname(path.join(stylesdir, preview_style))
stylesheet = path.basename(preview_style)
}
attributes = { 'copycss': true, 'stylesdir': stylesdir, 'stylesheet': stylesheet }
} else if (use_editor_stylesheet && !forHTMLSave) {
attributes = { 'copycss': true, 'stylesdir': this.stylesdir, 'stylesheet': 'asciidoctor-editor.css' }
} else {
// TODO: decide whether to use the included css or let ascidoctor.js decide
// attributes = { 'copycss': true, 'stylesdir': this.stylesdir, 'stylesheet': 'asciidoctor-default.css@' }
}
Object.keys(preview_attributes).forEach((key) => {
if (typeof preview_attributes[key] === "string") {
attributes[key] = preview_attributes[key];
}
})
attributes['env-vscode'] = ''
if (backend.startsWith('docbook'))
docbook.register()
const options = {
safe: 'unsafe',
doctype: 'article',
attributes: attributes,
header_footer: true,
to_file: false,
base_dir: base_dir,
sourcemap: true,
backend: backend,
}
try {
let ascii_doc = asciidoctor.load(text, options);
this.document = ascii_doc;
const blocksWithLineNumber = ascii_doc.findBy(function (b) { return typeof b.getLineNumber() !== 'undefined'; });
blocksWithLineNumber.forEach(function (block, key, myArray) {
block.addRole("data-line-" + block.getLineNumber());
})
let resultHTML = ascii_doc.convert(options);
//let result = this.fixLinks(resultHTML);
if (enableErrorDiagnostics) {
let diagnostics = [];
memoryLogger.getMessages().forEach((error) => {
//console.log(error); //Error from asciidoctor.js
let errorMessage = error.message.text;
let sourceLine = 0;
let relatedFile = null;
let relatedLine = 0;
let diagnosticSource = "asciidoctor.js";
let sourceRange = null;
if (error.message.source_location) { //There is a source location
if (error.message.source_location.path == "<stdin>") { //error is within the file we are parsing
sourceLine = error.message.source_location.lineno - 1;
sourceRange = doc.lineAt(sourceLine).range;
} else { //error is coming from an included file
relatedFile = error.message.source_location.file;
relatedLine = error.message.source_location.lineno - 1;
//try to find the include responsible from the info provided by asciidoctor.js
sourceLine = doc.getText().split('\n').indexOf(doc.getText().split('\n').find((str) => str.startsWith("include") && str.includes(error.message.source_location.path)));
if (sourceLine!=-1) {
sourceRange = doc.lineAt(sourceLine).range;
} else {
sourceRange = doc.lineAt(0).range;
}
}
} else {
// generic error (e.g. :source-highlighter: coderay)
errorMessage = error.message;
}
let severity = vscode.DiagnosticSeverity.Information;
if (error.severity=="WARN") {
severity = vscode.DiagnosticSeverity.Warning
} else if (error.severity=="ERROR") {
severity = vscode.DiagnosticSeverity.Error
} else if (error.severity=="DEBUG") {
severity = vscode.DiagnosticSeverity.Information
}
let diagnosticRelated = null;
if(relatedFile) {
diagnosticRelated = [
new vscode.DiagnosticRelatedInformation(
new vscode.Location(vscode.Uri.file(relatedFile),
new vscode.Position(0,0)
),
errorMessage
),
]
errorMessage = "There was an error in an included file";
}
var diagnosticError = new vscode.Diagnostic(sourceRange, errorMessage, severity);
diagnosticError.source = diagnosticSource;
if (diagnosticRelated) {
diagnosticError.relatedInformation = diagnosticRelated;
}
diagnostics.push(diagnosticError);
});
if(this.errorCollection) {
this.errorCollection.set(vscode.Uri.parse(doc.fileName), diagnostics);
}
}
resolve(resultHTML);
}
catch(e) {
vscode.window.showErrorMessage(e.toString())
}
})
}
private async convert_using_application(text: string, forHTMLSave: boolean, backend: string) {
const editor = vscode.window.activeTextEditor;
const doc = editor.document;
const documentPath = path.dirname(doc.fileName).replace('"', '\\"');
const workspacePath = vscode.workspace.workspaceFolders
const contains_style = !isNullOrUndefined(text.match(new RegExp("^\\s*:(stylesheet|stylesdir):", "img")));
const use_editor_stylesheet = vscode.workspace.getConfiguration('asciidoc', null).get('preview.useEditorStyle', false);
const preview_attributes = vscode.workspace.getConfiguration('asciidoc', null).get('preview.attributes', {});
const preview_style = vscode.workspace.getConfiguration('asciidoc', null).get('preview.style', "");
const useWorkspaceAsBaseDir = vscode.workspace.getConfiguration('asciidoc', null).get('useWorkspaceRoot');
this.document = null;
let base_dir = documentPath;
if (useWorkspaceAsBaseDir && typeof vscode.workspace.rootPath !== 'undefined') {
base_dir = vscode.workspace.rootPath.replace('"', '\\"');
}
return new Promise<string>((resolve) => {
let asciidoctor_command = vscode.workspace.getConfiguration('asciidoc', null).get('asciidoctor_command', 'asciidoctor');
var RUBYOPT = process.env['RUBYOPT']
if (RUBYOPT) {
var prevOpt
RUBYOPT = RUBYOPT.split(' ').reduce((acc, opt) => {
acc.push(prevOpt == '-E' ? (prevOpt = 'UTF-8:UTF-8') : (prevOpt = opt))
return acc
}, []).join(' ')
} else {
RUBYOPT = '-E UTF-8:UTF-8'
}
var options = { shell: true, cwd: path.dirname(this.filename), env: { ...process.env, RUBYOPT } }
var adoc_cmd_array = asciidoctor_command.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } ) ;
var adoc_cmd = adoc_cmd_array[0]
var adoc_cmd_args = adoc_cmd_array.slice(1)
if (contains_style) {
; // Used an empty if to make it easier to use elses later
} else if (preview_style != "") {
var stylesdir: string, stylesheet: string
if (path.isAbsolute(preview_style)) {
stylesdir = path.dirname(preview_style)
stylesheet = path.basename(preview_style)
} else {
if (workspacePath == undefined) {
stylesdir = documentPath
} else if (workspacePath.length > 0) {
stylesdir = workspacePath[0].uri.path
}
stylesdir = path.dirname(path.join(stylesdir, preview_style))
stylesheet = path.basename(preview_style)
}
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', `stylesdir=${stylesdir}`])
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', `stylesheet=${stylesheet}`])
} else if (use_editor_stylesheet && !forHTMLSave) {
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', `stylesdir=${this.stylesdir}@`])
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', 'stylesheet=asciidoctor-editor.css@'])
} else {
// TODO: decide whether to use the included css or let ascidoctor decide
// adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', `stylesdir=${this.stylesdir}@`])
// adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', 'stylesheet=asciidoctor-default.css@'])
}
adoc_cmd_args.push.apply(adoc_cmd_args, ['-b', backend])
Object.keys(preview_attributes).forEach((key) => {
if (typeof preview_attributes[key] === "string") {
var value: string = preview_attributes[key]
if (value.endsWith('!')) {
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', `${value}`])
} else {
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', `${key}=${value}`])
}
}
})
adoc_cmd_args.push.apply(adoc_cmd_args, ['-a', 'env-vscode'])
adoc_cmd_args.push.apply(adoc_cmd_args, ['-q', '-B', '"' + base_dir + '"', '-o', '-', '-'])
var asciidoctor = spawn(adoc_cmd, adoc_cmd_args, options);
asciidoctor.stderr.on('data', (data) => {
let errorMessage = data.toString();
console.error(errorMessage);
errorMessage += errorMessage.replace("\n", '<br><br>');
errorMessage += "<br><br>"
errorMessage += "<b>command:</b> " + adoc_cmd + " " + adoc_cmd_args.join(" ")
errorMessage += "<br><br>"
errorMessage += "<b>If the asciidoctor binary is not in your PATH, you can set the full path.<br>"
errorMessage += "Go to `File -> Preferences -> User settings` and adjust the asciidoc.asciidoctor_command</b>"
resolve(errorMessage);
})
var result_data = ''
/* with large outputs we can receive multiple calls */
asciidoctor.stdout.on('data', (data) => {
result_data += data.toString();
});
asciidoctor.on('close', (code) => {
//var result = this.fixLinks(result_data);
resolve(result_data);
})
asciidoctor.stdin.write(text);
asciidoctor.stdin.end();
});
}
private fixLinks(html: string): string {
let result = html.replace(
new RegExp("((?:src|href)=[\'\"])(?!(?:http:|https:|ftp:|#))(.*?)([\'\"])", "gmi"),
(subString: string, p1: string, p2: string, p3: string): string => {
return [
p1,
fileUrl(path.join(
path.dirname(this.filename),
p2
)),
p3,
].join("");
}
);
return result;
}
public async parseText(text: string, forHTMLSave: boolean = false, backend: string = 'html'): Promise<string> {
const use_asciidoctor_js = vscode.workspace.getConfiguration('asciidoc', null).get('use_asciidoctor_js');
if (use_asciidoctor_js)
return this.convert_using_javascript(text, forHTMLSave, backend)
else
return this.convert_using_application(text, forHTMLSave, backend)
}
}