1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 | <!doctype html> <html> <head> <title>CodeMirror: User Manual</title> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/> <link rel="stylesheet" type="text/css" href="docs.css"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style>dl dl {margin: 0;}</style> </head> <body> <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1> <pre class="grey"> <img src="baboon.png" class="logo" alt="logo"/>/* User manual and reference guide */ </pre> <div class="clear"><div class="leftbig blk"> <h2 id="overview">Overview</h2> <p>CodeMirror is a code-editor component that can be embedded in Web pages. The code library provides <em>only</em> the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the <a href="#addons">add-ons</a> included in the distribution, and the <a href="http://www.octolabs.com/javascripts/codemirror-ui/">CodeMirror UI</a> project, for reusable implementations of extra features.</p> <p>CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a few modes (see the <code>mode/</code> directory), and it isn't hard to <a href="#modeapi">write new ones</a> for other languages.</p> <h2 id="usage">Basic Usage</h2> <p>The easiest way to use CodeMirror is to simply load the script and style sheet found under <code>lib/</code> in the distribution, plus a mode script from one of the <code>mode/</code> directories and a theme stylesheet from <code>theme/</code>. (See also <a href="compress.html">the compression helper</a>.) For example:</p> <pre><script src="lib/codemirror.js"></script> <link rel="stylesheet" href="../lib/codemirror.css"> <script src="mode/javascript/javascript.js"></script></pre> <p>Having done this, an editor instance can be created like this:</p> <pre>var myCodeMirror = CodeMirror(document.body);</pre> <p>The editor will be appended to the document body, will start empty, and will use the mode that we loaded. To have more control over the new editor, a configuration object can be passed to <code>CodeMirror</code> as a second argument:</p> <pre>var myCodeMirror = CodeMirror(document.body, { value: "function myScript(){return 100;}\n", mode: "javascript" });</pre> <p>This will initialize the editor with a piece of code already in it, and explicitly tell it to use the JavaScript mode (which is useful when multiple modes are loaded). See <a href="#config">below</a> for a full discussion of the configuration options that CodeMirror accepts.</p> <p>In cases where you don't want to append the editor to an element, and need more control over the way it is inserted, the first argument to the <code>CodeMirror</code> function can also be a function that, when given a DOM element, inserts it into the document somewhere. This could be used to, for example, replace a textarea with a real editor:</p> <pre>var myCodeMirror = CodeMirror(function(elt) { myTextArea.parentNode.replaceChild(elt, myTextArea); }, {value: myTextArea.value});</pre> <p>However, for this use case, which is a common way to use CodeMirror, the library provides a much more powerful shortcut:</p> <pre>var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre> <p>This will, among other things, ensure that the textarea's value is updated when the form (if it is part of a form) is submitted. See the <a href="#fromTextArea">API reference</a> for a full description of this method.</p> <h2 id="config">Configuration</h2> <p>Both the <code>CodeMirror</code> function and its <code>fromTextArea</code> method take as second (optional) argument an object containing configuration options. Any option not supplied like this will be taken from <code>CodeMirror.defaults</code>, an object containing the default options. You can update this object to change the defaults on your page.</p> <p>Options are not checked in any way, so setting bogus option values is bound to lead to odd errors.</p> <p>These are the supported options:</p> <dl> <dt id="option_value"><code>value (string)</code></dt> <dd>The starting value of the editor.</dd> <dt id="option_mode"><code>mode (string or object)</code></dt> <dd>The mode to use. When not given, this will default to the first mode that was loaded. It may be a string, which either simply names the mode or is a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type associated with the mode. Alternatively, it may be an object containing configuration options for the mode, with a <code>name</code> property that names the mode (for example <code>{name: "javascript", json: true}</code>). The demo pages for each mode contain information about what configuration parameters the mode supports. You can ask CodeMirror which modes and MIME types are loaded with the <code>CodeMirror.listModes</code> and <code>CodeMirror.listMIMEs</code> functions.</dd> <dt id="option_theme"><code>theme (string)</code></dt> <dd>The theme to style the editor with. You must make sure the CSS file defining the corresponding <code>.cm-s-[name]</code> styles is loaded (see the <a href="../theme/"><code>theme</code></a> directory in the distribution). The default is <code>"default"</code>, for which colors are included in <code>codemirror.css</code>. It is possible to use multiple theming classes at once—for example <code>"foo bar"</code> will assign both the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes to the editor.</dd> <dt id="option_indentUnit"><code>indentUnit (integer)</code></dt> <dd>How many spaces a block (whatever that means in the edited language) should be indented. The default is 2.</dd> <dt id="option_tabSize"><code>tabSize (integer)</code></dt> <dd>The width of a tab character. Defaults to 4.</dd> <dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt> <dd>Whether, when indenting, the first N*<code>tabSize</code> spaces should be replaced by N tabs. Default is false.</dd> <dt id="option_electricChars"><code>electricChars (boolean)</code></dt> <dd>Configures whether the editor should re-indent the current line when a character is typed that might change its proper indentation (only works if the mode supports indentation). Default is true.</dd> <dt id="option_keyMap"><code>keyMap (string)</code></dt> <dd>Configures the keymap to use. The default is <code>"default"</code>, which is the only keymap defined in <code>codemirror.js</code> itself. Extra keymaps are found in the <a href="../keymap/"><code>keymap</code></a> directory.</dd> <dt id="option_extraKeys"><code>extraKeys (object)</code></dt> <dd>Can be used to specify extra keybindings for the editor. When given, should be an object with property names like <code>Ctrl-A</code>, <code>Home</code>, and <code>Ctrl-Alt-Left</code>. See the <code>CodeMirror.keyNames</code> object for the names of all the keys. The values in this object can either be functions, which will be called with the CodeMirror instance when the key is pressed, or strings, which should name commands defined in <code>CodeMirror.commands</code> (not documented properly, but looking at the source and the definition of the built-in keymaps, they should be rather obvious).</dd> <dt id="option_lineWrapping"><code>lineWrapping (boolean)</code></dt> <dd>Whether CodeMirror should scroll or wrap for long lines. Defaults to <code>false</code> (scroll).</dd> <dt id="option_lineNumbers"><code>lineNumbers (boolean)</code></dt> <dd>Whether to show line numbers to the left of the editor.</dd> <dt id="option_firstLineNumber"><code>firstLineNumber (integer)</code></dt> <dd>At which number to start counting lines. Default is 1.</dd> <dt id="option_gutter"><code>gutter (boolean)</code></dt> <dd>Can be used to force a 'gutter' (empty space on the left of the editor) to be shown even when no line numbers are active. This is useful for setting <a href="#setMarker">markers</a>.</dd> <dt id="option_fixedGutter"><code>fixedGutter (boolean)</code></dt> <dd>When enabled (off by default), this will make the gutter stay visible when the document is scrolled horizontally.</dd> <dt id="option_readOnly"><code>readOnly (boolean)</code></dt> <dd>This disables editing of the editor content by the user.</dd> <dt id="option_onChange"><code>onChange (function)</code></dt> <dd>When given, this function will be called every time the content of the editor is changed. It will be given the editor instance as first argument, and an <code>{from, to, newText, next}</code> object containing information about the changes that occurred as second argument. <code>from</code> and <code>to</code> are the positions (in the pre-change coordinate system) where the change started and ended. <code>newText</code> is an array of strings representing the text that replaced the changed range (split by line). If multiple changes happened during a single operation, the object will have a <code>next</code> property pointing to another change object (which may point to another, etc).</dd> <dt id="option_onCursorActivity"><code>onCursorActivity (function)</code></dt> <dd>Will be called when the cursor or selection moves, or any change is made to the editor content.</dd> <dt id="option_onGutterClick"><code>onGutterClick (function)</code></dt> <dd>When given, will be called whenever the editor gutter (the line-number area) is clicked. Will be given the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, and the raw <code>mousedown</code> event object as third argument.</dd> <dt id="option_onFocus"><code>onFocus, onBlur (function)</code></dt> <dd>The given functions will be called whenever the editor is focused or unfocused.</dd> <dt id="option_onScroll"><code>onScroll (function)</code></dt> <dd>When given, will be called whenever the editor is scrolled.</dd> <dt id="option_onHighlightComplete"><code>onHighlightComplete (function)</code></dt> <dd>Whenever the editor's content has been fully highlighted, this function (if given) will be called. It'll be given a single argument, the editor instance.</dd> <dt id="option_onUpdate"><code>onUpdate (function)</code></dt> <dd>Will be called whenever CodeMirror updates its DOM display.</dd> <dt id="option_matchBrackets"><code>matchBrackets (boolean)</code></dt> <dd>Determines whether brackets are matched whenever the cursor is moved next to a bracket.</dd> <dt id="option_workTime"><code>workTime, workDelay (number)</code></dt> <dd>Highlighting is done by a pseudo background-thread that will work for <code>workTime</code> milliseconds, and then use timeout to sleep for <code>workDelay</code> milliseconds. The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive.</dd> <dt id="option_pollInterval"><code>pollInterval (number)</code></dt> <dd>Indicates how quickly CodeMirror should poll its input textarea for changes. Most input is captured by events, but some things, like IME input on some browsers, doesn't generate events that allow CodeMirror to properly detect it. Thus, it polls. Default is 100 milliseconds.</dd> <dt id="option_undoDepth"><code>undoDepth (integer)</code></dt> <dd>The maximum number of undo levels that the editor stores. Defaults to 40.</dd> <dt id="option_tabindex"><code>tabindex (integer)</code></dt> <dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab index</a> to assign to the editor. If not given, no tab index will be assigned.</dd> <dt id="option_document"><code>document (DOM document)</code></dt> <dd>Use this if you want to display the editor in another DOM. By default it will use the global <code>document</code> object.</dd> <dt id="option_onKeyEvent"><code>onKeyEvent (function)</code></dt> <dd>This provides a rather low-level hook into CodeMirror's key handling. If provided, this function will be called on every <code>keydown</code>, <code>keyup</code>, and <code>keypress</code> event that CodeMirror captures. It will be passed two arguments, the editor instance and the key event. This key event is pretty much the raw key event, except that a <code>stop()</code> method is always added to it. You could feed it to, for example, <code>jQuery.Event</code> to further normalize it.<br>This function can inspect the key event, and handle it if it wants to. It may return true to tell CodeMirror to ignore the event. Be wary that, on some browsers, stopping a <code>keydown</code> does not stop the <code>keypress</code> from firing, whereas on others it does. If you respond to an event, you should probably inspect its <code>type</code> property and only do something when it is <code>keydown</code> (or <code>keypress</code> for actions that need character data).</dd> </dl> <h2 id="styling">Customized Styling</h2> <p>Up to a certain extent, CodeMirror's look can be changed by modifying style sheet files. The style sheets supplied by modes simply provide the colors for that mode, and can be adapted in a very straightforward way. To style the editor itself, it is possible to alter or override the styles defined in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p> <p>Some care must be taken there, since a lot of the rules in this file are necessary to have CodeMirror function properly. Adjusting colors should be safe, of course, and with some care a lot of other things can be changed as well. The CSS classes defined in this file serve the following roles:</p> <dl> <dt id="class_CodeMirror"><code>CodeMirror</code></dt> <dd>The outer element of the editor. This should be used for borders and positioning. Can also be used to set styles that should hold for everything inside the editor (such as font and font size), or to set a background.</dd> <dt id="class_CodeMirror_scroll"><code>CodeMirror-scroll</code></dt> <dd>This determines whether the editor scrolls (<code>overflow: auto</code> + fixed height). By default, it does. Giving this <code>height: auto; overflow: visible;</code> will cause the editor to resize to fit its content.</dd> <dt id="class_CodeMirror_focused"><code>CodeMirror-focused</code></dt> <dd>Whenever the editor is focused, the top element gets this class. This is used to hide the cursor and give the selection a different color when the editor is not focused.</dd> <dt id="class_CodeMirror_gutter"><code>CodeMirror-gutter</code></dt> <dd>Use this for giving a background or a border to the editor gutter. Don't set any padding here, use <code>CodeMirror-gutter-text</code> for that. By default, the gutter is 'fluid', meaning it will adjust its width to the maximum line number or line marker width. You can also set a fixed width if you want.</dd> <dt id="class_CodeMirror_gutter_text"><code>CodeMirror-gutter-text</code></dt> <dd>Used to style the actual line numbers. For the numbers to line up, you must make sure that the font in the gutter is the same as the one in the rest of the editor, so you should probably only set font style and size in the <code>CodeMirror</code> class.</dd> <dt id="class_CodeMirror_lines"><code>CodeMirror-lines</code></dt> <dd>The visible lines. If this has vertical padding, <code>CodeMirror-gutter</code> should have the same padding.</dd> <dt id="class_CodeMirror_cursor"><code>CodeMirror-cursor</code></dt> <dd>The cursor is a block element that is absolutely positioned. You can make it look whichever way you want.</dd> <dt id="class_CodeMirror_selected"><code>CodeMirror-selected</code></dt> <dd>The selection is represented by <code>span</code> elements with this class.</dd> <dt id="class_CodeMirror_matchingbracket"><code>CodeMirror-matchingbracket</code>, <code>CodeMirror-nonmatchingbracket</code></dt> <dd>These are used to style matched (or unmatched) brackets.</dd> </dl> <p>The actual lines, as well as the cursor, are represented by <code>pre</code> elements. By default no text styling (such as bold) that might change line height is applied. If you do want such effects, you'll have to give <code>CodeMirror pre</code> a fixed height. Also, you must still take care that character width is constant.</p> <p>If your page's style sheets do funky things to all <code>div</code> or <code>pre</code> elements (you probably shouldn't do that), you'll have to define rules to cancel these effects out again for elements under the <code>CodeMirror</code> class.</p> <p>Themes are also simply CSS files, which define colors for various syntactic elements. See the files in the <a href="../theme/"><code>theme</code></a> directory.</p> <h2 id="api">Programming API</h2> <p>A lot of CodeMirror features are only available through its API. This has the disadvantage that you need to do work to enable them, and the advantage that CodeMirror will fit seamlessly into your application.</p> <p>Whenever points in the document are represented, the API uses objects with <code>line</code> and <code>ch</code> properties. Both are zero-based. CodeMirror makes sure to 'clip' any positions passed by client code so that they fit inside the document, so you shouldn't worry too much about sanitizing your coordinates. If you give <code>ch</code> a value of <code>null</code>, or don't specify it, it will be replaced with the length of the specified line.</p> <dl> <dt id="getValue"><code>getValue() → string</code></dt> <dd>Get the current editor content.</dd> <dt id="setValue"><code>setValue(string)</code></dt> <dd>Set the editor content.</dd> <dt id="getSelection"><code>getSelection() → string</code></dt> <dd>Get the currently selected code.</dd> <dt id="replaceSelection"><code>replaceSelection(string)</code></dt> <dd>Replace the selection with the given string.</dd> <dt id="focus"><code>focus()</code></dt> <dd>Give the editor focus.</dd> <dt id="setOption"><code>setOption(option, value)</code></dt> <dd>Change the configuration of the editor. <code>option</code> should the name of an <a href="#config">option</a>, and <code>value</code> should be a valid value for that option.</dd> <dt id="getOption"><code>getOption(option) → value</code></dt> <dd>Retrieves the current value of the given option for this editor instance.</dd> <dt id="cursorCoords"><code>cursorCoords(start) → object</code></dt> <dd>Returns an <code>{x, y, yBot}</code> object containing the coordinates of the cursor relative to the top-left corner of the page. <code>yBot</code> is the coordinate of the bottom of the cursor. <code>start</code> is a boolean indicating whether you want the start or the end of the selection.</dd> <dt id="charCoords"><code>charCoords(pos) → object</code></dt> <dd>Like <code>cursorCoords</code>, but returns the position of an arbitrary characters. <code>pos</code> should be a <code>{line, ch}</code> object.</dd> <dt id="coordsChar"><code>coordsChar(object) → pos</code></dt> <dd>Given an <code>{x, y}</code> object (in page coordinates), returns the <code>{line, ch}</code> position that corresponds to it.</dd> <dt id="undo"><code>undo()</code></dt> <dd>Undo one edit (if any undo events are stored).</dd> <dt id="redo"><code>redo()</code></dt> <dd>Redo one undone edit.</dd> <dt id="historySize"><code>historySize() → object</code></dt> <dd>Returns an object with <code>{undo, redo}</code> properties, both of which hold integers, indicating the amount of stored undo and redo operations.</dd> <dt id="clearHistory"><code>clearHistory()</code></dt> <dd>Clears the editor's undo history.</dd> <dt id="indentLine"><code>indentLine(line, dir)</code></dt> <dd>Reset the given line's indentation to the indentation prescribed by the mode. If the second argument is given, indentation will be increased (if <code>dir</code> is true) or decreased (if false) by an <a href="#option_indentUnit">indent unit</a> instead.</dd> <dt id="getTokenAt"><code>getTokenAt(pos) → object</code></dt> <dd>Retrieves information about the token the current mode found at the given position (a <code>{line, ch}</code> object). The returned object has the following properties: <dl> <dt><code>start</code></dt><dd>The character (on the given line) at which the token starts.</dd> <dt><code>end</code></dt><dd>The character at which the token ends.</dd> <dt><code>string</code></dt><dd>The token's string.</dd> <dt><code>className</code></dt><dd>The class the mode assigned to the token. (Can be null when no class was assigned.)</dd> <dt><code>state</code></dt><dd>The mode's state at the end of this token.</dd> </dl></dd> <dt id="markText"><code>markText(from, to, className) → object</code></dt> <dd>Can be used to mark a range of text with a specific CSS class name. <code>from</code> and <code>to</code> should be <code>{line, ch}</code> objects. The method will return an object with two methods, <code>clear()</code>, which removes the mark, and <code>find()</code>, which returns a <code>{from, to}</code> (both document positions), indicating the current position of the marked range.</dd> <dt id="setBookmark"><code>setBookmark(pos) → object</code></dt> <dd>Inserts a bookmark, a handle that follows the text around it as it is being edited, at the given position. A bookmark has two methods <code>find()</code> and <code>clear()</code>. The first returns the current position of the bookmark, if it is still in the document, and the second explicitly removes the bookmark.</dd> <dt id="setMarker"><code>setMarker(line, text, className) → lineHandle</code></dt> <dd>Add a gutter marker for the given line. Gutter markers are shown in the line-number area (instead of the number for this line). Both <code>text</code> and <code>className</code> are optional. Setting <code>text</code> to a Unicode character like ● tends to give a nice effect. To put a picture in the gutter, set <code>text</code> to a space and <code>className</code> to something that sets a background image. If you specify <code>text</code>, the given text (which may contain HTML) will, by default, replace the line number for that line. If this is not what you want, you can include the string <code>%N%</code> in the text, which will be replaced by the line number.</dd> <dt id="clearMarker"><code>clearMarker(line)</code></dt> <dd>Clears a marker created with <code>setMarker</code>. <code>line</code> can be either a number or a handle returned by <code>setMarker</code> (since a number may now refer to a different line if something was added or deleted).</dd> <dt id="setLineClass"><code>setLineClass(line, className) → lineHandle</code></dt> <dd>Set a CSS class name for the given line. <code>line</code> can be a number or a line handle (as returned by <code>setMarker</code> or this function). Pass <code>null</code> to clear the class for a line.</dd> <dt id="hideLine"><code>hideLine(line) → lineHandle</code></dt> <dd>Hide the given line (either by number or by handle). Hidden lines don't show up in the editor, and their numbers are skipped when <a href="#option_lineNumbers">line numbers</a> are enabled. Deleting a region around them does delete them, and coping a region around will include them in the copied text.</dd> <dt id="showLine"><code>showLine(line) → lineHandle</code></dt> <dd>The inverse of <code>hideLine</code>—re-shows a previously hidden line, by number or by handle.</dd> <dt id="onDeleteLine"><code>onDeleteLine(line, func)</code></dt> <dd>Register a function that should be called when the line is deleted from the document.</dd> <dt id="lineInfo"><code>lineInfo(line) → object</code></dt> <dd>Returns the line number, text content, and marker status of the given line, which can be either a number or a handle returned by <code>setMarker</code>. The returned object has the structure <code>{line, handle, text, markerText, markerClass}</code>.</dd> <dt id="getLineHandle"><code>getLineHandle(num) → lineHandle</code></dt> <dd>Fetches the line handle for the given line number.</dd> <dt id="addWidget"><code>addWidget(pos, node, scrollIntoView)</code></dt> <dd>Puts <code>node</code>, which should be an absolutely positioned DOM node, into the editor, positioned right below the given <code>{line, ch}</code> position. When <code>scrollIntoView</code> is true, the editor will ensure that the entire node is visible (if possible). To remove the widget again, simply use DOM methods (move it somewhere else, or call <code>removeChild</code> on its parent).</dd> <dt id="matchBrackets"><code>matchBrackets()</code></dt> <dd>Force matching-bracket-highlighting to happen.</dd> <dt id="lineCount"><code>lineCount() → number</code></dt> <dd>Get the number of lines in the editor.</dd> <dt id="getCursor"><code>getCursor(start) → object</code></dt> <dd><code>start</code> is a boolean indicating whether the start or the end of the selection must be retrieved. If it is not given, the current cursor pos, i.e. the side of the selection that would move if you pressed an arrow key, is chosen. A <code>{line, ch}</code> object will be returned.</dd> <dt id="somethingSelected"><code>somethingSelected() → boolean</code></dt> <dd>Return true if any text is selected.</dd> <dt id="setCursor"><code>setCursor(pos)</code></dt> <dd>Set the cursor position. You can either pass a single <code>{line, ch}</code> object, or the line and the character as two separate parameters.</dd> <dt id="setSelection"><code>setSelection(start, end)</code></dt> <dd>Set the selection range. <code>start</code> and <code>end</code> should be <code>{line, ch}</code> objects.</dd> <dt id="getLine"><code>getLine(n) → string</code></dt> <dd>Get the content of line <code>n</code>.</dd> <dt id="setLine"><code>setLine(n, text)</code></dt> <dd>Set the content of line <code>n</code>.</dd> <dt id="removeLine"><code>removeLine(n)</code></dt> <dd>Remove the given line from the document.</dd> <dt id="getRange"><code>getRange(from, to) → string</code></td> <dd>Get the text between the given points in the editor, which should be <code>{line, ch}</code> objects.</dd> <dt id="replaceRange"><code>replaceRange(string, from, to)</code></dt> <dd>Replace the part of the document between <code>from</code> and <code>to</code> with the given string. <code>from</code> and <code>to</code> must be <code>{line, ch}</code> objects. <code>to</code> can be left off to simply insert the string at position <code>from</code>.</dd> <dt id="posFromIndex"><code>posFromIndex(index) → object</code></dt> <dd>Calculates and returns a <code>{line, ch}</code> object for a zero-based <code>index</code> who's value is relative to the start of the editor's text. If the <code>index</code> is out of range of the text then the returned object is clipped to start or end of the text respectively.</dd> <dt id="indexFromPos"><code>indexFromPos(object) → number</code></dt> <dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd> </dl> <p>The following are more low-level methods:</p> <dl> <dt id="operation"><code>operation(func) → result</code></dt> <dd>CodeMirror internally buffers changes and only updates its DOM structure after it has finished performing some operation. If you need to perform a lot of operations on a CodeMirror instance, you can call this method with a function argument. It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function.</dd> <dt id="refresh"><code>refresh()</code></dt> <dd>If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended.</dd> <dt id="getInputField"><code>getInputField() → textarea</code></dt> <dd>Returns the hiden textarea used to read input.</dd> <dt id="getWrapperElement"><code>getWrapperElement() → node</code></dt> <dd>Returns the DOM node that represents the editor. Remove this from your tree to delete an editor instance.</dd> <dt id="getScrollerElement"><code>getScrollerElement() → node</code></dt> <dd>Returns the DOM node that is responsible for the sizing and the scrolling of the editor. You can change the <code>height</code> and <code>width</code> styles of this element to resize an editor. (You might have to call the <a href="#refresh"><code>refresh</code></a> method afterwards.)</dd> <dt id="getGutterElement"><code>getGutterElement() → node</code></dt> <dd>Fetches the DOM node that represents the editor gutter.</dd> <dt id="getStateAfter"><code>getStateAfter(line) → state</code></dt> <dd>Returns the mode's parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. This can be useful for storing parsing errors in the state, or getting other kinds of contextual information for a line.</dd> </dl> <p id="fromTextArea">Finally, the <code>CodeMirror</code> object itself has a method <code>fromTextArea</code>. This takes a textarea DOM node as first argument and an optional configuration object as second. It will replace the textarea with a CodeMirror instance, and wire up the form of that textarea (if any) to make sure the editor contents are put into the textarea when the form is submitted. A CodeMirror instance created this way has two additional methods:</p> <dl> <dt id="save"><code>save()</code></dt> <dd>Copy the content of the editor into the textarea.</dd> <dt id="toTextArea"><code>toTextArea()</code></dt> <dd>Remove the editor, and restore the original textarea (with the editor's current content).</dd> <dt id="getTextArea"><code>getTextArea() → textarea</code></dt> <dd>Returns the textarea that the instance was based on.</dd> </dl> <p id="defineExtension">If you want to define extra methods in terms of the CodeMirror API, it is possible to use <code>CodeMirror.defineExtension(name, value)</code>. This will cause the given value (usually a method) to be added to all CodeMirror instances created from then on.</p> <h2 id="addons">Add-ons</h2> <p>The <code>lib/util</code> directory in the distribution contains a number of reusable components that implement extra editor functionality. In brief, they are:</p> <dl> <dt id="util_dialog"><a href="../lib/util/dialog.js"><code>dialog.js</code></a></dt> <dd>Provides a very simple way to query users for text input. Adds an <code>openDialog</code> method to CodeMirror instances, which can be called with an HTML fragment that provides the prompt (should include an <code>input</code> tag), and a callback function that is called when text has been entered. Depends on <code>lib/util/dialog.css</code>.</dd> <dt id="util_searchcursor"><a href="../lib/util/searchcursor.js"><code>searchcursor.js</code></a></dt> <dd>Adds the <code>getSearchCursor(query, start, caseFold) → cursor</code> method to CodeMirror instances, which can be used to implement search/replace functionality. <code>query</code> can be a regular expression or a string (only strings will match across lines—if they contain newlines). <code>start</code> provides the starting position of the search. It can be a <code>{line, ch}</code> object, or can be left off to default to the start of the document. <code>caseFold</code> is only relevant when matching a string. It will cause the search to be case-insensitive. A search cursor has the following methods: <dl> <dt><code>findNext(), findPrevious() → boolean</code></dt> <dd>Search forward or backward from the current position. The return value indicates whether a match was found. If matching a regular expression, the return value will be the array returned by the <code>match</code> method, in case you want to extract matched groups.</dd> <dt><code>from(), to() → object</code></dt> <dd>These are only valid when the last call to <code>findNext</code> or <code>findPrevious</code> did not return false. They will return <code>{line, ch}</code> objects pointing at the start and end of the match.</dd> <dt><code>replace(text)</code></dt> <dd>Replaces the currently found match with the given text and adjusts the cursor position to reflect the replacement.</dd> </dl></dd> <dt id="util_search"><a href="../lib/util/search.js"><code>search.js</code></a></dt> <dd>Implements the search commands. CodeMirror has keys bound to these by default, but will not do anything with them unless an implementation is provided. Depends on <code>searchcursor.js</code>, and will make use of <a href="#util_dialog"><code>openDialog</code></a> when available to make prompting for search queries less ugly.</dd> <dt id="util_foldcode"><a href="../lib/util/foldcode.js"><code>foldcode.js</code></a></dt> <dd>Helps with code folding. See <a href="../demo/folding.html">the demo</a> for an example. Call <code>CodeMirror.newFoldFunction</code> with a range-finder helper function to create a function that will, when applied to a CodeMirror instance and a line number, attempt to fold or unfold the block starting at the given line. A range-finder is a language-specific functoin that also takes an instance and a line number, and returns an end line for the block, or null if no block is started on that line. This file provides <code>CodeMirror.braceRangeFinder</code>, which finds blocks in brace languages (JavaScript, C, Java, etc).</dd> <dt id="util_runmode"><a href="../lib/util/runmode.js"><code>runmode.js</code></a></dt> <dd>Can be used to run a CodeMirror mode over text without actually opening an editor instance. See <a href="../demo/runmode.html">the demo</a> for an example.</dd> <dt id="util_simple-hint"><a href="../lib/util/simple-hint.js"><code>simple-hint.js</code></a></dt> <dd>Provides a framework for showing autocompletion hints. Defines <code>CodeMirror.simpleHint</code>, which takes a CodeMirror instance and a hinting function, and pops up a widget that allows the user to select a completion. Hinting functions are function that take an editor instance, and return a <code>{list, from, to}</code> object, where <code>list</code> is an array of strings (the completions), and <code>from</code> and <code>to</code> give the start and end of the token that is being completed. Depends on <code>lib/util/simple-hint.css</code>.</dd> <dt id="util_javascript-hint"><a href="../lib/util/javascript-hint.js"><code>javascript-hint.js</code></a></dt> <dd>Defines <code>CodeMirror.javaScriptHint</code>, which is a simple hinting function for the JavaScript mode.</dd> </dl> <h2 id="modeapi">Writing CodeMirror Modes</h2> <p>Modes typically consist of a single JavaScript file. This file defines, in the simplest case, a lexer (tokenizer) for your language—a function that takes a character stream as input, advances it past a token, and returns a style for that token. More advanced modes can also handle indentation for the language.</p> <p id="defineMode">The mode script should call <code>CodeMirror.defineMode</code> to register itself with CodeMirror. This function takes two arguments. The first should be the name of the mode, for which you should use a lowercase string, preferably one that is also the name of the files that define the mode (i.e. <code>"xml"</code> is defined <code>xml.js</code>). The second argument should be a function that, given a CodeMirror configuration object (the thing passed to the <code>CodeMirror</code> function) and an optional mode configuration object (as in the <a href="#option_mode"><code>mode</code></a> option), returns a mode object.</p> <p>Typically, you should use this second argument to <code>defineMode</code> as your module scope function (modes should not leak anything into the global scope!), i.e. write your whole mode inside this function.</p> <p>The main responsibility of a mode script is <em>parsing</em> the content of the editor. Depending on the language and the amount of functionality desired, this can be done in really easy or extremely complicated ways. Some parsers can be stateless, meaning that they look at one element (<em>token</em>) of the code at a time, with no memory of what came before. Most, however, will need to remember something. This is done by using a <em>state object</em>, which is an object that is always passed when reading a token, and which can be mutated by the tokenizer.</p> <p id="startState">Modes that use a state must define a <code>startState</code> method on their mode object. This is a function of no arguments that produces a state object to be used at the start of a document.</p> <p id="token">The most important part of a mode object is its <code>token(stream, state)</code> method. All modes must define this method. It should read one token from the stream it is given as an argument, optionally update its state, and return a style string, or <code>null</code> for tokens that do not have to be styled. For your styles, you can either use the 'standard' ones defined in the themes (without the <code>cm-</code> prefix), or define your own (as the <a href="../mode/diff/index.html">diff</a> mode does) and have people include a custom CSS file for your mode.<p> <p id="StringStream">The stream object encapsulates a line of code (tokens may never span lines) and our current position in that line. It has the following API:</p> <dl> <dt><code>eol() → boolean</code></dt> <dd>Returns true only if the stream is at the end of the line.</dd> <dt><code>sol() → boolean</code></dt> <dd>Returns true only if the stream is at the start of the line.</dd> <dt><code>peek() → character</code></dt> <dd>Returns the next character in the stream without advancing it. Will return <code>undefined</code> at the end of the line.</dd> <dt><code>next() → character</code></dt> <dd>Returns the next character in the stream and advances it. Also returns <code>undefined</code> when no more characters are available.</dd> <dt><code>eat(match) → character</code></dt> <dd><code>match</code> can be a character, a regular expression, or a function that takes a character and returns a boolean. If the next character in the stream 'matches' the given argument, it is consumed and returned. Otherwise, <code>undefined</code> is returned.</dd> <dt><code>eatWhile(match) → boolean</code></dt> <dd>Repeatedly calls <code>eat</code> with the given argument, until it fails. Returns true if any characters were eaten.</dd> <dt><code>eatSpace() → boolean</code></dt> <dd>Shortcut for <code>eatWhile</code> when matching white-space.</dd> <dt><code>skipToEnd()</code></dt> <dd>Moves the position to the end of the line.</dd> <dt><code>skipTo(ch) → boolean</code></dt> <dd>Skips to the next occurrence of the given character, if found on the current line (doesn't advance the stream if the character does not occur on the line). Returns true if the character was found.</dd> <dt><code>match(pattern, consume, caseFold) → boolean</code></dt> <dd>Act like a multi-character <code>eat</code>—if <code>consume</code> is true or not given—or a look-ahead that doesn't update the stream position—if it is false. <code>pattern</code> can be either a string or a regular expression starting with <code>^</code>. When it is a string, <code>caseFold</code> can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned by <code>match</code>, in case you need to extract matched groups.</dd> <dt><code>backUp(n)</code></dt> <dd>Backs up the stream <code>n</code> characters. Backing it up further than the start of the current token will cause things to break, so be careful.</dd> <dt><code>column() → integer</code></dt> <dd>Returns the column (taking into account tabs) at which the current token starts. Can be used to find out whether a token starts a new line.</dd> <dt><code>indentation() → integer</code></dt> <dd>Tells you how far the current line has been indented, in spaces. Corrects for tab characters.</dd> <dt><code>current() → string</code></dt> <dd>Get the string between the start of the current token and the current stream position.</dd> </dl> <p id="blankLine">By default, blank lines are simply skipped when tokenizing a document. For languages that have significant blank lines, you can define a <code>blankLine(state)</code> method on your mode that will get called whenever a blank line is passed over, so that it can update the parser state.</p> <p id="copyState">Because state object are mutated, and CodeMirror needs to keep valid versions of a state around so that it can restart a parse at any line, copies must be made of state objects. The default algorithm used is that a new state object is created, which gets all the properties of the old object. Any properties which hold arrays get a copy of these arrays (since arrays tend to be used as mutable stacks). When this is not correct, for example because a mode mutates non-array properties of its state object, a mode object should define a <code>copyState</code> method, which is given a state and should return a safe copy of that state.</p> <p id="compareStates">By default, CodeMirror will stop re-parsing a document as soon as it encounters a few lines that were highlighted the same in the old parse as in the new one. It is possible to provide an explicit way to test whether a state is equivalent to another one, which CodeMirror will use (instead of the unchanged-lines heuristic) to decide when to stop highlighting. You do this by providing a <code>compareStates</code> method on your mode object, which takes two state arguments and returns a boolean indicating whether they are equivalent. See the XML mode, which uses this to provide reliable highlighting of bad closing tags, as an example.</p> <p id="indent">If you want your mode to provide smart indentation (though the <a href="#indentLine"><code>indentLine</code></a> method and the <code>indentAuto</code> and <code>newlineAndIndent</code> commands, which keys can be <a href="#option_extraKeys">bound</a> to), you must define an <code>indent(state, textAfter)</code> method on your mode object.</p> <p>The indentation method should inspect the given state object, and optionally the <code>textAfter</code> string, which contains the text on the line that is being indented, and return an integer, the amount of spaces to indent. It should usually take the <a href="#option_indentUnit"><code>indentUnit</code></a> option into account.</p> <p id="electricChars">Finally, a mode may define an <code>electricChars</code> property, which should hold a string containing all the characters that should trigger the behaviour described for the <a href="#option_electricChars"><code>electricChars</code></a> option.</p> <p>So, to summarize, a mode <em>must</em> provide a <code>token</code> method, and it <em>may</em> provide <code>startState</code>, <code>copyState</code>, <code>compareStates</code>, and <code>indent</code> methods. For an example of a trivial mode, see the <a href="../mode/diff/diff.js">diff mode</a>, for a more involved example, see the <a href="../mode/clike/clike.js">C-like mode</a>.</p> <p>Sometimes, it is useful for modes to <em>nest</em>—to have one mode delegate work to another mode. An example of this kind of mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML mode</a>. To implement such nesting, it is usually necessary to create mode objects and copy states yourself. To create a mode object, there are <code>CodeMirror.getMode(options, parserConfig)</code>, where the first argument is a configuration object as passed to the mode constructor function, and the second argument is a mode specification as in the <a href="#option_mode"><code>mode</code></a> option. To copy a state object, call <code>CodeMirror.copyState(mode, state)</code>, where <code>mode</code> is the mode that created the given state.</p> <p>To make indentation work properly in a nested parser, it is advisable to give the <code>startState</code> method of modes that are intended to be nested an optional argument that provides the base indentation for the block of code. The JavaScript and CSS parser do this, for example, to allow JavaScript and CSS code inside the mixed-mode HTML mode to be properly indented.</p> <p>Finally, it is possible to associate your mode, or a certain configuration of your mode, with a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For example, the JavaScript mode associates itself with <code>text/javascript</code>, and its JSON variant with <code>application/json</code>. To do this, call <code>CodeMirror.defineMIME(mime, modeSpec)</code>, where <code>modeSpec</code> can be a string or object specifying a mode, as in the <a href="#option_mode"><code>mode</code></a> option.</p> </div><div class="rightsmall blk"> <h2>Contents</h2> <ul> <li><a href="#overview">Overview</a></li> <li><a href="#usage">Basic Usage</a></li> <li><a href="#config">Configuration</a></li> <li><a href="#styling">Customized Styling</a></li> <li><a href="#api">Programming API</a></li> <li><a href="#addons">Add-ons</a></li> <li><a href="#modeapi">Writing CodeMirror Modes</a></li> </ul> </div></div> <div style="height: 2em"> </div> </body> </html> |