Search code examples
javascriptcodemirror

Code mirror Java mode does not seem to work


I am trying to use Codemirror and it works fine for other modes. Here is my code:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <link href="codemirror.css" rel="stylesheet" />
    <link
      href="theme/ambiance.css"
      rel="stylesheet"
    />
    <script src="codemirror.js"></script>
    <script src="mode/javascript/javascript.js"></script>
  </head>
  <body>
    <textarea id="codepane">
function hello(){

}
      </textarea
    >
    <script>
      CodeMirror.fromTextArea(document.getElementById("codepane"), {
        mode: "javascript",
        indentWithTabs: true,
        smartIndent: true,
        lineNumbers: true,
        lineWrapping: true,
        matchBrackets: true,
        autofocus: true,
        theme: "ambiance",
      });
    </script>
  </body>
</html>

This is my output:

enter image description here

I am trying to change it to Java mode, but I am not able to find the Java mode in the mode folder enter image description here

I know I have to change the mode to mode: "text/x-java", but it does not work as there is no accompanying mode js file for java. Am I missing something here?


Solution

  • As you can see in the Codemirror website, you can see that when we click on the Java mode, it redirects us to c-like mode. So, you can use c-like mode js file your purpose.

    CodeMirror.fromTextArea(document.getElementById("codepane"), {
      mode: "text/x-java",
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      lineWrapping: true,
      matchBrackets: true,
      autofocus: true,
      theme: "ambiance",
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.3/codemirror.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.3/theme/ambiance.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.3/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.58.3/mode/clike/clike.min.js"></script>
    
    <textarea id="codepane">
    private class InnerClass {
      public int zero() {
        return 0;
      }
    }
    </textarea>

    Note - There might be some errors as I am not familiar with codemirror, but the above snippet must solve your issue.

    Edit - You can use "text/x-java" as the mode and load the click.js as given in the edited snippet to configure proper syntax highlighting.