Highlight a search pattern with codemirror - Javascript CodeMirror

Javascript examples for CodeMirror:Highlight

Description

Highlight a search pattern with codemirror

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
      <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/codemirror.css"> 
      <script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/codemirror.min.js"></script> 
      <script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/search.js"></script> 
      <script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/searchcursor.js"></script> 
      <script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/overlay.min.js"></script> 
      <script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/match-highlighter.js"></script> 
      <script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/python.js"></script> 
      <style type="text/css">

.cm-highlightSearch {background: yellow;}


      </style>
   </head>  
   <body> 
      <textarea id="myTextArea">print "hello world"</textarea> 
      <script>
        var keyword = 'hello';
        CodeMirror.defineMode("highlightSearch", function(config, parserConfig) {
          var searchOverlay = {//from   w  w w  . j  av  a 2  s .  c  om
            token: function(stream, state) {
                if (stream.match(keyword)) {
                    return "highlightSearch";
                }
                while (stream.next() != null && !stream.match(keyword, false)) {}
                return null;
            }
          };
          return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "python"), searchOverlay);
        });
        var myTextArea = document.getElementById('myTextArea');
        var myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
            'mode': 'highlightSearch',
            'lineNumbers': true
        });
        
      </script>  
   </body>
</html>

Related Tutorials