3
var fs = require("fs");
4
var vm = require("vm");
5
var components = require("./components");
6
var languagesCatalog = components.languages;
12
* Creates a new Prism instance with the given language loaded
14
* @param {string|string[]} languages
17
createInstance: function (languages) {
20
Prism: this.createEmptyPrism()
23
context = this.loadLanguages(languages, context);
29
* Loads the given languages and appends the config to the given Prism object
32
* @param {string|string[]} languages
33
* @param {{loadedLanguages: string[], Prism: Prism}} context
34
* @returns {{loadedLanguages: string[], Prism: Prism}}
36
loadLanguages: function (languages, context) {
37
if (typeof languages === 'string') {
38
languages = [languages];
43
languages.forEach(function (language) {
44
context = self.loadLanguage(language, context);
51
* Loads the given language (including recursively loading the dependencies) and
52
* appends the config to the given Prism object
55
* @param {string} language
56
* @param {{loadedLanguages: string[], Prism: Prism}} context
57
* @returns {{loadedLanguages: string[], Prism: Prism}}
59
loadLanguage: function (language, context) {
60
if (!languagesCatalog[language]) {
61
throw new Error("Language '" + language + "' not found.");
64
// the given language was already loaded
65
if (-1 < context.loadedLanguages.indexOf(language)) {
69
// if the language has a dependency -> load it first
70
if (languagesCatalog[language].require) {
71
context = this.loadLanguages(languagesCatalog[language].require, context);
74
// load the language itself
75
var languageSource = this.loadFileSource(language);
76
context.Prism = this.runFileWithContext(languageSource, {Prism: context.Prism}).Prism;
77
context.loadedLanguages.push(language);
84
* Creates a new empty prism instance
89
createEmptyPrism: function () {
90
var coreSource = this.loadFileSource("core");
91
var context = this.runFileWithContext(coreSource);
97
* Cached file sources, to prevent massive HDD work
100
* @type {Object.<string, string>}
106
* Loads the given file source as string
109
* @param {string} name
112
loadFileSource: function (name) {
113
return this.fileSourceCache[name] = this.fileSourceCache[name] || fs.readFileSync(__dirname + "/../../components/prism-" + name + ".js", "utf8");
118
* Runs a VM for a given file source with the given context
121
* @param {string} fileSource
122
* @param {*} [context]
126
runFileWithContext: function (fileSource, context) {
127
context = context || {};
128
vm.runInNewContext(fileSource, context);