xml-hint.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. (function() {
  2. CodeMirror.xmlHints = [];
  3. CodeMirror.xmlHint = function(cm, simbol) {
  4. if(simbol.length > 0) {
  5. var cursor = cm.getCursor();
  6. cm.replaceSelection(simbol);
  7. cursor = {line: cursor.line, ch: cursor.ch + 1};
  8. cm.setCursor(cursor);
  9. }
  10. CodeMirror.simpleHint(cm, getHint);
  11. };
  12. var getHint = function(cm) {
  13. var cursor = cm.getCursor();
  14. if (cursor.ch > 0) {
  15. var text = cm.getRange({line: 0, ch: 0}, cursor);
  16. var typed = '';
  17. var simbol = '';
  18. for(var i = text.length - 1; i >= 0; i--) {
  19. if(text[i] == ' ' || text[i] == '<') {
  20. simbol = text[i];
  21. break;
  22. }
  23. else {
  24. typed = text[i] + typed;
  25. }
  26. }
  27. text = text.slice(0, text.length - typed.length);
  28. var path = getActiveElement(text) + simbol;
  29. var hints = CodeMirror.xmlHints[path];
  30. if(typeof hints === 'undefined')
  31. hints = [''];
  32. else {
  33. hints = hints.slice(0);
  34. for (var i = hints.length - 1; i >= 0; i--) {
  35. if(hints[i].indexOf(typed) != 0)
  36. hints.splice(i, 1);
  37. }
  38. }
  39. return {
  40. list: hints,
  41. from: { line: cursor.line, ch: cursor.ch - typed.length },
  42. to: cursor
  43. };
  44. };
  45. };
  46. var getActiveElement = function(text) {
  47. var element = '';
  48. if(text.length >= 0) {
  49. var regex = new RegExp('<([^!?][^\\s/>]*).*?>', 'g');
  50. var matches = [];
  51. var match;
  52. while ((match = regex.exec(text)) != null) {
  53. matches.push({
  54. tag: match[1],
  55. selfclose: (match[0].slice(match[0].length - 2) === '/>')
  56. });
  57. }
  58. for (var i = matches.length - 1, skip = 0; i >= 0; i--) {
  59. var item = matches[i];
  60. if (item.tag[0] == '/')
  61. {
  62. skip++;
  63. }
  64. else if (item.selfclose == false)
  65. {
  66. if (skip > 0)
  67. {
  68. skip--;
  69. }
  70. else
  71. {
  72. element = '<' + item.tag + '>' + element;
  73. }
  74. }
  75. }
  76. element += getOpenTag(text);
  77. }
  78. return element;
  79. };
  80. var getOpenTag = function(text) {
  81. var open = text.lastIndexOf('<');
  82. var close = text.lastIndexOf('>');
  83. if (close < open)
  84. {
  85. text = text.slice(open);
  86. if(text != '<') {
  87. var space = text.indexOf(' ');
  88. if(space < 0)
  89. space = text.indexOf('\t');
  90. if(space < 0)
  91. space = text.indexOf('\n');
  92. if (space < 0)
  93. space = text.length;
  94. return text.slice(0, space);
  95. }
  96. }
  97. return '';
  98. };
  99. })();