/*
       * Five types to be split:
       * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
       * <ins>A</ins>X<ins>C</ins><del>D</del>
       * <ins>A</ins><del>B</del>X<ins>C</ins>
       * <ins>A</del>X<ins>C</ins><del>D</del>
       * <ins>A</ins><del>B</del>X<del>C</del>
       */

/* MAX_HEIGHT */

/* binding */

/* default */

/* default.line-height */

/* default.sum */

/* environment.IS_FIREFOX */

/* eslint-disable no-unused-expressions */

/* harmony default export */

/* useZoom */

/*#__PURE__*/

/**
   * Compute and return the score for a match with e errors and x location.
   * Accesses loc and pattern through being a closure.
   * @param {number} e Number of errors in match.
   * @param {number} x Location of match.
   * @return {number} Overall score for match (0.0 = good, 1.0 = bad).
   * @private
   */

/**
   * Does a substring of shorttext exist within longtext such that the substring
   * is at least half the length of longtext?
   * Closure, but does not reference any external variables.
   * @param {string} longtext Longer string.
   * @param {string} shorttext Shorter string.
   * @param {number} i Start index of quarter length substring within longtext.
   * @return {Array.<string>} Five element Array, containing the prefix of
   *     longtext, the suffix of longtext, the prefix of shorttext, the suffix
   *     of shorttext and the common middle.  Or null if there was no match.
   * @private
   */

/**
   * Given two strings, compute a score representing whether the internal
   * boundary falls on logical boundaries.
   * Scores range from 6 (best) to 0 (worst).
   * Closure, but does not reference any external variables.
   * @param {string} one First string.
   * @param {string} two Second string.
   * @return {number} The score.
   * @private
   */

/**
   * Split a text into an array of strings.  Reduce the texts to a string of
   * hashes where each Unicode character represents one line.
   * Modifies linearray and linehash through being a closure.
   * @param {string} text String to encode.
   * @return {string} Encoded string.
   * @private
   */

/**
 * @fileoverview Computes the difference between two texts to create a patch.
 * Applies the patch onto another text, allowing for errors.
 * @author fraser@google.com (Neil Fraser)
 */

/**
 * Add some padding on text start and end so that edges can match something.
 * Intended to be called only from within patch_apply.
 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
 * @return {string} The padding string added to each side.
 */

/**
 * Class containing the diff, match and patch methods.
 * @constructor
 */

/**
 * Class representing one diff tuple.
 * ~Attempts to look like a two-element array (which is what this used to be).~
 * Constructor returns an actual two-element array, to allow destructing @JackuB
 * See https://github.com/JackuB/diff-match-patch/issues/14 for details
 * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.
 * @param {string} text Text to be deleted, inserted, or retained.
 * @constructor
 */

/**
 * Class representing one patch operation.
 * @constructor
 */

/**
 * Compute a list of patches to turn text1 into text2.
 * Use diffs if provided, otherwise compute it ourselves.
 * There are four ways to call this function, depending on what data is
 * available to the caller:
 * Method 1:
 * a = text1, b = text2
 * Method 2:
 * a = diffs
 * Method 3 (optimal):
 * a = text1, b = diffs
 * Method 4 (deprecated, use method 3):
 * a = text1, b = text2, c = diffs
 *
 * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
 * Array of diff tuples for text1 to text2 (method 2).
 * @param {string|!Array.<!diff_match_patch.Diff>=} opt_b text2 (methods 1,4) or
 * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
 * @param {string|!Array.<!diff_match_patch.Diff>=} opt_c Array of diff tuples
 * for text1 to text2 (method 4) or undefined (methods 1,2,3).
 * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
 */

/**
 * Compute and return the destination text (all equalities and insertions).
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @return {string} Destination text.
 */

/**
 * Compute and return the source text (all equalities and deletions).
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @return {string} Source text.
 */

/**
 * Compute the Levenshtein distance; the number of inserted, deleted or
 * substituted characters.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @return {number} Number of changes.
 */

/**
 * Convert a diff array into a pretty HTML report.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @return {string} HTML representation.
 */

/**
 * Crush the diff into an encoded string which describes the operations
 * required to transform text1 into text2.
 * E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.
 * Operations are tab-separated.  Inserted text is escaped using %xx notation.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @return {string} Delta text.
 */

/**
 * Determine if the suffix of one string is the prefix of another.
 * @param {string} text1 First string.
 * @param {string} text2 Second string.
 * @return {number} The number of characters common to the end of the first
 *     string and the start of the second string.
 * @private
 */

/**
 * Determine the common prefix of two strings.
 * @param {string} text1 First string.
 * @param {string} text2 Second string.
 * @return {number} The number of characters common to the start of each
 *     string.
 */

/**
 * Determine the common suffix of two strings.
 * @param {string} text1 First string.
 * @param {string} text2 Second string.
 * @return {number} The number of characters common to the end of each string.
 */

/**
 * Diff Match and Patch
 * Copyright 2018 The diff-match-patch Authors.
 * https://github.com/google/diff-match-patch
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Do a quick line-level diff on both strings, then rediff the parts for
 * greater accuracy.
 * This speedup can produce non-minimal diffs.
 * @param {string} text1 Old string to be diffed.
 * @param {string} text2 New string to be diffed.
 * @param {number} deadline Time when the diff should be complete by.
 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
 * @private
 */

/**
 * Do the two texts share a substring which is at least half the length of the
 * longer text?
 * This speedup can produce non-minimal diffs.
 * @param {string} text1 First string.
 * @param {string} text2 Second string.
 * @return {Array.<string>} Five element Array, containing the prefix of
 *     text1, the suffix of text1, the prefix of text2, the suffix of
 *     text2 and the common middle.  Or null if there was no match.
 * @private
 */

/**
 * Emulate GNU diff's format.
 * Header: @@ -382,8 +481,9 @@
 * Indices are printed as 1-based, not 0-based.
 * @return {string} The GNU diff string.
 */

/**
 * Find the 'middle snake' of a diff, split the problem in two
 * and return the recursively constructed diff.
 * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
 * @param {string} text1 Old string to be diffed.
 * @param {string} text2 New string to be diffed.
 * @param {number} deadline Time at which to bail if not yet complete.
 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
 * @private
 */

/**
 * Find the differences between two texts.  Assumes that the texts do not
 * have any common prefix or suffix.
 * @param {string} text1 Old string to be diffed.
 * @param {string} text2 New string to be diffed.
 * @param {boolean} checklines Speedup flag.  If false, then don't run a
 *     line-level diff first to identify the changed areas.
 *     If true, then run a faster, slightly less optimal diff.
 * @param {number} deadline Time when the diff should be complete by.
 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
 * @private
 */

/**
 * Find the differences between two texts.  Simplifies the problem by stripping
 * any common prefix or suffix off the texts before diffing.
 * @param {string} text1 Old string to be diffed.
 * @param {string} text2 New string to be diffed.
 * @param {boolean=} opt_checklines Optional speedup flag. If present and false,
 *     then don't run a line-level diff first to identify the changed areas.
 *     Defaults to true, which does a faster, slightly less optimal diff.
 * @param {number=} opt_deadline Optional time when the diff should be complete
 *     by.  Used internally for recursive calls.  Users should set DiffTimeout
 *     instead.
 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
 */

/**
 * Given an array of patches, return another array that is identical.
 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
 * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
 */

/**
 * Given the location of the 'middle snake', split the diff in two parts
 * and recurse.
 * @param {string} text1 Old string to be diffed.
 * @param {string} text2 New string to be diffed.
 * @param {number} x Index of split point in text1.
 * @param {number} y Index of split point in text2.
 * @param {number} deadline Time at which to bail if not yet complete.
 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
 * @private
 */

/**
 * Given the original text1, and an encoded string which describes the
 * operations required to transform text1 into text2, compute the full diff.
 * @param {string} text1 Source string for the diff.
 * @param {string} delta Delta text.
 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
 * @throws {!Error} If invalid input.
 */

/**
 * Increase the context until it is unique,
 * but don't let the pattern expand beyond Match_MaxBits.
 * @param {!diff_match_patch.patch_obj} patch The patch to grow.
 * @param {string} text Source text.
 * @private
 */

