match-highlighter.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Highlighting text that matches the selection
  2. //
  3. // Defines an option highlightSelectionMatches, which, when enabled,
  4. // will style strings that match the selection throughout the
  5. // document.
  6. //
  7. // The option can be set to true to simply enable it, or to a
  8. // {minChars, style} object to explicitly configure it. minChars is
  9. // the minimum amount of characters that should be selected for the
  10. // behavior to occur, and style is the token style to apply to the
  11. // matches. This will be prefixed by "cm-" to create an actual CSS
  12. // class name.
  13. (function() {
  14. var DEFAULT_MIN_CHARS = 2;
  15. var DEFAULT_TOKEN_STYLE = "matchhighlight";
  16. function State(options) {
  17. this.minChars = typeof options == "object" && options.minChars || DEFAULT_MIN_CHARS;
  18. this.style = typeof options == "object" && options.style || DEFAULT_TOKEN_STYLE;
  19. this.overlay = null;
  20. }
  21. CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
  22. var prev = old && old != CodeMirror.Init;
  23. if (val && !prev) {
  24. cm._matchHighlightState = new State(val);
  25. cm.on("cursorActivity", highlightMatches);
  26. } else if (!val && prev) {
  27. var over = cm._matchHighlightState.overlay;
  28. if (over) cm.removeOverlay(over);
  29. cm._matchHighlightState = null;
  30. cm.off("cursorActivity", highlightMatches);
  31. }
  32. });
  33. function highlightMatches(cm) {
  34. cm.operation(function() {
  35. var state = cm._matchHighlightState;
  36. if (state.overlay) {
  37. cm.removeOverlay(state.overlay);
  38. state.overlay = null;
  39. }
  40. if (!cm.somethingSelected()) return;
  41. var selection = cm.getSelection().replace(/^\s+|\s+$/g, "");
  42. if (selection.length < state.minChars) return;
  43. cm.addOverlay(state.overlay = makeOverlay(selection, state.style));
  44. });
  45. }
  46. function makeOverlay(query, style) {
  47. return {token: function(stream) {
  48. if (stream.match(query)) return style;
  49. stream.next();
  50. stream.skipTo(query.charAt(0)) || stream.skipToEnd();
  51. }};
  52. }
  53. })();