javascriptcodemirrorui-codemirror

How to show line count in codemirror


I am using codemirror API in my application, i tried to show the total line count and when type to count new line but it was giving me another thing

I use this script to get the last-child of number, but when i have 29 lines it show this 1234567891011121314151617181920212223242526272829 which is not what i intent to do i want it to show just 29 and also onkeydown is not working at all

  <script>
    $(document).ready(function(){
      var tolalline = $('.CodeMirror-linenumber:last-child').text();
      $('#hcunter').text(tolalline);
      $('#inputTextToSave').keydown(function(){
        var tolalline = $('.CodeMirror-linenumber:last-child').text();
        $('#hcunter').text(tolalline);
      }
                                  );
      $("#alterTool").click(function(){
        $("#EditTool").toggle(1000);
      });
    });
  </script>

CodeMirror

<script>
    var editor = CodeMirror.fromTextArea(document.getElementById("inputTextToSave"), 
    {
        lineNumbers: true,
        viewportMargin: Infinity,
        //Theme
        styleActiveLine: true,
        matchBrackets: true,
        gutter: true
    });
</script>

Solution

  • To get numbers of lines you must use the css selector:

    .CodeMirror-code > div:last-child div.CodeMirror-gutter-elt
    

    So, if you want to count the lines, you will override the Enter key in extraKeys attribute of CodeMirror configuration. It would be:

      extraKeys:
      {
        Enter: function(){
          setTimeout(function() {
            var tolalline = $('.CodeMirror-code > div:last-child div.CodeMirror-gutter-elt').text();
            $('#hcunter').text(tolalline);
          }, 0);
          return CodeMirror.Pass;
        }
      }
    

    I set a setTimeout to create a minimun delay necessary. You don't need to set a onKeyDown event now.

    All code:

      var editor = CodeMirror.fromTextArea(document.getElementById("inputTextToSave"),
          {
            lineNumbers: true,
            viewportMargin: Infinity,
            //Theme
            styleActiveLine: true,
            matchBrackets: true,
            gutter: true,
            extraKeys:
            {
              Enter: function(){
                setTimeout(function() {
                  var tolalline = $('.CodeMirror-code > div:last-child div.CodeMirror-gutter-elt').text();
                  $('#hcunter').text(tolalline);
                }, 0);
                return CodeMirror.Pass;
              }
            }
          }
        );
    
    
    $(document).ready(function(){
      var tolalline = $('.CodeMirror-code > div:last-child div.CodeMirror-gutter-elt').text();
      $('#hcunter').text(tolalline);
      $("#alterTool").click(function(){
        $("#EditTool").toggle(1000);
      });
    });
    

    I hope that it's that you wanted! :-)