/**
 * Initialise the alphabet for the Bitap algorithm.
 * @param {string} pattern The text to encode.
 * @return {!Object} Hash of character locations.
 * @private
 */

/**
 * Locate the best instance of 'pattern' in 'text' near 'loc' using the
 * Bitap algorithm.
 * @param {string} text The text to search.
 * @param {string} pattern The pattern to search for.
 * @param {number} loc The location to search around.
 * @return {number} Best match index or -1.
 * @private
 */

/**
 * Locate the best instance of 'pattern' in 'text' near 'loc'.
 * @param {string} text The text to search.
 * @param {string} pattern The pattern to search for.
 * @param {number} loc The location to search around.
 * @return {number} Best match index or -1.
 */

/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 */

/**
 * Look through the patches and break up any which are longer than the maximum
 * limit of the match algorithm.
 * Intended to be called only from within patch_apply.
 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
 */

/**
 * Merge a set of patches onto the text.  Return a patched text, as well
 * as a list of true/false values indicating which patches were applied.
 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
 * @param {string} text Old text.
 * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
 *      new text and an array of boolean values.
 */

/**
 * Parse a textual representation of patches and return a list of Patch objects.
 * @param {string} textline Text representation of patches.
 * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
 * @throws {!Error} If invalid input.
 */

/**
 * Reduce the number of edits by eliminating operationally trivial equalities.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 */

/**
 * Reduce the number of edits by eliminating semantically trivial equalities.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 */

/**
 * Rehydrate the text in a diff from a string of line hashes to real lines of
 * text.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @param {!Array.<string>} lineArray Array of unique strings.
 * @private
 */

/**
 * Reorder and merge like edit sections.  Merge equalities.
 * Any edit section can move as long as it doesn't cross an equality.
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 */

/**
 * Split two texts into an array of strings.  Reduce the texts to a string of
 * hashes where each Unicode character represents one line.
 * @param {string} text1 First string.
 * @param {string} text2 Second string.
 * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
 *     An object containing the encoded text1, the encoded text2 and
 *     the array of unique strings.
 *     The zeroth element of the array of unique strings is intentionally blank.
 * @private
 */

/**
 * Take a list of patches and return a textual representation.
 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
 * @return {string} Text representation of patches.
 */

/**
 * The data structure representing a diff is an array of tuples:
 * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
 * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
 */

/**
 * loc is a location in text1, compute and return the equivalent location in
 * text2.
 * e.g. 'The cat' vs 'The big cat', 1->1, 5->8
 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
 * @param {number} loc Location within text1.
 * @return {number} Location within text2.
 */

/** @type {!Array.<!diff_match_patch.Diff>} */

/** @type {?number} */

/** @type {number} */

/** @type {string} */

/***/

/*, mode, …*/

/*, values...*/

//

//     Pos(0, 1, ...)

//     before   after

//   -> <del>abc</del>xxx<ins>def</ins>

//   -> <ins>def</ins>xxx<del>abc</del>

//  DIFF FUNCTIONS

//  MATCH FUNCTIONS

//  PATCH FUNCTIONS

// "add"/null, "subtract", or "prev". When aggressive is false

// "group" (to the start of next group of word or

// "gutter", "class", "widget"

// "line", "div" (display.lineDiv), "local"./null (editor), "window",

// "page" or "line". The resulting position will have a hitSide=true

// #3261: make sure, that we're not starting a second selection

// % (ET):  European Number Terminator

// 'Project' the visible viewport to cover the area that is being

// '\x00' is a valid character, but various debuggers don't like it.

// 'other' property containing the position of the secondary cursor

// 'simulates' scrolling that position into view in a cheap way, so

// 'this' becomes 'window' in a closure.

// 'whitespace'.  Since this function's purpose is largely cosmetic,

// 'wrap f in an operation, performed on its `this` parameter'.

// (Adjust for extended bound, if necessary.)

// (and non-touching) ranges, sorted, and an integer that indicates

// (backwards compatibility) while at the same time support features

// (ctrl-click), rectangle drag (alt-drag), or xwin

// (left-to-right), or an array of sections ({from, to, level}

// (markTextShared will call out to this again, once per

// (not linked ones).

// (returning false) when there is nothing to be done and forced is

// (typically set to true for forced single-line indents), empty

// (when the bar is hidden). If it is still visible, we keep

// + (ES):  European Number Separator

// , (CS):  Common Number Separator

// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the

// -- for invalidation -- followed by pairs of end positions and

// 1 (EN):  European Number

// 1.0 = very loose).  Note that Match_Threshold controls how closely the

// 1.0 to the score (0.0 is a perfect match).

// 20, but the first patch was found at 12, delta is 2 and the second patch

// @ts-ignore

// A CodeMirror instance represents an editor. This is the object

// A Pos instance represents a position within the text.

// A binary search to find the first character whose bounding box

// A bug in IE8 can cause this value to be negative, so guard it.

// A cursor Pos(line, char, "after") is on the same visual line as `char`

// A cursor Pos(line, char, "before") is on the same visual line as `char - 1`

// A deletion and an insertion is one substitution.

// A half-match was found, sort out the return data.

// A lineView may contain multiple logical lines (when merged by

// A match this many characters away from the expected location will add

// A mouse down can be a single click, double click, triple click,

// A new event is started when the previous origin does not match

// A new patch starts here.

// A shared marker spans multiple linked documents. It is

// A styles array always starts with a number identifying the

// A visibility: hidden element used to find the size of things.

// A visual line is a line as drawn on the screen. Folding, for

// AB     B|A     B|A

// AL is found, change the type of the European number to Arabic

// Ab     |Ab     A|b

// Abort measurement, if in progress

// Abort mouse wheel delta measurement, when scrolling explicitly

// Accumulated changes, for firing change events

// Actual scrollable element.

// Add a dummy entry at the end.

// Add a span to a line.

// Add new sub-event

// Add nullPadding equality.

// Add on and off methods to a constructor's prototype, to make

// Add one chunk for good luck.

// Add some padding on end of last diff.

// Add some padding on start of first diff.

// Add the prefix.

// Add the remaining character length.

// Add the suffix.

// Adds "Select all" to context menu in FF

// Adjust a position to refer to the post-change position of the

// Adjust the line structure

// After the previous speedup, the character can't be an equality.

// All nodes have parent links. The tree is used both to go from

// Allocate 2/3rds of the space for text1, the rest for text2.

// Allow "beforeChange" event handlers to influence a change

// Alphabetic keys

// Already drawn

// Already passed loc, downhill from here on in.

// An insertion or deletion.

// Anything else is an error.

// Append the end context for this patch.

// Apply a change to a document, and add it to the document's

// Arrays of change events and selections. Doing something adds an

// At any point we are certain `to` satisfies `pred`, don't know

// At what point is no match declared (0.0 = perfection, 1.0 = very loose).

// Attach a document to an editor.

// Attach the necessary event handlers when initializing the editor

// BIDI HELPERS

// Bail out at 65535 because

// Bail out if the visible area is already rendered and nothing changed.

// Because Android doesn't allow us to actually detect backspace

// Become the parent node

// Behavior of elts with overflow: auto and padding is

// Bidi parts are sorted left-to-right, and in a non-line-wrapping

// BidiSpan objects otherwise.

// Bidirectional ordering algorithm

// Binary search.

// Blank tokens are ok (from a trailing \t).

// Both matched.  Select the longest.

// Bottom overlap

// Briefly turn off draggability, to allow widgets to do

// Build a line's DOM representation from scratch

// Build up a reverse change object to add to the opposite history

// Build up a set of ranges to kill first, merging overlapping

// Build up the DOM representation for a single token, and add it to

// Bump all the patches forward.

// But check anyway.

// By default, updates that start and end at the beginning of a line

// CONCATENATED MODULE: ./node_modules/@ali/4ever-bamboo/dist-web/plugins/code/components/codemirror/index.js

// CONTENTEDITABLE INPUT STYLE

// CONTEXT MENU HANDLING

// Cache the text lengths to prevent multiple calls.

// Calculate a new scroll position needed to scroll the given

// Call f for all linked documents.

// Called when the window resizes

// Called whenever the selection changes, sets the new selection as

// Calls delayed callbacks and cursorActivity handlers until no

