index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Process {ruby base|ruby text}
  2. 'use strict';
  3. function ddmd_ruby (state, silent) {
  4. var token,
  5. tokens,
  6. max = state.posMax,
  7. start = state.pos,
  8. devPos,
  9. closePos,
  10. baseText,
  11. rubyText,
  12. baseArray,
  13. rubyArray;
  14. if (silent) { return false; }
  15. if (state.src.charCodeAt(start) !== 0x7b/* { */) { return false; }
  16. if (start + 4 >= max) {return false; }
  17. state.pos = start + 1;
  18. while (state.pos < max) {
  19. if (devPos) {
  20. if (
  21. state.src.charCodeAt(state.pos) === 0x7D/* } */
  22. && state.src.charCodeAt(state.pos - 1) !== 0x5C/* \ */
  23. ) {
  24. closePos = state.pos;
  25. break;
  26. }
  27. } else if (state.src.charCodeAt(state.pos) === 0x7C/* | */
  28. && state.src.charCodeAt(state.pos - 1) !== 0x5C/* \ */) {
  29. devPos = state.pos;
  30. }
  31. state.pos++;
  32. }
  33. if (!closePos || start + 1 === state.pos) {
  34. state.pos = start;
  35. return false;
  36. }
  37. state.posMax = state.pos;
  38. state.pos = start + 1;
  39. token = state.push('ruby_open', 'ruby', 1);
  40. token.markup = '{';
  41. baseText = state.src.slice(start + 1, devPos);
  42. rubyText = state.src.slice(devPos + 1, closePos);
  43. baseArray = baseText.split('');
  44. rubyArray = rubyText.split('|');
  45. if (baseArray.length === rubyArray.length) {
  46. baseArray.forEach(function(content, idx) {
  47. state.md.inline.parse(
  48. content,
  49. state.md,
  50. state.env,
  51. tokens = []
  52. );
  53. tokens.forEach(function(t) {
  54. state.tokens.push(t);
  55. });
  56. token = state.push('rt_open', 'rt', 1);
  57. state.md.inline.parse(
  58. rubyArray[idx],
  59. state.md,
  60. state.env,
  61. tokens = []
  62. );
  63. tokens.forEach(function(t) {
  64. state.tokens.push(t);
  65. });
  66. token = state.push('rt_close', 'rt', -1);
  67. });
  68. } else {
  69. state.md.inline.parse(
  70. baseText,
  71. state.md,
  72. state.env,
  73. tokens = []
  74. );
  75. tokens.forEach(function(t) {
  76. state.tokens.push(t);
  77. });
  78. token = state.push('rt_open', 'rt', 1);
  79. state.md.inline.parse(
  80. rubyText,
  81. state.md,
  82. state.env,
  83. tokens = []
  84. );
  85. tokens.forEach(function(t) {
  86. state.tokens.push(t);
  87. });
  88. token = state.push('rt_close', 'rt', -1);
  89. }
  90. token = state.push('ruby_close', 'ruby', -1);
  91. token.markup = '}';
  92. state.pos = state.posMax + 1;
  93. state.posMax = max;
  94. return true;
  95. }
  96. module.exports = function ruby_plugin(md) {
  97. md.inline.ruler.before('text', 'ddmd_ruby', ddmd_ruby);
  98. };