prism.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import { replaceAtPosition, indexOfGroup, keys, htmlEntities, hasCompleteOverlap, intersects } from './util';
  2. /**
  3. * Prism is a class used to highlight individual blocks of code
  4. *
  5. * @class
  6. */
  7. class Prism {
  8. constructor(options) {
  9. /**
  10. * Object of replacements to process at the end of the processing
  11. *
  12. * @type {Object}
  13. */
  14. const replacements = {};
  15. /**
  16. * Language associated with this Prism object
  17. *
  18. * @type {string}
  19. */
  20. let currentLanguage;
  21. /**
  22. * Object of start and end positions of blocks to be replaced
  23. *
  24. * @type {Object}
  25. */
  26. const replacementPositions = {};
  27. /**
  28. * Determines if the match passed in falls inside of an existing match.
  29. * This prevents a regex pattern from matching inside of another pattern
  30. * that matches a larger amount of code.
  31. *
  32. * For example this prevents a keyword from matching `function` if there
  33. * is already a match for `function (.*)`.
  34. *
  35. * @param {number} start start position of new match
  36. * @param {number} end end position of new match
  37. * @return {boolean}
  38. */
  39. function _matchIsInsideOtherMatch(start, end) {
  40. for (let key in replacementPositions) {
  41. key = parseInt(key, 10);
  42. // If this block completely overlaps with another block
  43. // then we should remove the other block and return `false`.
  44. if (hasCompleteOverlap(key, replacementPositions[key], start, end)) {
  45. delete replacementPositions[key];
  46. delete replacements[key];
  47. }
  48. if (intersects(key, replacementPositions[key], start, end)) {
  49. return true;
  50. }
  51. }
  52. return false;
  53. }
  54. /**
  55. * Takes a string of code and wraps it in a span tag based on the name
  56. *
  57. * @param {string} name name of the pattern (ie keyword.regex)
  58. * @param {string} code block of code to wrap
  59. * @param {string} globalClass class to apply to every span
  60. * @return {string}
  61. */
  62. function _wrapCodeInSpan(name, code) {
  63. let className = name.replace(/\./g, ' ');
  64. const globalClass = options.globalClass;
  65. if (globalClass) {
  66. className += ` ${globalClass}`;
  67. }
  68. return `<span class="${className}">${code}</span>`;
  69. }
  70. /**
  71. * Process replacements in the string of code to actually update
  72. * the markup
  73. *
  74. * @param {string} code the code to process replacements in
  75. * @return {string}
  76. */
  77. function _processReplacements(code) {
  78. const positions = keys(replacements);
  79. for (const position of positions) {
  80. const replacement = replacements[position];
  81. code = replaceAtPosition(position, replacement.replace, replacement.with, code);
  82. }
  83. return code;
  84. }
  85. /**
  86. * It is so we can create a new regex object for each call to
  87. * _processPattern to avoid state carrying over when running exec
  88. * multiple times.
  89. *
  90. * The global flag should not be carried over because we are simulating
  91. * it by processing the regex in a loop so we only care about the first
  92. * match in each string. This also seems to improve performance quite a
  93. * bit.
  94. *
  95. * @param {RegExp} regex
  96. * @return {string}
  97. */
  98. function _cloneRegex(regex) {
  99. let flags = '';
  100. if (regex.ignoreCase) {
  101. flags += 'i';
  102. }
  103. if (regex.multiline) {
  104. flags += 'm';
  105. }
  106. return new RegExp(regex.source, flags);
  107. }
  108. /**
  109. * Matches a regex pattern against a block of code, finds all matches
  110. * that should be processed, and stores the positions of where they
  111. * should be replaced within the string.
  112. *
  113. * This is where pretty much all the work is done but it should not
  114. * be called directly.
  115. *
  116. * @param {Object} pattern
  117. * @param {string} code
  118. * @param {number} offset
  119. * @return {mixed}
  120. */
  121. function _processPattern(pattern, code, offset = 0) {
  122. let regex = pattern.pattern;
  123. if (!regex) {
  124. return false;
  125. }
  126. // Since we are simulating global regex matching we need to also
  127. // make sure to stop after one match if the pattern is not global
  128. const shouldStop = !regex.global;
  129. regex = _cloneRegex(regex);
  130. const match = regex.exec(code);
  131. if (!match) {
  132. return false;
  133. }
  134. // Treat match 0 the same way as name
  135. if (!pattern.name && pattern.matches && typeof pattern.matches[0] === 'string') {
  136. pattern.name = pattern.matches[0];
  137. delete pattern.matches[0];
  138. }
  139. let replacement = match[0];
  140. const startPos = match.index + offset;
  141. const endPos = match[0].length + startPos;
  142. // In some cases when the regex matches a group such as \s* it is
  143. // possible for there to be a match, but have the start position
  144. // equal the end position. In those cases we should be able to stop
  145. // matching. Otherwise this can lead to an infinite loop.
  146. if (startPos === endPos) {
  147. return false;
  148. }
  149. // If this is not a child match and it falls inside of another
  150. // match that already happened we should skip it and continue
  151. // processing.
  152. if (_matchIsInsideOtherMatch(startPos, endPos)) {
  153. return {
  154. remaining: code.substr(endPos - offset),
  155. offset: endPos
  156. };
  157. }
  158. /**
  159. * Callback for when a match was successfully processed
  160. *
  161. * @param {string} repl
  162. * @return {void}
  163. */
  164. function onMatchSuccess(repl) {
  165. // If this match has a name then wrap it in a span tag
  166. if (pattern.name) {
  167. repl = _wrapCodeInSpan(pattern.name, repl);
  168. }
  169. // For debugging
  170. // console.log('Replace ' + match[0] + ' with ' + replacement + ' at position ' + startPos + ' to ' + endPos);
  171. // Store what needs to be replaced with what at this position
  172. replacements[startPos] = {
  173. 'replace': match[0],
  174. 'with': repl
  175. };
  176. // Store the range of this match so we can use it for
  177. // comparisons with other matches later.
  178. replacementPositions[startPos] = endPos;
  179. if (shouldStop) {
  180. return false;
  181. }
  182. return {
  183. remaining: code.substr(endPos - offset),
  184. offset: endPos
  185. };
  186. }
  187. /**
  188. * Helper function for processing a sub group
  189. *
  190. * @param {number} groupKey index of group
  191. * @return {void}
  192. */
  193. function _processGroup(groupKey) {
  194. const block = match[groupKey];
  195. // If there is no match here then move on
  196. if (!block) {
  197. return;
  198. }
  199. const group = pattern.matches[groupKey];
  200. const language = group.language;
  201. /**
  202. * Process group is what group we should use to actually process
  203. * this match group.
  204. *
  205. * For example if the subgroup pattern looks like this:
  206. *
  207. * 2: {
  208. * 'name': 'keyword',
  209. * 'pattern': /true/g
  210. * }
  211. *
  212. * then we use that as is, but if it looks like this:
  213. *
  214. * 2: {
  215. * 'name': 'keyword',
  216. * 'matches': {
  217. * 'name': 'special',
  218. * 'pattern': /whatever/g
  219. * }
  220. * }
  221. *
  222. * we treat the 'matches' part as the pattern and keep
  223. * the name around to wrap it with later
  224. */
  225. const groupToProcess = group.name && group.matches ? group.matches : group;
  226. /**
  227. * Takes the code block matched at this group, replaces it
  228. * with the highlighted block, and optionally wraps it with
  229. * a span with a name
  230. *
  231. * @param {string} passedBlock
  232. * @param {string} replaceBlock
  233. * @param {string|null} matchName
  234. */
  235. const _getReplacement = function(passedBlock, replaceBlock, matchName) {
  236. replacement = replaceAtPosition(indexOfGroup(match, groupKey), passedBlock, matchName ? _wrapCodeInSpan(matchName, replaceBlock) : replaceBlock, replacement);
  237. return;
  238. };
  239. // If this is a string then this match is directly mapped
  240. // to selector so all we have to do is wrap it in a span
  241. // and continue.
  242. if (typeof group === 'string') {
  243. _getReplacement(block, block, group);
  244. return;
  245. }
  246. let localCode;
  247. const prism = new Prism(options);
  248. // If this is a sublanguage go and process the block using
  249. // that language
  250. if (language) {
  251. localCode = prism.refract(block, language);
  252. _getReplacement(block, localCode);
  253. return;
  254. }
  255. // The process group can be a single pattern or an array of
  256. // patterns. `_processCodeWithPatterns` always expects an array
  257. // so we convert it here.
  258. localCode = prism.refract(block, currentLanguage, groupToProcess.length ? groupToProcess : [groupToProcess]);
  259. _getReplacement(block, localCode, group.matches ? group.name : 0);
  260. }
  261. // If this pattern has sub matches for different groups in the regex
  262. // then we should process them one at a time by running them through
  263. // the _processGroup function to generate the new replacement.
  264. //
  265. // We use the `keys` function to run through them backwards because
  266. // the match position of earlier matches will not change depending
  267. // on what gets replaced in later matches.
  268. const groupKeys = keys(pattern.matches);
  269. for (const groupKey of groupKeys) {
  270. _processGroup(groupKey);
  271. }
  272. // Finally, call `onMatchSuccess` with the replacement
  273. return onMatchSuccess(replacement);
  274. }
  275. /**
  276. * Processes a block of code using specified patterns
  277. *
  278. * @param {string} code
  279. * @param {Array} patterns
  280. * @return {string}
  281. */
  282. function _processCodeWithPatterns(code, patterns) {
  283. for (const pattern of patterns) {
  284. let result = _processPattern(pattern, code);
  285. while (result) {
  286. result = _processPattern(pattern, result.remaining, result.offset);
  287. }
  288. }
  289. // We are done processing the patterns so we should actually replace
  290. // what needs to be replaced in the code.
  291. return _processReplacements(code);
  292. }
  293. /**
  294. * Returns a list of regex patterns for this language
  295. *
  296. * @param {string} language
  297. * @return {Array}
  298. */
  299. function getPatternsForLanguage(language) {
  300. let patterns = options.patterns[language] || [];
  301. while (options.inheritenceMap[language]) {
  302. language = options.inheritenceMap[language];
  303. patterns = patterns.concat(options.patterns[language] || []);
  304. }
  305. return patterns;
  306. }
  307. /**
  308. * Takes a string of code and highlights it according to the language
  309. * specified
  310. *
  311. * @param {string} code
  312. * @param {string} language
  313. * @param {object} patterns optionally specify a list of patterns
  314. * @return {string}
  315. */
  316. function _highlightBlockForLanguage(code, language, patterns) {
  317. currentLanguage = language;
  318. patterns = patterns || getPatternsForLanguage(language);
  319. return _processCodeWithPatterns(htmlEntities(code), patterns);
  320. }
  321. this.refract = _highlightBlockForLanguage;
  322. }
  323. }
  324. export default Prism;