// Can not be merged, start a new event.

// Can't find valid trailing context.  Drop this patch.

// Cancel the current text selection if any (#5821)

// Candidate found.

// Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,

// Case 2: We move within an rtl part or in an rtl editor on the same visual line

// Case 3: Could not move within this bidi part in this visual line, so leave

// Case 3a: Look for other bidi parts on the same visual line

// Case 3b: Look for other bidi parts on the next visual line

// Case 4: Nowhere to move

// Change after

// Change before

// Change second copy to insert.

// Change some spaces to NBSP to prevent the browser from collapsing

// Change the content (text, markers) of a line. Automatically

// Character types for codepoints 0 to 0xff

// Character types for codepoints 0x600 to 0x6f9

// Check again based on the third quarter.

// Check for equality (speedup).

// Check for null inputs.

// Check that lines don't extend past the right of the current

// Check to see if the problem can be split in two.

// Chunk size for context length.

// Clear the marker.

// Clear the view.

// Clip forced viewport to actual scrollable area.

// Clip the change to the size of this doc

// Clip the part to the wrapped line.

// CodeMirror, copyright (c) by Marijn Haverbeke and others

// CodeMirror.prototype, for backwards compatibility and

// Collapsed markers have unique ids, in order to be able to order

// Commands are parameter-less actions that can be performed on an

// CommonJS

// Compare two positions, return 0 if they are the same, a negative

// Compute a style array (an array starting with a mode generation

// Compute a suitable new viewport (from & to)

// Compute diffs from text1 and text2.

// Compute text1 from diffs.

// Compute the base array of styles

// Compute the character length of a line, taking into account

// Compute the character position closest to the given coordinates.

// Compute the default character width.

// Compute the default text height.

// Compute the diff on the middle block.

// Compute the head context for the next patch.

// Compute the lines that are visible in a given viewport (defaults

// Compute the position of the end of a change (its 'to' property

// Compute the relative visual position of the head compared to the

// Compute whether a line is hidden. Lines count as hidden when they

// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,

// Connect or disconnect spans from a line.

// Context may be "window", "page", "div", or "local"./null.

// Continuing lines, if any

// Convert a style as returned by a mode (either null, or a string

// Convert the diff back to original text.

// Converts a {top, bottom, left, right} box from line-local

// Cost of an empty edit operation in terms of edit characters.

// Count the number of lines in the view whose DOM representation is

// Counts the column offset in a string, taking tabs into account.

// Covers bottom of gutter when coverGutterNextToScrollbar is on

// Covers bottom-right square when both scrollbars are present.

// Coverts a box from "div" coords to another coordinate system.

// Create a history change event from an updateDoc-style change

// Create a marker, wire it up to the right lines, and

// Create a range of LineView objects for the given lines.

// Create one of several smaller patches.

// Created with markText and setBookmark methods. A TextMarker is a

// Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,

// Current rendered range (may be bigger than the view window).

// Cursor-blinking

// DISPLAY DRAWING

// DOCUMENT DATA STRUCTURE

// DOM structure.

// Deep copy the patches so that no changes are made to originals.

// Default to positioning above (if specified and possible); otherwise default to positioning below

// Defaults.

// Define some regex patterns for matching boundaries.

// Delete the offending records and add the merged ones.

// Deletion

// Deletion or equality.  Only take as much as we can stomach.

// Deletion.

// Detach a line from the document tree and its markers.

// Detect drag-and-drop

// Determine effective options based on given values and defaults.

// Determine if we should prevent the cursor being placed to the left/right of an atomic marker

// Determines whether an event happened in the gutter, and fires the

// Diff took too long and hit the deadline or

// Distinguish coordinates nearer to the left or right side of the box

// Distributed under an MIT license: https://codemirror.net/5/LICENSE

// Do a bulk-read of the DOM positions and sizes needed to draw the

// Does the actual updating of the line display. Bails out

// Doesn't consider line feeds a character.

// Doesn't do anything on an empty line.

// Doesn't do anything with non-empty selections.

// Doesn't scan more than one line above to find a character.

// Don't connect empty markers unless clearWhenEmpty is false

// Don't do a replace if the drop happened inside of the selected text.

// Don't leave long text in the textarea, since it makes further polling slow

// Don't risk returning a non-optimal diff if we have unlimited time.

// Draws a cursor for the given range

// Draws the given range as a highlighted selection

// Due to the fact that we still support jurassic IE versions, some

// Duplicate record.

// EDITOR CONSTRUCTOR

// ESM COMPAT FLAG

// EVENT HANDLING

// EXPORTS

// EXTENSIONS

// EXTERNAL MODULE: ./node_modules/@ali/4ever-bamboo/dist-web/plugins/code/constants/languages.js

// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js

// EXTERNAL MODULE: ./node_modules/@babel/runtime/regenerator/index.js

// EXTERNAL MODULE: ./node_modules/react/index.js

// Each port of this function behaves slightly differently due to

// Each token begins with a one character parameter which specifies the

// Edges are the best.

// Elements are added to these to represent selection and cursors.

// Eliminate an equality that is smaller or equal to the edits on both

// Eliminate freak matches (e.g. blank lines)

// Eliminate the null case.

// Empty space (in pixels) above the view

// Ensure a given position is not inside an atomic range.

// Ensure at least a single node is present, for measuring.

// Ensure is a {from: {line, ch}, to: {line, ch}} object, and

// Ensure previous input has been read, so that the handler sees a

// Ensure that, if the cursor was in the whitespace at the start

// Ensure the editor is re-focused

// Ensure the lineView.wrapping.heights array is populated. This is

// Ensure there's a token end at the current position, and that i points at it

// Ensure we are in an operation.

// Equality found.

// Equality or deletion.

// Equality or insertion.

// Escape the body of the patch with %xx notation.

// Every position after the last character on a line is considered to stick

// Examples (upper-case letters are RTL, lower-case are LTR):

// Extend all selections (pos is an array of selections with length

// Extend the lengths.

// Extend the primary selection range, discard the rest.

// Extending unicode characters. A series of a non-extending char +

// Extra arguments are stored as the mode's dependencies, which is

// FIXME

// FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems

// Factor out any common prefixies.

// Factor out any common suffixies.

// Fails unpredictably on IE[67] when mouse is dragged around quickly.

// Fall back to "prev" when the mode doesn't have an indentation

// Fall through.

// Feature-detect IE's crummy client rect reporting for bidi text

// Fed to the mode parsers, provides helper functions to make

// Fetch the parser token for a given character. Useful for hacks

// Fill gap with whole-line-spans

// Fill in a browser-detected starting value on browsers where we

// Find a line map (mapping character offsets to text nodes) and a

// Find a line view that corresponds to the given line number.

// Find any overlaps between deletions and insertions.

// Find out whether a line ends or starts in a collapsed span. If

// Find the height above the given line.

// Find the line at the given vertical position, using the height

// Find the line object corresponding to the given line number.

// Find the longest line in the document.

// Find the part of the input that is actually new

// Find the part that overlaps with the start of this text

// Find the position of the marker in the document. Returns a {from,

// Find the top change event in the history. Pop off selection

// Find the view element corresponding to a given line. Return null

// Find the word at the given position (as returned by coordsChar).

// Finds the line to start with when starting a parse. Tries to

// Finish an operation, updating the display and signalling delayed events

// Fire change events, and delayed event handlers

// Fire events for markers that are hidden/unidden by editing or

// First check if the second quarter is the seed for a half-match.

// First move into "page" coordinate system

// First pass: exact match.

// First, search the line map for the text node corresponding to,

// Fix up .from in last (or move them into first in case of sameLine)

// Fix up .to properties of first

// Flag that indicates that lines might need to be redrawn

// Flag that indicates whether we expect input to appear real soon

// For big changes, we hide the enclosing element during the

// For relative vertical movement. Dir may be -1 or 1. Unit can be

// Force a relayout, or Opera won't use our image for some obscure reason

// Force the view to cover a given range, adding empty view element

// Found a match.  :)

// From here, the methods are part of the public interface. Most

// Full overlap

// Function keys

// Functions to run when options are changed.

// Gap in the middle

// Get a {top, bottom, left, right} box (in line-local coordinates)

