entity.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Process html entity - {, ¯, ", ...
  2. 'use strict';
  3. var entities = require('../common/entities');
  4. var has = require('../common/utils').has;
  5. var isValidEntityCode = require('../common/utils').isValidEntityCode;
  6. var fromCodePoint = require('../common/utils').fromCodePoint;
  7. var DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
  8. var NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
  9. module.exports = function entity(state, silent) {
  10. var ch, code, match, token, pos = state.pos, max = state.posMax;
  11. if (state.src.charCodeAt(pos) !== 0x26/* & */) return false;
  12. if (pos + 1 >= max) return false;
  13. ch = state.src.charCodeAt(pos + 1);
  14. if (ch === 0x23 /* # */) {
  15. match = state.src.slice(pos).match(DIGITAL_RE);
  16. if (match) {
  17. if (!silent) {
  18. code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10);
  19. token = state.push('text_special', '', 0);
  20. token.content = isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD);
  21. token.markup = match[0];
  22. token.info = 'entity';
  23. }
  24. state.pos += match[0].length;
  25. return true;
  26. }
  27. } else {
  28. match = state.src.slice(pos).match(NAMED_RE);
  29. if (match) {
  30. if (has(entities, match[1])) {
  31. if (!silent) {
  32. token = state.push('text_special', '', 0);
  33. token.content = entities[match[1]];
  34. token.markup = match[0];
  35. token.info = 'entity';
  36. }
  37. state.pos += match[0].length;
  38. return true;
  39. }
  40. }
  41. }
  42. return false;
  43. };