match-highlighter.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Define match-highlighter commands. Depends on searchcursor.js
  2. // Use by attaching the following function call to the onCursorActivity 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 && cursor.from().ch === cm.getCursor(true).ch))
  30. state.marked.push(cm.markText(cursor.from(), cursor.to(), className));
  31. }
  32. }
  33. });
  34. }
  35. }
  36. CodeMirror.defineExtension("matchHighlight", function(className, minChars) {
  37. markDocument(this, className, minChars);
  38. });
  39. })();