// Get rid of the null case.

// Get the bidi ordering for the given line (and cache it). Returns

// Get the line number of the start of the next visual line after

// Get the line number of the start of the visual line that the

// Get the lines between from and to, as array of strings.

// Get the part of a document between two positions, as an array of

// Get the spans that 'stick out' on both sides

// Give beforeSelectionChange handlers a change to influence a

// Given a MIME type, a {name, ...options} config object, or a name

// Given a change object, compute the new set of marker spans that

// Given a line object, find its line number by walking up through

// Given a mode and a state (for that mode), find the inner mode and

// Given a mode spec (anything that resolveMode accepts), find and

// Given a mouse event, find the corresponding position. If liberal

// Given a prepared measurement object, measures the position of an

// Grow first equality.

// Grow last equality.

// HIGHLIGHT WORKER

// Handle a key from the keydown event.

// Handle a key from the keypress event

// Handle the interaction of a change to a document with the editor

// Helper for deleting text near the selection(s), used to implement

// Helper used to collapse a small branch into a single leaf.

// Helpers used when computing which overlapping collapsed span

// Here we depart from the documented algorithm, in order to avoid

// Highest score beyond which we give up.

// Historically this was determined using the inclusiveLeft/Right option, but the new way to control it

// Holds info about a single rendered line when it was rendered

// How far to search for a match (0 = exact location, 1000+ = broad match).

// IE < 10 will throw when accessed while the page is loading or in an iframe.

// IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.

// IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.

// IE does strange things with escape.

// IE doesn't fire input events, so we schedule a read for the pasted content in this way

// IE's approach to draggable

// IE8 will throw if the textarea is display: none or not in DOM

// If a box around the coordinates was found, use that

// If an editor sits on the top or bottom of the window, partially

// If border: 0; -- iOS fails to open keyboard (issue #1287)

// If e is null or undefined we interpret this as someone trying

// If it is a text node, use a range to retrieve the coordinates.

// If it is a widget, simply get the box for the whole widget.

// If nothing changed, bail.

// If pos == Pos(_, 0, "before"), pos and end are unchanged

// If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch

// If shift is held or the extend flag is set, extends a range to

// If shifts were made, the diff needs reordering and another shift sweep.

// If the histories were shared, split them again

// If the line isn't plain left-to-right text, first figure out

// If the max line changed since it was last measured, measure it,

// If the result is smaller than 25 lines, ensure that it is a

// If the total number of characters is odd, then the front path will collide

// If this isn't the first part, the part's start is also after

// If we need to scroll a specific position into view, do so.

// Imperfect match.  Run a diff to get a framework of equivalent

// In a wrapped line, rtl text on wrapping boundaries can do things

// Indent the given line. The how parameter can be "smart",

// Information about the rendered lines.

// Initialise the alphabet.

// Initialise the bit arrays.

// Input must be lineSpace-local ("div" coordinate system).

// Insert an equality and swap and trim the surrounding edits.

// Insert the given array of lines at offset 'at', count them as

// Insertion

// Insertion.

// Insertions are harmless.

// Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.

// Intentionally ignore the first and last element (don't need checking).

// Intermediate scroll position, not pushed to DOM yet

// Is there a nearby exact match? (speedup)

// It also indexes by height, and is used to convert between height

// Iterate over the document. Supports two forms -- with only one

// Iterate over the logical lines that make up this visual line.

// Just add some text (speedup).

// Just delete some text (speedup).

// KEYMAP DISPATCH

// Kludge to work around strange IE behavior where it'll sometimes

// Kludges for bugs and behavior differences that can't be feature

// Known modes, by name and by MIME

// L (L):   Left-to-Right

// LINE DATA STRUCTURE

// Label for screenreaders, accessibility

// Let the drag handler handle this.

// Lightweight event framework. on/off also work on DOM nodes,

// Lightweight form of highlight -- proceed over this line and

// Line objects. These hold state related to a line, including

// Line widgets are block elements displayed above or below a line.

// Lines with gutter elements, widgets or a background class need to

// Listen to wheel events in order to try and update the viewport on time.

// Look for the first and last matches of pattern in text.  If two different

// Look up the name of a key as indicated by an event object.

// Loop over the elements in the view, syncing cur (the DOM nodes

// Make sure that at the end of the operation the current cursor is

// Make sure we didn't create any zero-length spans

// Making deep copies is hard in JavaScript.

// Malformed URI sequence.

// Measure a bunch of lines, for browsers that compute

// Measurement can be split in two steps, the set-up work that

// Merge the results.

// Merge this change into the last event

// Merge this equality with the previous one.

// Method 1: text1, text2

// Method 2: diffs

// Method 3: text1, diffs

// Method 4: text1, text2, diffs

// Might be a file drop, in which case we simply extract the text

// Might be a text scaling operation, clear size caches.

// Minimal default mode.

// Minor equality.

// Mirror x2 onto top-left coordinate system.

// Modifier key presses don't count as 'real' key presses for the

// Modifying text would create many large strings to garbage collect.

// More lower-level change function, handling only a single document

// Most of the external API clips given positions to make sure they

// Move cursor behind the two swapped characters afterwards.

// Move the hidden textarea near the cursor to prevent scrolling artifacts

// Move y into line-local coordinate space

// Moved around its parent to cover visible view.

// Multiple lines

// N (ON):  Other Neutrals

// N1. A sequence of neutrals takes the direction of the

// N2. Any remaining neutrals take the embedding direction.

// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).

// Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)

// Neutral.

// Next, remove those actual ranges.

// No changes made which could affect previous entry, keep going.

// No hope for a (better) match at greater error levels.

// No match found.  :(

// Non-public interface for adding and removing lines.

// Normal behavior is to insert the new text into every selection

// Normal drop

// Normal selection, as opposed to text dragging.

// Normalize the diff.

// Not a candidate, and can never become one.

// Not drawn yet

// Note that the save and find-related commands aren't defined by

// Note that, despite the name, this function is also used to check

// Now get accurate coordinates for this place, in order to get a

// Number keys

// Number of logical lines in this visual line

// Number of pixels added to scroller and sizer to hide scrollbar

// Number of seconds to map a diff before giving up (0 for infinity).

// Often, we want to signal events at a point where we are in the

// Old-fashioned briefly-focus-a-textarea hack

// Older IE's will not fire a second mousedown for a double click

// On Android Chrome (version 56, at least), backspacing into an

// On Chrome 102, viewport updates somehow stop wheel-based

// On some browsers, horizontal scrolling will cause redraws to

// One-char codes used for character types:

// Only extract an overlap if it is as big as the edit ahead or behind it.

// Only prevent default scrolling if vertical scrolling is

// Opera has no cut event... we try to at least catch the key combo

// Opera is difficult.

// Operation (insert, delete, equal)

// Operations are used to wrap a series of changes to the editor

// Optimize some code when these features are not used.

// Optimized case for simple insertion -- don't want to add

// Optionally wire in some hacks into the token-rendering

// Otherwise, simply returns the range between the given positions.

// Our model of the DOM might be outdated, in which case the range we try to set can be impossible

// Outputs a number of spans to make up a line, taking highlighting

// Overlap detected.

// Overlap found.  Insert an equality and trim the surrounding edits.

// Override magic textarea content restore that IE sometimes does

// POSITION MEASUREMENT

// Pass the `paste` event to the textarea so it's handled by its event listener.

// Passed to option handlers when there is no old value.

// Perfect match, just shove the replacement text in.

// Perform a change on the document data structure.

// Performance analysis: https://neil.fraser.name/news/2007/10/09/

// Performance analysis: https://neil.fraser.name/news/2010/11/04/

// Pick up the leftover patch if not empty.

// Pointless.

// Poll for input changes, using the normal rate of polling. This

// Pop all selection events off the end of a history array. Stop at

// Pos objects returned contain a line object, rather than a line

// Position the mover div to align with the current scroll position

// Positions returned by coordsChar contain some extra information.

// Possibly split or suppress the update based on the presence

// Prepare DOM reads needed to update the scrollbars. Done in one

// Prevent clicks in the scrollbars from killing focus

// Prevent normal selection in the editor (we handle our own)

// Prevent selection and cursors from interfering with the scroll

