match-highlighter.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Define match-highlighter commands. Depends on searchcursor.js
  2. // Use by attaching the following function call to the cursorActivity event:
  3. //myCodeMirror.matchHighlight(minChars);
  4. // And including a special span.CodeMirror-matchhighlight css class (also optionally a separate one for .CodeMirror-focused -- see demo matchhighlighter.html)
  5. (function() {
  6. var DEFAULT_MIN_CHARS = 2;
  7. function MatchHighlightState() {
  8. this.marked = [];
  9. }
  10. function getMatchHighlightState(cm) {
  11. return cm._matchHighlightState || (cm._matchHighlightState = new MatchHighlightState());
  12. }
  13. function clearMarks(cm) {
  14. var state = getMatchHighlightState(cm);
  15. for (var i = 0; i < state.marked.length; ++i)
  16. state.marked[i].clear();
  17. state.marked = [];
  18. }
  19. function markDocument(cm, className, minChars) {
  20. clearMarks(cm);
  21. minChars = (typeof minChars !== 'undefined' ? minChars : DEFAULT_MIN_CHARS);
  22. if (cm.somethingSelected() && cm.getSelection().replace(/^\s+|\s+$/g, "").length >= minChars) {
  23. var state = getMatchHighlightState(cm);
  24. var query = cm.getSelection();
  25. cm.operation(function() {
  26. if (cm.lineCount() < 2000) { // This is too expensive on big documents.
  27. for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
  28. //Only apply matchhighlight to the matches other than the one actually selected
  29. if (cursor.from().line !== cm.getCursor(true).line ||
  30. cursor.from().ch !== cm.getCursor(true).ch)
  31. state.marked.push(cm.markText(cursor.from(), cursor.to(),
  32. {className: className}));
  33. }
  34. }
  35. });
  36. }
  37. }
  38. CodeMirror.defineExtension("matchHighlight", function(className, minChars) {
  39. markDocument(this, className, minChars);
  40. });
  41. })();