-
Notifications
You must be signed in to change notification settings - Fork 97
/
asciidocParser.ts
346 lines (313 loc) · 13.1 KB
/
asciidocParser.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
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
import * as vscode from 'vscode'
import * as path from 'path'
import { AsciidoctorWebViewConverter } from './asciidoctorWebViewConverter'
import { Asciidoctor } from '@asciidoctor/core'
import { ExtensionContentSecurityPolicyArbiter, AsciidoctorExtensionsSecurityPolicyArbiter } from './security'
import { AsciidocPreviewConfigurationManager } from './features/previewConfig'
import { SkinnyTextDocument } from './util/document'
import { IncludeItems } from './asciidoctorFindIncludeProcessor'
import { AsciidocContributionProvider } from './asciidocExtensions'
import { getAsciidoctorConfigContent } from './features/asciidoctorConfig'
const asciidoctorFindIncludeProcessor = require('./asciidoctorFindIncludeProcessor')
const asciidoctor = require('@asciidoctor/core')
const docbookConverter = require('@asciidoctor/docbook-converter')
const processor = asciidoctor()
const highlightjsBuiltInSyntaxHighlighter = processor.SyntaxHighlighter.for('highlight.js')
const highlightjsAdapter = require('./highlightjs-adapter')
docbookConverter.register()
export type AsciidoctorBuiltInBackends = 'html5' | 'docbook5'
const previewConfigurationManager = new AsciidocPreviewConfigurationManager()
export class AsciidocParser {
private stylesdir: string
private apsArbiter: AsciidoctorExtensionsSecurityPolicyArbiter
public prependExtension: Asciidoctor.Extensions.PreprocessorKlass
constructor (
readonly contributionProvider: AsciidocContributionProvider,
readonly aspArbiter: AsciidoctorExtensionsSecurityPolicyArbiter = null,
private errorCollection: vscode.DiagnosticCollection = null
) {
this.prependExtension = processor.Extensions.createPreprocessor('PreprendConfigPreprocessorExtension', {
postConstruct: function () {
this.asciidoctorConfigContent = ''
},
process: function (doc, reader) {
if (this.asciidoctorConfigContent.length > 0) {
// otherwise an empty line at the beginning breaks level 0 detection
reader.pushInclude(this.asciidoctorConfigContent, undefined, undefined, 1, {})
}
},
}).$new()
// Asciidoctor.js in the browser environment works with URIs however for desktop clients
// the stylesdir attribute is expected to look like a file system path (especially on Windows)
if (process.env.BROWSER_ENV) {
this.stylesdir = vscode.Uri.joinPath(contributionProvider.extensionUri, 'media').toString()
} else {
this.stylesdir = vscode.Uri.joinPath(contributionProvider.extensionUri, 'media').fsPath
}
}
// Export
public async export (
text: string,
textDocument: vscode.TextDocument,
backend: AsciidoctorBuiltInBackends,
asciidoctorAttributes = {}
): Promise<{ output: string, document: Asciidoctor.Document }> {
const asciidocConfig = vscode.workspace.getConfiguration('asciidoc', null)
if (this.errorCollection) {
this.errorCollection.clear()
}
const memoryLogger = processor.MemoryLogger.create()
processor.LoggerManager.setLogger(memoryLogger)
const registry = processor.Extensions.create()
await this.registerAsciidoctorExtensions(registry)
highlightjsBuiltInSyntaxHighlighter.$register_for('highlight.js', 'highlightjs')
const baseDir = AsciidocParser.getBaseDir(textDocument.fileName)
const options: { [key: string]: any } = {
attributes: {
'env-vscode': '',
env: 'vscode',
...asciidoctorAttributes,
},
backend,
extension_registry: registry,
header_footer: true,
safe: 'unsafe',
...(baseDir && { base_dir: baseDir }),
}
const document = processor.load(text, options)
const output = document.convert(options)
if (asciidocConfig.get('enableErrorDiagnostics')) {
this.reportErrors(memoryLogger, textDocument)
}
return { output, document }
}
// Load
public static load (textDocument: SkinnyTextDocument): { document: Asciidoctor.Document, baseDocumentIncludeItems: IncludeItems } {
const memoryLogger = processor.MemoryLogger.create()
processor.LoggerManager.setLogger(memoryLogger)
const registry = processor.Extensions.create()
asciidoctorFindIncludeProcessor.register(registry)
asciidoctorFindIncludeProcessor.resetIncludes()
const baseDir = AsciidocParser.getBaseDir(textDocument.fileName)
const document = processor.load(textDocument.getText(), {
attributes: {
'env-vscode': '',
env: 'vscode',
},
extension_registry: registry,
sourcemap: true,
safe: 'unsafe',
...(baseDir && { base_dir: baseDir }),
})
// QUESTION: should we report error?
return { document, baseDocumentIncludeItems: asciidoctorFindIncludeProcessor.getBaseDocIncludes() }
}
// Convert (preview)
public async convertUsingJavascript (
text: string,
doc: SkinnyTextDocument,
context: vscode.ExtensionContext,
editor: vscode.WebviewPanel,
line?:number
): Promise<{ html: string, document: Asciidoctor.Document }> {
// extension context should be at constructor
const cspArbiter = new ExtensionContentSecurityPolicyArbiter(context.globalState, context.workspaceState)
const workspacePath = vscode.workspace.workspaceFolders
const previewAttributes = vscode.workspace.getConfiguration('asciidoc.preview', null).get('asciidoctorAttributes', {})
const enableErrorDiagnostics = vscode.workspace.getConfiguration('asciidoc.debug', null).get('enableErrorDiagnostics')
if (this.errorCollection) {
this.errorCollection.clear()
}
const memoryLogger = processor.MemoryLogger.create()
processor.LoggerManager.setLogger(memoryLogger)
const registry = processor.Extensions.create()
const asciidoctorWebViewConverter = new AsciidoctorWebViewConverter(
doc,
context,
editor,
cspArbiter,
this.contributionProvider,
previewConfigurationManager,
line
)
processor.ConverterFactory.register(asciidoctorWebViewConverter, ['webview-html5'])
await this.registerAsciidoctorExtensions(registry)
if (context && editor) {
highlightjsAdapter.register(highlightjsBuiltInSyntaxHighlighter, context, editor)
} else {
highlightjsBuiltInSyntaxHighlighter.$register_for('highlight.js', 'highlightjs')
}
const attributes: { [key: string]: any } = {}
Object.keys(previewAttributes).forEach((key) => {
const attributeValue = previewAttributes[key]
if (typeof attributeValue === 'string') {
attributes[key] = workspacePath === undefined
? attributeValue
// eslint-disable-next-line no-template-curly-in-string
: attributeValue.replace('${workspaceFolder}', workspacePath[0].uri.path)
}
})
attributes['env-vscode'] = ''
attributes.env = 'vscode'
attributes['relfilesuffix@'] = '.adoc'
const baseDir = AsciidocParser.getBaseDir(doc.fileName)
const templateDirs = this.getTemplateDirs()
const options: { [key: string]: any } = {
attributes,
backend: 'webview-html5',
extension_registry: registry,
header_footer: true,
safe: 'unsafe',
sourcemap: true,
...(baseDir && { base_dir: baseDir }),
}
if (templateDirs.length !== 0) {
options.template_dirs = templateDirs
}
try {
const asciidoctorConfigContent = await getAsciidoctorConfigContent(doc.uri)
if (asciidoctorConfigContent !== undefined) {
(this.prependExtension as any).asciidoctorConfigContent = asciidoctorConfigContent
}
const document = processor.load(text, options)
const blocksWithLineNumber = document.findBy(function (b) {
return typeof b.getLineNumber() !== 'undefined'
})
blocksWithLineNumber.forEach(function (block) {
block.addRole('data-line-' + block.getLineNumber())
})
const resultHTML = document.convert(options)
if (enableErrorDiagnostics) {
this.reportErrors(memoryLogger, doc)
}
return { html: resultHTML, document }
} catch (e) {
vscode.window.showErrorMessage(e.toString())
throw e
}
}
private reportErrors (memoryLogger: Asciidoctor.MemoryLogger, textDocument: SkinnyTextDocument) {
const diagnostics = []
memoryLogger.getMessages().forEach((error) => {
let errorMessage = error.getText()
let sourceLine = 0
let relatedFile = null
const diagnosticSource = 'asciidoctor.js'
// allocate to line 0 in the absence of information
let sourceRange = textDocument.lineAt(0).range
const location = error.getSourceLocation()
if (location) { //There is a source location
if (location.getPath() === '<stdin>') { //error is within the file we are parsing
sourceLine = location.getLineNumber() - 1
// ensure errors are always associated with a valid line
sourceLine = sourceLine >= textDocument.lineCount ? textDocument.lineCount - 1 : sourceLine
sourceRange = textDocument.lineAt(sourceLine).range
} else { //error is coming from an included file
relatedFile = error.getSourceLocation()
// try to find the include responsible from the info provided by asciidoctor.js
sourceLine = textDocument.getText().split('\n').indexOf(textDocument.getText().split('\n').find((str) => str.startsWith('include') && str.includes(relatedFile.path)))
if (sourceLine !== -1) {
sourceRange = textDocument.lineAt(sourceLine).range
}
}
} else {
// generic error (e.g. :source-highlighter: coderay)
errorMessage = error.message
}
let severity = vscode.DiagnosticSeverity.Information
if (error.getSeverity() === 'WARN') {
severity = vscode.DiagnosticSeverity.Warning
} else if (error.getSeverity() === 'ERROR') {
severity = vscode.DiagnosticSeverity.Error
} else if (error.getSeverity() === 'DEBUG') {
severity = vscode.DiagnosticSeverity.Information
}
let diagnosticRelated = null
if (relatedFile) {
diagnosticRelated = [
new vscode.DiagnosticRelatedInformation(
new vscode.Location(vscode.Uri.file(relatedFile.file),
new vscode.Position(0, 0)
),
errorMessage
),
]
errorMessage = 'There was an error in an included file'
}
const diagnosticError = new vscode.Diagnostic(sourceRange, errorMessage, severity)
diagnosticError.source = diagnosticSource
if (diagnosticRelated) {
diagnosticError.relatedInformation = diagnosticRelated
}
diagnostics.push(diagnosticError)
})
if (this.errorCollection) {
this.errorCollection.set(textDocument.uri, diagnostics)
}
}
/**
* Get the base directory.
* @param documentFileName The file system path of the text document.
* @private
*/
private static getBaseDir (documentFilePath: string): string | undefined {
const documentPath = process.env.BROWSER_ENV
? undefined
: path.dirname(path.resolve(documentFilePath))
const useWorkspaceAsBaseDir = vscode.workspace.getConfiguration('asciidoc', null).get('useWorkspaceRootAsBaseDirectory')
return useWorkspaceAsBaseDir && typeof vscode.workspace.rootPath !== 'undefined'
? vscode.workspace.rootPath
: documentPath
}
/**
* Get user defined template directories from configuration.
* @private
*/
private getTemplateDirs () {
const templatesDir = vscode.workspace.getConfiguration('asciidoc.preview', null).get<string[]>('templates', [])
return templatesDir
}
private async confirmAsciidoctorExtensionsTrusted (): Promise<boolean> {
if (!this.isAsciidoctorExtensionsRegistrationEnabled()) {
return false
}
const extensionFiles = await this.getExtensionFilesInWorkspace()
const extensionsCount = extensionFiles.length
if (extensionsCount === 0) {
return false
}
return this.aspArbiter.confirmAsciidoctorExtensionsTrustMode(extensionsCount)
}
private async registerAsciidoctorExtensions (registry) {
const enableKroki = vscode.workspace.getConfiguration('asciidoc.extensions', null).get('enableKroki')
if (enableKroki) {
const kroki = require('asciidoctor-kroki')
kroki.register(registry)
}
registry.preprocessor(this.prependExtension)
await this.registerExtensionsInWorkspace(registry)
}
private async getExtensionFilesInWorkspace (): Promise<vscode.Uri[]> {
return vscode.workspace.findFiles('.asciidoctor/lib/**/*.js')
}
private isAsciidoctorExtensionsRegistrationEnabled (): boolean {
return vscode.workspace.getConfiguration('asciidoc.extensions', null).get('registerWorkspaceExtensions')
}
private async registerExtensionsInWorkspace (registry) {
const extensionsTrusted = await this.confirmAsciidoctorExtensionsTrusted()
if (!extensionsTrusted) {
return
}
const extfiles = await this.getExtensionFilesInWorkspace()
for (const extfile of extfiles) {
const extPath = extfile.fsPath
try {
delete require.cache[extPath]
const extjs = require(extPath)
extjs.register(registry)
} catch (e) {
vscode.window.showErrorMessage(extPath + ': ' + e.toString())
}
}
}
}