// Prevent this from being ran twice

// Prevent wrapper from ever scrolling

// Propagate the scroll position to the actual DOM scroller

// Propagate to the linked documents

// Public alias.

// Quick check for common null cases.

// Quick check for the worst case.

// Quit if there's nothing to scroll here

// R (R):   Right-to-Left

// Ran off the bottom of the graph.

// Ran off the left of the graph.

// Ran off the right of the graph.

// Ran off the top of the graph.

// Re-align line numbers and gutter marks to compensate for

// Re-set this, in case some other handler touched the

// Re-synchronize the fake scrollbars with the actual size of the

// Read and store the height of line widgets associated with the

// Read input from the textarea, and update the document to match.

// Read the actual heights of the rendered lines, and update their

// Rebasing/resetting history to deal with externally-sourced changes

// Rebuild the gutter elements, ensure the margin to the left of the

// Redefine these in your program to override the defaults.

// Rediff any replacement blocks, this time character-by-character.

// Redraw the line's text. Interacts with the background and text

// Redraw the selection and/or cursor

// Register a change in the history. Merges changes that are within

// Register a change to a single line. Type must be one of "text",

// Remember that these lines changed, for updating the display

// Remove a span from an array, returning undefined if no spans are

// Remove spans that are empty and don't have a clearWhenEmpty

// Remove the big old patch.

// Remove the dummy entry at the end.

// Remove the n lines at offset 'at'.

// Render a line into the hidden node display.externalMeasured. Used

// Render the DOM representation of the text of a line. Also builds

// Reset the counters.

// Reset the current text selection only if the click is done outside of the selection

// Reset the input to correspond to the selection (or to be empty,

// Reset the selection to a single range.

// Restore the prefix and suffix.

// Retrieve and filter the old marked spans stored in a change event.

// Retry a maximum of 4 times when nonsense rectangles are returned

// Return a selection that does not partially select any atomic

// Return true when the given mouse event happened in a widget

// Returned or thrown by various protocols to signal 'I'm not

// Returns a box for a given cursor position, which may have an

// Returns a function that estimates the height of a line, to use as

// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.

// Returns a number indicating which of two overlapping collapsed

// Returns an array of logical lines that continue the visual line

// Returns null if characters are ordered as they appear

// Returns the value from the range [`from`; `to`] that satisfies

// Returns true if the given side of a box is after the given

// Reverse overlap found.

// Revert a change stored in a document's history.

// Roll back the start points.

// Run a binary search to determine how far from 'loc' we can stray at this

// Run a handler that was bound to a key.

// Run overlays, adjust style array.

// Run the given function in an operation

// Run the given mode's parser over a line, calling f for each token.

// SCROLLBARS

// SCROLLING THINGS INTO VIEW

// SHARED TEXTMARKERS

// STRING STREAM

// Safari returns null in some cases (#2780)

// Scan for the best match; each iteration allows for one more error.

// Scan the text on a line-by-line basis first.

// Scroll a given position into view (immediately), verifying that

// Scroll a given set of coordinates into view (immediately).

// Search an array of spans for a span matching the given marker.

// Second pass: look for single edits surrounded on both sides by equalities

// Second, step character by character right, looking for the best fit.

// Secondary cursor, shown when on a 'jump' in bi-directional text

// See #6982. FIXME remove when this has been fixed for a while in Chrome

// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html

// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm

// See if "".split is the broken IE version, if so, provide an

// See input.poll and input.reset

// See issue #2901

// Select-all will be greyed out if there's nothing to select, so

// Selection objects are immutable. A new one is created every time

// Self-resetting timeout for the poller

// Send an event to consumers responding to changes in gutter width.

// Set a deadline by which time the diff must be complete.

// Set a new selection.

// Set autofocus to true if this textarea is focused, or if it has

// Set of handlers to fire cursorActivity on

// Set pos and end to the cursor positions around the character pos sticks to

// Set to the height of the document, allowing scrolling.

// Set to true when a non-horizontal-scrolling line widget is

// Set up methods on CodeMirror's prototype to redirect to the editor's document.

// Set when the widest line needs to be determined anew

// Setting all elements to -1 is faster in Chrome & Firefox than mixing

// Shared markers (across linked documents) are handled separately

// Shift the edit over the next equality.

// Shift the edit over the previous equality.

// Shorter text is inside the longer text (speedup).

// Should be 0.

// Showing up as a widget implies collapsed (widget replaces text)

// Signals that the marker's widget changed, and surrounding layout

// Since the delta values reported on mouse wheel events are

// Since this is called a *lot*, try to bail out as cheaply as

// Single character string.

// Single line

// Small equality inside a patch.

// So we'll insert a junk entry to avoid generating a null character.

// Some browsers fire contextmenu *after* opening the menu, at

// Some browsers fire keypress events for backspace

// Some browsers use the wrong event properties to signal cmd/ctrl on OS X

// Start a new operation.

// Start a text drag. When it ends, see if any dragging actually

// Start by looking for a single character match

// Start of next patch.

// Start with a 1/4 length substring at position i as a seed.

// Store a relative adjustment to the scroll position in the current

// Store some values that we'll need later (but don't want to force a relayout for)

// Store the map and a cache object for the current logical line

// String.fromCharCode(65536) == String.fromCharCode(0)

// Strip the padding off.

// Sub-views need their line numbers shifted when text is added

// Subtract the delta for this failed patch from subsequent patches.

// Such overlap is not allowed.

// Suppress optimizelegibility in Webkit, since it breaks text

// Swap insertions for deletions if diff is reversed.

// Swap the two chars left and right of each selection's head.

// Sync editor state

// Sync scroller and scrollbar, ensure the gutter elements are

// Sync scrolling between fake scrollbars and real scrollable

// Sync the actual display DOM structure with display.view, removing

// Sync the scrollable area and scrollbars, ensure the viewport

// TEXTAREA INPUT STYLE

// TEXTMARKER SPANS

// TEXTMARKERS

// Take an unsorted, potentially overlapping set of ranges, and

// Test whether there exists a collapsed span that partially

// The 'scroll' parameter given to many of these indicated whether

// The >= encourages trailing rather than leading whitespace on edits.

// The DOM events that CodeMirror handles can be overridden by

// The DOM updates done when an operation finishes are batched so

// The alphabet (s) is a sparse hash, so the following line generates

// The awkward -1 offsets are needed because findFirst (called

// The default configuration options.

// The display handles the DOM integration, both for input reading

// The document is represented as a BTree consisting of leaves, with

// The element in which the editor lives.

// The end points match, but the content is unacceptably bad.

// The following export code was added by @ForbesLindesay

// The inverse of countColumn -- find the offset that corresponds to

// The number of bits in an int.

// The padding-right forces the element to have a 'border', which

// The publicly visible API. Note that methodOp(f) means

// The reason we want to know the amount a wheel event will scroll

// The returned object contains the DOM node, this map, and

// The semihidden textarea that is focused when the editor is

// The spans will have null for their from/to properties when the

// The starting line

// The textarea is kept positioned near the cursor to prevent the

// There is *some* kind of drag-and-drop support in IE6-8, but I

// There might have been a widget with a focused element that got

// These must be handled carefully, because naively registering a

// These objects are used to represent the visible (currently drawn)

// These two are, on init, called from the constructor because they

// This attribute is respected by automatic translation systems such as Google Translate,

// This can be used to attach properties to mode objects from

// This hack (see related code in patchDisplay) makes sure the

// This is CodeMirror (https://codemirror.net/5), a code editor

// This is a kludge to keep keymaps mostly working as raw objects

// This is a large deletion.  Let it pass in one chunk.

// This is a single edit surrounded by equalities.

// This is a whole-line replace. Treated specially to make

// This is not the complete set of editor methods. Most of the

// This match will almost certainly be better than any existing match.

// This test prevents this from firing when a context

// This will be set to a {lineWise: bool, text: [string]} object, so

// Throw away the equality we just deleted.

// Throw away the equality we just deleted;

// Throw away the previous equality (it needs to be reevaluated).

// Throw away the previous equality.

// Thus, in rtl, we are looking for the first (content-order) character

// To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.

// To determine which side to associate with, get the box to the

// To find out whether the scrollbar is still visible, we

// To make the context menu work, we need to briefly unhide the

// Told you so.

// Top overlap

// Tracks the maximum line length so that the horizontal scrollbar

// Tracks which cursorActivity handlers have been called already

// Tries to rebase an array of history events given a change in the

// Trim off common prefix (speedup).

// Trim off common suffix (speedup).

// True when shift is held down.

// Truncate the longer string.

// Try to move start of change to start of selection if ambiguous

// Turn mouse into crosshair when Alt is held on Mac.

// UPDATING

// Unfinished key sequence

// Unique ID

// Unlike Unidiff, our patch lists have a rolling context.

// Update current marker set

// Update prepatch text & pos to reflect the application of the

// Update the current character count.

// Update the height of a line, propagating the height change

// Updated line heights might result in the drawn area not

// Updates a single range in the selection.

// Updates the display.view data structure for a given change to the

// Upon reaching an equality, check for prior redundancies.

// Use the result from this iteration as the maximum for the next.

// Used both to provide a JSON-safe object in .getHistory, and, when

// Used by replaceSelections to allow moving the selection to the

// Used by the isClean() method

// Used for cursor motion and such.

// Used for horizontal relative motion. Dir is -1 or 1 (left or

// Used for measuring wheel scrolling granularity

// Used for the algorithm that adjusts markers for a change in the

// Used for un/re-doing changes from the history. Combines the

// Used mostly to find indentation.

// Used to 'clip' out readOnly ranges when making a change.

// Used to add methods to editor and doc instances, wrapping them in

// Used to catch context-menu undo

// Used to cheaply estimate the coordinates for a position. Used for

// Used to detect need to update scrollbar

// Used to ensure that the line number gutter is still the right

// Used to ensure timeout re-tries don't fire when another extend

// Used to force a redraw

// Used to get the editor into a consistent state again when options change.

// Used to iterate over a part of the tree.

// Used to only resize the line number gutter when necessary (when

// Used to scroll to a specific position

// Used to store marked span information in the history.

// Used to suppress mouse event handling when a touch happens

// Used to track when changes can be merged into a single undo

// Used to track whether anything happened since the context menu

// Used to work around IE issue with selection being forgotten when focus moves away from textarea

// Used when mouse-selecting to adjust the anchor to the proper side

// Utility for applying a change to a line by handle or number,

// Utility for getTokenAt and getLineTokens

// Verify that the selection does not partially select any atomic

// Very basic readline/emacs-style bindings, which are standard on Mac.

// Visible

// W1. Examine each non-spacing mark (NSM) in the level run, and

// W2. Search backwards from each instance of a European number

// W3. Change all ALs to R.

// W4. A single European separator between two European numbers

// W5. A sequence of European terminators adjacent to European

// W6. Otherwise, separators and terminators change to Other

// W7. Search backwards from each instance of a European number

// WTF?

// Walk the front path one step.

// Walk the reverse path one step.

// Walk the text, pulling out a substring for each line.

// Was the location was deleted?

// We have an improvement, save it back to the diff.

// Webkit browsers on OS X abort momentum scrolls when the target

// Webkit seems to refuse to render text nodes longer than 57444

// What about in the other direction? (speedup)

// When a node has grown, check whether it should be split.

// When an 'electric' character is inserted, immediately trigger a reindent

// When an aspect of a line changes, a string is added to

// When an event has just come in that is likely to add or change

// When an operation has its scrollToPos property set, and another

// When deleting a large block of text (over ~64 characters), how close do

// When directly calling `measureCharPrepared`, we have to adjust

// When lines outside of the viewport are measured, they are drawn in this.

// When passing loc, don't exceed our current distance from loc.

// When pasting N lines into N selections, insert one line per selection

// When something is selected, it is present in the textarea, and

// When the window loses focus, we want to show the editor as blurred

// When the window resizes, we need to refresh active editors.

// When un/re-doing restores text containing marked spans, those

// Whether the selection needs to be redrawn

// Whether this reset should be careful to leave existing text (for compositing)

// Whether to reset the input textarea

// Will contain the actual code, positioned to cover the viewport.

// Will contain the gutters, if any.

// With a wrapped rtl chunk (possibly spanning multiple bidi parts),

// Work around Chrome issue (#2712)

// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)

// Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206

// Work around nonsense dimensions being reported for stretches of

// Work around nonsensical selection resetting in IE9/10, and

// Work around problem with bounding client rects on ranges being

// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)

// Works around a throw-scroll bug in OS X Webkit

// Wrapper around buildLineContent which will reuse the structure

// Wraps a function in an operation. Returns the wrapped function.

// Wraps and hides input textarea

// Wraps everything that needs to exist inside the vertically-padded coordinate system

// You can find some technical background for some of the code below

// `pred` and is closest to `from`. Assumes that at least `to`

// a change event.

// a monster delete.

// a particular column.

// a single operation, or are close together with an origin that

// aB     a|B     aB|

// ab     a|b     a|b

// above or below them in the parent document.

// actual character (or fetches it from the cache).

// actual scrolling happens, reducing flickering.

// actually covering the viewport. Keep looping until it does.

// actually exist within the document.

// actually possible. Otherwise, it causes vertical scroll

// added. As an optimization, line widget aligning is skipped when

// additional methods and properties).

// algorithm, to deal with browser quirks.

// aligned.

// all, so a binary search doesn't work, and we want to return a

// allows merging (starting with "+") into a single event.

// alternative way to split lines.

// an array of bottom offsets for the lines that make up a drawn

// anchor (<0 is to the left, >0 to the right)

// and 'resetSelectionOnContextMenu' option is true.

// and after `char - 1` in writing order of `char - 1`

// and also looks for line-wide styles.

// and before `char` in writing order of `char`

// and content drawing. It holds references to DOM nodes and

// and end-of-level-run (eor) are used at level run boundaries.

// and ensure the document's width matches it.

// and h scrollbar is present.

// and increase length until no match is found.

// and insert it.

// and line object, and to find the total height of the document.

// and marked text into account.

// and may also be respected by tools used by human translators.

// and preventDefault-ing the event in that handler.

// and returns null if it was. forRect is used by rectangular

// and simulates a backspace press in this case.

// and then, because it's not editable, hide the virtual keyboard.

// and, from that, detects the way it can convert deltas to pixel

// any number of extending chars is treated as a single unit as far

// applies to the whole line, and the measurement of the actual

// are also available from CodeMirror (editor) instances.

// are left alone.

// are part of a visual line that starts with another line, or when

// are simply ignored.

// are treated specially, in order to make the association of line

// area, ensure viewport is updated when scrolling.

// aren't currently visible.

// argument, it calls that for each line in the document. With

// arrays with one element for each line in (after) the change.

// as editing and measuring is concerned. This is not fully correct,

// as the last (content-order) character).

// at http://marijnhaverbeke.nl/blog/#cm-internals .

// autofocus and no other element is focused.

// b (BN):  Boundary Neutral

// backspace, delete, and similar functionality.

// base X position

// be wrapped, and have the extra elements added to the wrapper div

// before the event, the event's positions are updated. Uses a

// being wrong would just be a slight flicker on the first wheel

// better than glitching out.

// build a selection out of it. 'Consumes' ranges array (modifying

// building up an actual levels array. Since there are only three

// bumped when mode/overlay changes, used to invalidate highlighting info

// but using getBoundingClientRect to get a sub-pixel-accurate

// can be kept static when scrolling.

// change is on 3

// change the type of the NSM to the type of the previous

// changed.

// changes to a European number. A single common separator between

// character position, returning an array of remaining chunks (or

// character. Functions like coordsChar, that need to do a lot of

// character. If the NSM is at the start of the level run, it will

// characters in the part's range

// characters, and returns inaccurate measurements in nodes

// check whether the element under the pixel in the bottom

// chunk of lines in them, and branches, with up to ten leaves or

// classes because the mode may output tokens that influence these

// classes.

// code matches their width.

// collabSelections 变化时，重新绘制协同 selection

// collapsed ranges (see markText) that might hide parts, and join

// collapsed spans). The widgets for all of them need to be drawn.

// combined and executed at once.

// comparing ids when the spans cover exactly the same range.

// compatibility wrappers are needed.

// consistent view of the document

// contain multiple lines when collapsed ranges are present.)

// containing one or more styles) to a CSS style. This is cached,

// content.

// convenience.

// coordinates

// coordinates beyond the right of the text.

// coordinates into another coordinate system. Context may be one of

// coordinates, in top-to-bottom, left-to-right order.

// coordinates.

// coordsCharInner is safe. As such, we first find the extent of the

// copy-on-write scheme for the positions, to avoid having to

// couldn't get it to work yet.

// counts as the larger one.

// cover the line in which the change took place. Removes spans

// covers the visible area.

// cursor and display (which would be awkward, slow, and

// date.

// default. User code or addons can define them. Unknown commands

// delta keeps track of the offset between the expected and actual location

// detaching a document, to split the history in two

// detected are enabled based on userAgent etc sniffing.

// different (in number of selected ranges, emptiness, or time).

// different reference viewports and invalidate our calculations.

// direction. European and Arabic numbers act as if they were R in

// display-related state.

// document).

// document. From and to are in pre-change coordinates. Lendiff is

// document. If the change touches the same lines as the event, the

// document. Line objects hold arrays (markedSpans) containing

// document. These functions cut an array of spans at a given

// doesn't cross line boundaries), "word" (across next word), or

// e.g. lineArray[4] == 'Hello\n'

// e.g. lineHash['Hello\n'] == 4

// e.g: <del>abcxxx</del><ins>xxxdef</ins>

// e.g: <del>xxxabc</del><ins>defxxx</ins>

// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC

// editor width

// editor, mostly used for keybindings.

// element is kept around.

// end points of a delete need to match.

// entirely within the change, reconnects spans belonging to the

// equal the number of selections)

// error level.

// error-prone). Instead, display updates are batched and then all

// eslint-disable-next-line guard-for-in

// eslint-disable-next-line react-hooks/exhaustive-deps

// estimated pixels/delta value, we just handle horizontal

// event

// event to done and clears undo. Undoing moves events from done

// event, and everything 'behind' it, is discarded. If the change is

// events that are in the way.

// example, can cause multiple logical lines to appear on the same

// existed in the history (so that deleting around a span and then

// explicit embedding into account, we can build up the order on

// fact that it'll be scrolled into view on input from scrolling

// false for lines that are fully left-to-right, and an array of

// false.

// find a line with a stateAfter, so that it can start with a

// first approximation until the line becomes visible (and is thus

// focused, and receives input.

// for a given character.

// for bound mouse clicks.

// for measurement, while not in view.

// for the widgets at this line.

// forces those lines into the viewport (if possible).

// found, then change the type of the European number to L.

// fractional heights.

// garbage collected.

// generally horribly unpredictable, this code starts by measuring

// get the type of sor.

// given line is part of (usually that is the line itself).

// given line number is part of.

// given line.

// handle that can be used to clear or find a marked position in the

// handled in onMouseDown for these browsers.

// handler for each editor will cause the editors to never be

// handlers for the corresponding event.

// handling this'.

// happen before the gutter has been realigned, causing it to

// happen, and treat as a click if it didn't.

// happened in the meantime (clearTimeout isn't reliable -- at

// has an effective expected position of 22.

// have to be initialized before the editor can start at all.

// having the given height.

// height, and ensure (see op.scrollToPos) properties.

// height.

// help recognize paste/cut edits in input.poll

// hidden or updated, if so re-focus it.

// highlighting info (the styles array).

// highlighting overlays, as added by addOverlay

// history, and propagating it to all linked documents.

// hitSide=true property if it reached the end of the document.

// horizontal scrolling.

// https://github.com/codemirror/CodeMirror/pull/5673

// https://github.com/google/diff-match-patch/wiki/Unidiff

// iOS exposes the clipboard API, but seems to discard content inserted into it

// if the clear happens after their scheduled firing time).

// implemented as a meta-marker-object controlling multiple normal

// implemented in JavaScript on top of the browser's DOM.

// in display.externalMeasured when possible.

// in display.lineDiv) with the view as we go.

// in the rtl chunk that is on the last line (that is, the same line

// in which case reading its value would be expensive.

// include a given position (and optionally a second position).

// inconsistent across browsers. This is used to ensure the

// indicating that such a marker is present on that line. Multiple

// indices.

// inexplicable appearance of private area unicode characters on

// information about line-wide styles that were set by the mode.

// information in the document tree.

// initialize an actual mode object.

// integers and undefined.

// intermediate scroll updates.

// invalidates cached information and tries to re-estimate the

// is false, it checks whether a gutter or scrollbar was clicked,

// is large (issue #3579)

// is needed on Webkit to be able to get line-level bounding

// is needed.

// is that it gives us a chance to update the display before the

// is true, that means the coordinates lie outside the line's

// is with selectLeft/Right

// it actually became visible (as line heights are accurately

// it could be that the last bidi part is not on the last visual line,

// it enabled, if it's hidden, we disable pointer events.

// it got selected.

// it).

// iter aborts when callback returns a truthy value

// iter aborts when callback returns truthy value

// its parent links.

// itself (when the bar is still visible) or its filler child

// jitter on OSX trackpads when deltaX is small and deltaY

// just completed patch.

// know one. These don't have to be accurate -- the result of them

// least on Chrome, the timeouts still happen even when cleared,

// left (we don't store arrays for lines without spans).

// left of the character and compare it's vertical position to the

// letting go of the mouse button.

// levels (0, 1, 2) in an implementation that doesn't take

// like normalization and multi-stroke key bindings. It compiles a

// line numbers to line objects, and to go from objects to numbers.

// line's height.

// line.

// line. When lineWrapping is on, there might be more than one

// lineIsHidden depends on the presence of the spans, so needs a second pass

// lineView.changes. This updates the relevant part of the line's

// lines are divided into visual lines. regLineChange (below)

// lines are not indented, and places where the mode returns Pass

// lines may point to the same marker when it spans across lines.

// links back to the lines they currently touch.

// load a mode. (Preferred mechanism is the require/define calls.)

// logical lines, if those are connected by collapsed ranges.

// m (NSM): Non-Spacing Mark

// marked ranges.

// marker continues beyond the start/end of the line. Markers have

// markers.

// matches are found, increase the pattern length.

// measured, the position of something may 'drift' during drawing).

// measurement cache for the given line number. (A line view might

// measurements in a row, can thus ensure that the set-up work is

// measuring on line wrapping boundaries.

// menu is closed (since the input reset would kill the

// merged when similar and close together in time.

// method.

// methods defined on the Doc type are also injected into

// middle of some work, but don't want the handler to start calling

// middle-click-paste. Or it might be a click on something we should

// mode/overlays that it is based on (for easy invalidation).

// model 里有的 syntax 是不标准的(比如语雀拷贝)，这里先做一层处理

// modifying the selection.

// n (AN):  Arabic Number

// new changesets for every character typed

// new normalized keymap, and then updates the old object to reflect

// new ones appear

// node, and is the document object itself (meaning it has

// nodes for lines that are no longer in view, and creating the ones

// non-word-non-whitespace chars). The visually param controls

// normal dragging things.

// not interfere with, such as a scrollbar or widget.

// not reset the textarea when typing, because that breaks IME).

// nothing interesting happens.

// now (after some event like 'keypress' or 'input') and are

// number (used to prevent looking up the same line twice).

// number of diffs equals number of characters, no commonality at all.

// number when a is less, and a positive number otherwise.

// number.

// numbers changes to all European numbers.

// object.

// objects) in the order in which they occur visually.

// of a bidi jump depending on the visual position of the head.

// of code points as a group.

// of read-only spans in its range.

// of the current position. The resulting position will have a

// of the line, it is moved to the end of that space.

// of the previous patch.  If there are patches expected at positions 10 and

// of the scroll event is removed from the scrollable element.

// offsets afterwards.

// on a bidi boundary.

// on our hidden textarea on reload

// on these below) will treat its first bound as inclusive,

// only done once.

// operation (to be applied when the operation finishes).

// operation is active, when a timeout fires.

// operation of this token (delete, insert, equality).

// operations.

// option of false.

// or "page".

// or clipping off existing ones as needed.

// or closest to, the target character.

// ordering. This finds the first part whose end is after the given

// other branch nodes below them. The top node is always a branch

// other lines onto it.

// other methods on the editor, which might be in an inconsistent

// our fake cursor out of view. On webkit, when wrap=off, paste is

// out of date (or nonexistent).

// outside the actual mode definition.

// overlaps (covers the start or end, but not both) of a new span.

// parse correctly.

// parsers more succinct.

// part of the document. A LineView may correspond to multiple

// part that only spans one line so that the binary search in

// patch_splitMax will only provide an oversized pattern in the case of

// polling intensively.

// possible when it is clear that nothing happened. hasSelection

// presses in a sane way, this code checks for when that happens

// properly measurable).

// property if it reached the end of the document.

// purpose of keymap fallthrough.

// r (AL):  Right-to-Left Arabic

// ranges.

// rather than force total conformity.

// re-fire a series of drag-related events right after the drop (#1551)

// reallocate them all on every rebase, but also avoid problems with

// rectangle into view. Returns an object with scrollTop and

// rectangles for it (in measureChar).

// refers to the pre-change end).

// registering a (non-DOM) handler on the editor for the event name,

// registering events on such objects more convenient.

// registering native DOM handlers.

// registers single-line changes.

// result of computing the existing spans with the set of spans that

// result.

// returned incorrectly when zoomed on IE10 and below.

// returning the number and optionally registering the line as

// right corner of the scrollbar box is the scrollbar box

// right), unit can be "codepoint", "char", "column" (like char, but

// right-click take effect on it.

// right-to-left text.

// runs as long as the editor is focused.

// s (B):   Paragraph Separator

// same marker that appear on both sides of the change, and cuts off

// same text, or the end of the change if the change covers it.

// satisfies `pred`. Supports `from` being greater than `to`.

// scroll (if it is large enough).

// scroll action is applied before the end of the operation, this

// scrollLeft properties. When these are undefined, the

// scrollable area is big enough.

// scrolled into view (if we know enough to estimate it).

// scrolled out of view, this ensures that the cursor is visible.

// scrolling entirely here. It'll be slightly off from native, but

// scrolling. Turning off pointer events during the scroll seems

// second as exclusive, but we want to actually address the

// seen text (can be empty), which is stored in prevInput (we must

// select-all detection hack)

// selected (unless it is huge, in which case a placeholder is

// selection in the meantime.

// selection into the 'done' array when it was significantly

// selection update.

// selections, and tries to estimate a character position even for

// shared position objects being unsafely updated.

// shot to minimize update/measure roundtrips.

// should be recomputed.

// shown.

// sides of it.

// signalLater looks whether there are any handlers, and schedules

// since some scripts/fonts/browsers also treat other configurations

// since visual lines contain content order-consecutive chunks.

// single leaf node.

// situation, we can take this ordering to correspond to the visual

// size for the current document size. Returns true when an update

// smallest indentation, which tends to need the least context to

// so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)

// so, return the marker for that span.

// some key combos in Mac (#2689).

// something in the input textarea, we poll faster, to ensure that

// spans is larger (and thus includes the other). Falls back to

// spans partially within the change. Returns an array of span

// spans that aren't on the line.

// specific stretches of text, and is used by the measuring code.

// stack (redo when undoing, and vice versa).

// start of selection drag, start of text drag, new cursor

// start or around the replaced test. Hint may be "start" or "around".

// started by the argument, or undefined if there are no such lines.

// starting around 5000 chars.

// starting with * are always merged, those starting with + are

// starts after the coordinates. If we run across any whose box wrap

// state at the position that the state refers to.

// state in such a way that each change won't have to update the

// state on line 1 looked ahead 2 -- so saw 3

// state or simply not expect any other events to happen.

// stored heights to match.

// stores highlight worker timeout

// stores maps added by addKeyMap

// string, return a mode config object.

// strings.

// style strings), which is used to highlight the tokens on the

// subtle differences in each language's definition of things like

// support for the old title property

// sure line objects move the way they are supposed to.

// surrounding strong text if the text on both sides has the same

// t (S):   Segment Separator

// terms of their influence on neutrals. Start-of-level-run (sor)

// test 1 + 2 < 3 should cover this

// text was made out of.

// text.split('\n') would would temporarily double our memory footprint.

// text2 is not used.

// textarea (making it as unobtrusive as possible) to let the

// that are not there yet, and updating the ones that are out of

// that don't correspond to the ordering in our `order` array at

// that have been explicitly cleared should not be restored.

// that start, move one part back.

// that the effect of intermediate scroll commands is not ignored.

// that the minimum number of relayouts are required.

// that this (partially) implements.

// that this document is part of.

// that user code is usually dealing with.

// that want to inspect the mode state (say, for completion).

// that, when pasting, we know what kind of selections the copied

// the amount of lines added or subtracted by the change. This is

// the amount of lines crosses a boundary that makes its width change)

// the change appears on the screen quickly.

// the choice has been made to use each language's native features

// the contents have to be to match the expected contents. (0.0 = perfection,

// the coordinates, and the coordinates aren't on the same line as

// the coordinates, store that.

// the current bidi part

// the current, or the origins don't allow matching. Origins

// the fly, without following the level-based algorithm.

// the given line.

// the line map. Takes care to render special characters separately.

// the new cursor position should be scrolled into view after

// the next index in the string, or towards the character to the right

// the pending selection in the history, and pushes the old pending

// the right of the character position, for example). When outside

// the scroll effect that the first few mouse wheel events have,

// the second being non-inclusive).

// the selection changes. A selection is one or more non-overlapping

// the the current scroll position). viewport may contain top,

// them to be executed when the last operation ends, or, if no

// them, which is needed for uniquely determining an outer marker

// they are entirely covered by collapsed, non-widget span.

// this adds a zero-width space so that we can later check whether

// this is false.

// this.

// three, it iterates over the range given by the first two (with

// to avoid the issue.

// to explicitly cancel the selection rather than the user

// to the found position (so xRel > 0 means the coordinates are to

// to the last character on the line.

// to undone, redoing moves them in the other direction.

// to} object by default. Side can be passed to get a specific side

// trailing spaces at the end of a line when rendering text (issue #1362).

// two numbers of the same type changes to that type.

// undefined if nothing remains).

// undoing

// undoing brings back the span).

// uneditable block element will put the cursor in that element,

// unstandardized between browsers and even browser versions, and

// until the first strong type (R, L, AL, or sor) is found. If an

// until the first strong type (R, L, or sor) is found. If an L is

// up a 'line map', which points at the DOM nodes that represent

// update state, but don't save a style array. Used for lines that

// update, since that speeds up the operations on most browsers.

// updateDisplay_W2 will use these properties to do the actual resizing

// upwards to parent nodes.

// used by (legacy) mechanisms like loadmode.js to automatically

// used for changes that span multiple lines, or change the way

// used to disable editing during key handlers when in readOnly mode

// used). When nothing is selected, the cursor sits after previously

// valid state. If that fails, it returns the line with the

// vertical range.

// vertical/horizontal position does not need to be adjusted.

// very slow. So make the area wide instead.

// view, so that we don't interleave reading and writing to the DOM.

// view, that getCursor returns, etc).

// visual line. This finds the start of the visual line that the

// w (WS):  Whitespace

// warnings.

// was opened.

// when measurement is needed for a line that's not in the viewport.

// when not typing and nothing is selected)

// when the line isn't visible.

// when they overlap (they may nest, but not partially overlap).

// whether `from` does.

// whether, in right-to-left text, direction 1 means to move towards

// which bidi section the coordinates fall into.

// which can be shifted sideways to eliminate an equality.

// which causes page_Offset and bounding client rects to use

// which one is the primary selection (the one that's scrolled into

// which point we can't mess with it anymore. Context menu is

// widgets and marker elements with the text behave more intuitive.

// width and height.

// will be the case when there is a lot of text in the textarea,

// with the reverse path.

// wrapped line, and then do a flat search in which we discard any

// wrapper for elt, which removes the elt from the accessibility tree

// wriggle around in a most unseemly way. When we have an

// xRel is the relative x position of the input coordinates compared

// {from, to, marker} object pointing to such marker objects, and

// 避免闪烁

// 阻止移动端的事件冒泡到 slate-editor
