TextEditor.pas

File name
C:\Users\Andreas Rejbrand\Documents\Dev\TextEditor\TextEditor.pas
Date exported
Time exported
Formatting processor
TPascalFormattingProcessor
{******************************************************************************}
{                                                                              }
{ Rejbrand Text Editor Control 3.1                                             }
{                                                                              }
{ Copyright © 2015-2019 Andreas Rejbrand                                       }
{                                                                              }
{ https://english.rejbrand.se/                                                 }
{                                                                              }
{******************************************************************************}

unit TextEditor;

interface

uses
  Windows, SysUtils, Classes, Types, Controls, Graphics, Messages, Menus,
  ExtCtrls, RichEdit, CommCtrl, Forms, BitmapEffects, TextEncodings,
  UnicodeData, ActiveX, System.Win.ComObj, ShlObj, Generics.Defaults,
  Generics.Collections, UITypes, Math;

resourcestring
  SNumOnlyErrorTitle = 'Character not allowed';
  SNumOnlyErrorText = 'You can only type a number here.';
  SControlLineInputTitle = 'Text input not allowed';
  SControlLineInputText = 'You cannot enter text on a control line.';
  SPicture = 'Picture';
  SImageFilter = 'All images|*.bmp; *.jpg; *.jpeg; *.jpe; *.png; *.gif; *.ico|Bitmap images|*.bmp|JPEG images|*.jpg; *.jpeg; *.jpe|PNG images|*.png|GIF images|*.gif|Icons|*.ico';
  SOpenImageDialogCaption = 'Select image';
  SControl = 'Control';
  SRemovedControl = 'Removed control';
  SCliHistoryDialogCaption = 'Command History';
  SMultiSelectCaption = 'Character Selection';
  SMultiCharDlgLvColumnTitleDescription = 'Description';
  SMultiCharDlgLvColumnTitleCodepoint = 'Codepoint';
  SMultiCharDlgLvColumnTitleBlock = 'Block';
  SNewFileName = 'New file %d';

  SMenuOpenURL = 'Open URL';
  SMenuOpenURLHint = 'Opens %s.';
  SMenuUndo = 'Undo';
  SMenuUndoHint = 'Undoes the previous operation in the undo list.';
  SMenuRedo = 'Redo';
  SMenuRedoHint = 'Redoes the next operation in the undo list.';
  SMenuCut = 'Cut';
  SMenuCutHint = 'Moves the selected text to the clipboard.';
  SMenuCopy = 'Copy';
  SMenuCopyHint = 'Copies the selected text to the clipboard.';
  SMenuPaste = 'Paste';
  SMenuPasteHint = 'Pastes the contents of the clipboard at the caret, replacing any selection.';
  SMenuClear = 'Clear';
  SMenuClearHint = 'Removes the selected text.';
  SMenuSelectAll = 'Select all';
  SMenuSelectAllHint = 'Selects all text.';
  SMenuSetBookmark = 'Set bookmark';
  SMenuSetBookmarkItemHint = 'Sets this bookmark to the current caret position.';
  SMenuGotoBookmark = 'Goto bookmark';
  SMenuGotoBookmarkItemHint = 'Moves the caret to this bookmark.';
  SMenuClearBookmark = 'Clear bookmark';
  SMenuClearBookmarkItemHint = 'Clears (removes) this bookmark.';
  SMenuClasses = 'Classes';
  SMenuClassesItemHint = 'Assigns this class to the current line.';
  SMenuActivateControl = 'Activate control';
  SMenuActivateControlHint = 'Activates this control.';
  SMenuTransform = 'Transform';
  SMenuTransformUpperCase = 'To upper case';
  SMenuTransformUpperCaseHint = 'Converts the selected text to upper case.';
  SMenuTransformLowerCase = 'To lower case';
  SMenuTransformLowerCaseHint = 'Converts the selected text to lower case.';
  SMenuTransformInvertCase = 'Invert case';
  SMenuTransformInvertCaseHint = 'Inverts the case of the characters in the selection.';
  SMenuTransformCamelCase = 'To camel case';
  SMenuTransformCamelCaseHint = 'Enforces camel case (Camel Case) in the selection.';
  SMenuTransformSentenceCase = 'To sentence case';
  SMenuTransformSentenceCaseHint = 'Enforces sentence case in the selection.';
  SMenuTransformReverse = 'Reverse text';
  SMenuTransformReverseHint = 'Reverses the selected text.';
  SMenuTransformROT13 = 'Perform ROT-13';
  SMenuTransformROT13Hint = 'Performs ROT-13 on the selected text.';
  SMenuTransformCaesar = 'Apply Caesar cipher...';
  SMenuTransformCaesarHint = 'Performs the Caesar cipher on the selected text.';
  SMenuTransformVigenere = 'Apply Vigenère cipher...';
  SMenuTransformVigenereHint = 'Performs the Vigenère cipher on the selected text.';
  SMenuTransformVigenereInverse = 'Apply inverse Vigenère cipher...';
  SMenuTransformVigenereInverseHint = 'Performs the inverse Vigenère cipher on the selected text.';
  SCaesarNTitle = 'Caesar Cipher';
  SCaesarNText = 'Please enter the parameter of the Caesar cipher:';
  SVigenereTitle = 'Vigenère Cipher';
  SVigenereText = 'Please enter the parameter of the Vigenère cipher:';
  SMenuNoBookmarksSetParen = '(No bookmarks set.)';
  SMenuClearAllBookmarks = 'Clear all';
  SMenuClearAllBookmarksHint = 'Clears all bookmarks.';
  SMenuUseNoClass = 'No class';
  SMenuUseNoClassHint = 'Assigns no class to the current line.';

  SBookmarkDescriptionInvalid = 'Invalid bookmark';
  SBookmarkDescription = 'Bookmark %d (%d, %d)';
  SBookmarkDescriptionEmpty = 'Bookmark %d (empty)';

  SMenuCopyImage = 'Copy image';
  SMenuCopyImageHint = 'Copies the image to the clipboard.';
  SMenuDeleteImage = 'Remove image';
  SMenuDeleteImageHint = 'Removes the image.';
  SMenuChangeImage = 'Change image...';
  SMenuChangeImageHint = 'Replaces the image with a different one.';

  SMenuRulerProperties = 'Properties';
  SMenuRulerPropertiesHint = 'Displays or modifies the ruler properties.';

  SMoveHere = 'Move here';
  SCopyHere = 'Copy here';
  SCancel = 'Cancel';

  SFPSlowTitle = 'Text Editor Control';
  SFPSlowText = 'The formatting processor used for interactive formatting (syntax highlighting) appears to be slow. Do you want to disable interactive formatting?';
  SRestoreWrapAtText = 'Do you want to restore the default wrap at characters?';
  SRestoreWrapAtCaption = 'TTextEditor control';

  SNotifyDragMove = 'Drag to move the selection to the new position. (Press Esc to abort.)';
  SNotifyDragCopy = 'Drag to copy the selection to the new position. (Press Esc to abort.)';
  SNotifyReadOnlyError = 'You cannot edit a read-only line.';
  SNotifyInputError = 'Invalid operation.';
  SNotifyPrinting = 'Printing...';
  SNotifyScrollMode = 'Scroll mode';
  SNotifyScript = 'Script running... (Press Esc to abort.)';
  SNotifyMultiCharSelect = 'Press F9 to show a list of related characters.';
  SNotifyReadOnlyMode = 'Read-only mode';
  SNotifyMultiCaretMode = 'Multi-caret mode. (Press Esc to abort.)';

  SReadOnlyErrorText = 'You cannot edit a read-only line.';
  SReadOnlyErrorTitle = 'Read only';

  SUndoSelectionTransformed = 'Selection transformed (%s)';
  SUndoTextTransformed = 'Text transformed (%s)';
  SUndoLineCleared = 'Line cleared';
  SUndoSelectionCleared = 'Selection cleared';
  SUndoFirstPost = 'First version since undo history was removed';
  SUndoTyped = 'Typed';
  SUndoInitialText = 'Initial text';
  SUndoCutToClipboard = 'Cut to clipboard';
  SUndoTrimRight = 'Lines trimmed to the right';
  SUndoTextCleared = 'Document cleared';
  SUndoBookmarksCleared = 'Bookmarks cleared';
  SUndoWordWrap = 'Word wrap performed';
  SUndoTextInserted = 'Text inserted';
  SUndoTextSurrounded = 'Selection surrounded by "%s" and "%s"';
  SUndoReplacedAll = 'Replaced %d instance(s) of "%s" by "%s"';
  SUndoUnicodeReplacedCodepoint = 'Unicode codepoint replaced by character';
  SUndoLinesSwapped = 'Lines swapped';
  SUndoMouseMove = 'Selection moved using mouse';
  SUndoMouseCopy = 'Selection copied using mouse';
  SUndoMouseMoveExtSrc = 'External text moved here using mouse';
  SUndoMouseCopyExtSrc = 'External text copied here using mouse';
  SUndoMouseMoveExtDst = 'Selection moved to external document';
  SUndoNewFile = 'Document created';
  SUndoBookmarkCleared = 'Bookmark cleared';
  SUndoBookmarkAdded = 'Bookmark added';
  SUndoIndentIncreased = 'Indent increased';
  SUndoDocumentLoaded = 'Document loaded';
  SUndoPastedFromClipboard = 'Pasted from clipboard';
  SUndoIndentRemoved = 'Indent removed';
  SUndoIndentDecreased = 'Indent decreased';
  SUndoReverted = 'Reverted to version #%d from %s';
  SUndoSorted = 'Sorted lines';
  SUndoMadeLinesUnique = 'Removed duplicates, made lines unique';
  SUndoScript = 'Script executed';
  SUndoScriptAbort = 'Script partially executed before being aborted';
  SUndoCliHistory = 'Command-line history item recalled';
  SUndoFillWithChar = 'Filled selection with character %s';
  SUndoLinesTruncated = 'Lines truncated';
  SUndoLinesFiltered = 'Lines filtered';
  SUndoAutoReplaced = 'Auto-replaced code';

  SDefaultPrintJobTitle = 'Text file';
  SDefaultFileName = 'Untitled file';

  STransformNameUpperCase = 'upper case';
  STransformNameLowerCase = 'lower case';
  STransformNameInvertCase = 'invert case';
  STransformNameCamelCase = 'camel case';
  STransformNameSentenceCase = 'sentence case';
  STransformNameReverse = 'reverse text';
  STransformNameRot13 = 'ROT-13';
  STransformNameCaesarN = 'Caesar %d';
  STransformNameVigenere = 'Vigenère';

  SNoInteractiveFormattingParen = '(No interactive formatting)';

  SHTMLExportFileName = 'File name';
  SHTMLExportDate = 'Date exported';
  SHTMLExportTime = 'Time exported';
  SHTMLExportFP = 'Formatting processor';

  SInvalidOpMsgSingleLineModeInsertLine = 'Cannot insert line in single-line mode.';
  SInvalidOpMsgInvalidChrIndex = 'TTextFile: Invalid character index %d.';
  SNoLineComparer = 'Cannot sort because no line comparison function has been assigned.';
  SIllegalLineComparer = 'Illegal line-comparing function assigned.';

const
  FORMATETC_UNICODETEXT: TFormatEtc =
    (
      cfFormat: CF_UNICODETEXT;
      ptd: nil;
      dwAspect: DVASPECT_CONTENT;
      lindex: -1;
      tymed: TYMED_HGLOBAL
    );

type
  TChangeType = (ctNone, ctFile, ctLineRange, ctBlock, ctLine, ctLineFrom,
    ctChar, ctTwoChars, ctPostFile);
  TChangeRecord = record
    ChangeType: TChangeType;
    Data1, Data2, Data3, Data4: integer;
  { -      -      -      -      ctNone      }
  { -      -      -      -      ctFile      }
  { y1,    y2     A      -      ctLineRange }
  { ymin   ymax   xmin   xmax   ctBlock     }
  { y      -      -      -      ctLine      }
  { y      x      -      -      ctLineFrom  }
  { y      x      -      -      ctChar      }
  { y1     x1     y2     x2     ctTwoChars  }
  { n      -      -      -      ctPostFile  }
  { A = 0 // unspecified cause              }
  {     1 // caused by a single VK_RETURN   }
  {       // on y1                          }
  {     2 // caused by removal of #13#10 at }
  {       // the end of y1                  }
  { Unused parameters MUST be zero.         }
  end;
  TChangeRecords = array of TChangeRecord;

function MakeChangeRecord(ChangeType: TChangeType; Data1, Data2, Data3, Data4: integer): TChangeRecord;

const
  NO_CHANGE_RECORD: TChangeRecord = (ChangeType: ctNone; Data1: 0; Data2: 0; Data3: 0; Data4: 0);
  FILE_CHANGE_RECORD: TChangeRecord = (ChangeType: ctFile; Data1: 0; Data2: 0; Data3: 0; Data4: 0);

type
  TChangeEvent = procedure(Sender: TObject; ChangeType: TChangeType; Data1,
    Data2, Data3, Data4: integer) of object;
  // Caution! A line that has changed ***need not exist*** in the new text file!
  // Still, the visual owner component may need to clear a previously occupied line on the screen.

function ChangeUnion(const ChangeRecord1, ChangeRecord2: TChangeRecord): TChangeRecord;

type
  TSelectionType = (stLineBased, stBlock);

  TCaretPos = class
  private
    FCaretPos: TPoint;
    FSelStartPos: TPoint;
    FSelectionType: TSelectionType;
    FOnChange: TNotifyEvent;
    FOnSelChange: TChangeEvent;
    FSavedSelExtent: TChangeRecord;
    procedure SetCaretPos(const Value: TPoint);
    procedure Changed;
    procedure SelChanged(ChangeType: TChangeType; Data1, Data2, Data3, Data4: integer);
    procedure SelRemoved;
    procedure SetSelEndPos(const Value: TPoint);
    procedure SetSelectionType(const Value: TSelectionType);
    function GetSelExtent(ACaretPos, ASelEndPos: TPoint; ASelectionType: TSelectionType): TChangeRecord;
    procedure SaveSelExtent; inline;
    function GetFirstPoint: TPoint;
    function GetLastPoint: TPoint;
  public
    constructor Create;
    procedure Reset;
    property Data: TPoint read FCaretPos;
    property SelEnd: TPoint read FSelStartPos;
    property FirstPoint: TPoint read GetFirstPoint;
    property LastPoint: TPoint read GetLastPoint;
    property X: Integer read FCaretPos.X;
    property Y: Integer read FCaretPos.Y;
    procedure SetPoint(X, Y: integer; SelEnd: boolean = false); overload;
    procedure SetPoint(Point: TPoint; SelEnd: boolean = false); overload; inline;
    procedure SetX(X: integer; SelEnd: boolean = false);
    procedure SetY(Y: integer; SelEnd: boolean = false);
    procedure CreateSelection(const ASelStart, ASelEnd: TPoint;
      const ASelectionType: TSelectionType = stLineBased);
    procedure RemoveSelection;
    property SelectionType: TSelectionType read FSelectionType write SetSelectionType default stLineBased;
    procedure GetSelBdry(const PointA, PointB: TPoint; out FirstPoint, SecondPoint: TPoint); overload;
    procedure GetSelBdry(out FirstPoint, SecondPoint: TPoint); overload;
    procedure InternalPush(Size: integer; LastLine: boolean = true);
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property OnSelChange: TChangeEvent read FOnSelChange write FOnSelChange;
  end;

  TEditMode = (emText, emConsole, emReadOnly);
  EReadOnlyViolation = class(Exception);

  TAutoReplaceItem = record
    Token,
    ReplacedValue: string;
  end;
  TAutoReplaceItems = array of TAutoReplaceItem;

const
  NUM_BOOKMARKS = 17;
  INTERNAL_BOOKMARK = -1;

type
  TBookmarkList = array[-1..NUM_BOOKMARKS - 1] of TPoint;

const
  EMPTY_BOOKMARK: TPoint = (X: -1; Y: -1);

type
  TUndoDataItem = record
    Text: string;
    Classes: string;
    CaretPos: TPoint;
    SelStartPos: TPoint;
    SelType: TSelectionType;
    Time: TDateTime;
    Comment: string;
    UID: integer; { RichEdit UNDONAMEID }
    Bookmarks: TBookmarkList;
  end;
  TUndoData = array of TUndoDataItem;

  THistoryManager = class
  public const
    UNDO_SIGNATURE = $4F444E55;
    UNDO_SIGNATURE_ITEM = $4D455449;
  strict private const
    DEFAULT_MAX_UNDO_SIZE = 536870912;
    HISTORY_ALLOC_BY = 1024;
  strict private
    FUndoData: TUndoData;
    FMaxSize: integer;
    FActualLength: integer;
    FSize: integer;
    FFirstItem: integer;
    FHistoryIndex: integer;
    function GetLength: integer;
    function SizeOfItem(ItemIndex: integer): integer;
    procedure SetMaxSize(Value: integer);
    procedure ClearItem(ItemIndex: integer);
    function RemoveFirstItem: boolean;
    procedure TrimLeft;
    function GetUndoData(Index: integer): TUndoDataItem;
    function GetLastItem: integer;
    procedure Revert;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Add(AUndoDataItem: TUndoDataItem); overload;
    procedure Add(const AText: string; const AClasses: string;
      const ACaretPos, ASelStartPos: TPoint; ASelType: TSelectionType;
      const ATime: TDateTime; const AComment: string;
      const ABookmarks: TBookmarkList; AUID: integer = 0); overload;
    procedure Clear;
    function Undo(out UndoData: TUndoDataItem): boolean;
    function CanUndo: boolean;
    function Redo(out UndoData: TUndoDataItem): boolean;
    function CanRedo: boolean;
    function GotoVersion(Index: integer; out UndoData: TUndoDataItem): boolean;
    procedure CreateDataStream(out Data: pointer; out Len: UInt64);
    procedure SaveToStream(AStream: TStream);
    procedure LoadFromStream(AStream: TStream);
    procedure LoadFromBuffer(const Data: pointer; const Len: UInt64);
    property UndoData[Index: integer]: TUndoDataItem read GetUndoData;
    property Sizes[Index: integer]: integer read SizeOfItem;
    property Count: integer read GetLength;
    property Size: integer read FSize;
    property FirstItem: integer read FFirstItem;
    property LastItem: integer read GetLastItem;
    property HistoryIndex: integer read FHistoryIndex;
    property MaxSize: integer read FMaxSize write SetMaxSize default DEFAULT_MAX_UNDO_SIZE;
  end;

  TFindQuery = record
    SearchString: string;
    MatchCase: boolean;
    MatchWord: boolean;
    Linebreak: boolean;
    UCBlock: integer;
  end;

const
  FQ_NULL = 0;
  FQ_NONASCII = -1;
  FQ_CONTROL = -2;
  FQ_NONCHAR = -3;
  FQ_MIN = -3;

function MakeFindQuery(const ASearchString: string; AMatchCase, AMatchWord, ALinebreak: boolean): TFindQuery; overload;
function MakeFindQuery(UCBlock: integer): TFindQuery; overload;

type
  TTextSpan = record
    A, B: TPoint;
  end;

  TFindData = array of TTextSpan;

  TFileStatisticsFlags = set of (fsfCharTypes, fsfLines, fsfWords, fsSourceCode,
    fsCaseSensitive);

const
  FILE_STAT_ALL = [fsfCharTypes, fsfLines, fsfWords];
  FILE_STAT_CHARS = [fsfCharTypes];
  FILE_STAT_LINES = [fsfLines];
  FILE_STAT_WORDS = [fsfWords];

const
  LINE_CONTROL_CLASS = #$FFFF {noncharacter};
  LINE_CONTROL_PREFIX = #$FFFC#$FFFF {object replacement char + noncharacter};
  LINE_CLASS_INDICATOR = #$FFFE {noncharacter};

type
  TFileStatistics = record
    Flags: TFileStatisticsFlags;
    NumLines: integer;
    NumChars: integer;
    NumLetters: integer;
    NumDigits: integer;
    NumWhitespace: integer;
    NumPunctuation: integer;
    MaxLineLength: integer;
    AvgLineLength: real;
    LineLengthDistr: array of integer;
    NumWords: integer;
    MaxWordLength: integer;
    AvgWordLength: real;
    WordLengthDistr: array of integer;
    procedure Clear;
  end;

  TCharTestFunction = function(C: char): boolean;

  TLineChangeType = (lctAll, lctAppend, lctChangeFrom);
  TLineChangeEvent = procedure(Sender: TObject; ChangeType: TLineChangeType; From: integer) of object;

  TControlEvent = procedure(Sender: TObject; ControlID: integer) of object;
  TLineEvent = procedure(Sender: TObject; LineIndex: integer) of object;

  TGetControlTextEvent = procedure(Sender: TObject; LineIndex: integer; var ControlText: string) of object;

  TChrTransformFunc = reference to function(C: char): char;
  TTextTransformFunc = reference to function(const AText: string): string;

function ChrUpperCase(C: char): char;
function ChrLowerCase(C: char): char;
function ChrInvertCase(C: char): char;
function ChrROT13(C: char): char;
function ChrCaesar(N: integer): TChrTransformFunc;
function TxtVigenère(const Key: string; decode: boolean = false): TTextTransformFunc;
function TxtCamelCase(const AText: string): string;
function TxtSentenceCase(const AText: string): string;
function ReverseText(const AText: string): string;

const
  UNICODE_RETURN_SYMBOL = #$23CE;
  UNICODE_RETURN_SYMBOL_ALTERNATIVE = #$21B5;

const
  DEFAULT_WRAP_AT = #$9#$20#$1680#$2000#$2001#$2002#$2003#$2004#$2005#$2006 +
   #$2008#$2009#$200A#$205F#$3000#$180E#$200B#$200C#$200D#$002D#$00AD#$2010 +
   #$2013#$2014';:@?=>)]}';

type
  TEditorState = class
  private var
    FValid: boolean;
    FFormattingProcessorClassName: string;
    FScrollPos: TPoint;
    FMultiSize: boolean;
    FOverwrite: boolean;
    FHiddenChrs: boolean;
    FRulerVisible: boolean;
    FZoomLevel: integer;
    FFPCache: PByte;
    FFPCacheLen: integer;
  public
    constructor Create;
    destructor Destroy; override;
    property Valid: boolean read FValid write FValid;
    property FormattingProcessor: string read FFormattingProcessorClassName
      write FFormattingProcessorClassName;
    property ScrollPos: TPoint read FScrollPos write FScrollPos;
    property MultiSize: boolean read FMultiSize write FMultiSize;
    property Overwrite: boolean read FOverwrite write FOverwrite;
    property HiddenChrs: boolean read FHiddenChrs write FHiddenChrs;
    property RulerVisible: boolean read FRulerVisible write FRulerVisible;
    property ZoomLevel: integer read FZoomLevel write FZoomLevel;
    property FPCache: PByte read FFPCache write FFPCache;
    property FPCacheLen: integer read FFPCacheLen write FFPCacheLen;
  end;

  TLineComparer = function(const LineA, LineB: string): integer;

  PFilterOptions = ^TFilterOptions;
  TFilterOptions = record
    RemoveMatchingLines: boolean; // if not, remove all lines that do NOT match the criteria
    Contains,
    StartsWith,
    EndsWith: string;
    MatchCase: boolean;
  end;

  TPointArray = array of TPoint;

  TWordFreqItem = class
    Count: Int64;
    InNaturalCase: string;
    IsLower: boolean;
    constructor Create(AInNaturalCase: string; AIsLower: Boolean = False;
      ACount: Int64 = 1);
  end;

  TWordFreqDict = TObjectDictionary<string, TWordFreqItem>;

  TTextFile = class
  private var
    FFindData: TFindData; // TTextEditor needs fast access from 20160728
  strict private const
    TEXTFILE_SIGNATURE: cardinal = $53455452;
    TEXTFILE_SIGNATURE_FPCACHE: cardinal = $41435046;
    TEXTFILE_SIGNATURE_UNDO: cardinal = $4F444E55;
  strict private type
    TFixedString = record
      strict private const
        MAXLEN = 1024;
      public
        Data: array[0..MAXLEN] of char;
        class operator Implicit(const S: string): TFixedString;
        class operator Implicit(const S: TFixedString): string;
    end;
    TStreamHeader = record
      Signature: cardinal;
      CaretPos,
      SelEndPos: TPoint;
      SelectionType: TSelectionType;
      EditMode: TEditMode;
      Modified: boolean;
      FileName: TFixedString;
      LineCount: integer;
      Bookmarks: TBookmarkList;
      ScrollPos: TPoint;
      MultiSize,
      Overwrite,
      HiddenChars,
      RulerVisible: boolean;
      ZoomLevel: integer;
      Encoding: TTextFileFormatInfo;
      RecentlyOpened: boolean;
      StrictReadOnly: boolean;
      UseLineClasses: boolean;
      FPClassName: TFixedString;
      // array[0..LineCount - 1] of record LineTxt, LineClass: string end;
    end;
  strict private var
    FLines: array of string;
    FClasses: array of string;
    FCaretPos: TCaretPos;
    FOnCaretPosChange: TNotifyEvent;
    FOnCaretPosSelChange: TChangeEvent;
    FOnChange: TChangeEvent;
    FCaretAfterEOL: boolean;
    FOnInputError: TNotifyEvent;
    FOnReadOnlyError: TNotifyEvent;
    FAutoIndent: boolean;
    FIndentSize: integer;
    FEditMode: TEditMode;
    FModified: boolean;
    FFileName: TFileName;
    FOnModified: TNotifyEvent;
    FAutoReplaceItems: TAutoReplaceItems;
    FHistoryManager: THistoryManager;
    FFindDataActualLength: integer;
    FOnFindDataClear: TNotifyEvent;
    FFindResultValid: boolean;
    FFindQuery: TFindQuery; // stored by Find, used by ReplaceAll immediately afterwards
    FSingleLine: boolean;
    FOnLineChange: TLineChangeEvent;
    FOnControlRemoved: TControlEvent;
    FOnLineClassChange: TLineEvent;
    FControlAware: boolean;
    FOnGetControlText: TGetControlTextEvent;
    FBookmarks: TBookmarkList;
    FOnBookmarksMoved: TNotifyEvent;
    FWrapAt: string;
    FEditorState: TEditorState;
    FLineComparer: TLineComparer;
    FSortReverseOrder: boolean;
    FDesiredCol: integer; {in chars}
    FPreserveDesiredCol: boolean;
    FMultiAddLineMode: boolean;
    FEncoding: TTextFileFormatInfo;
    FRecentlyOpened: boolean;
    FOnLockVisualUpdates,
    FOnUnlockVisualUpdates: TNotifyEvent;
    FStrictReadOnly: boolean;
    FUseLineClasses: boolean;
    function GetLine(Index: Integer): string;
    procedure SetLine(Index: Integer; const Value: string);
    function GetClass(Index: Integer): string;
    procedure SetClass(Index: Integer; const Value: string);
    function GetLineCount: integer; inline;
    function GetPhysicalLineWidth(Index: Integer): integer; inline;
    function GetVirtualLineWidth(Index: Integer): integer; inline;
    function GetMaxLineWidth: integer;
    function GetChar(Y, X: Integer): char; overload;
    function GetChar(APoint: TPoint): char; overload; inline;
    procedure CaretPosChange(Sender: TObject);
    procedure CaretPosSelChange(Sender: TObject; ChangeType: TChangeType; Data1,
      Data2, Data3, Data4: integer);
    procedure Changed(ChangeType: TChangeType; Data1: integer = 0; Data2: integer = 0;
      Data3: integer = 0; Data4: integer = 0);
    procedure PostFileChanged(const NumLines: integer);
    procedure InternalAddLine(const ALine: string; const AClassName: string);
    procedure InternalAddLines(const NumLines: integer);
    procedure InternalInsertLine(const LineIndex: integer; const ALine: string; const AClassName: string);
    procedure InternalInsertLines(const LineIndex: integer; const NumLines: integer);
    procedure InternalDeleteLine(const LineIndex: integer); inline;
    procedure InternalDeleteLines(const LineIndex: integer; const NumLines: integer);
    procedure IssueInputError;
    function GetIndentOnReturn(out Len: integer): string; overload;
    function TextIsMultiline(const AText: string): boolean;
    function GetFirstLine(const AText: string): string;
    function GetVirtualSpace: string; overload;
    function GetVirtualSpace(LineIndex, Col: integer): string; overload;
    function GetText: string;
    function GetClassesAsText: string;
    procedure SetText(const Value: string); overload;
    procedure SetText(const Value, Classes: string); overload;
    function GetNumCharacters: integer;
    function GetVirtualTextLength: integer;
    function GetPhysicalTextLength: integer;
    function GetClassLength: integer;
    function GetSelText: string;
    procedure InternalZero;
    function GetSelLength: integer;
    procedure SetSelLength(const Value: integer);
    procedure IssueReadOnlyError;
    procedure Modified;
    function PrevChar(const APoint: TPoint): TPoint;
    function NextChar(const APoint: TPoint): TPoint;
    procedure LoadAutoReplaceItems;
    function GetSelStart: integer;
    procedure SetSelStart(const Value: integer);
    procedure InternalClearFindData;
    procedure ClearFindData;
    procedure AddFindData(const A, B: TPoint); overload; inline;
    procedure AddFindData(const A: TPoint); overload; inline;
    procedure EndAddFindData;
    function GetFindData(Index: integer): TTextSpan;
    function GetFindCount: integer;
    procedure ReplaceInLineDiffWidth(const ReplaceText: string);
    procedure ReplaceInLineSameWidth(const ReplaceText: string);
    procedure ReplaceMultilineDiffWidth(const ReplaceText: string);
    procedure ReplaceMultilineSameWidth(const ReplaceText: string);
    function CompareFindQuery(const AFindQuery: TFindQuery): boolean;
    function HasQueryResult(const AFindQuery: TFindQuery): boolean;
    function GetSingleLineText: string;
    procedure SetSingleLine(const Value: boolean);
    procedure SetCaretAfterEOL(const Value: boolean);
    procedure LineArrayChanged;
    function IsControlLine: boolean; overload; inline;
    function IsControlLine(LineIndex: integer): boolean; overload; inline;
    procedure LineClassChanged(LineIndex: integer);
    function GetCurrentClass: string;
    function GetControlText(LineIndex: integer): string;
    function GetDecoratedControlText(LineIndex: integer): string; inline;
    function GetEmptyBookmarkIndex: integer;
    function GetBookmark(Index: Integer): TPoint;
    function GetBookmarkCount: integer;
    function GetUsedBookmarkCount: integer;
    function GetHasBookmarks: boolean;
    function PushBookmarks(LineIndex, ColIndex: integer; NumChars: integer = 1): boolean; // e.g. InsertChar
    function PushMultiCarets(var ACarets: TPointArray; LineIndex, ColIndex: integer; NumChars: integer = 1): boolean;
    function PushBookmarksInternal(LineIndex: integer; NumChars: integer = 1): boolean; // e.g. RemoveIndent
    function PushBookmarksEx(FirstLine, LastLine: integer; NumChars: integer = 1): boolean; // e.g. AddIndent
    function QushBookmarks(LineIndex, ColIndex: integer): boolean; // e.g. Backspace #13#10
    function QushBookmarksEx(SelectionType: TSelectionType; // e.g. ClearSelection
      const FirstPoint, SecondPoint: TPoint): boolean;
    function RushBookmarks(const FirstPoint: TPoint): boolean; // e.g. Return
    function RushBookmarksInternal(const FirstPoint: TPoint): boolean; // e.g. Return
    function RushBookmarksEx(const FirstPoint, SecondPoint: TPoint): boolean; // e.g. InsertText
    function SushBookmarks(FirstLine, SecondLine: integer; Silent: boolean = false): boolean; // e.g. SwapLines
    function TushBookmarks(Line: integer; NumLines: integer = 1): boolean; // e.g. InsertLine
    function TushBookmarksInternal(Line: integer; NumLines: integer = 1): boolean; // e.g. InsertLine
    function DeleteBookmarksOnLine(Line: integer): boolean;
    procedure BookmarksMoved;
    procedure InternalSwapLines(FirstLine, SecondLine: integer;
      BookmarkAware: boolean = true);
    procedure SortRecursive(AFirstLine, ALastLine: integer; BookmarkAware: boolean = true);
    procedure SetChar(Y, X: Integer; const Value: char);
    procedure IntersectFindDataWithSelection;
    procedure ApplyUndoRecord(const UndoData: TUndoDataItem);
    procedure LockVisualUpdates;
    procedure UnlockVisualUpdates;
    function LineMatches(LineIndex: integer;
      const ACriteria: TFilterOptions): boolean;
    function GetAutoReplaceItem(Index: integer): TAutoReplaceItem;
    function GetAutoReplaceItemCount: integer;
    procedure SanitizeSelection;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    function GetIndexOfPoint(const APoint: TPoint): integer;
    function GetPhysicalIndexOfPoint(const APoint: TPoint): integer; { physical in the sense that #13#10 is included; controls are still 1 char }
    function GetPhysicalPhysicalIndexOfPoint(const APoint: TPoint): integer; { physical in both senses }
    function GetPointOfIndex(const Index: integer): TPoint;
    function CharacterExists(Y, X: integer): boolean; overload; inline;
    function CharacterExists(APoint: TPoint): boolean; overload; inline;
    function CharacterExistsEx(Y, X: integer): boolean; overload; inline;
    function CharacterExistsEx(APoint: TPoint): boolean; overload; inline;
    function ValidCaretPos(APoint: TPoint): boolean; inline;
    function AtEOL: boolean; inline;
    function AtOrBeyondEOL: boolean; inline;
    function BeyondEOL: boolean; inline;
    function AtEOF: boolean; inline;
    function AtOrBeyondEOF: boolean; inline;
    function AtLastLine: boolean; inline;
    function AtSOF: boolean; inline;
    function CurrentLine: string;
    function LineToRight: string;
    function LineToLeft: string;
    procedure GotoSOF(Selection: boolean = false);
    procedure GotoEOF(Selection: boolean = false);
    procedure GotoBottomRight(Selection: boolean = false);
    procedure AddLine(const ALine: string; const AClassName: string); overload;
    procedure AddLine(const ALine: string); overload;
    procedure BeginAddLine;
    procedure EndAddLine;
    procedure InsertLine(const ALine: string; const AClassName: string; LineIndex: integer); overload;
    procedure InsertLine(const ALine: string; LineIndex: integer); overload;
    procedure InsertChar(const AChar: char; const Overwrite: boolean = false);
    procedure MultiInsertChar(var ACarets: TPointArray; const AChar: char; const Overwrite: boolean = false);
    procedure Backspace(Word: boolean = false);
    procedure MultiBackspace(var ACarets: TPointArray);
    procedure Delete(Word: boolean = false);
    procedure Left(Word: boolean = false; Selection: boolean = false; Block: boolean = false);
    procedure Right(Word: boolean = false; Selection: boolean = false; Block: boolean = false);
    procedure Up(Selection: boolean = false; Block: boolean = false);
    procedure Down(Selection: boolean = false; Block: boolean = false);
    procedure Return;
    procedure Home(AFile: boolean = false; Selection: boolean = false);
    procedure KEnd(AFile: boolean = false; Selection: boolean = false);
    function HasSelection: boolean; inline;
    function SelectionIsMultiline: boolean; inline;
    procedure ClearSelection;
    function PrevWordBoundary(Point: TPoint): integer; overload; inline;
    function NextWordBoundary(Point: TPoint): integer; overload; inline;
    function PrevWordBoundary(Y, X: integer): integer; overload;
    function NextWordBoundary(Y, X: integer): integer; overload;
    function PrevWordBoundary: integer; overload;
    function NextWordBoundary: integer; overload;
    function GetIndent(LineIndex: integer): integer; overload;
    function GetIndent: integer; overload;
    function LineIsEmpty(const LineIndex: integer): boolean;
    procedure InsertText(const AText: string);
    procedure MultiInsertText(var ACarets: TPointArray; const AText: string);
    procedure InsertTextAsBlock(const AText: string);
    procedure SurroundText(const APrefix, APostfix: string);
    procedure CutToClipboard;
    procedure CopyToClipboard;
    function PasteFromClipboard: boolean;
    function PasteFromClipboardAsBlock: boolean;
    procedure ClearLine(LineIndex: integer); overload;
    procedure ClearLine; overload;
    function SwapLines(FirstLine, SecondLine: integer): boolean;
    function SwapLinesAbove: boolean;
    function SwapLinesBelow: boolean;
    function ReplaceCodepoint: boolean;
    function IsCharInRgn(X, Y: integer; SelectionType: TSelectionType; const FirstPoint, SecondPoint: TPoint): boolean; overload;
    function IsCharInRgn(const Point: TPoint; SelectionType: TSelectionType; const FirstPoint, SecondPoint: TPoint): boolean; overload; inline;
    function IsCharSel(const X, Y: integer): boolean; overload;
    function IsCharSel(const Point: TPoint): boolean; overload; inline;
    function IsCharFound(const X, Y: integer): boolean;
    procedure SelectAll;
    procedure SelectNone;
    procedure SelectAllNone;
    function AllSelected: boolean;
    function GetWordBoundary(const Point: TPoint; out StartPos, EndPos: integer; PascalIdent: boolean = false): boolean; overload;
    function GetWordBoundary(out StartPos, EndPos: integer; PascalIdent: boolean = false): boolean; overload;
    function GetWord(const Point: TPoint; PascalIdent: boolean = false): string; overload;
    function GetWord(PascalIdent: boolean = false): string; overload;
    function GetURLAtCaret(out AURL: string): boolean;
    function SelectWord: boolean;
    procedure SelectLines(const ALineA, ALineB: integer);
    procedure SelectLine(const ALineIndex: integer); overload;
    procedure SelectLine; overload;
    procedure NewFile;
    procedure NewFileAndInitUndo;
    procedure SaveToFile(const FileName: TFileName; TrimRight: boolean = false;
      AExport: boolean = false);
    procedure LoadFromFile(const FileName: TFileName; Encoding: TEncoding;
      ClassAware: boolean = false);
    procedure LoadFromFileAndInitUndo(const FileName: TFileName; Encoding: TEncoding);
    procedure AddIndent;
    procedure RemoveIndent;
    procedure RemoveAllIndent;
    function CanAutoReplace(out StartPos, Index: integer): boolean;
    procedure DoAutoReplace(const StartPos, Index: integer);
    function AutoReplace: boolean;
    function MatchBracket(const BracketPoint: TPoint): TPoint;
    procedure AddUndoRecord(const AComment: string; UID: UNDONAMEID); overload;
    procedure AddUndoRecord; overload;
    procedure ClearUndoHistory;
    function CanUndo: boolean;
    function Undo: boolean;
    function CanRedo: boolean;
    function Redo: boolean;
    function GotoHistoryVersion(Index: integer): boolean;
    function Find(AFindData: TFindQuery; AInternal: boolean = false): integer;
    function ReplaceAll(const ReplaceText: string; SelOnly: boolean = false): integer;
    function NumCharsOfType(CharTestFunction: TCharTestFunction): integer;
    function GetFileStatistics(AFileStatisticsFlags: TFileStatisticsFlags = FILE_STAT_ALL;
      AWordFreqs: TWordFreqDict = nil): TFileStatistics;
    function GetUnicodeBlockStatistics: TIntegerArray;
    function GetControlCharCount: integer;
    function GetNoncharacterCount: integer;
    function LineExists(LineIndex: integer): boolean; inline;
    function DeleteControlAtLine(const LineIndex: integer): boolean;
    procedure TrimRight;
    procedure ClearBookmarks;
    procedure AddBookmark(AIndex: integer; const APoint: TPoint); overload;
    procedure AddBookmark(AIndex: integer); overload;
    function AddBookmark(const APoint: TPoint): integer; overload;
    function AddBookmark: integer; overload;
    function GotoBookmark(AIndex: integer): boolean;
    function RemoveGhostBookmarks: boolean;
    function ChrTransform(Transformation: TChrTransformFunc): boolean;
    procedure ChrTransformText(Transformation: TChrTransformFunc);
    function FillWithChar(const AChar: char): boolean;
    property CaretPos: TCaretPos read FCaretPos;
    property Lines[Index: Integer]: string read GetLine write SetLine;
    property Classes[Index: Integer]: string read GetClass write SetClass;
    property PhysicalLineWidths[Index: Integer]: integer read GetPhysicalLineWidth;
    property VirtualLineWidths[Index: Integer]: integer read GetVirtualLineWidth;
    property Character[Y, X: Integer]: char read GetChar write SetChar;
    function UnsafeGetChar(Y, X: integer): char; inline;
    function IsWrappable(const AChar: char): boolean; inline;
    procedure FindWhereToWrap(ALineIndex: integer; MaxLength: integer;
      var AWrapList: TIntegerDynArray);
    procedure WordWrap(ALineLength: integer = 80; ANice: boolean = true;
      AChr: char = #0);
    function Sort(AFirstLine, ALastLine: integer; BookmarkAware: boolean): boolean; overload;
    function Sort(BookmarkAware: boolean): boolean; overload;
    function SortSelection(BookmarkAware: boolean): boolean;
    property LineComparer: TLineComparer read FLineComparer write FLineComparer;
    property SortReverseOrder: boolean read FSortReverseOrder write FSortReverseOrder default false;
    function MakeLinesUnique: boolean;
    procedure TruncateAt(AFirstLine, ALastLine, AIndex: integer;
      AChar: char = #0; PreserveChar: boolean = false; AReverse: boolean = false);
    procedure Filter(const AFilterOptions: TFilterOptions);

    procedure SaveToStream(AStream: TStream);
    procedure CreateDataStream(out Data: pointer; out Len: UInt64);
    procedure LoadFromStream(AStream: TStream);
    procedure LoadFromBuffer(const Data: pointer; const Len: UInt64);

    property MaxLineWidth: integer read GetMaxLineWidth;
    property LineCount: integer read GetLineCount;
    property CaretAfterEOL: boolean read FCaretAfterEOL write SetCaretAfterEOL default true;
    property AutoIndent: boolean read FAutoIndent write FAutoIndent;
    property NumCharacters: integer read GetNumCharacters;
    property VirtualTextLength: integer read GetVirtualTextLength;
    property PhysicalTextLength: integer read GetPhysicalTextLength;
    property PlainText: string read GetText write SetText;
    property SelText: string read GetSelText write InsertText;
    property SelStart: integer read GetSelStart write SetSelStart;
    property SelLength: integer read GetSelLength write SetSelLength;
    property IndentSize: integer read FIndentSize write FIndentSize;
    property EditMode: TEditMode read FEditMode write FEditMode default emText;
    property FileModified: boolean read FModified write FModified default false;
    property FileName: TFileName read FFileName write FFileName;
    property HistoryManager: THistoryManager read FHistoryManager;
    property FindData[Index: integer]: TTextSpan read GetFindData;
    property FindCount: integer read GetFindCount;
    property SingleLine: boolean read FSingleLine write SetSingleLine default false;

    { Setting ControlAware to false while line controls are present will cause undefined
      behaviour. Remove all line controls prior to setting this flag to false. At
      text-editor level and above, use public method DeleteAllLineControls. }
    property ControlAware: boolean read FControlAware write FControlAware default false;

    function Empty: boolean;
    property Bookmarks[Index: Integer]: TPoint read GetBookmark write AddBookmark;
    property BookmarkCount: integer read GetBookmarkCount;
    property UsedBookmarkCount: integer read GetUsedBookmarkCount;
    property HasBookmarks: boolean read GetHasBookmarks;
    property WrapAt: string read FWrapAt write FWrapAt;
    property EditorState: TEditorState read FEditorState write FEditorState;
    property Encoding: TTextFileFormatInfo read FEncoding write FEncoding;
    property RecentlyOpened: boolean read FRecentlyOpened;
    property StrictReadOnly: boolean read FStrictReadOnly write FStrictReadOnly default false;
    property UseLineClasses: boolean read FUseLineClasses write FUseLineClasses default false;

    property AutoReplaceItems[Index: integer]: TAutoReplaceItem read GetAutoReplaceItem;
    property AutoReplaceItemCount: integer read GetAutoReplaceItemCount;

    property OnChange: TChangeEvent read FOnChange write FOnChange;
    property OnCaretPosChange: TNotifyEvent read FOnCaretPosChange write FOnCaretPosChange;
    property OnCaretPosSelChange: TChangeEvent read FOnCaretPosSelChange write FOnCaretPosSelChange;
    property OnFileModified: TNotifyEvent read FOnModified write FOnModified;
    property OnInputError: TNotifyEvent read FOnInputError write FOnInputError;
    property OnReadOnlyError: TNotifyEvent read FOnReadOnlyError write FOnReadOnlyError;
    property OnFindDataClear: TNotifyEvent read FOnFindDataClear write FOnFindDataClear;
    property OnLineChange: TLineChangeEvent read FOnLineChange write FOnLineChange;
    property OnControlRemoved: TControlEvent read FOnControlRemoved write FOnControlRemoved;
    property OnLineClassChange: TLineEvent read FOnLineClassChange write FOnLineClassChange;
    property OnGetControlText: TGetControlTextEvent read FOnGetControlText write FOnGetControlText;
    property OnBookmarksMoved: TNotifyEvent read FOnBookmarksMoved write FOnBookmarksMoved;
    property OnLockVisualUpdates: TNotifyEvent read FOnLockVisualUpdates write FOnLockVisualUpdates;
    property OnUnlockVisualUpdates: TNotifyEvent read FOnUnlockVisualUpdates write FOnUnlockVisualUpdates;
  end;

const
  EDITOR_COMMAND_RIGHT = 1;
  EDITOR_COMMAND_LEFT = 2;
  EDITOR_COMMAND_DOWN = 3;
  EDITOR_COMMAND_UP = 4;
  EDITOR_COMMAND_HOME = 5;
  EDITOR_COMMAND_END = 6;
  EDITOR_COMMAND_PAGE_UP = 7;
  EDITOR_COMMAND_PAGE_DOWN = 8;
  EDITOR_COMMAND_BACKSPACE = 9;
  EDITOR_COMMAND_DELETE = 10;
  EDITOR_COMMAND_CLEAR_SELECTION = 11;
  EDITOR_COMMAND_SELECT_ALL = 12;
  EDITOR_COMMAND_SELECT_NONE = 13;
  EDITOR_COMMAND_SELECT_ALL_NONE = 14;
  EDITOR_COMMAND_SELECT_WORD = 15;
  EDITOR_COMMAND_SELECT_LINE = 16;
  EDITOR_COMMAND_CLEAR_LINE = 17;
  EDITOR_COMMAND_CUT = 18;
  EDITOR_COMMAND_COPY = 19;
  EDITOR_COMMAND_PASTE = 20;
  EDITOR_COMMAND_UNDO = 21;
  EDITOR_COMMAND_REDO = 22;
  EDITOR_COMMAND_CLEAR_UNDO_BUFFER = 23;
  EDITOR_COMMAND_GOTO_SOF = 24;
  EDITOR_COMMAND_GOTO_EOF = 25;
  EDITOR_COMMAND_RETURN = 26;
  EDITOR_COMMAND_CHAR = 27;
  EDITOR_COMMAND_GET_AT_SOF = 28;
  EDITOR_COMMAND_GET_AT_EOL = 29;
  EDITOR_COMMAND_GET_BEYOND_EOL = 30;
  EDITOR_COMMAND_GET_AT_EOF = 31;
  EDITOR_COMMAND_GET_AT_LAST_LINE = 32;
  EDITOR_COMMAND_GET_HAS_SELECTION = 33;
  EDITOR_COMMAND_GET_LINE_NUMBER_0 = 34;
  EDITOR_COMMAND_GET_COL_NUMBER_0 = 35;
  EDITOR_COMMAND_GET_CHR_INDEX = 36;
  EDITOR_COMMAND_GOTO_POINT = 37;
  EDITOR_COMMAND_GOTO_INDEX = 38;
  EDITOR_COMMAND_GET_SEL_LENGTH = 39;
  EDITOR_COMMAND_SET_SEL_LENGTH = 40;
  EDITOR_COMMAND_GET_EDIT_MODE = 41;
  EDITOR_COMMAND_SET_EDIT_MODE = 42;
  EDITOR_COMMAND_GET_SELECTION_MODE = 43;
  EDITOR_COMMAND_SET_SELECTION_MODE = 44;
  EDITOR_COMMAND_GET_OVERWRITE = 45;
  EDITOR_COMMAND_SET_OVERWRITE = 46;
  EDITOR_COMMAND_GET_AUTO_REPLACE = 47;
  EDITOR_COMMAND_SET_AUTO_REPLACE = 48;
  EDITOR_COMMAND_GET_CHAR = 49;
  EDITOR_COMMAND_ADD_INDENT = 50;
  EDITOR_COMMAND_REMOVE_INDENT = 51;
  EDITOR_COMMAND_TRIM_INDENT = 52;
  EDITOR_COMMAND_SWAP_UP = 53;
  EDITOR_COMMAND_SWAP_DOWN = 54;
  EDITOR_COMMAND_GET_AUTO_INDENT = 55;
  EDITOR_COMMAND_SET_AUTO_INDENT = 56;
  EDITOR_COMMAND_GET_CARET_BEYOND_EOL = 57;
  EDITOR_COMMAND_SET_CARET_BEYOND_EOL = 58;
  EDITOR_COMMAND_GET_NUM_CHARACTERS = 59;
  EDITOR_COMMAND_GET_TEXT_SIZE = 60;
  EDITOR_COMMAND_GET_NUM_LINES = 61;
  EDITOR_COMMAND_GET_MAX_WIDTH = 62;
  EDITOR_COMMAND_SCROLL_TO_CARET = 63;
  EDITOR_COMMAND_REPLACE_TOKEN = 64;
  EDITOR_COMMAND_REPLACE_CODEPOINT = 65;
  EDITOR_COMMAND_UPDATE_SCROLLBARS = 66;
  EDITOR_COMMAND_UPDATE_CARET = 67;
  EDITOR_COMMAND_UPDATE_CURSOR = 68;
  EDITOR_COMMAND_REDRAW = 69;
  EDITOR_COMMAND_REDRAW_LINE = 70;
  EDITOR_COMMAND_REDRAW_LINE_RANGE = 71;
  EDITOR_COMMAND_REDRAW_BLOCK = 72;
  EDITOR_COMMAND_GET_MODIFIED = 73;
  EDITOR_COMMAND_SET_MODIFIED = 74;
  EDITOR_COMMAND_NEW = 75;
  EDITOR_COMMAND_CLEAR = 76;
  EDITOR_COMMAND_OPEN = 77;
  EDITOR_COMMAND_SAVE = 78;
  EDITOR_COMMAND_GET_HIDDEN = 79;
  EDITOR_COMMAND_SET_HIDDEN = 80;
  EDITOR_COMMAND_SET_SELECTION = 81;
  EDITOR_COMMAND_GET_MATCH_BRACKETS = 82;
  EDITOR_COMMAND_SET_MATCH_BRACKETS = 83;
  EDITOR_COMMAND_GET_BRACKET_HIGHLIGHT = 84;
  EDITOR_COMMAND_GET_SCROLL_POS_X = 85;
  EDITOR_COMMAND_GET_SCROLL_POS_Y = 86;
  EDITOR_COMMAND_SET_SCROLL_POS = 87;
  EDITOR_COMMAND_REDRAW_CHAR = 88;
  EDITOR_COMMAND_REDRAW_CHARS = 89;
  EDITOR_COMMAND_GET_INDENT = 90;
  EDITOR_COMMAND_SET_INDENT = 91;
  EDITOR_COMMAND_GET_TAB_LENGTH = 92;
  EDITOR_COMMAND_SET_TAB_LENGTH = 93;
  EDITOR_COMMAND_GET_SINGLE_LINE = 94;
  EDITOR_COMMAND_SET_SINGLE_LINE = 95;
  EDITOR_COMMAND_GET_LABEL_MODE = 96;
  EDITOR_COMMAND_SET_LABEL_MODE = 97;
  EDITOR_COMMAND_GET_ELLIPSIS_MODE = 98;
  EDITOR_COMMAND_SET_ELLIPSIS_MODE = 99;
  EDITOR_COMMAND_GET_INPUT_TRANSFORM = 100;
  EDITOR_COMMAND_SET_INPUT_TRANSFORM = 101;
  EDITOR_COMMAND_GET_NUMBERS_ONLY = 102;
  EDITOR_COMMAND_SET_NUMBERS_ONLY = 103;
  EDITOR_COMMAND_GET_PASSWORD_CHAR = 104;
  EDITOR_COMMAND_SET_PASSWORD_CHAR = 105;
  EDITOR_COMMAND_GET_UNICODE_FALLBACK = 106;
  EDITOR_COMMAND_SET_UNICODE_FALLBACK = 107;
  EDITOR_COMMAND_ESCAPE = 108;
  EDITOR_COMMAND_USE_DEFAULT_FALLBACK_FONTS = 109;
  EDITOR_COMMAND_SHOW_BALLOON = 110;
  EDITOR_COMMAND_HIDE_BALLOON = 111;
  EDITOR_COMMAND_SHOW_BALLOON_POS = 112;
  EDITOR_COMMAND_IS_BALLOON_VISIBLE = 113;
  EDITOR_COMMAND_ADJUST_HEIGHT = 114;
  EDITOR_COMMAND_GET_UNDO_LENGTH = 115;
  EDITOR_COMMAND_GET_UNDO_SIZE = 116;
  EDITOR_COMMAND_GET_UNDO_MAX_SIZE = 117;
  EDITOR_COMMAND_SET_UNDO_MAX_SIZE = 118;
  EDITOR_COMMAND_GET_UNDO_FIRST_INDEX = 119;
  EDITOR_COMMAND_GET_UNDO_LAST_INDEX = 120;
  EDITOR_COMMAND_GET_UNDO_POSITION = 121;
  EDITOR_COMMAND_WINDOWS_MESSAGE = 122;
  EDITOR_COMMAND_COPY_ALL = 123;
  EDITOR_COMMAND_FIND = 124;
  EDITOR_COMMAND_GET_FIND_COUNT = 125;
  EDITOR_COMMAND_FIND_NEXT = 126;
  EDITOR_COMMAND_FIND_PREV = 127;
  EDITOR_COMMAND_FIND_FROM_TOP = 128;
  EDITOR_COMMAND_GET_START_OVER = 129;
  EDITOR_COMMAND_SET_START_OVER = 130;
  EDITOR_COMMAND_REPLACE_ALL = 131;
  EDITOR_COMMAND_ADD_UNDO_RECORD = 132;
  EDITOR_COMMAND_POSTTYPE = 133;
  EDITOR_COMMAND_TYPE_TIMER_EMD = 134;
  EDITOR_COMMAND_TYPE_TIMER_DISABLE = 135;
  EDITOR_COMMAND_TYPE_TIMER_DISCONNECT = 136;
  EDITOR_COMMAND_TYPE_TIMER_CONNECT = 137;
  EDITOR_COMMAND_GET_ENABLED = 138;
  EDITOR_COMMAND_SET_ENABLED = 139;
  EDITOR_COMMAND_IS_FOCUSED = 140;
  EDITOR_COMMAND_TRY_FOCUS = 141;
  EDITOR_COMMAND_GET_FIRST_VISIBLE_LINE = 142;
  EDITOR_COMMAND_GET_LAST_VISIBLE_LINE = 143;
  EDITOR_COMMAND_RECOMPUTE_HOR_EXTENT = 144;
  EDITOR_COMMAND_ACTIVATE_CONTROL = 145;
  EDITOR_COMMAND_REMOVE_LINE_CONTROL = 146;
  EDITOR_COMMAND_ADD_LINE_CONTROL = 147;
  EDITOR_COMMAND_ADD_GRAPHICS = 148;
  EDITOR_COMMAND_INSERT_LINE_CONTROL = 149;
  EDITOR_COMMAND_INSERT_GRAPHICS = 150;
  EDITOR_COMMAND_TRIM_RIGHT = 151;
  EDITOR_COMMAND_BOOKMARK_SET_MENU = 152;
  EDITOR_COMMAND_BOOKMARK_GO_MENU = 153;
  EDITOR_COMMAND_BOOKMARK_CLEAR_MENU = 154;
  EDITOR_COMMAND_BOOKMARK_SET = 155;
  EDITOR_COMMAND_BOOKMARK_GO = 156;
  EDITOR_COMMAND_BOOKMARK_CLEAR = 157;
  EDITOR_COMMAND_BOOKMARK_CLEAR_ALL = 158;
  EDITOR_COMMAND_CLASS_MENU = 159;
  EDITOR_COMMAND_CLASS_USE = 160;
  EDITOR_COMMAND_CLASS_REMOVE = 161;
  EDITOR_COMMAND_SET_FP = 162;
  EDITOR_COMMAND_EXPORT_HTML = 163;
  EDITOR_COMMAND_OPEN_URL_AT_CARET = 164;
  EDITOR_COMMAND_SELECT_LINE_INDEX = 165;
  EDITOR_COMMAND_SELECT_LINE_RANGE = 166;
  EDITOR_COMMAND_DISABLE_SCROLL_TO_CARET = 167;
  EDITOR_COMMAND_ENABLE_SCROLL_TO_CARET = 168;
  EDITOR_COMMAND_CREATE_SELECTION = 169;
  EDITOR_COMMAND_CREATE_BLOCK_SELECTION = 170;
  EDITOR_COMMAND_GET_LINE_HIGHLIGHT = 171;
  EDITOR_COMMAND_SET_LINE_HIGHLIGHT = 172;
  EDITOR_COMMAND_REDRAW_RULER = 173;
  EDITOR_COMMAND_REDRAW_RULER_LINE = 174;
  EDITOR_COMMAND_PRINT = 175;
  EDITOR_COMMAND_PRINT_SELECTION = 176;
  EDITOR_COMMAND_SET_PRINT_MARGINS = 177;
  EDITOR_COMMAND_SET_PRINT_WW_OPTIONS = 178;
  EDITOR_COMMAND_PRINT_DIALOG = 179;
  EDITOR_COMMAND_GET_PRINT_VMARGIN = 180;
  EDITOR_COMMAND_GET_PRINT_HMARGIN = 181;
  EDITOR_COMMAND_GET_PRINT_WW_OPTIONS = 182;
  EDITOR_COMMAND_GET_PRINT_WW_CHAR = 183;
  EDITOR_COMMAND_GET_PRINT_WW_COLOR = 184;
  EDITOR_COMMAND_WORDWRAP = 185;
  EDITOR_COMMAND_UPPER_CASE = 186;
  EDITOR_COMMAND_LOWER_CASE = 187;
  EDITOR_COMMAND_INVERT_CASE = 188;
  EDITOR_COMMAND_SEL_UPPER_CASE = 189;
  EDITOR_COMMAND_SEL_LOWER_CASE = 190;
  EDITOR_COMMAND_SEL_INVERT_CASE = 191;
  EDITOR_COMMAND_CAMEL_CASE = 192;
  EDITOR_COMMAND_SENTENCE_CASE = 193;
  EDITOR_COMMAND_SEL_CAMEL_CASE = 194;
  EDITOR_COMMAND_SEL_SENTENCE_CASE = 195;
  EDITOR_COMMAND_SEL_TRANSFORM_MENU = 196;
  EDITOR_COMMAND_ROT13 = 197;
  EDITOR_COMMAND_CAESAR = 198;
  EDITOR_COMMAND_VIGENERE = 199;
  EDITOR_COMMAND_SEL_ROT13 = 200;
  EDITOR_COMMAND_SEL_CAESAR = 201;
  EDITOR_COMMAND_SEL_VIGENERE = 202;
  EDITOR_COMMAND_UPDATE_SCROLL_MODE = 203;
  EDITOR_COMMAND_GET_SCROLL_MODE = 204;
  EDITOR_COMMAND_SORT = 205;
  EDITOR_COMMAND_SORT_ALL = 206;
  EDITOR_COMMAND_SORT_SEL = 207;
  EDITOR_COMMAND_SET_LINE_COMPARER = 208;
  EDITOR_COMMAND_GET_LINE_COMPARER = 209;
  EDITOR_COMMAND_SET_SORT_REVERSE = 210;
  EDITOR_COMMAND_GET_SORT_REVERSE = 211;
  EDITOR_COMMAND_MAKE_LINES_UNIQUE = 212;
  EDITOR_COMMAND_CLI_NEW_PROMPT = 213;
  EDITOR_COMMAND_CLI_WRITELN = 214;
  EDITOR_COMMAND_ABORT_SCRIPT = 215;
  EDITOR_COMMAND_WRITE_INT = 216;
  EDITOR_COMMAND_ABORT_SCRIPT_IF_EOL = 217;
  EDITOR_COMMAND_ABORT_SCRIPT_IF_LL = 218;
  EDITOR_COMMAND_ABORT_SCRIPT_IF_EOF = 219;
  EDITOR_COMMAND_ABORT_SCRIPT_IF_SOF = 220;
  EDITOR_COMMAND_SET_SCRIPT_COUNTER = 221;
  EDITOR_COMMAND_GET_SCRIPT_COUNTER = 222;
  EDITOR_COMMAND_GET_LINE_NUMBER_1 = 223;
  EDITOR_COMMAND_GET_COL_NUMBER_1 = 224;
  EDITOR_COMMAND_WRITE_DATE = 225;
  EDITOR_COMMAND_WRITE_TIME = 226;
  EDITOR_COMMAND_WRITE_DATETIME = 227;
  EDITOR_COMMAND_GET_TICKCOUNT = 228;
  EDITOR_COMMAND_GET_RANDOM_INTEGER = 229;
  EDITOR_COMMAND_FIX_REMOVED_LINE_CONTROLS = 230;
  EDITOR_COMMAND_CLI_HISTORY_UP = 231;
  EDITOR_COMMAND_CLI_HISTORY_DOWN = 232;
  EDITOR_COMMAND_CLI_HISTORY_CLEAR = 233;
  EDITOR_COMMAND_CLI_HISTORY_ADD = 234;
  EDITOR_COMMAND_CLI_GET_HISTORY_LENGTH = 235;
  EDITOR_COMMAND_CLI_GET_HISTORY_INDEX = 236;
  EDITOR_COMMAND_CLI_HISTORY_RECALL = 237;
  EDITOR_COMMAND_BEGIN_ADD_LINES = 238;
  EDITOR_COMMAND_END_ADD_LINES = 239;
  EDITOR_COMMAND_GET_LISTBOX_MODE = 240;
  EDITOR_COMMAND_SET_LISTBOX_MODE = 241;
  EDITOR_COMMAND_WRITE_STRING = 242;
  EDITOR_COMMAND_WRITE_INPUT_DIALOG = 243;
  EDITOR_COMMAND_SET_AS_HYPHEN_ASTERISK_TOGGLE = 244;
  EDITOR_COMMAND_SET_MULTI_CHAR_SELECT = 245;
  EDITOR_COMMAND_GET_MULTI_CHAR_SELECT = 246;
  EDITOR_COMMAND_SET_MULTI_CHAR_REPORT_VIEW = 247;
  EDITOR_COMMAND_GET_MULTI_CHAR_REPORT_VIEW = 248;
  EDITOR_COMMAND_SET_NO_VERIFY_FONT = 249;
  EDITOR_COMMAND_SET_DOUBLE_BUFFERING = 250;
  EDITOR_COMMAND_REPLACE_ALL_IN_SELECTION = 251;
  EDITOR_COMMAND_SET_BITMAP_EFFECT = 252;
  EDITOR_COMMAND_GET_BITMAP_EFFECT = 253;
  EDITOR_COMMAND_SET_DISABLED_EFFECT = 254;
  EDITOR_COMMAND_GET_DISABLED_EFFECT = 255;
  EDITOR_COMMAND_REPEAT = 256;
  EDITOR_COMMAND_REPEAT_EX_SET_NUM = 257;
  EDITOR_COMMAND_REPEAT_EX_SET_COMMAND = 258;
  EDITOR_COMMAND_REPEAT_EX = 259;
  EDITOR_COMMAND_RESTORE_MARGINS = 260;
  EDITOR_COMMAND_FILL_WITH_CHAR = 261;
  EDITOR_COMMAND_PASTE_AS_BLOCK = 262;
  EDITOR_COMMAND_TRUNCATE_AT = 263;
  EDITOR_COMMAND_TRUNCATE_AT_IN_FILE = 264;
  EDITOR_COMMAND_TRUNCATE_AT_IN_SELECTION = 265;
  EDITOR_COMMAND_GET_JUST_OPENED = 266;
  EDITOR_COMMAND_LOAD_DEFAULT_CLASSES = 267;
  EDITOR_COMMAND_BEGIN_VISUAL_UPDATE = 268;
  EDITOR_COMMAND_END_VISUAL_UPDATE = 269;
  EDITOR_COMMAND_SURROUND_SEL = 270;
  EDITOR_COMMAND_FILTER_LINES = 271;
  EDITOR_COMMAND_UPDATE_SPI = 272;
  EDITOR_COMMAND_SET_STRICT_READONLY = 273;
  EDITOR_COMMAND_REMOVE_GHOST_BOOKMARKS = 274;
  EDITOR_COMMAND_CHARACTER_FIND = 275;
  EDITOR_COMMAND_SEL_REVERSE = 276;
  EDITOR_COMMAND_CENTER_ON_SELECTION = 277;

  IMAGE_COMMAND_COPY = 1;
  IMAGE_COMMAND_REMOVE = 2;
  IMAGE_COMMAND_CHANGE = 3;

  RULER_COMMAND_PROPERTIES = 1;

type
  TFontRecord = record
    Size: integer;
    Style: TFontStyles;
    Color: TColor;
    BoxSize: TSize;
  end;

  TClassRecord = record
    Name: string;
    Format: TFontRecord;
  end;

  TClassArray = array of TClassRecord;

function FontRecord(ASize: integer; AStyle: TFontStyles; AColor: TColor): TFontRecord;
function MakeClass(const AName: string; ASize: integer; AStyle: TFontStyles; AColor: TColor): TClassRecord;

type
  TInputTransform = (itNone, itUpperCase, itLowerCase, itSuperscript,
    itSubscript, itCircled, itParenthesized, itFullStop, itDoublyCircled);

  TBalloonPersistence = (bpTime, bpScroll, bpCaretPos, bpModify, bpRemain);
  TBalloonIconKind = (bikNone = TTI_NONE, bikInfo = TTI_INFO,
    bikWarning = TTI_WARNING, bikError = TTI_ERROR, bikInfoLarge = TTI_INFO_LARGE,
    bikWarningLarge = TTI_WARNING_LARGE, bikErrorLarge = TTI_ERROR_LARGE);

  TLineControlRecord = record
    ID: integer;
    Control: TControl;
  end;

  TCSSDeclaration = record
    CSSProperty: string;
    Value: string;
  end;

  TCSSDeclarationBlock = array of TCSSDeclaration;

  TCSSRule = record
    Selector: string;
    Declarations: TCSSDeclarationBlock;
  end;

  TCSSRules = array of TCSSRule;

function MakeCSSDeclaration(const AProperty, AValue: string): TCSSDeclaration;
function MakeCSSOptionalDeclaration(const AUse: boolean; const AProperty, AValue: string): TCSSDeclaration;
function MakeCSSRule(const ASelector: string; const ADeclarations: array of TCSSDeclaration): TCSSRule;
function CSSColor(const AColor: TColor): string;

const
  SC_BLACK = $00000000;
  SC_BLUE = $00FF0000;
  SC_RED = $00000099;
  SC_GREEN = $00008000;
  SC_GRAY = $00999999;
  SC_INTENSE_RED = $000000FF;

type
  TColorScheme = record
    Default,
    Accent1,
    Accent2,
    Accent3,
    Soft,
    Intense: TColor;
  end;

const
  DEFAULT_COLORS: TColorScheme = (Default: SC_BLACK; Accent1: SC_BLUE; Accent2:
    SC_GREEN; Accent3: SC_RED; Soft: SC_GRAY; Intense: SC_INTENSE_RED);

type
  TGetLineWidthEvent = function(ALineIndex: integer): integer of object;
  TGetCharEvent = function(ALineIndex, ACol: integer): char of object;
  TGetLineCountEvent = function: integer of object;
  TGetWordEvent = function(const APoint: TPoint; APascalIdent: boolean = false): string of object;
  TGetWordBoundaryEvent = function(const APoint: TPoint; out SP, EP: integer): boolean of object;

  TFormattingProcessor = class(TComponent)
  strict private
    FUpdateLevel: integer;
    FOnChange: TNotifyEvent;
    FOnGetLineWidth: TGetLineWidthEvent;
    FOnGetChar: TGetCharEvent;
    FOnGetLineCount: TGetLineCountEvent;
    FOnGetWord: TGetWordEvent;
    FOnGetWordBoundary: TGetWordBoundaryEvent;
  strict protected
    procedure Changed;
    function TextLineWidth(ALineIndex: integer): integer; inline;
    function TextChar(ALineIndex, ACol: integer): char; inline;
    function TextLineCount: integer; inline;
    function TextGetWord(const APoint: TPoint; APascalIdent: boolean = false): string; inline;
    function TextGetWordBoundary(const APoint: TPoint; out SP, EP: integer): boolean; inline;
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: integer; ACol: integer; AChar: char;
      var AFontRecord: TFontRecord); virtual; abstract;
    function FileChangeNotification(ChangeType: TChangeType;
      Data1, Data2, Data3, Data4: Integer): TChangeRecord; virtual;
    function GetCSSRules: TCSSRules; virtual; abstract;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): integer; virtual; abstract;
    procedure BeginUpdate;
    procedure EndUpdate;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); virtual; abstract;
    function GetCache(out ACache: PByte): integer; virtual; { Returns size. Returns nil and 0 if not implemented. }
    function RestoreCache(ACache: PByte; ASize: integer): boolean; virtual; { Returns true iff implemented }
    procedure ClearCache; virtual;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property OnGetLineWidth: TGetLineWidthEvent read FOnGetLineWidth write FOnGetLineWidth;
    property OnGetChar: TGetCharEvent read FOnGetChar write FOnGetChar;
    property OnGetLineCount: TGetLineCountEvent read FOnGetLineCount write FOnGetLineCount;
    property OnGetWord: TGetWordEvent read FOnGetWord write FOnGetWord;
    property OnGetWordBoundary: TGetWordBoundaryEvent read FOnGetWordBoundary write FOnGetWordBoundary;
  end;

  TVowelsAndConsonantsFormattingProcessor = class(TFormattingProcessor)
  private const
    DEFAULT_VOWEL_COLOR = SC_RED;
    DEFAULT_CONSONANT_COLOR = SC_GREEN;
    DEFAULT_VOWELS_BOLD = true;
    DEFAULT_CONSONANTS_BOLD = false;
  private const
    CSS_CLASS_VOWEL = 0;
    CSS_CLASS_CONSONANT = 1;

    CSS_CLASS_HIGH = CSS_CLASS_CONSONANT;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FVowelColor,
    FConsonantColor: TColor;
    FVowelsBold: boolean;
    FConsonantsBold: boolean;
    procedure SetConsonantColor(const Value: TColor);
    procedure SetVowelColor(const Value: TColor);
    procedure SetConsonantsBold(const Value: boolean);
    procedure SetVowelsBold(const Value: boolean);
    function IsVowel(const AChar: Char): boolean;
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer; AChar: Char): integer; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property VowelColor: TColor read FVowelColor write SetVowelColor default DEFAULT_VOWEL_COLOR;
    property ConsonantColor: TColor read FConsonantColor write SetConsonantColor default DEFAULT_CONSONANT_COLOR;
    property VowelsBold: boolean read FVowelsBold write SetVowelsBold default DEFAULT_VOWELS_BOLD;
    property ConsonantBold: boolean read FConsonantsBold write SetConsonantsBold default DEFAULT_CONSONANTS_BOLD;
  end;

  TXMLFormattingProcessor = class(TFormattingProcessor)
  private type
    TXMLChrKind = (ckXmlUndefined = -1, ckXmlText, ckXmlTag, ckXmlTagName,
      ckXmlParam, ckXmlValue, ckXmlComment, ckCDATAMarker, ckCDATA,
      ckXmlSignatureOnly);
    TFmtBreak = record
      x: integer;
      kind: TXMLChrKind;
      signature: cardinal;
    end;
  private const
    DEFAULT_TAG_COLOR = SC_BLUE;
    DEFAULT_TAG_NAME_COLOR = SC_RED;
    DEFAULT_TAG_NAME_BOLD = false;
    DEFAULT_PARAM_COLOR = SC_BLUE;
    DEFAULT_VALUE_COLOR = SC_GREEN;
    DEFAULT_COMMENT_COLOR = SC_GRAY;
    DEFAULT_CDATAM_COLOR = SC_GRAY;
    DEFAULT_CDATAM_BOLD = true;
    DEFAULT_CDATA_COLOR = SC_BLACK;
  private const
    CSS_CLASS_TEXT = 0;
    CSS_CLASS_TAG = 1;
    CSS_CLASS_TAG_NAME = 2;
    CSS_CLASS_PARAM = 3;
    CSS_CLASS_VALUE = 4;
    CSS_CLASS_COMMENT = 5;
    CSS_CLASS_CDATAMARKER = 6;
    CSS_CLASS_CDATA = 7;

    CSS_CLASS_HIGH = CSS_CLASS_CDATA;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FValueColor: TColor;
    FParamColor: TColor;
    FTagColor: TColor;
    FCommentColor: TColor;
    FTokens: array of array of TFmtBreak;
    FTagNameColor: TColor;
    FTagNameBold: boolean;
    FCDATAMColor: TColor;
    FCDATAMBold: boolean;
    FCDATAColor: TColor;
    procedure SetParamColor(const Value: TColor);
    procedure SetTagColor(const Value: TColor);
    procedure SetValueColor(const Value: TColor);
    function ParseText(AFromLine: integer = 0;
      SingleLinePossibility: boolean = false; ANumLines: integer = 1): integer;
    function GetChrKind(ALineIndex, ACol: Integer): TXMLChrKind;
    procedure SetCommentColor(const Value: TColor);
    procedure PushTokensDownFrom(ALineIndex: integer);
    procedure PushTokensUpFrom(ALineIndex: integer);
    procedure SetTagNameBold(const Value: boolean);
    procedure SetTagNameColor(const Value: TColor);
    procedure SetCDATAMBold(const Value: boolean);
    procedure SetCDATAMColor(const Value: TColor);
    procedure SetCDATAColor(const Value: TColor);
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property TagColor: TColor read FTagColor write SetTagColor default DEFAULT_TAG_COLOR;
    property TagNameColor: TColor read FTagNameColor write SetTagNameColor default DEFAULT_TAG_NAME_COLOR;
    property TagNameBold: boolean read FTagNameBold write SetTagNameBold default DEFAULT_TAG_NAME_BOLD;
    property ParamColor: TColor read FParamColor write SetParamColor default DEFAULT_PARAM_COLOR;
    property ValueColor: TColor read FValueColor write SetValueColor default DEFAULT_VALUE_COLOR;
    property CommentColor: TColor read FCommentColor write SetCommentColor default DEFAULT_COMMENT_COLOR;
    property CDATAMarkerColor: TColor read FCDATAMColor write SetCDATAMColor default DEFAULT_CDATAM_COLOR;
    property CDATAMarkerBold: boolean read FCDATAMBold write SetCDATAMBold default DEFAULT_CDATAM_BOLD;
    property CDATAColor: TColor read FCDATAColor write SetCDATAColor default DEFAULT_CDATA_COLOR;
  end;

  TCSSFormattingProcessor = class(TFormattingProcessor)
  private type
    TCSSChrKind = (ckCssUndefined = -1, ckCssSelector, ckCssBlockDelim,
      ckCssProperty, ckCssValue, ckCssImportant, ckCssComment);
    TFmtBreak = record
      x: integer;
      kind: TCSSChrKind;
      signature: cardinal;
    end;
  private const
    DEFAULT_SELECTOR_COLOR = SC_RED;
    DEFAULT_SELECTOR_BOLD = false;
    DEFAULT_PROPERTY_COLOR = SC_BLUE;
    DEFAULT_VALUE_COLOR = SC_BLACK;
    DEFAULT_COMMENT_COLOR = SC_GRAY;
    DEFAULT_BLOCK_DELIM_COLOR = SC_RED;
    DEFAULT_BLOCK_DELIM_BOLD = false;
    DEFAULT_IMPORTANT_COLOR = SC_INTENSE_RED;
    DEFAULT_IMPORTANT_BOLD = true;
  private const
    CSS_CLASS_SELECTOR = 0;
    CSS_CLASS_PROPERTY = 1;
    CSS_CLASS_VALUE = 2;
    CSS_CLASS_COMMENT = 3;
    CSS_CLASS_BLOCK_DELIM = 4;
    CSS_CLASS_IMPORTANT = 5;

    CSS_CLASS_HIGH = CSS_CLASS_IMPORTANT;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FSelectorColor: TColor;
    FSelectorBold: boolean;
    FPropertyColor: TColor;
    FValueColor: TColor;
    FCommentColor: TColor;
    FTokens: array of array of TFmtBreak;
    FBlockDelimColor: TColor;
    FBlockDelimBold: boolean;
    FImportantBold: boolean;
    FImportantColor: TColor;
    procedure SetSelectorColor(const Value: TColor);
    procedure SetSelectorBold(const Value: boolean);
    procedure SetPropertyColor(const Value: TColor);
    procedure SetValueColor(const Value: TColor);
    procedure SetCommentColor(const Value: TColor);
    function GetChrKind(ALineIndex, ACol: Integer): TCSSChrKind;
    function ParseText(AFromLine: integer = 0;
      SingleLinePossibility: boolean = false; ANumLines: integer = 1): integer;
    procedure SetBlockDelimColor(const Value: TColor);
    procedure SetBlockDelimBold(const Value: boolean);
    procedure SetImportantBold(const Value: boolean);
    procedure SetImportantColor(const Value: TColor);
    procedure PushTokensDownFrom(ALineIndex: integer);
    procedure PushTokensUpFrom(ALineIndex: integer);
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property SelectorColor: TColor read FSelectorColor write SetSelectorColor default DEFAULT_SELECTOR_COLOR;
    property SelectorBold: boolean read FSelectorBold write SetSelectorBold default DEFAULT_SELECTOR_BOLD;
    property PropertyColor: TColor read FPropertyColor write SetPropertyColor default DEFAULT_PROPERTY_COLOR;
    property ValueColor: TColor read FValueColor write SetValueColor default DEFAULT_VALUE_COLOR;
    property CommentColor: TColor read FCommentColor write SetCommentColor default DEFAULT_COMMENT_COLOR;
    property BlockDelimColor: TColor read FBlockDelimColor write SetBlockDelimColor default DEFAULT_BLOCK_DELIM_COLOR;
    property BlockDelimBold: boolean read FBlockDelimBold write SetBlockDelimBold default DEFAULT_BLOCK_DELIM_BOLD;
    property ImportantColor: TColor read FImportantColor write SetImportantColor default DEFAULT_IMPORTANT_COLOR;
    property ImportantBold: boolean read FImportantBold write SetImportantBold default DEFAULT_IMPORTANT_BOLD;
  end;

  TINIFormattingProcessor = class(TFormattingProcessor)
  private const
    DEFAULT_SECTION_COLOR = SC_RED;
    DEFAULT_SECTION_BOLD = true;
    DEFAULT_NAME_COLOR = SC_BLUE;
    DEFAULT_VALUE_COLOR = SC_BLACK;
    DEFAULT_COMMENT_COLOR = SC_GRAY;
  private const
    CSS_CLASS_SECTION = 0;
    CSS_CLASS_NAME = 1;
    CSS_CLASS_VALUE = 2;
    CSS_CLASS_COMMENT = 3;
    CSS_CLASS_EQUALS = 4;

    CSS_CLASS_HIGH = CSS_CLASS_EQUALS;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FSectionColor: TColor;
    FSectionBold: boolean;
    FValueColor: TColor;
    FNameColor: TColor;
    FCommentColor: TColor;
    procedure SetSectionColor(const Value: TColor);
    procedure SetSectionBold(const Value: boolean);
    procedure SetCommentColor(const Value: TColor);
    procedure SetNameColor(const Value: TColor);
    procedure SetValueColor(const Value: TColor);
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: char;
      var AFontRecord: TFontRecord); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property SectionColor: TColor read FSectionColor write SetSectionColor default DEFAULT_SECTION_COLOR;
    property SectionBold: boolean read FSectionBold write SetSectionBold default DEFAULT_SECTION_BOLD;
    property NameColor: TColor read FNameColor write SetNameColor default DEFAULT_NAME_COLOR;
    property ValueColor: TColor read FValueColor write SetValueColor default DEFAULT_VALUE_COLOR;
    property CommentColor: TColor read FCommentColor write SetCommentColor DEFAULT DEFAULT_COMMENT_COLOR;
  end;

  TPascalFormattingProcessor = class(TFormattingProcessor)
  private type
    TPascalChrKind = (ckPasUndefined = -1, ckPasKeyword, ckPasString,
      ckPasNumber, ckPasComment, ckPasCompilerDirective);
    TFmtBreak = record
      x: integer;
      kind: TPascalChrKind;
      signature: cardinal;
    end;
  private const
    PASCAL_IDENTS: array[0..118] of string = ('absolute', 'abstract', 'and',
      'array', 'as', 'asm', 'assembler', 'automated', 'begin', 'case', 'cdecl',
      'class', 'const', 'constructor', 'contains', 'default', 'delayed',
      'deprecated', 'destructor', 'dispid', 'dispinterface', 'div', 'do',
      'downto', 'dynamic', 'else', 'end', 'except', 'experimental', 'export',
      'exports', 'external', 'far', 'file', 'final', 'finalization', 'finally',
      'for', 'forward', 'function', 'goto', 'helper', 'if', 'implementation',
      'implements', 'in', 'index', 'inherited', 'initialization', 'inline',
      'interface', 'is', 'label', 'library', 'local', 'message', 'mod', 'name',
      'near', 'nil', 'nodefault', 'not', 'object', 'of', 'operator', 'or', 'out',
      'overload', 'override', 'package', 'packed', 'pascal', 'platform',
      'private', 'procedure', 'program', 'property', 'protected', 'public',
      'published', 'raise', 'read', 'readonly', 'record', 'reference',
      'register', 'reintroduce', 'repeat', 'requires', 'resident',
      'resourcestring', 'safecall', 'sealed', 'set', 'shl', 'shr', 'static',
      'stdcall', 'stored', 'strict', 'string', 'then', 'threadvar', 'to', 'try',
      'type', 'unit', 'unsafe', 'until', 'uses', 'var', 'varargs', 'while',
      'winapi', 'virtual', 'with', 'write', 'writeonly', 'xor');
  private const
    DEFAULT_KEYWORD_COLOR = SC_RED;
    DEFAULT_KEYWORD_BOLD = true;
    DEFAULT_STRING_COLOR = SC_BLUE;
    DEFAULT_NUMBER_COLOR = SC_BLUE;
    DEFAULT_COMMENT_COLOR = SC_GREEN;
    DEFAULT_COMPILER_DIRECTIVE_COLOR = SC_RED;
  private const
    CSS_CLASS_DEFAULT = 0;
    CSS_CLASS_KEYWORD = 1;
    CSS_CLASS_STRING = 2;
    CSS_CLASS_NUMBER = 3;
    CSS_CLASS_COMMENT = 4;
    CSS_CLASS_COMPILER_DIRECTIVE = 5;

    CSS_CLASS_HIGH = CSS_CLASS_COMPILER_DIRECTIVE;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FKeywordColor: TColor;
    FKeywordBold: boolean;
    FStringColor: TColor;
    FNumberColor: TColor;
    FCommentColor: TColor;
    FTokens: array of array of TFmtBreak;
    FCompilerDirectiveColor: TColor;
    procedure SetKeywordColor(const Value: TColor);
    procedure SetKeywordBold(const Value: boolean);
    procedure SetStringColor(const Value: TColor);
    procedure SetNumberColor(const Value: TColor);
    procedure SetCommentColor(const Value: TColor);
    procedure SetCompilerDirectiveColor(const Value: TColor);
    function ParseText(AFromLine: integer = 0;
      SingleLinePossibility: boolean = false; ANumLines: integer = 1): integer;
    function GetChrKind(ALineIndex, ACol: Integer): TPascalChrKind;
    procedure PushTokensDownFrom(ALineIndex: integer);
    procedure PushTokensUpFrom(ALineIndex: integer);
  public
    constructor Create(AOwner: TComponent); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    function GetCSSRules: TCSSRules; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
    function GetCache(out ACache: PByte): Integer; override;
    function RestoreCache(ACache: PByte; ASize: Integer): Boolean; override;
    procedure ClearCache; override;
  published
    property KeywordColor: TColor read FKeywordColor write SetKeywordColor default DEFAULT_KEYWORD_COLOR;
    property KeywordBold: boolean read FKeywordBold write SetKeywordBold default DEFAULT_KEYWORD_BOLD;
    property StringColor: TColor read FStringColor write SetStringColor default DEFAULT_STRING_COLOR;
    property NumberColor: TColor read FNumberColor write SetNumberColor default DEFAULT_NUMBER_COLOR;
    property CommentColor: TColor read FCommentColor write SetCommentColor default DEFAULT_COMMENT_COLOR;
    property CompilerDirectiveColor: TColor read FCompilerDirectiveColor write SetCompilerDirectiveColor default DEFAULT_COMPILER_DIRECTIVE_COLOR;
  end;

  TAlgoSimFormattingProcessor = class(TFormattingProcessor)
  private const
    DEFAULT_KEYWORD_COLOR = SC_RED;
    DEFAULT_KEYWORD_BOLD = true;
    DEFAULT_STRING_COLOR = SC_BLUE;
    DEFAULT_NUMBER_COLOR = SC_BLUE;
    DEFAULT_COMMENT_COLOR = SC_GREEN;
  private const
    CSS_CLASS_DEFAULT = 0;
    CSS_CLASS_KEYWORD = 1;
    CSS_CLASS_STRING = 2;
    CSS_CLASS_NUMBER = 3;
    CSS_CLASS_COMMENT = 4;

    CSS_CLASS_HIGH = CSS_CLASS_COMMENT;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FKeywordColor: TColor;
    FKeywordBold: boolean;
    FStringColor: TColor;
    FNumberColor: TColor;
    FCommentColor: TColor;
    procedure SetKeywordColor(const Value: TColor);
    procedure SetKeywordBold(const Value: boolean);
    procedure SetStringColor(const Value: TColor);
    procedure SetNumberColor(const Value: TColor);
    procedure SetCommentColor(const Value: TColor);
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property KeywordColor: TColor read FKeywordColor write SetKeywordColor default DEFAULT_KEYWORD_COLOR;
    property KeywordBold: boolean read FKeywordBold write SetKeywordBold default DEFAULT_KEYWORD_BOLD;
    property StringColor: TColor read FStringColor write SetStringColor default DEFAULT_STRING_COLOR;
    property NumberColor: TColor read FNumberColor write SetNumberColor default DEFAULT_NUMBER_COLOR;
    property CommentColor: TColor read FCommentColor write SetCommentColor default DEFAULT_COMMENT_COLOR;
  end;

  THTMLFormattingProcessor = class(TFormattingProcessor)
  private type
    THTMLChrKind = (ckHtmlUndefined = -1, ckHtmlText, ckHtmlTag, ckHtmlTagName, ckHtmlParam,
      ckHtmlValue, ckHtmlComment, ckHtmlDoctype, ckHtmlCssSelector, ckHtmlCssBlockDelim,
      ckHtmlCssProperty, ckHtmlCssValue, ckHtmlCssImportant, ckHtmlCssComment,
      ckHtmlScript);
    TFmtBreak = record
      x: integer;
      kind: THtmlChrKind;
      signature: cardinal;
    end;
  private const
    DEFAULT_TAG_COLOR = SC_BLUE;
    DEFAULT_TAG_NAME_COLOR = SC_RED;
    DEFAULT_TAG_NAME_BOLD = false;
    DEFAULT_PARAM_COLOR = SC_BLUE;
    DEFAULT_VALUE_COLOR = SC_GREEN;
    DEFAULT_COMMENT_COLOR = SC_GRAY;
    DEFAULT_CSS_SELECTOR_COLOR = SC_RED;
    DEFAULT_CSS_SELECTOR_BOLD = false;
    DEFAULT_CSS_PROPERTY_COLOR = SC_BLUE;
    DEFAULT_CSS_VALUE_COLOR = SC_GREEN;
    DEFAULT_CSS_COMMENT_COLOR = SC_GRAY;
    DEFAULT_CSS_BLOCK_DELIM_COLOR = SC_RED;
    DEFAULT_CSS_BLOCK_DELIM_BOLD = false;
    DEFAULT_CSS_IMPORTANT_COLOR = SC_INTENSE_RED;
    DEFAULT_CSS_IMPORTANT_BOLD = true;
    DEFAULT_DOCTYPE_COLOR = SC_GRAY;
    DEFAULT_DOCTYPE_BOLD = false;
    DEFAULT_DOCTYPE_ITALICS = true;

  private const
    CSS_CLASS_TEXT = 0;
    CSS_CLASS_TAG = 1;
    CSS_CLASS_TAG_NAME = 2;
    CSS_CLASS_PARAM = 3;
    CSS_CLASS_VALUE = 4;
    CSS_CLASS_COMMENT = 5;
    CSS_CLASS_CSS_SELECTOR = 6;
    CSS_CLASS_CSS_PROPERTY = 7;
    CSS_CLASS_CSS_VALUE = 8;
    CSS_CLASS_CSS_COMMENT = 9;
    CSS_CLASS_CSS_BLOCK_DELIM = 10;
    CSS_CLASS_CSS_IMPORTANT = 11;
    CSS_CLASS_DOCTYPE = 12;
    CSS_CLASS_SCRIPT = 13;

    CSS_CLASS_HIGH = CSS_CLASS_SCRIPT;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FValueColor: TColor;
    FParamColor: TColor;
    FTagColor: TColor;
    FTagNameColor: TColor;
    FTagNameBold: boolean;
    FCommentColor: TColor;
    FCssSelectorColor: TColor;
    FCssSelectorBold: boolean;
    FCssPropertyColor: TColor;
    FCssValueColor: TColor;
    FCssCommentColor: TColor;
    FCssBlockDelimColor: TColor;
    FCssBlockDelimBold: boolean;
    FCssImportantBold: boolean;
    FCssImportantColor: TColor;
    FDoctypeColor: TColor;
    FDoctypeBold: boolean;
    FDoctypeItalics: boolean;
    FTokens: array of array of TFmtBreak;
    procedure SetParamColor(const Value: TColor);
    procedure SetTagColor(const Value: TColor);
    procedure SetValueColor(const Value: TColor);
    function ParseText(AFromLine: integer = 0;
      SingleLinePossibility: boolean = false; ANumLines: integer = 1): integer;
    function GetChrKind(ALineIndex, ACol: Integer): THtmlChrKind;
    procedure SetCommentColor(const Value: TColor);
    procedure SetCssBlockDelimBold(const Value: boolean);
    procedure SetCssBlockDelimColor(const Value: TColor);
    procedure SetCssCommentColor(const Value: TColor);
    procedure SetCssImportantBold(const Value: boolean);
    procedure SetCssImportantColor(const Value: TColor);
    procedure SetCssPropertyColor(const Value: TColor);
    procedure SetCssSelectorBold(const Value: boolean);
    procedure SetCssSelectorColor(const Value: TColor);
    procedure SetCssValueColor(const Value: TColor);
    procedure SetDoctypeBold(const Value: boolean);
    procedure SetDoctypeColor(const Value: TColor);
    procedure SetDoctypeItalics(const Value: boolean);
    procedure SetTagNameBold(const Value: boolean);
    procedure SetTagNameColor(const Value: TColor);
    procedure PushTokensDownFrom(ALineIndex: integer);
    procedure PushTokensUpFrom(ALineIndex: integer);
  public
    constructor Create(AOwner: TComponent); override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property TagColor: TColor read FTagColor write SetTagColor default DEFAULT_TAG_COLOR;
    property TagNameColor: TColor read FTagNameColor write SetTagNameColor default DEFAULT_TAG_NAME_COLOR;
    property TagNameBold: boolean read FTagNameBold write SetTagNameBold default DEFAULT_TAG_NAME_BOLD;
    property ParamColor: TColor read FParamColor write SetParamColor default DEFAULT_PARAM_COLOR;
    property ValueColor: TColor read FValueColor write SetValueColor default DEFAULT_VALUE_COLOR;
    property CommentColor: TColor read FCommentColor write SetCommentColor default DEFAULT_COMMENT_COLOR;
    property CssSelectorColor: TColor read FCssSelectorColor write SetCssSelectorColor default DEFAULT_CSS_SELECTOR_COLOR;
    property CssSelectorBold: boolean read FCssSelectorBold write SetCssSelectorBold default DEFAULT_CSS_SELECTOR_BOLD;
    property CssPropertyColor: TColor read FCssPropertyColor write SetCssPropertyColor default DEFAULT_CSS_PROPERTY_COLOR;
    property CssValueColor: TColor read FCssValueColor write SetCssValueColor default DEFAULT_CSS_VALUE_COLOR;
    property CssCommentColor: TColor read FCssCommentColor write SetCssCommentColor default DEFAULT_CSS_COMMENT_COLOR;
    property CssBlockDelimColor: TColor read FCssBlockDelimColor write SetCssBlockDelimColor default DEFAULT_CSS_BLOCK_DELIM_COLOR;
    property CssBlockDelimBold: boolean read FCssBlockDelimBold write SetCssBlockDelimBold default DEFAULT_CSS_BLOCK_DELIM_BOLD;
    property CssImportantColor: TColor read FCssImportantColor write SetCssImportantColor default DEFAULT_CSS_IMPORTANT_COLOR;
    property CssImportantBold: boolean read FCssImportantBold write SetCssImportantBold default DEFAULT_CSS_IMPORTANT_BOLD;
    property DoctypeColor: TColor read FDoctypeColor write SetDoctypeColor default DEFAULT_DOCTYPE_COLOR;
    property DoctypeBold: boolean read FDoctypeBold write SetDoctypeBold default DEFAULT_DOCTYPE_Bold;
    property DoctypeItalics: boolean read FDoctypeItalics write SetDoctypeItalics default DEFAULT_DOCTYPE_Italics;
  end;

  TMediaWikiFormattingProcessor = class(TFormattingProcessor)
  private const
    DEFAULT_HEADING1_COLOR = SC_BLUE;
    DEFAULT_HEADING1_BOLD = true;
    DEFAULT_HEADING1_ITALICS = true;
    DEFAULT_HEADING2_COLOR = SC_BLUE;
    DEFAULT_HEADING2_BOLD = true;
    DEFAULT_HEADING2_ITALICS = false;
    DEFAULT_HEADING3_COLOR = SC_BLUE;
    DEFAULT_HEADING3_BOLD = false;
    DEFAULT_HEADING3_ITALICS = true;
    DEFAULT_HEADING4_COLOR = SC_BLUE;
    DEFAULT_HEADING4_BOLD = false;
    DEFAULT_HEADING4_ITALICS = false;
    DEFAULT_HEADING5_COLOR = SC_GRAY;
    DEFAULT_HEADING5_BOLD = false;
    DEFAULT_HEADING5_ITALICS = true;
    DEFAULT_HEADING6_COLOR = SC_GRAY;
    DEFAULT_HEADING6_BOLD = false;
    DEFAULT_HEADING6_ITALICS = false;
    DEFAULT_WIKILINK_COLOR = SC_RED;
    DEFAULT_EXTLINK_COLOR = SC_RED;
    DEFAULT_TEMPLATE_COLOR = SC_GREEN;
    DEFAULT_TEMPLATE_NAME_BOLD = true;
    DEFAULT_BOLD_BOLD = true;
    DEFAULT_ITALICS_ITALICS = true;
    DEFAULT_INDENT_COLOR = SC_GRAY;
  private const
    CSS_CLASS_TEXT = 0;
    CSS_CLASS_HEADING1 = 1;
    CSS_CLASS_HEADING2 = 2;
    CSS_CLASS_HEADING3 = 3;
    CSS_CLASS_HEADING4 = 4;
    CSS_CLASS_HEADING5 = 5;
    CSS_CLASS_HEADING6 = 6;
    CSS_CLASS_WIKILINK = 7;
    CSS_CLASS_EXTLINK = 8;
    CSS_CLASS_TEMPLATE_NAME = 9;
    CSS_CLASS_TEMPLATE = 10;
    CSS_CLASS_BOLD = 11;
    CSS_CLASS_ITALICS = 12;
    CSS_CLASS_BOLDITALICS = 13;
    CSS_CLASS_INDENT = 14;

    CSS_CLASS_HIGH = CSS_CLASS_INDENT;
    CSS_CLASS_LENGTH = CSS_CLASS_HIGH + 1;
  private var
    FHeading4Color: TColor;
    FHeading1Italics: boolean;
    FHeading4Italics: boolean;
    FHeading2Bold: boolean;
    FHeading3Bold: boolean;
    FHeading1Bold: boolean;
    FHeading4Bold: boolean;
    FHeading2Color: TColor;
    FHeading3Color: TColor;
    FHeading1Color: TColor;
    FHeading2Italics: boolean;
    FHeading3Italics: boolean;
    FWikilinkColor: TColor;
    FTemplateColor: TColor;
    FBoldBold: boolean;
    FItalicsItalics: boolean;
    FExtlinkColor: TColor;
    FIndentColor: TColor;
    FTemplateNameBold: boolean;
    FHeading5Color: TColor;
    FHeading5Italics: boolean;
    FHeading5Bold: boolean;
    FHeading6Italics: boolean;
    FHeading6Bold: boolean;
    FHeading6Color: TColor;
    procedure SetHeading1Bold(const Value: boolean);
    procedure SetHeading1Color(const Value: TColor);
    procedure SetHeading1Italics(const Value: boolean);
    procedure SetHeading2Bold(const Value: boolean);
    procedure SetHeading2Color(const Value: TColor);
    procedure SetHeading2Italics(const Value: boolean);
    procedure SetHeading3Bold(const Value: boolean);
    procedure SetHeading3Color(const Value: TColor);
    procedure SetHeading3Italics(const Value: boolean);
    procedure SetHeading4Bold(const Value: boolean);
    procedure SetHeading4Color(const Value: TColor);
    procedure SetHeading4Italics(const Value: boolean);
    procedure SetWikilinkColor(const Value: TColor);
    procedure SetTemplateColor(const Value: TColor);
    procedure SetBoldBold(const Value: boolean);
    procedure SetItalicsItalics(const Value: boolean);
    procedure SetExtlinkColor(const Value: TColor);
    procedure SetIndentColor(const Value: TColor);
    procedure SetTemplateNameBold(const Value: boolean);
    procedure SetHeading5Bold(const Value: boolean);
    procedure SetHeading5Color(const Value: TColor);
    procedure SetHeading5Italics(const Value: boolean);
    procedure SetHeading6Bold(const Value: boolean);
    procedure SetHeading6Color(const Value: TColor);
    procedure SetHeading6Italics(const Value: boolean);
  public
    constructor Create(AOwner: TComponent); override;
    function GetCSSRules: TCSSRules; override;
    function GetCharCSSClass(ALineIndex: Integer; ACol: Integer;
      AChar: Char): Integer; override;
    procedure GetCharFormat(ALineIndex: Integer; ACol: Integer; AChar: Char;
      var AFontRecord: TFontRecord); override;
    function FileChangeNotification(ChangeType: TChangeType; Data1: Integer;
      Data2: Integer; Data3: Integer; Data4: Integer): TChangeRecord; override;
    procedure Assign(Source: TPersistent); override;
    procedure ApplyColorScheme(const AColorScheme: TColorScheme); override;
  published
    property Heading1Color: TColor read FHeading1Color write SetHeading1Color default DEFAULT_HEADING1_COLOR;
    property Heading1Bold: boolean read FHeading1Bold write SetHeading1Bold default DEFAULT_HEADING1_BOLD;
    property Heading1Italics: boolean read FHeading1Italics write SetHeading1Italics default DEFAULT_HEADING1_BOLD;
    property Heading2Color: TColor read FHeading2Color write SetHeading2Color default DEFAULT_HEADING2_COLOR;
    property Heading2Bold: boolean read FHeading2Bold write SetHeading2Bold default DEFAULT_HEADING2_BOLD;
    property Heading2Italics: boolean read FHeading2Italics write SetHeading2Italics default DEFAULT_HEADING2_BOLD;
    property Heading3Color: TColor read FHeading3Color write SetHeading3Color default DEFAULT_HEADING3_COLOR;
    property Heading3Bold: boolean read FHeading3Bold write SetHeading3Bold default DEFAULT_HEADING3_BOLD;
    property Heading3Italics: boolean read FHeading3Italics write SetHeading3Italics default DEFAULT_HEADING3_BOLD;
    property Heading4Color: TColor read FHeading4Color write SetHeading4Color default DEFAULT_HEADING4_COLOR;
    property Heading4Bold: boolean read FHeading4Bold write SetHeading4Bold default DEFAULT_HEADING4_BOLD;
    property Heading4Italics: boolean read FHeading4Italics write SetHeading4Italics default DEFAULT_HEADING4_BOLD;
    property Heading5Color: TColor read FHeading5Color write SetHeading5Color default DEFAULT_HEADING5_COLOR;
    property Heading5Bold: boolean read FHeading5Bold write SetHeading5Bold default DEFAULT_HEADING5_BOLD;
    property Heading5Italics: boolean read FHeading5Italics write SetHeading5Italics default DEFAULT_HEADING5_BOLD;
    property Heading6Color: TColor read FHeading6Color write SetHeading6Color default DEFAULT_HEADING6_COLOR;
    property Heading6Bold: boolean read FHeading6Bold write SetHeading6Bold default DEFAULT_HEADING6_BOLD;
    property Heading6Italics: boolean read FHeading6Italics write SetHeading6Italics default DEFAULT_HEADING6_BOLD;
    property WikilinkColor: TColor read FWikilinkColor write SetWikilinkColor default DEFAULT_WIKILINK_COLOR;
    property ExtlinkColor: TColor read FExtlinkColor write SetExtlinkColor default DEFAULT_EXTLINK_COLOR;
    property TemplateColor: TColor read FTemplateColor write SetTemplateColor default DEFAULT_TEMPLATE_COLOR;
    property TemplateNameBold: boolean read FTemplateNameBold write SetTemplateNameBold default DEFAULT_TEMPLATE_NAME_BOLD;
    property BoldBold: boolean read FBoldBold write SetBoldBold default DEFAULT_BOLD_BOLD;
    property ItalicsItalics: boolean read FItalicsItalics write SetItalicsItalics default DEFAULT_ITALICS_ITALICS;
    property IndentColor: TColor read FIndentColor write SetIndentColor default DEFAULT_INDENT_COLOR;
  end;

  TPrintSettings = class(TPersistent)
  strict private var
    FVerticalMargin: integer;
    FHorizontalMargin: integer;
    FWordWrap: boolean;
    FNiceWordWrap: boolean;
    FWordWrapChar: char;
    FShowWordWrapIcon: boolean;
    FWordWrapIconColor: TColor;
  public const
    DEFAULT_VERTICAL_MARGIN = 200;
    DEFAULT_HORIZONTAL_MARGIN = 220;
    DEFAULT_WORD_WRAP = true;
    DEFAULT_NICE_WORD_WRAP = true;
    DEFAULT_WORD_WRAP_CHAR = '↳';
    DEFAULT_SHOW_WORD_WRAP_ICON = false;
    DEFAULT_WORD_WRAP_ICON_COLOR = clBlack;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property VerticalMargin: integer read FVerticalMargin write FVerticalMargin default DEFAULT_VERTICAL_MARGIN;
    property HorizontalMargin: integer read FHorizontalMargin write FHorizontalMargin default DEFAULT_HORIZONTAL_MARGIN;
    property WordWrap: boolean read FWordWrap write FWordWrap default DEFAULT_WORD_WRAP;
    property NiceWordWrap: boolean read FNiceWordWrap write FNiceWordWrap default DEFAULT_NICE_WORD_WRAP;
    property WordWrapIcon: char read FWordWrapChar write FWordWrapChar default DEFAULT_WORD_WRAP_CHAR;
    property ShowWordWrapIcon: boolean read FShowWordWrapIcon write FShowWordWrapIcon default DEFAULT_SHOW_WORD_WRAP_ICON;
    property WordWrapIconColor: TColor read FWordWrapIconColor write FWordWrapIconColor default DEFAULT_WORD_WRAP_ICON_COLOR;
  end;

  TProgressStartEvent = procedure(Sender: TObject; NumSteps: integer) of object;
  TProgressEvent = function(Sender: TObject; CurStep: integer; NumSteps: integer): boolean of object;
  TProgressCompleteEvent = TNotifyEvent;

  TNotificationMessage = procedure(Sender: TObject; MsgID: cardinal; AClear: boolean = false) of object;
  TSimpleNotificationMessage = procedure(Sender: TObject; MsgID: cardinal; const AStr: string) of object;

  TGraphicControlCracker = type TGraphicControl;

  TBorderType = (btNone, btWin32ThinLine, btWin32SunkenEdge, btThemeBorder,
    btSimpleColor);

  TTextFileOwner = (tfoEditor, tfoApplication);

  TSelectionBarBehaviour = (sbbAlwaysSelect, sbbNeverSelect, sbbAuto, sbbAutoMixed);

  TCliGetPromptClassEvent = procedure(Sender: TObject; var AClassName: string) of object;
  TCliInputEvent = procedure(Sender: TObject; const AInput: string; var NewPrompt: boolean) of object;

  TParamType = (ptConstant, ptCommand);
  TScriptParam = record
    ParamType: TParamType;
    ParamValue: integer;
  end;

  TEditorCommand = record
    Verb: integer;
    Param1,
    Param2,
    Param3,
    Param4: TScriptParam;
  end;
  TEditorScript = array of TEditorCommand;

function MakeEditorCommand(Verb: integer; Param1: integer = 0;
  ParamType1: TParamType = ptConstant; Param2: integer = 0;
  ParamType2: TParamType = ptConstant; Param3: integer = 0;
  ParamType3: TParamType = ptConstant; Param4: integer = 0;
  ParamType4: TParamType = ptConstant): TEditorCommand;

const
  MultiCharHyphen: array[0..6] of char = (#$002D, #$2010, #$2011, #$00AD, #$2013, #$2014, #$2212);
  MultiCharAsterisk: array[0..4] of char = (#$002A, #$2022, #$22C5, #$00D7, #$2219);
  MultiCharDoubleQuote: array[0..5] of char = (#$0022, #$201C, #$201D, #$201E, #$00BB, #$00AB);
  MultiCharSingleQuote: array[0..5] of char = (#$0027, #$2018, #$2019, #$201A, #$203A, #$2039);

type
  TScrollBehaviour = (sbDefault, sbLine, sbPixel);

  TTextEditor = class;

  TTextEditorDataObject = class(TInterfacedObject, IDataObject)
  strict private type
    TEnumFormatEtc = class(TInterfacedObject, IEnumFORMATETC)
      strict private
        FIndex: integer;
      public
        function Next(celt: Longint; out elt;
          pceltFetched: PLongint): HResult; stdcall;
        function Skip(celt: Longint): HResult; stdcall;
        function Reset: HResult; stdcall;
        function Clone(out Enum: IEnumFormatEtc): HResult; stdcall;
    end;
  public const
    FMT_UNICODETEXT = 0;
  class var
    Formats: TFormatEtcArray;
  private
    FTextEditor: TTextEditor;
    FBuffer: string;
    function GetMatchingFormatIdx(const AFormatEtc: TFormatEtc): integer;
  public
    class constructor ClassCreate;
    class function CreateHGlobal(Data: pointer; Len: UInt64; uFlags: DWORD;
      out hGlobal: HGLOBAL): HRESULT; static;
    constructor Create(AEditor: TTextEditor);
    function DAdvise(const formatetc: tagFORMATETC; advf: Integer;
      const advSink: IAdviseSink; out dwConnection: Integer): HRESULT; stdcall;
    function DUnadvise(dwConnection: Integer): HRESULT; stdcall;
    function EnumDAdvise(out enumAdvise: IEnumSTATDATA): HRESULT; stdcall;
    function EnumFormatEtc(dwDirection: Integer;
      out enumFormatEtc: IEnumFORMATETC): HRESULT; stdcall;
    function GetCanonicalFormatEtc(const formatetc: tagFORMATETC;
      out formatetcOut: tagFORMATETC): HRESULT; stdcall;
    function GetData(const formatetcIn: tagFORMATETC;
      out medium: tagSTGMEDIUM): HRESULT; stdcall;
    function GetDataHere(const formatetc: tagFORMATETC;
      out medium: tagSTGMEDIUM): HRESULT; stdcall;
    function QueryGetData(const formatetc: tagFORMATETC): HRESULT; stdcall;
    function SetData(const formatetc: tagFORMATETC; var medium: tagSTGMEDIUM;
      fRelease: LongBool): HRESULT; stdcall;
  end;

  TTextEditor = class(TCustomControl, IDropTarget, IDropSource)
  private type
    TTextEditorRegion = (terText, terSelectionBar);
  public const
    DEFAULT_LINE_HIGHLIGHT_COLOR = $00EEEEEE;
    DEFAULT_BRACKET_HIGHLIGHT_COLOR = $0077D9F5;
    DEFAULT_RULER_WIDTH = 60;
    DEFAULT_MARGIN_LEFT = 80;
    DEFAULT_MARGIN_TOP = 4;
    DEFAULT_MARGIN_RIGHT = 4;
    DEFAULT_MARGIN_BOTTOM = 4;
    DEFAULT_NOTIFICATION_MSG_DURATION = 5000;
  public const
    EN_NULL = 0;
    EN_DRAG_MOVE = 1;
    EN_DRAG_COPY = 2;
    EN_READ_ONLY_ERROR = 3;
    EN_INPUT_ERROR = 4;
    EN_PRINTING = 5;
    EN_SCROLL_MODE = 6;
    EN_SCRIPT = 7;
    EN_MULTICHAR = 8;
    EN_READONLY = 9;
    EN_MULTICARET = 10;
    EN_MAX = 10;
  private const
    FNotificationStrs: array[0..EN_MAX] of string =
      ('',
       SNotifyDragMove,
       SNotifyDragCopy,
       SNotifyReadOnlyError,
       SNotifyInputError,
       SNotifyPrinting,
       SNotifyScrollMode,
       SNotifyScript,
       SNotifyMultiCharSelect,
       SNotifyReadOnlyMode,
       SNotifyMultiCaretMode);
  private const
    EDITOR_NOTIFY = $10000;
  private const
    WM_MOUSEHWHEEL = $020E;
  private var
    FTextFile: TTextFile;
    FClassArray: TClassArray;
    FBkColor: TColor;
    FFgColor: TColor;
    FSelBkColor: TColor;
    FSelFgColor: TColor;
    FFndBkColor: TColor;
    FFndFgColor: TColor;
    FUseSystemColors: boolean;
    FForegroundColor: TColor;
    FBackgroundColor: TColor;
    FFontSize: TSize;
    FFont: TFont;
    FLetterSpacing: integer;
    FLineSpacing: integer;
    FAutoIndent: boolean;
    FHandleHotkeys: boolean;
    FHandleBookmarkHotkeys: boolean;
    FSelForegroundColor: TColor;
    FSelBackgroundColor: TColor;
    FOnSelChange: TNotifyEvent;
    FOnChange: TNotifyEvent;
    FBeepOnInputError: boolean;
    FErrorMessageOnReadOnlyError: boolean;
    FOverwrite: boolean;
    FOLEDragging: boolean;
    FOLEInternalDrop: boolean;
    FDropLocation: TPoint;
    FLastDropEffect: integer;
    FDoubleClicking: Boolean;
    FIndentSize: integer;
    FScrollPos: TPoint;
    FPrevCursorX, FPrevCursorY: integer;
    FMouseDownX, FMouseDownY: integer;
    FShowHiddenCharacters: boolean;
    FOnModified: TNotifyEvent;
    FLineHighlight: boolean;
    FLineHighlightColor: TColor;
    FOldCaretPosY: integer;
    FMatchBrackets: boolean;
    FBracketHighlight: boolean;
    FBracketPos1, FBracketPos2: TPoint;
    FBracketHighlightColor: TColor;
    FAutoReplace: boolean;
    FPopupMenu: TPopupMenu;
    FRulerMenu: TPopupMenu;
    FImagePopup: TPopupMenu;
    FTypeTimer: TTimer;
    FMessageInterface: boolean;
    FInputTransform: TInputTransform;
    FStartOver: boolean;
    FGLYPHBM: TBitmap;
    FFONTBM: TBitmap;
    FFallbackFonts: TStringList;
    FGlyphSets: array of PGlyphSet;
    FUnicodeFallback: boolean;
    FPasswordChar: char;
    FNumbersOnly: boolean;
    FHintWindow: HWND;
    FToolInfo: TToolInfo;
    FBalloonPoint: TPoint;
    FBalloonPersistence: TBalloonPersistence;
    FBalloonTimer: TTimer;
    FTabLength: integer;
    FLabelStyle: boolean;
    FLabelEllipsis: boolean;
    FBlinkRemover: TTimer;
    FAutoHeight: boolean;
    FMultiSize: boolean;
    FCurrentFormat: TFontRecord;
    FFontSizes: array of TSize;
    FAccumLineHeights: array of integer;
    FCachedHorizontalExtent: integer;
    FLineControls: array of TLineControlRecord;
    FNextControlID: cardinal;
    FOnBookmarksMoved: TNotifyEvent;
    FFormattingProcessor: TFormattingProcessor;
    FRulerWidth,
    FMarginLeft,
    FMarginRight,
    FMarginTop,
    FMarginBottom: integer;
    FRegion: TTextEditorRegion;
    FSelectionBarInitialLine: integer;
    FRulerFont: TFont;
    FCaretVisible: boolean;
    FNoScrollToCaret: boolean;
    FRulerColor: TColor;
    FZoom: integer;
    FOnZoomChange: TNotifyEvent;
    FPrintSettings: TPrintSettings;
    FOnPrintProgress: TProgressEvent;
    FOnPrintEnd: TProgressCompleteEvent;
    FOnPrintBegin: TProgressStartEvent;
    FRightLineColor: TColor;
    FRightLinePos: integer;
    FRightLine: boolean;
    FBorderColor: TColor;
    FBorderType: TBorderType;
    FTextFileOwner: TTextFileOwner;
    FRulerPopupMenu: TPopupMenu;
    FSelectionBarBehaviour: TSelectionBarBehaviour;
    FNotifications: array of integer;
    FOnNotification: TNotificationMessage;
    FOnSimpleNotification: TSimpleNotificationMessage;
    FScrollMode: boolean;
    FNotifyMsgDuration: integer;
    FOnCliGetPromptClass: TCliGetPromptClassEvent;
    FOnCliInput: TCliInputEvent;
    FScriptRunning: Boolean;
    FScriptCounter: integer;
    FAbortScript: Boolean;
    FDesiredColumn: integer; {in px}
    FPreserveDesiredColumn: boolean;
    FCliHistory: array of string;
    FCliHistoryIndex: integer;
    FListBoxMode: boolean;
    FOnListBoxChange: TNotifyEvent;
    FOnListBoxSelect: TNotifyEvent;
    FValidPaintState: boolean;
    FCliMultiOutput: boolean;
    FMultiCharSelect: boolean;
    FMultiCharSelectDlgFrm: TForm;
    FMultiCharReportView: boolean;
    Flv: HWND;
    FMultiCharSelectDlgDefaultWndProc: TWndMethod;
    FASHyphenAsteriskToggle: boolean;
    FNoVerifyFont: boolean;
    FDisabledEffect: TBitmapEffect;
    FBitmapEffect: TBitmapEffect;
    FRepeatExNum: integer;
    FRepeatExCommand: integer;
    FOnFindDataClear: TNotifyEvent;
    FOnOverwriteChange: TNotifyEvent;
    FVisualUpdateLock: integer;
    FScrollBehaviour: TScrollBehaviour;
    FSPIScrollLines: integer;
    FCaretAfterEOL: boolean;
    FMultipleCarets: boolean;
    FCarets: TPointArray;
    FAllowBitmapPaste: boolean;
    FWantTab, FWantReturn: boolean;
    FDragDataObj: IDataObject;
    FDragCompatFmt: boolean;
    FRightDrag: boolean;
    FInsertionPoint: TPoint;
    FDropMenu: TPopupMenu;
    FDropMenuMove, FDropMenuCopy: TMenuItem;
    FDropTargetHelper: IDropTargetHelper;
    FExpectDragDrop: boolean;
    FDragButton: TMouseButton;
    FDragButtonOLE: integer;
    FMouseContSel: boolean;
    FPDict: TDictionary<string, TFormattingProcessor>;
    FDragScrollFirstChance: UInt64;
    FXDRAG, FYDRAG: integer;
    procedure SetUseSystemColors(const Value: boolean);
    procedure SetupColors;
    procedure SetBackgroundColor(const Value: TColor);
    procedure SetForegroundColor(const Value: TColor);
    procedure SetupFontMetrics;
    procedure SetFont(const Value: TFont);
    procedure DrawLine(LineIndex: Integer; From, ATo: integer; AForceFindHighlight: boolean = false); overload;
    procedure DrawSpan(const ATextSpan: TTextSpan; AForceFindHighlight: boolean = false);
    procedure ApplyFont(const AClassName: string; ATo: TCanvas = nil);
    procedure ReapplyFont(ATo: TCanvas = nil); inline;
    procedure FontChange(Sender: TObject);
    procedure SetLetterSpacing(const Value: integer);
    procedure SetLineSpacing(const Value: integer);
    procedure TextFileChange(Sender: TObject; ChangeType: TChangeType; Data1,
      Data2, Data3, Data4: Integer);
    procedure TextFileCaretPosSelChange(Sender: TObject; ChangeType: TChangeType; Data1,
      Data2, Data3, Data4: Integer);
    procedure TextFileCaretPosChange(Sender: TObject);
    procedure SetCaretAfterEOL(const Value: boolean);
    procedure TextFileInputError(Sender: TObject);
    procedure SetAutoIndent(const Value: boolean);
    function GetText: string;
    procedure SetText(const Value: string);
    procedure SetSelBackgroundColor(const Value: TColor);
    procedure SetSelForegroundColor(const Value: TColor);
    procedure ApplyInteractiveFormatting(const X, Y: integer; ATo: TCanvas = nil);
    procedure ApplyCharacterColors(const X, Y: integer; AForceFindHighlight: boolean = false);
    function GetCaretPos: TPoint;
    function GetSelEndPos: TPoint;
    procedure SetCaretPos(const Value: TPoint);
    procedure SetSelEndPos(const Value: TPoint);
    function GetSelType: TSelectionType;
    procedure SetSelType(const Value: TSelectionType);
    procedure VisualUpdate(ChangeType: TChangeType; Data1, Data2, Data3, Data4: integer);
    procedure UpdateCaret;
    function GetSelText: string;
    procedure ChangeCursor(Shift: TShiftState; Y: Integer; X: Integer); overload;
    procedure ChangeCursor(Shift: TShiftState); overload;
    procedure ChangeCursor; overload;
    procedure SetIndentSize(const Value: integer);
    function GetSelLength: integer;
    function SafeSelLength: integer;
    procedure SetSelLength(const Value: integer);
    procedure UpdateScrollBars;
    procedure SetScrollPosY(Value: integer; Lim: boolean = false);
    procedure SetScrollPosX(Value: integer);
    function FirstVisibleLine(TrueValue: boolean = false): integer;
    function LastVisibleLine(TrueValue: boolean = false): integer;
    procedure DrawVisibleLine(LineIndex: Integer; From: Integer = 0);
    function ScrollToCaret: boolean;
    procedure SetScrollPosXY(X, Y: integer; Lim: boolean = false);
    procedure Escape(AAll: boolean = false);
    procedure SetEditMode(const Value: TEditMode);
    procedure SetShowHiddenCharacters(const Value: boolean);
    function Reveal(const C: char): char;
    procedure TextFileModified(Sender: TObject);
    procedure SetLineHighlight(const Value: boolean);
    procedure SetLineHighlightColor(const Value: TColor);
    procedure SetMatchBrackets(const Value: boolean);
    function IsBracketHighlight(const X, Y: integer): boolean; inline;
    procedure SetBracketHighlightColor(const Value: TColor);
    procedure MenuPopup(Sender: TObject);
    procedure MenuItemMessage(Sender: TObject);
    function GetSelStart: integer;
    procedure SetSelStart(const Value: integer);
    procedure SetOverwrite(const Value: boolean);
    procedure TypeTimerTimer(Sender: TObject);
    procedure PostType;
    procedure SetFindBackgroundColor(const Value: TColor);
    procedure SetFindForegroundColor(const Value: TColor);
    procedure SelectFindItem(ItemIndex: integer);
    procedure SetSingleLine(const Value: boolean);
    function GetSingleLine: boolean;
    function GetFontChrs(const AFontName: TFontName; out GlyphSet: PGlyphSet): boolean;
    function ChrInGlyphSet(GlyphSet: PGlyphSet; Codepoint: integer): boolean; overload;
    function ChrInGlyphSet(GlyphSet: PGlyphSet; Character: char): boolean; overload; inline;
//    function FontHasGlyph(const AFontName: TFontName; const AGlyph: char): boolean;
    procedure UseBestFont(const AChar: Char);
    procedure SetFallbackFonts(const Value: TStringList);
    procedure FallbackFontsChange(Sender: TObject);
    procedure BuildFontDataArray;
    procedure FreeFontDataArray;
    procedure SetUnicodeFallback(const Value: boolean);
    procedure SetPasswordChar(const Value: char);
    function GetBalloonPosition: TPoint;
    procedure BalloonTimerTimer(Sender: TObject);
    procedure SetLabelStyle(const Value: boolean);
    procedure SetLabelEllipsis(const Value: boolean);
    procedure BlinkBracket;
    procedure BlinkRemoverTimer(Sender: TObject);
    procedure SetBracketHighlight(const PointA, PointB: TPoint);
    procedure ClearBracketHighlight;
    procedure HighlightCurrentBracket;
    procedure SetAutoHeight(const Value: boolean);
    procedure AdjustHeight;
    procedure SetMultiSize(const Value: boolean);
    function GetClassRecord(Index: integer): TClassRecord;
    function GetNumClasses: integer;
    procedure UpdateFontBoxSize(ClassIndex: integer);
    procedure UpdateFontBoxSizes;
    procedure TextFileLineChange(Sender: TObject;
      LineChangeType: TLineChangeType; From: integer);
    procedure RebuildLineCache;
    procedure DoSetCaretPos; inline;
    function GetTotalVerticalExtent: integer;
    function GetTotalHorizontalExtent: integer;
    procedure RecomputeHorizontalExtent;
    function GetControlFromID(ID: integer): TControl;
    function GetIDFromControl(AControl: TControl): integer;
    function GetControlIDFromLine(LineIndex: integer): integer;
    function GetLineFromControlID(ID: integer): integer;
    function GetLineControlSize(LineIndex: integer): TSize;
    procedure ClearControls;
    procedure UpdateLineControls;
    procedure FixRemovedLineControlLines;
    function LineIsControl(LineIndex: integer): boolean;
    function LineIsWinControlOrHasPopup(LineIndex: integer): boolean;
    function GetControlFromLine(LineIndex: integer): TControl;
    function LineWidths(LineIndex: integer): integer; // in px, control-aware
    function MaxLineWidth: integer;                   // in px, control-aware
    procedure TextFileLineClassChange(Sender: TObject; LineIndex: integer);
    procedure TextFileControlRemoved(Sender: TObject; ControlID: integer);
    procedure TextFileGetControlText(Sender: TObject; LineIndex: integer;
      var ControlText: string);
    procedure InvalidateLineControl(LineIndex: integer);
    function GetLineTop(LineIndex: integer): integer;
    function GetLineBottom(LineIndex: integer): integer;
    function GetLineBottomVirtual(LineIndex: integer): integer;
    function GetCharLeft(LineIndex, ColIndex: integer): integer;
    function GetCharRight(LineIndex, ColIndex: integer): integer;
    function ActivateControl: HWND;
    procedure ImageMenuCommand(Sender: TObject);
    function GetLine(Index: integer): string;
    procedure SetLine(Index: integer; const Value: string);
    function GetClass(Index: integer): string;
    procedure SetClass(Index: integer; const Value: string);
    procedure ForceSetClass(Index: integer; const Value: string);
    function GetLineCount: integer;
    function FileIsEmpty: boolean;
    procedure GotoSamePixelAtPrevLine(Shift: boolean);
    procedure GotoSamePixelAtNextLine(Shift: boolean);
    function GetBookmark(Index: integer): TPoint;
    function GetBookmarkCount: integer;
    function GetUsedBookmarkCount: integer;
    procedure TextFileBookmarksMoved(Sender: TObject);
    function GetBookmarkDescr(BookmarkIndex: integer): string;
    procedure BookmarkHistoryRecord(const APoint: TPoint);
    procedure SetFormattingProcessor(const Value: TFormattingProcessor;
      AInitialize: boolean = true);
    procedure FormattingProcessorChanged(Sender: TObject);
    function FormattingProcessorGetLineWidth(ALineIndex: integer): integer;
    function FormattingProcessorGetChar(ALineIndex, ACol: integer): char;
    function FormattingProcessorGetLineCount: integer;
    function FormattingProcessorGetWord(const APoint: TPoint;
      APascalIdent: boolean = false): string;
    function FormattingProcessorGetWordBoundary(const APoint: TPoint; out SP,
      EP: integer): boolean;
    function FPFileChangeNotification(ChangeType: TChangeType; Data1, Data2,
      Data3, Data4: Integer): TChangeRecord;
    function TextContentRect: TRect;
    function NonRulerRect: TRect;
    function RulerRect: TRect;
    function LeftColumnRect: TRect;
    procedure DrawRuler;
    procedure RulerFontChange(Sender: TObject);
    procedure UpdateRuler;
    procedure UpdateRulerLine(const ALineIndex: integer);
    procedure BinaryHideCaret;
    procedure BinaryShowCaret;
    procedure SetMarginBottom(const Value: integer);
    procedure SetMarginLeft(const Value: integer);
    procedure SetMarginRight(const Value: integer);
    procedure SetMarginTop(const Value: integer);
    procedure SetRulerWidth(const Value: integer);
    function GetRulerVisible: boolean;
    procedure SetRulerVisible(const Value: boolean);
    procedure SetRulerColor(const Value: TColor);
    procedure SetZoom(const Value: integer);
    procedure MoveBalloonPostScroll;
    procedure SetRightLine(const Value: boolean);
    procedure SetRightLineColor(const Value: TColor);
    procedure SetRightLinePos(const Value: integer);
    procedure SetBorderColor(const Value: TColor);
    procedure SetBorderType(const Value: TBorderType);
    function GetWrapAt: string;
    procedure SetWrapAt(const Value: string);
    function GetFalse: boolean;
    procedure RestoreWrapAt(const Value: boolean);
    procedure SetTextFile(const Value: TTextFile);
    procedure ConnectTextFileToEditor;
    procedure DisconnectTextFileFromEditor;
    function GetEditMode: TEditMode;
    procedure SetFormattingProcessorSmple(const Value: TFormattingProcessor);
    procedure RulerMenuCommand(Sender: TObject);
    procedure RulerPropertiesApply(Sender: TObject);
    function GetFunctionalSelectionBarWidth: integer;
    function CharAtVirtualPixelEx(Pixel: TPoint; const CP: boolean = false): TPoint;
    function CharAtPhysicalPixelEx(Pixel: TPoint; const CP: boolean = false): TPoint;
    function NotifyApp(const MsgID: integer): boolean;
    function NotifyAppWithTimer(const MsgID: integer): boolean;
    procedure RemoveNotification(const MsgID: integer);
    function GetNotification(AIndex: integer): integer;
    function GetNotificationCount: integer;
    function GetNotificationStr(MsgID: integer): string;
    procedure TextFileReadOnlyError(Sender: TObject);
    procedure UpdateScrollMode;
    function GetLineComparer: TLineComparer;
    procedure SetLineComparer(const Value: TLineComparer);
    function GetSortReverseOrder: boolean;
    procedure SetSortReverseOrder(const Value: boolean);
    function CliHistoryUp: boolean;
    function CliHistoryDown: boolean;
    function GetCliHistory(Index: integer): string;
    procedure SetCliHistory(Index: integer; const Value: string);
    function GetCliHistoryCount: integer;
    function GetCliHistoryIndex: integer;
    procedure SetListBoxMode(const Value: boolean);
    procedure SetListBoxItemIndex(const Value: integer);
    function GetListBoxItemIndex: integer;
    procedure CliHistoryDialogListBoxSelect(Sender: TObject);
    procedure NeedValidPaintState;
    procedure CliHistoryDialogListBoxKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DoMultiCharSelect(AChrs: array of char);
    procedure MultiCharSelectDlgResize(Sender: TObject);
    procedure MultiCharSelectDlgWndProc(var Message: TMessage);
    procedure MultiCharSelectDlgActivate(Sender: TObject);
    function CharInSet(AChar: char; ASet: array of char): boolean;
    function CharInAnyMultiCharSet(AChar: char): boolean;
    procedure VerifyFont;
    procedure SetDisabledEffect(const Value: TBitmapEffect);
    procedure SetBitmapEffect(const Value: TBitmapEffect);
    procedure TextFileFindDataClear(Sender: TObject);
    procedure CheckCaretBeyondEOL;
    procedure TextFileLockVisualUpdates(Sender: TObject);
    procedure TextFileUnlockVisualUpdates(Sender: TObject);
    procedure UpdateSPI;
    procedure DoAutoReplace;
    function GetCaretAfterEOL: boolean;
    procedure CreateNewCaretAt(const APoint: TPoint);
    procedure EnterMultiCaretMode;
    function GetLastMultiCaret: TPoint;
    function IsCaretVisible: boolean;
    procedure IndicateInsertionPoint(const APoint: TPoint);
    procedure RemoveInsertionPoint;
    {$HINTS OFF}
    procedure InvalidateChar(const AChar: TPoint);
    {$HINTS ON}
    procedure InvalidateCharAndPrev(const AChar: TPoint);
    procedure GetDragDropEffect(var dwEffect: Integer; grfKeyState: Integer);
    procedure DragDropNotify(dwEffect: Integer);
    function FPFromString(const FPClassName: string): TFormattingProcessor;
  protected
    procedure Paint; override;
    procedure KeyPress(var Key: Char); override;
    procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
    procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
    procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
    procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
    procedure KeyDown(var Key: Word; Shift: TShiftState); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer;
      Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer;
      Y: Integer); override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    procedure DblClick; override;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
    procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
    procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL;
    procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
    procedure WMMouseHWheel(var Message: TWMMouseWheel); message WM_MOUSEHWHEEL;
    procedure WndProc(var Message: TMessage); override;
    procedure Loaded; override;
    procedure CreateWnd; override;
    procedure DestroyWnd; override;
    procedure WMEnable(var Message: TWMEnable); message WM_ENABLE;
    procedure WMContextMenu(var Message: TWMContextMenu);
      message WM_CONTEXTMENU;
    procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
    procedure WMNCPaint(var Message: TWMNCPaint); message WM_NCPAINT;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure WMNCActivate(var Message: TWMNCActivate); message WM_NCACTIVATE;
    procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE;

    { IDropTarget }
    function IDropTarget.DragEnter = DropTargetDragEnter;
    function DropTargetDragEnter(const dataObj: IDataObject;
      grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT;
      stdcall;
    function IDropTarget.DragOver = DropTargetDragOver;
    function DropTargetDragOver(grfKeyState: Longint; pt: TPoint;
      var dwEffect: Longint): HRESULT;
      stdcall;
    function IDropTarget.DragLeave = DropTargetDragLeave;
    function DropTargetDragLeave: HRESULT;
      stdcall;
    function IDropTarget.Drop = DropTargetDrop;
    function DropTargetDrop(const dataObj: IDataObject; grfKeyState:
      Longint; pt: TPoint; var dwEffect: Longint): HRESULT; stdcall;

    { IDropSource }
    function GiveFeedback(dwEffect: Longint): HRESULT; stdcall;
    function QueryContinueDrag(fEscapePRessed: BOOL; grfKeyState: Longint): HRESULT;
      stdcall;

  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure UseDefaultFallbackFonts;
    function EditorCommand(Command: integer; Param1: integer = 0;
      Param2: integer = 0; Param3: integer = 0; Param4: integer = 0): integer;
    function CommandEnabled(Command: integer): boolean;
    function CommandVisible(Command: integer): boolean;
    procedure BeginVisualUpdate;
    procedure EndVisualUpdate(AUpdate: boolean = false);
    procedure CutToClipboard;
    procedure CopyToClipboard;
    procedure CopyAll;
    function PasteFromClipboard: boolean;
    function PasteFromClipboardAsBlock: boolean;
    procedure ClearLine(LineIndex: integer); overload;
    procedure ClearLine; overload;
    procedure AddLine(const AText: string; const AClassName: string); overload;
    procedure AddLine(const AText: string); overload;
    procedure AddLine; overload;
    procedure BeginAddLine;
    procedure EndAddLine;
    procedure InsertLine(const AText: string; const AClassName: string; LineIndex: integer); overload;
    procedure InsertLine(const AText: string; LineIndex: integer); overload;
    procedure InsertLine(LineIndex: integer); overload;
    procedure InsertChar(const AChar: Char; AOverwrite: boolean = false);
    procedure InsertText(const AText: string);
    procedure InsertTextAsBlock(const AText: string);
    procedure SurroundText(const APrefix, APostfix: string);
    procedure TransformText(Transformation: TTextTransformFunc;
      const TransformName: string);
    function TransformSelection(Transformation: TTextTransformFunc;
      const TransformName: string): boolean;
    procedure ChrTransformText(Transformation: TChrTransformFunc;
      const TransformName: string);
    function ChrTransformSelection(Transformation: TChrTransformFunc;
      const TransformName: string): boolean;
    function FillWithChar(const AChar: char): boolean;
    property TextFile: TTextFile read FTextFile write SetTextFile;
    property CaretPos: TPoint read GetCaretPos write SetCaretPos;
    property SelEndPos: TPoint read GetSelEndPos write SetSelEndPos;
    property SelectionType: TSelectionType read GetSelType write SetSelType;
    function GetWordBoundary(const Point: TPoint; out StartPos, EndPos: integer): boolean; overload;
    function GetWordBoundary(out StartPos, EndPos: integer): boolean; overload;
    function GetWord(const Point: TPoint): string; overload;
    function GetWord: string; overload;
    function GetURLAtCaret(out AURL: string): boolean;
    function OpenURLAtCaret: boolean;
    function SelectWord: boolean;
    procedure SwapLinesAbove;
    procedure SwapLinesBelow;
    procedure SelectLines(const ALineA, ALineB: integer);
    procedure SelectLine(ALineIndex: integer); overload;
    procedure SelectLine; overload;
    procedure SelectAll;
    procedure SelectNone;
    procedure SelectAllNone;
    procedure Backspace(Word: boolean = false);
    procedure Delete(Word: boolean = false);
    procedure Return;
    procedure ReplaceCodepoint;
    function CharAtVirtualPixel(Pixel: TPoint): TPoint;
    function CharAtPhysicalPixel(Pixel: TPoint): TPoint;
    function CaretPosAtVirtualPixel(Pixel: TPoint): TPoint; {top-left of possible caret}
    function CaretPosAtPhysicalPixel(Pixel: TPoint): TPoint;
    function VirtualPixelAtChar(const Point: TPoint): TPoint; {top-left of chr box}
    function PhysicalPixelAtChar(const Point: TPoint): TPoint;
    function GetCharAtCaret: char;
    function GetCharBeforeCaret: char;
    procedure ClearSelection;
    procedure MoveSelection(const ANewPos: TPoint);
    procedure CopySelection(const ANewPos: TPoint);
    procedure AddIndent;
    procedure RemoveIndent;
    procedure RemoveAllIndent;
    procedure PageUp(Selection: boolean = false);
    procedure PageDown(Selection: boolean = false);
    function CanUndo: boolean;
    function Undo: boolean;
    function CanRedo: boolean;
    function Redo: boolean;
    function GotoHistoryVersion(Index: integer): boolean;
    procedure ClearUndoHistory;
    procedure MakeUndoRoot;
    procedure TypeTimerEnd;
    procedure AddUndoRecord(const AComment: string; UID: UNDONAMEID);
    procedure Clear;
    procedure NewFile;
    procedure LoadFromFile(const FileName: TFileName; const Encoding: TEncoding);
    procedure SaveToFile(const FileName: TFileName; TrimRight: boolean = false);
    procedure Print(const ATitle: string;
      AFirstLine: integer = 0; ALastLine: integer = -1); overload;
    procedure Print(AFirstLine: integer = 0; ALastLine: integer = -1); overload;
    procedure PrintSelection(const ATitle: string); overload;
    procedure PrintSelection; overload;
    property SelText: string read GetSelText write InsertText;
    property SelStart: integer read GetSelStart write SetSelStart;
    property SelLength: integer read GetSelLength write SetSelLength;
    function Find(AFindQuery: TFindQuery): integer;
    function FindNext: integer;
    function FindPrevious: integer;
    function FindFromTop: integer;
    property StartOver: boolean read FStartOver write FStartOver;
    function ReplaceAll(const FindQuery: TFindQuery;
      const ReplaceText: string; SelOnly: boolean = false): integer;
    function ShowBalloon(const ATitle, AText: string; AKind: TBalloonIconKind;
      APersistence: TBalloonPersistence; const APoint: TPoint): boolean;
    procedure HideBalloon;
    function BalloonVisible: boolean;
    procedure AddClass(const AClassRecord: TClassRecord);
    function RemoveClass(const AClassName: string): boolean;
    procedure ClearClasses;
    function GetClassFromName(const AClassName: string; out AClassRecord: TClassRecord): boolean;
    function GetClassIndex(const AClassName: string): integer;
    function ClassExists(const AClassName: string): boolean; overload; inline;
    function ClassExists(const AClassName: string; out Index: integer): boolean; overload; inline;
    property Classes[Index: integer]: TClassRecord read GetClassRecord;
    property ClassCount: integer read GetNumClasses;
    procedure AddLineControl(AControl: TControl);
    procedure InsertLineControl(AControl: TControl; LineIndex: integer);
    procedure AddGraphic(AGraphic: TGraphic);
    function DeleteControlAtLine(const LineIndex: integer): boolean;
    procedure CenterOnSelection(AReducedScroll: boolean = false);
    property TotalVerticalExtent: integer read GetTotalVerticalExtent;
    property TotalHorizontalExtent: integer read GetTotalHorizontalExtent;

    { Removes all line controls and resets the FTextFile.ControlAware flag. }
    procedure DeleteAllLineControls;

    procedure InsertGraphic(AGraphic: TGraphic; LineIndex: integer);
    function ControlInSelection: boolean;
    procedure TrimRight;
    procedure ClearBookmarks; inline;
    procedure AddBookmark(AIndex: integer; const APoint: TPoint); overload; inline;
    procedure AddBookmark(AIndex: integer); overload; inline;
    function AddBookmark(const APoint: TPoint): integer; overload; inline;
    function AddBookmark: integer; overload; inline;
    function GotoBookmark(AIndex: integer): boolean; inline;
    function BookmarkUsed(AIndex: integer): boolean; inline;
    function GetLineBookmark(ALineIndex: integer): integer;
    property LineCount: integer read GetLineCount;
    property Lines[Index: integer]: string read GetLine write SetLine;
    property LineClasses[Index: integer]: string read GetClass write SetClass; { Does not add an undo item. Should it?! }
    property Bookmarks[Index: integer]: TPoint read GetBookmark;
    property BookmarkCount: integer read GetBookmarkCount;
    property UsedBookmarkCount: integer read GetUsedBookmarkCount;
    procedure ExportToHTML(const FileName: TFileName);
    procedure RemoveAllMargins;
    procedure RestoreAllMargins;
    procedure ZoomIn;
    procedure ZoomOut;
    procedure ResetZoom;
    procedure WordWrap(ALineLength: integer = 80; ANice: boolean = true;
      AChr: char = #0);

    property Notifications[AIndex: integer]: integer read GetNotification;
    property NotificationCount: integer read GetNotificationCount;
    property NotificationStr[MsgID: integer]: string read GetNotificationStr;

    function HasNotificationMessage(MsgID: integer): boolean;
    function Sort(AFirstLine, ALastLine: integer): boolean; overload;
    function Sort: boolean; overload;
    function SortSelection: boolean;
    property LineComparer: TLineComparer read GetLineComparer write SetLineComparer;
    property SortReverseOrder: boolean read GetSortReverseOrder write SetSortReverseOrder;
    function MakeLinesUnique: boolean;
    procedure TruncateAt(AFirstLine, ALastLine, AIndex: integer;
      AChar: char = #0; PreserveChar: boolean = false; AReverse: boolean = false); overload;
    procedure TruncateAt(AIndex: integer;
      AChar: char = #0; PreserveChar: boolean = false; AReverse: boolean = false); overload;
    procedure TruncateAtInSelection(AIndex: integer;
      AChar: char = #0; PreserveChar: boolean = false; AReverse: boolean = false);
    procedure Filter(const AFilterOptions: TFilterOptions); overload;
    procedure Filter(const Contains, Starts, Ends: string; CaseSensitive: boolean;
      RemoveMatches: boolean); overload;

    procedure CliNewPrompt;
    procedure CliBeginOutput;
    procedure CliEndOutput;
    procedure CliWriteLn(const AStr, AClass: string); overload;
    procedure CliWriteLn(const AStr: string); overload;
    procedure CliWriteLn; overload;
    procedure CliAddHistory(const AStr: string);
    procedure CliClearHistory;
    property CliHistory[Index: integer]: string read GetCliHistory write SetCliHistory;
    property CliHistoryCount: integer read GetCliHistoryCount;
    property CliHistoryIndex: integer read GetCliHistoryIndex;
    function CliHistoryRecall(Index: integer): boolean;
    function CliHistoryDialog: integer;
    function CliHistoryDialogSelect: boolean;

    procedure RunScript(const AScript: TEditorScript; AIterations: integer = 1;
      ACounterInit: integer = 1; ACounterInc: integer = 1);
    procedure AbortScript;

    procedure LoadDefaultClasses;

    procedure PushEditorState;

    procedure RegisterFP(FormattingProcessor: TFormattingProcessor);
  published
    property Align;
    property AlignWithMargins;
    property Anchors;
    property BorderType: TBorderType read FBorderType write SetBorderType default btThemeBorder;
    property BorderWidth;
    property BorderColor: TColor read FBorderColor write SetBorderColor default clSilver;
    property Enabled;
    property Margins;
    property PopupMenu;
    property RulerPopupMenu: TPopupMenu read FRulerPopupMenu write FRulerPopupMenu;
    property TabStop default true;
    property TabOrder;
    property OnClick;
    property OnDblClick;
    property OnKeyDown;
    property OnKeyPress;
    property OnKeyUp;
    property OnMouseEnter;
    property OnMouseLeave;
    property OnMouseMove;
    property OnMouseDown;
    property OnMouseUp;
    property OnMouseActivate;
    property OnEnter;
    property OnExit;
    property BitmapEffect: TBitmapEffect read FBitmapEffect write SetBitmapEffect default beNone;
    property DisabledEffect: TBitmapEffect read FDisabledEffect write SetDisabledEffect default beGrayscale;
    property HandleHotkeys: boolean read FHandleHotkeys write FHandleHotkeys default true;
    property HandleBookmarkHotkeys: boolean read FHandleBookmarkHotkeys write FHandleBookmarkHotkeys default true;
    property UseSystemColors: boolean read FUseSystemColors write SetUseSystemColors default true;
    property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor default clWhite;
    property ForegroundColor: TColor read FForegroundColor write SetForegroundColor default clBlack;
    property SelBackgroundColor: TColor read FSelBackgroundColor write SetSelBackgroundColor default clBlack;
    property SelForegroundColor: TColor read FSelForegroundColor write SetSelForegroundColor default clWhite;
    property FindBackgroundColor: TColor read FFndBkColor write SetFindBackgroundColor default clYellow;
    property FindForegroundColor: TColor read FFndFgColor write SetFindForegroundColor default clBlack;
    property Font: TFont read FFont write SetFont;
    property LetterSpacing: integer read FLetterSpacing write SetLetterSpacing default 1;
    property LineSpacing: integer read FLineSpacing write SetLineSpacing default 1;
    property CaretAfterEOL: boolean read GetCaretAfterEOL write SetCaretAfterEOL default true;
    property AutoIndent: boolean read FAutoIndent write SetAutoIndent default true;
    property PlainText: string read GetText write SetText;
    property BeepOnInputError: boolean read FBeepOnInputError write FBeepOnInputError default true;
    property ErrorMessageOnReadOnlyError: boolean read FErrorMessageOnReadOnlyError write FErrorMessageOnReadOnlyError default true;
    property Overwrite: boolean read FOverwrite write SetOverwrite default false;
    property IndentSize: integer read FIndentSize write SetIndentSize default 2;
    property EditMode: TEditMode read GetEditMode write SetEditMode default emText;
    property ShowHiddenCharacters: boolean read FShowHiddenCharacters write SetShowHiddenCharacters default false;
    property LineHighlight: boolean read FLineHighlight write SetLineHighlight default false;
    property LineHighlightColor: TColor read FLineHighlightColor write SetLineHighlightColor default DEFAULT_LINE_HIGHLIGHT_COLOR;
    property MatchBrackets: boolean read FMatchBrackets write SetMatchBrackets default true;
    property BracketHighlightColor: TColor read FBracketHighlightColor write SetBracketHighlightColor default DEFAULT_BRACKET_HIGHLIGHT_COLOR;
    property AutoReplace: boolean read FAutoReplace write FAutoReplace default false;
    property MessageInterface: boolean read FMessageInterface write FMessageInterface default true;
    property InputTransform: TInputTransform read FInputTransform write FInputTransform default itNone;
    property SingleLine: boolean read GetSingleLine write SetSingleLine default false;
    property FallbackFonts: TStringList read FFallbackFonts write SetFallbackFonts;
    property UnicodeFallback: boolean read FUnicodeFallback write SetUnicodeFallback default true;
    property PasswordChar: char read FPasswordChar write SetPasswordChar default #0;
    property NumbersOnly: boolean read FNumbersOnly write FNumbersOnly default false;
    property TabLength: integer read FTabLength write FTabLength default 2;
    property LabelStyle: boolean read FLabelStyle write SetLabelStyle default false;
    property LabelEllipsis: boolean read FLabelEllipsis write SetLabelEllipsis default true;
    property AutoHeight: boolean read FAutoHeight write SetAutoHeight default true;
    property MultiSize: boolean read FMultiSize write SetMultiSize default false;
    property FormattingProcessor: TFormattingProcessor read FFormattingProcessor write SetFormattingProcessorSmple;
    property RulerFont: TFont read FRulerFont write FRulerFont;
    property RulerVisible: boolean read GetRulerVisible write SetRulerVisible stored false;
    property MarginLeft: integer read FMarginLeft write SetMarginLeft default DEFAULT_MARGIN_LEFT;
    property MarginRight: integer read FMarginRight write SetMarginRight default DEFAULT_MARGIN_Right;
    property MarginTop: integer read FMarginTop write SetMarginTop default DEFAULT_MARGIN_Top;
    property MarginBottom: integer read FMarginBottom write SetMarginBottom default DEFAULT_MARGIN_Bottom;
    property RulerWidth: integer read FRulerWidth write SetRulerWidth default DEFAULT_RULER_WIDTH;
    property RulerColor: TColor read FRulerColor write SetRulerColor default clDefault;
    property PrintSettings: TPrintSettings read FPrintSettings;
    property Zoom: integer read FZoom write SetZoom default 100;
    property RightLine: boolean read FRightLine write SetRightLine default false;
    property RightLinePos: integer read FRightLinePos write SetRightLinePos default 580;
    property RightLineColor: TColor read FRightLineColor write SetRightLineColor default clSilver;
    property WrapAt: string read GetWrapAt write SetWrapAt;
    property WrapAtRestore: boolean read GetFalse write RestoreWrapAt default false;
    property TextFileOwner: TTextFileOwner read FTextFileOwner write FTextFileOwner default tfoEditor;
    property SelectionBarBehaviour: TSelectionBarBehaviour read FSelectionBarBehaviour write FSelectionBarBehaviour default sbbAutoMixed;
    property NotificationMsgDuration: integer read FNotifyMsgDuration write FNotifyMsgDuration default DEFAULT_NOTIFICATION_MSG_DURATION;
    property ListBoxMode: boolean read FListBoxMode write SetListBoxMode;
    property ListBoxItemIndex: integer read GetListBoxItemIndex write SetListBoxItemIndex;
    property MultiCharSelect: boolean read FMultiCharSelect write FMultiCharSelect default true;
    property MultiCharReportView: boolean read FMultiCharReportView write FMultiCharReportView default false;
    property ScrollBehaviour: TScrollBehaviour read FScrollBehaviour write FScrollBehaviour default sbDefault;
    property AllowBitmapPaste: boolean read FAllowBitmapPaste write FAllowBitmapPaste default false;
    property Visible;
    property WantTab: boolean read FWantTab write FWantTab default true;
    property WantReturn: boolean read FWantReturn write FWantReturn default true;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property OnSelChange: TNotifyEvent read FOnSelChange write FOnSelChange;
    property OnModified: TNotifyEvent read FOnModified write FOnModified;
    property OnOverwriteChange: TNotifyEvent read FOnOverwriteChange write FOnOverwriteChange;
    property OnBookmarksMoved: TNotifyEvent read FOnBookmarksMoved write FOnBookmarksMoved;
    property OnZoomChange: TNotifyEvent read FOnZoomChange write FOnZoomChange;
    property OnPrintBegin: TProgressStartEvent read FOnPrintBegin write FOnPrintBegin;
    property OnPrintProgress: TProgressEvent read FOnPrintProgress write FOnPrintProgress;
    property OnPrintEnd: TProgressCompleteEvent read FOnPrintEnd write FOnPrintEnd;
    property OnNotification: TNotificationMessage read FOnNotification write FOnNotification;
    property OnSimpleNotification: TSimpleNotificationMessage read FOnSimpleNotification write FOnSimpleNotification;
    property OnCliGetPromptClass: TCliGetPromptClassEvent read FOnCliGetPromptClass write FOnCliGetPromptClass;
    property OnCliInput: TCliInputEvent read FOnCliInput write FOnCliInput;
    property OnListBoxChange: TNotifyEvent read FOnListBoxChange write FOnListBoxChange;
    property OnListBoxSelect: TNotifyEvent read FOnListBoxSelect write FOnListBoxSelect;
    property OnFindDataClear: TNotifyEvent read FOnFindDataClear write FOnFindDataClear;
  end;

procedure Register;

const
  // Cursors
  RTE_CURSOR_BASE = 10;
  crBlock = TCursor(RTE_CURSOR_BASE + 1);
  crBlockCopy = TCursor(RTE_CURSOR_BASE + 2);
  crHand = TCursor(RTE_CURSOR_BASE + 3);
  crHandHold = TCursor(RTE_CURSOR_BASE + 4);
  crLineSel = TCursor(RTE_CURSOR_BASE + 5);

var
  FixedWidthFonts: TStrings;
  GlobalFileNumber: integer = 1;

type
  DynIntegerArray = array of integer;
  DynStringArray = array of string;

function FormatDataSize(const ASize: Int64): string;
function Split(const Str: string; const Delim: string): DynStringArray;

implementation

{$R TextEditorCursors.res}

{$WARN WIDECHAR_REDUCED OFF}

uses Character, StrUtils, Clipbrd, IMouse, SHFolder, Dialogs, ShellAPI,
  Printers, Themes, RulerPropertiesWin, MultiInput, StdCtrls, ComCtrls;

const
  CARET_WIDTH = 2;
  SCROLL_EXTRA = 120;
  AUTO_HEIGHT_PADDING = 2;

procedure Register;
begin
  RegisterComponents('Rejbrand 2015', [TTextEditor,
    TVowelsAndConsonantsFormattingProcessor, TXMLFormattingProcessor,
    TCSSFormattingProcessor, TINIFormattingProcessor, TPascalFormattingProcessor,
    TAlgoSimFormattingProcessor, THTMLFormattingProcessor,
    TMediaWikiFormattingProcessor]);
end;

function B(A: boolean): integer;
begin
  if A then
    result := 1
  else
    result := 0;
end;

function GetAppDataFolder: string;
var
  i: integer;
begin
  SetLength(result, MAX_PATH);
  if SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, PChar(result)) <> S_OK then
    Exit('');
  i := Pos(#0, result);
  if i > 0 then
    SetLength(result, i-1);
end;

function GetAutoReplaceDataFileName: string;
var
  AppData: string;
begin
  AppData := GetAppDataFolder;
  if AppData = '' then Exit('');
  result := AppData + '\Rejbrand\AutoReplace\1.0\autoreplace.dat';
end;

function FontRecord(ASize: integer; AStyle: TFontStyles; AColor: TColor): TFontRecord;
begin
  result.Size := ASize;
  result.Style := AStyle;
  result.Color := AColor;
end;

function MakeClass(const AName: string; ASize: integer; AStyle: TFontStyles; AColor: TColor): TClassRecord;
begin
  result.Name := AName;
  result.Format := FontRecord(ASize, AStyle, AColor);
end;

function MakeFindQuery(const ASearchString: string; AMatchCase, AMatchWord, ALinebreak: boolean): TFindQuery;
begin
  result.SearchString := ASearchString;
  result.MatchCase := AMatchCase;
  result.MatchWord := AMatchWord;
  result.Linebreak := ALinebreak;
  result.UCBlock := 0;
end;

function MakeFindQuery(UCBlock: integer): TFindQuery; overload;
begin
  result.SearchString := '';
  result.MatchCase := false;
  result.MatchWord := false;
  result.Linebreak := false;
  result.UCBlock := UCBlock;
end;

function SamePoint(const Point1, Point2: TPoint): boolean; inline;
begin
  result := (Point1.X = Point2.X) and (Point1.Y = Point2.Y);
end;

function SameChangeRecord(const ChangeRecord1, ChangeRecord2: TChangeRecord): boolean; inline;
begin
  result := (ChangeRecord1.ChangeType = ChangeRecord2.ChangeType) and
            (ChangeRecord1.Data1      = ChangeRecord2.Data1)      and
            (ChangeRecord1.Data2      = ChangeRecord2.Data2)      and
            (ChangeRecord1.Data3      = ChangeRecord2.Data3)      and
            (ChangeRecord1.Data4      = ChangeRecord2.Data4);
end;

// No false positives, but (rare) false negatives are possible
function ChangeSubset(const ChangeRecord1, ChangeRecord2: TChangeRecord): boolean;

  function IsOneOfThem(const Y, X: integer): boolean;
  begin
    // Assuming: ChangeRecord2.ChangeType = ctTwoChars
    result := ((Y = ChangeRecord2.Data1) and (X = ChangeRecord2.Data2))
                                         OR
              ((Y = ChangeRecord2.Data3) and (X = ChangeRecord2.Data4));
  end;

begin
  result := false;
  case ChangeRecord2.ChangeType of
    ctFile:
      Exit(true);
    ctLineRange:
      case ChangeRecord1.ChangeType of
        ctNone:
          Exit(true);
        ctFile:
          Exit(false);
        ctLineRange:
          Exit((ChangeRecord1.Data1 >= ChangeRecord2.Data1) and (ChangeRecord1.Data2 <= ChangeRecord2.Data2));
        ctBlock:
          Exit((ChangeRecord1.Data1 >= ChangeRecord2.Data1) and (ChangeRecord1.Data2 <= ChangeRecord2.Data2));
        ctLine:
          Exit(InRange(ChangeRecord1.Data1, ChangeRecord2.Data1, ChangeRecord2.Data2));
        ctLineFrom:
          Exit(InRange(ChangeRecord1.Data1, ChangeRecord2.Data1, ChangeRecord2.Data2));
        ctChar:
          Exit(InRange(ChangeRecord1.Data1, ChangeRecord2.Data1, ChangeRecord2.Data2));
        ctTwoChars:
          Exit(InRange(ChangeRecord1.Data1, ChangeRecord2.Data1, ChangeRecord2.Data2) and InRange(ChangeRecord1.Data3, ChangeRecord2.Data1, ChangeRecord2.Data2));
      end;
    ctBlock:
      case ChangeRecord1.ChangeType of
        ctNone:
          Exit(true);
        ctFile:
          Exit(false);
        ctLineRange:
          Exit(false);
        ctBlock:
          Exit((ChangeRecord1.Data1 >= ChangeRecord2.Data1) and (ChangeRecord1.Data2 <= ChangeRecord2.Data2) and (ChangeRecord1.Data3 >= ChangeRecord2.Data3) and (ChangeRecord1.Data4 <= ChangeRecord2.Data4));
        ctLine:
          Exit(false);
        ctLineFrom:
          Exit(false);
        ctChar:
          Exit(InRange(ChangeRecord1.Data1, ChangeRecord2.Data1, ChangeRecord2.Data2) and InRange(ChangeRecord1.Data2, ChangeRecord2.Data3, ChangeRecord2.Data4));
        ctTwoChars:
          Exit(InRange(ChangeRecord1.Data1, ChangeRecord2.Data1, ChangeRecord2.Data2) and InRange(ChangeRecord1.Data2, ChangeRecord2.Data3, ChangeRecord2.Data4) and InRange(ChangeRecord1.Data3, ChangeRecord2.Data1, ChangeRecord2.Data2) and InRange(ChangeRecord1.Data4, ChangeRecord2.Data3, ChangeRecord2.Data4));
      end;
    ctLine:
      case ChangeRecord1.ChangeType of
        ctNone:
          Exit(true);
        ctFile:
          Exit(false);
        ctLineRange:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 = ChangeRecord2.Data1));
        ctBlock:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 = ChangeRecord2.Data1));
        ctLine:
          Exit(ChangeRecord1.Data1 = ChangeRecord2.Data1);
        ctLineFrom:
          Exit(ChangeRecord1.Data1 = ChangeRecord2.Data1);
        ctChar:
          Exit(ChangeRecord1.Data1 = ChangeRecord2.Data1);
        ctTwoChars:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data3 = ChangeRecord2.Data1));
      end;
    ctLineFrom:
      case ChangeRecord1.ChangeType of
        ctNone:
          Exit(true);
        ctFile:
          Exit(false);
        ctLineRange:
          Exit((ChangeRecord2.Data2 = 0) and (ChangeRecord1.Data1 = ChangeRecord1.Data2) and (ChangeRecord1.Data1 = ChangeRecord2.Data1));
        ctBlock:
          Exit((ChangeRecord1.Data1 = ChangeRecord1.Data2) and (ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data3 >= ChangeRecord2.Data2));
        ctLine:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord2.Data2 = 0));
        ctLineFrom:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 >= ChangeRecord2.Data2));
        ctChar:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 >= ChangeRecord2.Data2));
        ctTwoChars:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 >= ChangeRecord2.Data2) and (ChangeRecord1.Data3 = ChangeRecord2.Data1) and (ChangeRecord1.Data4 >= ChangeRecord2.Data2));
      end;
    ctChar:
      case ChangeRecord1.ChangeType of
        ctNone:
          Exit(true);
        ctFile:
          Exit(false);
        ctLineRange:
          Exit(false);
        ctBlock:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord2.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data3 = ChangeRecord2.Data2) and (ChangeRecord2.Data3 = ChangeRecord2.Data2));
        ctLine:
          Exit(false);
        ctLineFrom:
          Exit(false);
        ctChar:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 = ChangeRecord2.Data2));
        ctTwoChars:
          Exit((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 = ChangeRecord2.Data2) and (ChangeRecord1.Data3 = ChangeRecord2.Data1) and (ChangeRecord1.Data4 = ChangeRecord2.Data2));
      end;
    ctTwoChars:
      case ChangeRecord1.ChangeType of
        ctNone:
          Exit(true);
        ctFile:
          Exit(false);
        ctLineRange:
          Exit(false);
        ctBlock:
          Exit(((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord2.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data3 = ChangeRecord2.Data2) and (ChangeRecord2.Data3 = ChangeRecord2.Data2))   OR   ((ChangeRecord1.Data1 = ChangeRecord2.Data3) and (ChangeRecord2.Data1 = ChangeRecord2.Data3) and (ChangeRecord1.Data3 = ChangeRecord2.Data4) and (ChangeRecord2.Data3 = ChangeRecord2.Data4)));
        ctLine:
          Exit(false);
        ctLineFrom:
          Exit(false);
        ctChar:
          Exit(((ChangeRecord1.Data1 = ChangeRecord2.Data1) and (ChangeRecord1.Data2 = ChangeRecord2.Data2))   OR   ((ChangeRecord1.Data1 = ChangeRecord2.Data3) and (ChangeRecord1.Data2 = ChangeRecord2.Data4)));
        ctTwoChars:
          Exit(IsOneOfThem(ChangeRecord1.Data1, ChangeRecord1.Data2) and IsOneOfThem(ChangeRecord1.Data3, ChangeRecord1.Data4));
      end;
  end;
end;

function MakeChangeRecord(ChangeType: TChangeType; Data1, Data2, Data3, Data4: integer): TChangeRecord;
begin
  result.ChangeType := ChangeType;
  result.Data1 := Data1;
  result.Data2 := Data2;
  result.Data3 := Data3;
  result.Data4 := Data4;
end;

function ChangeUnion(const ChangeRecord1, ChangeRecord2: TChangeRecord): TChangeRecord;
begin

  if (ChangeRecord1.ChangeType = ctFile) or (ChangeRecord2.ChangeType = ctFile) then
    Exit(FILE_CHANGE_RECORD);

  if ChangeSubset(ChangeRecord1, ChangeRecord2) then
    Exit(ChangeRecord2);

  if ChangeSubset(ChangeRecord2, ChangeRecord1) then
    Exit(ChangeRecord1);

  if (ChangeRecord1.ChangeType = ctChar) and (ChangeRecord1.ChangeType = ctChar) then
  begin
    result.ChangeType := ctTwoChars;
    result.Data1 := ChangeRecord1.Data1;
    result.Data2 := ChangeRecord1.Data2;
    result.Data3 := ChangeRecord2.Data1;
    result.Data4 := ChangeRecord2.Data2;
    Exit;
  end;

  if (ChangeRecord1.ChangeType = ctBlock) and (ChangeRecord2.ChangeType = ctBlock) then
  begin
    result.ChangeType := ctBlock;
    result.Data1 := Min(ChangeRecord1.Data1, ChangeRecord2.Data1);
    result.Data2 := Max(ChangeRecord1.Data2, ChangeRecord2.Data2);
    result.Data3 := Min(ChangeRecord1.Data3, ChangeRecord2.Data3);
    result.Data4 := Max(ChangeRecord1.Data4, ChangeRecord2.Data4);
    Exit;
  end;

  if (ChangeRecord1.ChangeType = ctLineRange) and (ChangeRecord2.ChangeType = ctLineRange) then
  begin
    result.ChangeType := ctLineRange;
    result.Data1 := Min(ChangeRecord1.Data1, ChangeRecord2.Data1);
    result.Data2 := Max(ChangeRecord1.Data2, ChangeRecord2.Data2);
    Exit;
  end;

  if (ChangeRecord1.ChangeType = ctLineRange) and (ChangeRecord2.ChangeType in [ctLine, ctLineFrom, ctChar]) then
  begin
    result.ChangeType := ctLineRange;
    result.Data1 := Min(ChangeRecord1.Data1, ChangeRecord2.Data1);
    result.Data2 := Max(ChangeRecord1.Data2, ChangeRecord2.Data1);
    Exit;
  end;

  if (ChangeRecord2.ChangeType = ctLineRange) and (ChangeRecord1.ChangeType in [ctLine, ctLineFrom, ctChar]) then
  begin
    result.ChangeType := ctLineRange;
    result.Data1 := Min(ChangeRecord2.Data1, ChangeRecord1.Data1);
    result.Data2 := Max(ChangeRecord2.Data2, ChangeRecord1.Data1);
    Exit;
  end;

  result := FILE_CHANGE_RECORD;

end;

function MakeEditorCommand(Verb: integer; Param1: integer = 0;
  ParamType1: TParamType = ptConstant; Param2: integer = 0;
  ParamType2: TParamType = ptConstant; Param3: integer = 0;
  ParamType3: TParamType = ptConstant; Param4: integer = 0;
  ParamType4: TParamType = ptConstant): TEditorCommand;
begin
  result.Verb := Verb;
  result.Param1.ParamType := ParamType1;
  result.Param1.ParamValue := Param1;
  result.Param2.ParamType := ParamType2;
  result.Param2.ParamValue := Param2;
  result.Param3.ParamType := ParamType3;
  result.Param3.ParamValue := Param3;
  result.Param4.ParamType := ParamType4;
  result.Param4.ParamValue := Param4;
end;

// Private utilities

function Occurrences(const Str: string; const Chr: char): integer; overload;
var
  i: integer;
begin
  result := 0;
  for i := 1 to Str.Length do
    if Str[i] = Chr then
      inc(result);
end;

function Occurrences(const Str: string; const SubStr: string;
  out indices: DynIntegerArray): integer; overload;
const
  ALLOC_BY = 4096;
var
  i: integer;
begin
  result := 0;
  i := 0;
  SetLength(indices, ALLOC_BY);
  repeat
    i := PosEx(SubStr, Str, i + 1);
    if i > 0 then
    begin
      if result = length(indices) then
        SetLength(indices, Length(indices) + ALLOC_BY);
      indices[result] := i;
      inc(result);
    end;
  until i = 0;
  SetLength(indices, result);
end;

function Occurrences2(const Str: string; const SubStr: string;
  out indices: DynIntegerArray): integer; overload;
const
  ALLOC_BY = 4096;
var
  i: integer;
begin
  result := 0;
  i := 0;
  SetLength(indices, ALLOC_BY);
  repeat
    i := PosEx(SubStr, Str, i + 1);
    if i > 0 then
    begin
      if result = length(indices) then
        SetLength(indices, Length(indices) + ALLOC_BY);
      indices[result] := i;
      inc(result);
    end;
  until i = 0;
  SetLength(indices, result + 1);
  indices[result] := Length(Str) + 1;
end;

function FormatDataSize(const ASize: Int64): string;
const
  prefixes: array[0..6] of string = ('', 'k', 'M', 'G', 'T', 'P', 'E');
var
  val: real;
  n: integer;
begin
  if ASize < 0 then
    raise Exception.CreateFmt('FormatDataSize: Invalid data size %d.', [ASize]);
  val := ASize;
  for n := 0 to high(prefixes) do
  begin
    if (val <= 1000) or (n = high(prefixes)) then
    begin
      result := FormatFloat('0.##', val) + #32 + prefixes[n] + 'B';
      break;
    end;
    val := val / 1024;
  end;
end;

function Split(const Str: string; const Delim: string): DynStringArray;
var
  n: integer;
  indices: DynIntegerArray;
  i: Integer;
begin
  n := Occurrences2(Str, Delim, indices);
  SetLength(result, n + 1);
  if n = 0 then
    result[0] := Str
  else
  begin
    result[0] := Copy(Str, 1, indices[0] - 1);
    for i := 0 to n - 1 do
      result[i+1] := Copy(Str, indices[i] + Length(Delim), indices[i + 1] - indices[i] - Length(Delim));
  end;
end;

{ Text transformation functions }

function imod(const x: integer; const y: integer): integer;
begin
  if x >= 0 then
    imod := x - floor(x/y) * y
  else
    imod := x + ceil(-x/y) * y;
end;

function ChrUpperCase(C: char): char;
begin
  result := AnsiUpperCase(C)[1];
end;

function ChrLowerCase(C: char): char;
begin
  result := AnsiLowerCase(C)[1];
end;

function ChrInvertCase(C: char): char;
begin
  if C.IsUpper then
    result := AnsiLowerCase(C)[1]
  else
    result := AnsiUpperCase(C)[1];
end;

function ChrROT13(C: char): char;
begin
  if InRange(ord(C), ord('A'), ord('Z')) then
    result := Chr(ord('A') + (ord(C) - ord('A') + 13) mod 26)
  else if InRange(ord(C), ord('a'), ord('z')) then
    result := Chr(ord('a') + (ord(C) - ord('a') + 13) mod 26)
  else
    result := C;
end;

function ChrCaesar(N: integer): TChrTransformFunc;
begin
  result := function(C: char): char
    begin
      if InRange(ord(C), ord('A'), ord('Z')) then
        result := Chr(ord('A') + imod((ord(C) - ord('A') + N), 26))
      else if InRange(ord(C), ord('a'), ord('z')) then
        result := Chr(ord('a') + imod((ord(C) - ord('a') + N), 26))
      else
        result := C;
    end;
end;

function TxtVigenère(const Key: string; decode: boolean = false): TTextTransformFunc;
var
  n: integer;
  KeyChrs: array of byte;
  i: Integer;
  factor: integer;
begin
  n := Length(Key);
  SetLength(KeyChrs, n);
  for i := 1 to n do
    if InRange(ord(Key[i]), ord('A'), ord('Z')) then
      KeyChrs[i - 1] := ord(Key[i]) - ord('A')
    else
      raise Exception.Create('Invalid character in Vigenère key.');

  factor := IfThen(decode, -1, 1);
  result := function(const AText: string): string
    var
      j: Integer;
    begin
      SetLength(result, Length(AText));
      for j := 1 to Length(AText) do
      begin
        if InRange(ord(AText[j]), ord('A'), ord('Z')) then
          result[j] := Chr(ord('A') + imod(ord(AText[j]) - ord('A') + factor * KeyChrs[(j - 1) mod n], 26))
        else if InRange(ord(AText[j]), ord('a'), ord('z')) then
          result[j] := Chr(ord('a') + imod(ord(AText[j]) - ord('a') + factor * KeyChrs[(j - 1) mod n], 26))
        else
          result[j] := AText[j];
      end;
    end;
end;

function TxtCamelCase(const AText: string): string;
var
  i: Integer;
  StartOfWord: boolean;
begin
  StartOfWord := true;
  result := AText;
  for i := 1 to Length(AText) do
  begin
    if StartOfWord and IsCharAlpha(AText[i]) then
    begin
      result[i] := AnsiUpperCase(AText[i])[1];
      StartOfWord := false;
    end
    else if AText[i].IsWhiteSpace then
      StartOfWord := true;
  end;
end;

function TxtSentenceCase(const AText: string): string;
var
  StartOfSentence: boolean;
  i: Integer;
begin
  StartOfSentence := true;
  result := AText;
  for i := 1 to AText.Length do
    if StartOfSentence and IsCharAlpha(AText[i]) then
    begin
      result[i] := AnsiUpperCase(AText[i])[1];
      StartOfSentence := false;
    end
    else if AText[i] in ['.', '!', '?'] then
      StartOfSentence := true;
end;

function ReverseText(const AText: string): string;
var
  i, j: integer;
begin
  SetLength(result, AText.Length);
  if AText.IsEmpty then
    Exit;
  i := 1;
  j := result.Length;
  while j > 0 do
  begin
    if (AText[i] = #13) and (i < AText.Length) and (AText[i + 1] = #10) then
    begin
      result[j] := #10;
      result[j - 1] := #13;
      inc(i);
      dec(j);
    end
    else
      result[j] := AText[i];
    inc(i);
    dec(j);
  end;
end;

{ TTextEditor }

function IsKeyDown(const AKey: integer): boolean;
begin
  result := GetKeyState(AKey) and $8000 <> 0;
end;

function IsKeyOn(const AKey: integer): boolean;
begin
  result := GetKeyState(AKey) and 1 = 1;
end;

function GetScrollMode: boolean;
var
  AltDown, ScrlLockOn: boolean;
begin
  AltDown := IsKeyDown(VK_LMENU);
  ScrlLockOn := IsKeyOn(VK_SCROLL);
  result := (AltDown xor ScrlLockOn) and not IsKeyDown(VK_SHIFT);
end;

procedure TTextEditor.ChangeCursor(Shift: TShiftState);
var
  P: TPoint;
begin
  if GetCursorPos(P) then
    with ScreenToClient(P) do
      ChangeCursor(Shift, Y, X);
end;

procedure TTextEditor.ChangeCursor(Shift: TShiftState; Y, X: Integer);
var
  CP: TPoint;
begin

  if not (FValidPaintState and Visible) then Exit;

  if FScriptRunning then
  begin
    Cursor := crHourGlass;
    Exit;
  end;

  CP := CharAtPhysicalPixel(Point(X, Y));

  if FScrollMode then
    if csLButtonDown in ControlState then
      Cursor := crHandHold
    else
      Cursor := crHand
  else if X < GetFunctionalSelectionBarWidth then
    Cursor := crLineSel
  else
    if ((X >= FMarginLeft) and FTextFile.IsCharSel(CP)) and not SingleLine then
      if ssCtrl in Shift then
        Cursor := crBlockCopy
      else
        Cursor := crBlock
    else
      Cursor := crIBeam;

end;

function TTextEditor.CaretPosAtVirtualPixel(Pixel: TPoint): TPoint;
begin
  result := CharAtVirtualPixelEx(Pixel, true);
end;

procedure TTextEditor.CenterOnSelection(AReducedScroll: boolean);
var
  p1, p2, p: TPoint;
begin

  p1 := VirtualPixelAtChar(TextFile.CaretPos.Data);

  if TextFile.HasSelection then
    p2 := VirtualPixelAtChar(TextFile.CaretPos.SelEnd)
  else
    p2 := p1;

  p.X := p1.X + (p2.X - p1.X) div 2 - ClientWidth div 2;
  p.Y := p1.Y + (p2.Y - p1.Y) div 2 - ClientHeight div 2;

  if AReducedScroll then
  begin
    if Abs(FScrollPos.X - p.X) < ClientWidth div 3 then
      p.X := FScrollPos.X;
    if Abs(FScrollPos.Y - p.Y) < ClientHeight div 3 then
      p.Y := FScrollPos.Y;
  end;

  SetScrollPosXY(p.X, p.Y);

end;

function TTextEditor.CaretPosAtPhysicalPixel(Pixel: TPoint): TPoint;
begin
  result := CharAtPhysicalPixelEx(Pixel, true);
end;

function TTextEditor.ChrInGlyphSet(GlyphSet: PGlyphSet;
  Codepoint: integer): boolean;

  function InInterval(Val, Start, Length: integer): boolean; inline;
  begin
    InInterval := (Val >= Start) and (Val < Start + Length);
  end;

var
  i: Integer;
begin
  result := false;
  if GlyphSet = nil then Exit;
  for i := 0 to GlyphSet^.cRanges - 1 do
    with GlyphSet^.ranges[i] do
      if InInterval(Codepoint, ord(wcLow), cGlyphs) then
        Exit(true);
end;

function TTextEditor.ChrInGlyphSet(GlyphSet: PGlyphSet;
  Character: char): boolean;
begin
  result := ChrInGlyphSet(GlyphSet, ord(Character));
end;

function TTextEditor.ChrTransformSelection(Transformation: TChrTransformFunc;
  const TransformName: string): boolean;
begin
  TypeTimerEnd;
  result := FTextFile.ChrTransform(Transformation);
  if result then
    AddUndoRecord(Format(SUndoSelectionTransformed, [TransformName]), UID_UNKNOWN);
end;

procedure TTextEditor.ChrTransformText(Transformation: TChrTransformFunc;
  const TransformName: string);
begin
  TypeTimerEnd;
  FTextFile.ChrTransformText(Transformation);
  AddUndoRecord(Format(SUndoTextTransformed, [TransformName]), UID_UNKNOWN);
end;

procedure TTextEditor.ClearLine;
begin
  TypeTimerEnd;
  FTextFile.ClearLine;
  AddUndoRecord(SUndoLineCleared, UID_DELETE);
end;

procedure TTextEditor.ClearSelection;
begin
  TypeTimerEnd;
  FTextFile.ClearSelection;
  AddUndoRecord(SUndoSelectionCleared, UID_DELETE);
end;

procedure TTextEditor.ClearUndoHistory;
begin
  FTypeTimer.Enabled := false;
  FTextFile.ClearUndoHistory;
  AddUndoRecord(SUndoFirstPost, UID_UNKNOWN);
end;

procedure TTextEditor.CliAddHistory(const AStr: string);
begin
  SetLength(FCliHistory, Length(FCliHistory) + 1);
  FCliHistory[high(FCliHistory)] := AStr;
end;

procedure TTextEditor.CliBeginOutput;
begin
  FCliMultiOutput := true;
end;

procedure TTextEditor.CliClearHistory;
begin
  SetLength(FCliHistory, 0);
end;

procedure TTextEditor.CliEndOutput;
begin
  FCliMultiOutput := false;
  CliNewPrompt;
end;

procedure TTextEditor.CliHistoryDialogListBoxSelect(Sender: TObject);
begin
  if (Sender is TTextEditor) and (TTextEditor(Sender).Parent is TForm) then
    TForm(TTextEditor(Sender).Parent).ModalResult := mrOk;
end;

procedure TTextEditor.CliHistoryDialogListBoxKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  if Key = VK_ESCAPE then
    if (Sender is TTextEditor) and (TTextEditor(Sender).Parent is TForm) then
      TForm(TTextEditor(Sender).Parent).ModalResult := mrCancel;
end;

function TTextEditor.CliHistoryDialog: integer;
var
  frm: TForm;
  lb: TTextEditor;
  i: Integer;
begin
  result := -1;
  frm :=  TForm.Create(nil);
  try
    frm.Caption := SCliHistoryDialogCaption;
    frm.BorderStyle := bsSizeToolWin;
    frm.ClientWidth := 512;
    frm.ClientHeight := 256;
    with ClientToScreen(Point(ClientWidth div 2 - frm.ClientWidth div 2,
      ClientHeight div 2 - frm.ClientHeight div 2)) do
    begin
      frm.Left := X;
      frm.Top := Y;
    end;
    lb := TTextEditor.Create(frm);
    lb.Parent := frm;
    lb.Align := alClient;
    lb.TabStop := true;
    lb.UseSystemColors := Self.UseSystemColors;
    lb.Color := Self.Color;
    lb.Font.Assign(Self.Font);
    lb.LineHighlightColor := Self.LineHighlightColor;
    if lb.Color = lb.LineHighlightColor then
    begin
      lb.Color := clWhite;
      lb.Font.Color := clBlack;
      lb.LineHighlightColor := DEFAULT_LINE_HIGHLIGHT_COLOR;
    end;
    lb.ListBoxMode := true;
    lb.RulerWidth := 32;
    lb.MarginLeft := 40;
    lb.RulerColor := Self.RulerColor;
    lb.OnKeyDown := CliHistoryDialogListBoxKeyDown;
    lb.OnListBoxSelect := CliHistoryDialogListBoxSelect;

    lb.BeginAddLine;
    for i := 0 to CliHistoryCount - 1 do
      lb.AddLine(CliHistory[i]);
    lb.EndAddLine;

    if FCliHistoryIndex <> -1 then
      lb.ListBoxItemIndex := FCliHistoryIndex;

    if frm.ShowModal = mrOk then
      result := lb.ListBoxItemIndex;
  finally
    frm.Free;
  end;
end;

function TTextEditor.CliHistoryDialogSelect: boolean;
var
  index: integer;
begin
  index := CliHistoryDialog;
  result := index <> -1;
  if result then
    CliHistoryRecall(index);
end;

function TTextEditor.CliHistoryDown: boolean;
begin
  result := InRange(FCliHistoryIndex, 0, high(FCliHistory) - 1);
  if result then
  begin
    inc(FCliHistoryIndex);
    TypeTimerEnd;
    Lines[LineCount - 1] := FCliHistory[FCliHistoryIndex];
    FTextFile.GotoEOF;
    AddUndoRecord(SUndoCliHistory, UID_UNKNOWN);
  end;
end;

function TTextEditor.CliHistoryRecall(Index: integer): boolean;
begin
  result := InRange(Index, 0, high(FCliHistory));
  if result then
  begin
    FCliHistoryIndex := Index;
    TypeTimerEnd;
    Lines[LineCount - 1] := FCliHistory[FCliHistoryIndex];
    FTextFile.GotoEOF;
    AddUndoRecord(SUndoCliHistory, UID_UNKNOWN);
  end;
end;

function TTextEditor.CliHistoryUp: boolean;
begin
  result := InRange(FCliHistoryIndex, 1, high(FCliHistory) + 1);
  if result then
  begin
    dec(FCliHistoryIndex);
    TypeTimerEnd;
    Lines[LineCount - 1] := FCliHistory[FCliHistoryIndex];
    FTextFile.GotoEOF;
    AddUndoRecord(SUndoCliHistory, UID_UNKNOWN);
  end;
end;

procedure TTextEditor.CliNewPrompt;
var
  ClassName: string;
begin
  FTypeTimer.Enabled := false;
  ClassName := '';
  if Assigned(FOnCliGetPromptClass) then
    FOnCliGetPromptClass(Self, ClassName);
  AddLine('', ClassName);
  ClearUndoHistory;
  FCliHistoryIndex := high(FCliHistory) + 1;
end;

procedure TTextEditor.CliWriteLn(const AStr, AClass: string);
begin
  if FTextFile.LineIsEmpty(LineCount - 1) then
  begin
    Lines[LineCount - 1] := AStr;
    LineClasses[LineCount - 1] := AClass;
  end
  else
    AddLine(AStr, AClass);
  if not FCliMultiOutput then
    CliNewPrompt;
end;

procedure TTextEditor.CliWriteLn(const AStr: string);
begin
  CliWriteLn(AStr, '');
end;

procedure TTextEditor.CliWriteLn;
begin
  CliWriteLn('', '');
end;

procedure TTextEditor.ClearLine(LineIndex: integer);
begin
  FTextFile.ClearLine(LineIndex);
end;

function TTextEditor.CommandEnabled(Command: integer): boolean;
var
  dummy: string;
begin
  result := true;
  case Command and $FFFF of
    EDITOR_COMMAND_PASTE:
      result := (Clipboard.HasFormat(CF_TEXT) or (FAllowBitmapPaste and Clipboard.HasFormat(CF_BITMAP) and not SingleLine)) and Enabled;
    EDITOR_COMMAND_PASTE_AS_BLOCK:
      result := Clipboard.HasFormat(CF_TEXT) and Enabled;
    EDITOR_COMMAND_CUT, EDITOR_COMMAND_COPY, EDITOR_COMMAND_CLEAR_SELECTION:
      result := FTextFile.HasSelection and Enabled;
    EDITOR_COMMAND_UNDO:
      result := CanUndo;
    EDITOR_COMMAND_REDO:
      result := CanRedo;
    EDITOR_COMMAND_SELECT_ALL:
      result := (not FTextFile.Empty) and Enabled;
    EDITOR_COMMAND_ACTIVATE_CONTROL:
      result := LineIsWinControlOrHasPopup(CaretPos.Y);
    EDITOR_COMMAND_CLASS_MENU:
      result := not LineIsControl(CaretPos.Y);
    EDITOR_COMMAND_OPEN_URL_AT_CARET:
      result := GetURLAtCaret(dummy);
    EDITOR_COMMAND_SEL_UPPER_CASE .. EDITOR_COMMAND_SEL_INVERT_CASE,
    EDITOR_COMMAND_SEL_ROT13 .. EDITOR_COMMAND_SEL_CAESAR:
      result := FTextFile.HasSelection;
    EDITOR_COMMAND_SEL_CAMEL_CASE .. EDITOR_COMMAND_SEL_SENTENCE_CASE,
    EDITOR_COMMAND_SEL_VIGENERE, EDITOR_COMMAND_SEL_REVERSE:
      result := FTextFile.HasSelection and (FTextFile.CaretPos.SelectionType = stLineBased);
    EDITOR_COMMAND_SORT_ALL, EDITOR_COMMAND_SORT:
      result := FTextFile.LineCount >= 2;
    EDITOR_COMMAND_SORT_SEL:
      result := FTextFile.HasSelection;
    EDITOR_COMMAND_ABORT_SCRIPT:
      result := FScriptRunning;
    EDITOR_COMMAND_SAVE, EDITOR_COMMAND_SET_EDIT_MODE:
      result := not FTextFile.StrictReadOnly;
  end;
end;

function TTextEditor.CommandVisible(Command: integer): boolean;
var
  dummy: string;
begin
  result := true;
  case Command and $FFFF of
    EDITOR_COMMAND_ACTIVATE_CONTROL:
      result := LineIsWinControlOrHasPopup(CaretPos.Y);
    EDITOR_COMMAND_BOOKMARK_SET_MENU,
    EDITOR_COMMAND_BOOKMARK_GO_MENU,
    EDITOR_COMMAND_BOOKMARK_CLEAR_MENU:
      result := not SingleLine;
    EDITOR_COMMAND_CLASS_MENU:
      result := (ClassCount > 0) and FTextFile.UseLineClasses;
    EDITOR_COMMAND_OPEN_URL_AT_CARET:
      result := GetURLAtCaret(dummy);
    EDITOR_COMMAND_SEL_TRANSFORM_MENU:
      result := FTextFile.HasSelection;
  end;
end;

function TTextEditor.ControlInSelection: boolean;
var
  FirstPoint, SecondPoint: TPoint;
  i: Integer;
begin
  result := false;
  if not FTextFile.ControlAware then Exit;
  FTextFile.CaretPos.GetSelBdry(FirstPoint, SecondPoint);
  for i := FirstPoint.Y to SecondPoint.Y do
    if LineIsControl(i) then
      Exit(true);
end;

procedure TTextEditor.CopyAll;
begin
  Clipboard.AsText := GetText;
end;

procedure TTextEditor.CopySelection(const ANewPos: TPoint);
var
  S: string;
begin
  if FTextFile.IsCharSel(ANewPos) then Exit;
  TypeTimerEnd;
  S := SelText;
  FTextFile.CaretPos.SetPoint(ANewPos);
  FTextFile.InsertText(S);
  AddUndoRecord(SUndoMouseCopy, UID_DRAGDROP);
end;

procedure TTextEditor.CopyToClipboard;
begin
  FTextFile.CopyToClipboard;
end;

procedure TTextEditor.FallbackFontsChange(Sender: TObject);
begin
  BuildFontDataArray;
  Invalidate;
end;

procedure TTextEditor.BalloonTimerTimer(Sender: TObject);
begin
  FBalloonTimer.Enabled := false;
  HideBalloon;
end;

procedure TTextEditor.UpdateSPI;
begin
  SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, FSPIScrollLines, 0);
end;

constructor TTextEditor.Create(AOwner: TComponent);
var
  item, item2: TMenuItem;
begin
  inherited;
  FPDict := TDictionary<string, TFormattingProcessor>.Create;
  FInsertionPoint := Point(-1, -1);
  FWantReturn := true;
  FWantTab := true;
  FAllowBitmapPaste := false;
  UpdateSPI;
  FMultipleCarets := false;
  SetLength(FCarets, 0);
  FCaretAfterEOL := true;
  FScrollBehaviour := sbDefault;
  FIndentSize := 2;
  FAutoIndent := true;
  FVisualUpdateLock := 0;
  FBitmapEffect := beNone;
  FDisabledEffect := beGrayscale;
  Width := 400;
  Height := 200;
  DoubleBuffered := true;
  FNoVerifyFont := false;
  FMultiCharReportView := false;
  FASHyphenAsteriskToggle := false;
  FMultiCharSelect := true;
  FCliMultiOutput := false;
  FValidPaintState := false;
  FCliHistoryIndex := -1;
  SetLength(FCliHistory, 0);
  FPreserveDesiredColumn := false;
  FScriptCounter := 0;
  FAbortScript := false;
  FScriptRunning := false;
  FNotifyMsgDuration := DEFAULT_NOTIFICATION_MSG_DURATION;
  SetLength(FNotifications, 0);
  FSelectionBarBehaviour := sbbAutoMixed;
  FTextFileOwner := tfoEditor;
  FBorderColor := clSilver;
  FRightLine := false;
  FRightLinePos := 580;
  FRightLineColor := clSilver;
  FPrintSettings := TPrintSettings.Create;
  FZoom := 100;
  FRulerColor := clDefault;
  FNoScrollToCaret := false;
  FRulerWidth := DEFAULT_RULER_WIDTH;
  FMarginLeft := DEFAULT_MARGIN_LEFT;
  FMarginRight := DEFAULT_MARGIN_RIGHT;
  FMarginTop := DEFAULT_MARGIN_TOP;
  FMarginBottom := DEFAULT_MARGIN_BOTTOM;
  FNextControlID := 0;
  FCachedHorizontalExtent := 0;
  FMultiSize := false;
  FAutoHeight := true;
  FLabelStyle := false;
  FLabelEllipsis := true;
  FTabLength := 2;
  FBalloonTimer := TTimer.Create(nil);
  FBalloonTimer.Enabled := false;
  FBalloonTimer.Interval := 10000;
  FBalloonTimer.OnTimer := BalloonTimerTimer;
  FNumbersOnly := false;
  FPasswordChar := #0;
  FGLYPHBM := TBitmap.Create;
  FFONTBM := TBitmap.Create;
  FUnicodeFallback := true;
  FFallbackFonts := TStringList.Create;
  FFallbackFonts.OnChange := FallbackFontsChange;
  FBorderType := btThemeBorder;
  FStartOver := true;
  FFndBkColor := clYellow;
  FFndFgColor := clBlack;
  FInputTransform := itNone;
  FMessageInterface := true;
  FAutoReplace := false;
  FScrollPos := Point(0, 0);
  FBracketHighlight := false;
  FShowHiddenCharacters := false;
  FLineHighlight := false;
  FLineHighlightColor := DEFAULT_LINE_HIGHLIGHT_COLOR;
  FBracketHighlightColor := DEFAULT_BRACKET_HIGHLIGHT_COLOR;
  FDoubleClicking := false;
  Cursor := crIBeam;
  FUseSystemColors := true;
  FBackgroundColor := clWhite;
  FForegroundColor := clBlack;
  FSelBackgroundColor := clBlack;
  FSelForegroundColor := clWhite;
  FLetterSpacing := 1;
  FLineSpacing := 1;
  FTextFile := TTextFile.Create;
  ConnectTextFileToEditor;
  FTextFile.AutoIndent := true;
  FFont := TFont.Create;
  VerifyFont;
  FFont.OnChange := FontChange;
  SetupColors;
  FHandleHotkeys := true;
  FHandleBookmarkHotkeys := true;
  FBeepOnInputError := true;
  FErrorMessageOnReadOnlyError := true;
  FOverwrite := false;
  FMatchBrackets := true;
  FRulerFont := TFont.Create;
  FRulerFont.OnChange := RulerFontChange;

  ControlStyle := ControlStyle + [csPannable];

  FTypeTimer := TTimer.Create(nil);
  FTypeTimer.Enabled := false;
  FTypeTimer.Interval := 2000;
  FTypeTimer.OnTimer := TypeTimerTimer;

  // Cursors
  Screen.Cursors[crBlock] := LoadImage(hInstance, 'SELHOVER', IMAGE_CURSOR,
    0, 0, LR_DEFAULTCOLOR);
  Screen.Cursors[crBlockCopy] := LoadImage(hInstance, 'SELCOPY', IMAGE_CURSOR,
    0, 0, LR_DEFAULTCOLOR);
  Screen.Cursors[crHand] := LoadImage(hInstance, 'HAND', IMAGE_CURSOR, 0, 0,
    LR_DEFAULTCOLOR);
  Screen.Cursors[crHandHold] := LoadImage(hInstance, 'HANDHOLD', IMAGE_CURSOR,
    0, 0, LR_DEFAULTCOLOR);
  Screen.Cursors[crLineSel] := LoadImage(hInstance, 'LINESEL', IMAGE_CURSOR,
    0, 0, LR_DEFAULTCOLOR);

  // Popup menu
  FPopupMenu := TPopupMenu.Create(nil);
  FPopupMenu.OnPopup := MenuPopup;

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuOpenURL;
  item.Hint := SMenuOpenURLHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_OPEN_URL_AT_CARET;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := '-';
  item.Tag := 0;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuUndo;
  item.Hint := SMenuUndoHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_UNDO;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuRedo;
  item.Hint := SMenuRedoHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_REDO;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := '-';
  item.Tag := 0;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuCut;
  item.Hint := SMenuCutHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_CUT;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuCopy;
  item.Hint := SMenuCopyHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_COPY;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuPaste;
  item.Hint := SMenuPasteHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_PASTE;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuClear;
  item.Hint := SMenuClearHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_CLEAR_SELECTION;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := '-';
  item.Tag := 0;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuSelectAll;
  item.Hint := SMenuSelectAllHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_SELECT_ALL;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := '-';
  item.Tag := 0;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuSetBookmark;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_BOOKMARK_SET_MENU;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuGotoBookmark;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_BOOKMARK_GO_MENU;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuClearBookmark;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_BOOKMARK_CLEAR_MENU;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := '-';
  item.Tag := 0;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuClasses;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_CLASS_MENU;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuActivateControl;
  item.Hint := SMenuActivateControlHint;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_ACTIVATE_CONTROL;
  FPopupMenu.Items.Add(item);

  item := TMenuItem.Create(FPopupMenu);
  item.Caption := SMenuTransform;
  item.OnClick := MenuItemMessage;
  item.Tag := EDITOR_COMMAND_SEL_TRANSFORM_MENU;
  FPopupMenu.Items.Add(item);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformUpperCase;
  item2.Hint := SMenuTransformUpperCaseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_UPPER_CASE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformLowerCase;
  item2.Hint := SMenuTransformLowerCaseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_LOWER_CASE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformInvertCase;
  item2.Hint := SMenuTransformInvertCaseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_INVERT_CASE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformCamelCase;
  item2.Hint := SMenuTransformCamelCaseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_CAMEL_CASE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformSentenceCase;
  item2.Hint := SMenuTransformSentenceCaseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_SENTENCE_CASE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := '-';
  item2.OnClick := MenuItemMessage;
  item2.Tag := 0;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformReverse;
  item2.Hint := SMenuTransformReverseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_REVERSE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformROT13;
  item2.Hint := SMenuTransformROT13Hint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_ROT13;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformCaesar;
  item2.Hint := SMenuTransformCaesarHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_CAESAR;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformVigenere;
  item2.Hint := SMenuTransformVigenereHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_VIGENERE;
  item.Add(item2);

  item2 := TMenuItem.Create(item);
  item2.Caption := SMenuTransformVigenereInverse;
  item2.Hint := SMenuTransformVigenereInverseHint;
  item2.OnClick := MenuItemMessage;
  item2.Tag := EDITOR_COMMAND_SEL_VIGENERE or $00010000;
  item.Add(item2);

  // Image popup
  FImagePopup := TPopupMenu.Create(nil);

  item := TMenuItem.Create(FImagePopup);
  item.Caption := SMenuCopyImage;
  item.Hint := SMenuCopyImageHint;
  item.OnClick := ImageMenuCommand;
  item.Tag := IMAGE_COMMAND_COPY;
  FImagePopup.Items.Add(item);

  item := TMenuItem.Create(FImagePopup);
  item.Caption := SMenuDeleteImage;
  item.Hint := SMenuDeleteImageHint;
  item.OnClick := ImageMenuCommand;
  item.Tag := IMAGE_COMMAND_REMOVE;
  FImagePopup.Items.Add(item);

  item := TMenuItem.Create(FImagePopup);
  item.Caption := SMenuChangeImage;
  item.Hint := SMenuChangeImageHint;
  item.OnClick := ImageMenuCommand;
  item.Tag := IMAGE_COMMAND_CHANGE;
  FImagePopup.Items.Add(item);

  // Ruler menu
  FRulerMenu := TPopupMenu.Create(nil);

  item := TMenuItem.Create(FRulerMenu);
  item.Caption := SMenuRulerProperties;
  item.Hint := SMenuRulerPropertiesHint;
  item.OnClick := RulerMenuCommand;
  item.Tag := RULER_COMMAND_PROPERTIES;
  FRulerMenu.Items.Add(item);

  // Drop context menu
  FDropMenu := TPopupMenu.Create(nil);

  FDropMenuMove := TMenuItem.Create(FDropMenu);
  FDropMenuMove.Caption := SMoveHere;
  FDropMenu.Items.Add(FDropMenuMove);

  FDropMenuCopy := TMenuItem.Create(FDropMenu);
  FDropMenuCopy.Caption := SCopyHere;
  FDropMenu.Items.Add(FDropMenuCopy);

  item := TMenuItem.Create(FDropMenu);
  item.Caption := '-';
  FDropMenu.Items.Add(item);

  item := TMenuItem.Create(FDropMenu);
  item.Caption := SCancel;
  FDropMenu.Items.Add(item);

  UseDefaultFallbackFonts;
  BuildFontDataArray;

  FBlinkRemover := TTimer.Create(nil);
  FBlinkRemover.Enabled := false;
  FBlinkRemover.Interval := 500;
  FBlinkRemover.OnTimer := BlinkRemoverTimer;

  TabStop := true;

  OleInitialize(nil);

  CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER,
    IID_IDropTargetHelper, FDropTargetHelper);

  FXDRAG := Abs(GetSystemMetrics(SM_CXDRAG));
  FYDRAG := Abs(GetSystemMetrics(SM_CYDRAG));

end;

procedure TTextEditor.ImageMenuCommand(Sender: TObject);
var
  bm: TBitmap;
begin
  if not (FImagePopup.PopupComponent is TImage) then Exit;
  if not (Sender is TMenuItem) then Exit;

  case TMenuItem(Sender).Tag of
    IMAGE_COMMAND_COPY:
      if TImage(FImagePopup.PopupComponent).Picture.Graphic is TIcon then
      begin
        bm := TBitmap.Create;
        try
          bm.SetSize(TImage(FImagePopup.PopupComponent).Picture.Width,
            TImage(FImagePopup.PopupComponent).Picture.Height);
          bm.Canvas.Draw(0, 0, TImage(FImagePopup.PopupComponent).Picture.Graphic);
          Clipboard.Assign(bm);
        finally
          bm.Free;
        end;
      end
      else
        Clipboard.Assign(TImage(FImagePopup.PopupComponent).Picture);
    IMAGE_COMMAND_REMOVE:
      FTextFile.ClearLine(
        GetLineFromControlID(GetIDFromControl(TControl(FImagePopup.PopupComponent))));
    IMAGE_COMMAND_CHANGE:
      with TOpenDialog.Create(nil) do
        try
          Options := [ofPathMustExist, ofFileMustExist];
          Filter := SImageFilter;
          Title := SOpenImageDialogCaption;
          if Execute then
          begin
            TImage(FImagePopup.PopupComponent).Picture.LoadFromFile(FileName);
            TextFileLineClassChange(Sender,
              GetLineFromControlID(GetIDFromControl(TControl(FImagePopup.PopupComponent))));
          end;
        finally
          Free;
        end;
  end;
end;

procedure TTextEditor.RulerPropertiesApply(Sender: TObject);
begin
  if Sender is TRulerPropertiesFrm then
    with TRulerPropertiesFrm(Sender) do
    begin
      RulerFont.Assign(PrFont);
      RulerColor := PrColor;
      RulerWidth := PrWidth;
    end;
end;

procedure TTextEditor.RulerMenuCommand(Sender: TObject);
begin
  if not (Sender is TMenuItem) then Exit;

  case TMenuItem(Sender).Tag of
    RULER_COMMAND_PROPERTIES:
      with TRulerPropertiesFrm.Create(nil) do
        try
          PrFont.Assign(FRulerFont);
          PrColor := FRulerColor;
          PrWidth := FRulerWidth;
          OnApply := RulerPropertiesApply;
          ShowModal;
        finally
          Free;
        end;
  end;
end;

procedure TTextEditor.TextFileGetControlText(Sender: TObject; LineIndex: integer;
  var ControlText: string);
var
  ctl: TControl;
  len: integer;
begin
  ControlText := '';
  ctl := GetControlFromLine(LineIndex);
  if Assigned(ctl) then
  begin
    if ctl is TWinControl then
    begin
      SetLength(ControlText, 128);
      len := GetWindowText(TWinControl(ctl).Handle, PChar(ControlText),
        Length(ControlText));
      SetLength(ControlText, len);
    end
    else
      ControlText := SPicture;
  end;
end;

procedure TTextEditor.TextFileBookmarksMoved(Sender: TObject);
begin
  UpdateRuler;
  if Assigned(FOnBookmarksMoved) then
    FOnBookmarksMoved(Self);
end;

procedure TTextEditor.BlinkRemoverTimer(Sender: TObject);
begin
  FBlinkRemover.Enabled := false;
  if FMatchBrackets then
    HighlightCurrentBracket;
end;

function TTextEditor.BookmarkUsed(AIndex: integer): boolean;
begin
  result := not SamePoint(Bookmarks[AIndex], EMPTY_BOOKMARK);
end;

procedure TTextEditor.BuildFontDataArray;
var
  i: Integer;
begin
  FreeFontDataArray;
  SetLength(FGlyphSets, 1 + FFallbackFonts.Count);
  for i := low(FGlyphSets) to high(FGlyphSets) do
    FGlyphSets[i] := nil;
  if Screen.Fonts.IndexOf(FFont.Name) <> -1 then
    GetFontChrs(FFont.Name, FGlyphSets[0]);
  for i := 0 to FFallbackFonts.Count - 1 do
    if Screen.Fonts.IndexOf(FFallbackFonts[i]) <> -1 then
      GetFontChrs(FFallbackFonts[i], FGlyphSets[i + 1]);
end;

procedure TTextEditor.FreeFontDataArray;
var
  i: Integer;
begin
  for i := low(FGlyphSets) to high(FGlyphSets) do
    if FGlyphSets[i] <> nil then
      FreeMem(FGlyphSets[i]);
  SetLength(FGlyphSets, 0);
end;

procedure TTextEditor.TypeTimerEnd;
begin
  if FTypeTimer.Enabled then
    TypeTimerTimer(Self);
end;

procedure TTextEditor.TypeTimerTimer(Sender: TObject);
begin
  FTypeTimer.Enabled := false;
  AddUndoRecord(SUndoTyped, UID_TYPING);
end;

procedure TTextEditor.PostType;
begin
  FTypeTimer.Enabled := false;
  FTypeTimer.Enabled := true;
end;

procedure TTextEditor.Print(AFirstLine, ALastLine: integer);
begin
  Print(ExtractFileName(FTextFile.FileName), AFirstLine, ALastLine);
end;

procedure TTextEditor.PrintSelection(const ATitle: string);
var
  FirstPoint, SecondPoint: TPoint;
begin
  if not FTextFile.HasSelection then Exit;
  FTextFile.CaretPos.GetSelBdry(FirstPoint, SecondPoint);
  Print(ATitle, FirstPoint.Y, SecondPoint.Y);
end;

procedure TTextEditor.PrintSelection;
begin
  PrintSelection(ExtractFileName(FTextFile.FileName));
end;

procedure TTextEditor.PushEditorState;
begin
  TypeTimerEnd;
  if Assigned(FTextFile) then
  begin
    if Assigned(FFormattingProcessor) then
      FTextFile.EditorState.FormattingProcessor := FFormattingProcessor.ClassName
    else
      FTextFile.EditorState.FormattingProcessor := '';
    FTextFile.EditorState.ScrollPos := FScrollPos;
    FTextFile.EditorState.MultiSize := FMultiSize;
    FTextFile.EditorState.Overwrite := FOverwrite;
    FTextFile.EditorState.HiddenChrs := FShowHiddenCharacters;
    FTextFile.EditorState.RulerVisible := RulerVisible;
    FTextFile.EditorState.ZoomLevel := FZoom;
    if Assigned(FFormattingProcessor) then
      FTextFile.EditorState.FFPCacheLen := FFormattingProcessor.GetCache(FTextFile.EditorState.FFPCache)
    else
    begin
      FTextFile.EditorState.FFPCacheLen := 0;
      FTextFile.EditorState.FFPCache := nil;
    end;
    FTextFile.EditorState.Valid := true;
  end;
end;

function TTextEditor.QueryContinueDrag(fEscapePRessed: BOOL;
  grfKeyState: Longint): HRESULT;
begin
  if fEscapePressed then
    result := DRAGDROP_S_CANCEL
  else if (grfKeyState and FDragButtonOLE) = 0 then
    result := DRAGDROP_S_DROP
  else
    result := S_OK;
end;

procedure TTextEditor.Print(const ATitle: string;
  AFirstLine: integer = 0; ALastLine: integer = -1);
var
  x, y: integer;
  px, py: integer;
  fs: TSize;
  WrapList: TIntegerDynArray;
  LineLength, ChrsPerLine: integer;

  procedure CheckNewPage;
  begin
    if py + fs.cy > Printer.PageHeight - FPrintSettings.VerticalMargin then
    begin
      Printer.NewPage;
      py := FPrintSettings.VerticalMargin;
    end;
  end;

  function WrapNow: boolean;

    function ShouldWrapAt(X: integer): boolean;
    var
      i: Integer;
    begin
      result := false;
      for i := low(WrapList) to high(WrapList) do
        if WrapList[i] = X then
          Exit(true);
    end;

  begin
    result := FPrintSettings.WordWrap and
      (
          ((not FPrintSettings.NiceWordWrap) and (px > Printer.PageWidth - FPrintSettings.HorizontalMargin))
                                  or
          (FPrintSettings.NiceWordWrap and (ShouldWrapAt(x)))
      )
  end;

  function Scale(const ASize: TSize): TSize;
  begin
    result.cx := ASize.cx * 6; {TODO: determine actual res}
    result.cy := ASize.cy * 6;
  end;

var
  ctl: TControl;

begin

  if ALastLine = -1 then ALastLine := LineCount - 1;

  NotifyApp(EN_PRINTING);

  if Assigned(FOnPrintBegin) then
    FOnPrintBegin(Self, ALastLine - AFirstLine + 1);

  Enabled := false;

  try

    with Printer do
    begin
      BeginDoc;
      Title := ATitle;

      py := FPrintSettings.VerticalMargin;

      for y := AFirstLine to ALastLine do
      begin
        ApplyFont(LineClasses[y], Canvas);
        if LineIsControl(y) then
          fs := Scale(GetLineControlSize(y))
        else
          fs := Canvas.TextExtent('M');
        CheckNewPage;
        px := FPrintSettings.HorizontalMargin;
        LineLength := FTextFile.VirtualLineWidths[y];
        ChrsPerLine := (PageWidth - 2*FPrintSettings.HorizontalMargin) div fs.cx;
        if FPrintSettings.WordWrap then
        begin
          if FPrintSettings.NiceWordWrap then
            FTextFile.FindWhereToWrap(y, ChrsPerLine, WrapList)
          else
            SetLength(WrapList, 0);
        end;
        for x := 0 to LineLength - 1 do
        begin
          if WrapNow then
          begin
            inc(py, fs.cy + LineSpacing);
            CheckNewPage;
            px := FPrintSettings.HorizontalMargin;
            if FPrintSettings.ShowWordWrapIcon then
            begin
              Canvas.Font.Color := FPrintSettings.WordWrapIconColor;
              Canvas.Font.Style := [];
              Canvas.TextOut(px - 3 * fs.cx div 2, py, FPrintSettings.WordWrapIcon);
            end;
          end;
          if LineIsControl(y) then
          begin

            ctl := GetControlFromLine(y);
            if ctl is TWinControl then // Apparently (e.g.) edit controls do not like the WM_PAINT appraoch
              with TBitmap.Create do
                try
                  SetSize(ctl.Width, ctl.Height);
                  TWinControl(ctl).PaintTo(Canvas, 0, 0);
                  StretchBlt(Printer.Handle, px, py, fs.cx, fs.cy,
                    Canvas.Handle, 0, 0, Width, Height, SRCCOPY);
                finally
                  Free;
                end
            else if ctl is TGraphicControl then
              with TBitmap.Create do
                try
                  SetSize(ctl.Width, ctl.Height);
                  Canvas.Lock;
                  TGraphicControl(ctl).Perform(WM_PAINT, Canvas.Handle, 0);
                  Canvas.Unlock;
                  StretchBlt(Printer.Handle, px, py, fs.cx, fs.cy,
                    Canvas.Handle, 0, 0, Width, Height, SRCCOPY);
                finally
                  Free;
                end

          end
          else
          begin
            ReapplyFont(Canvas);
            ApplyInteractiveFormatting(x, y, Canvas);
            Canvas.TextOut(px, py, FTextFile.Character[y, x]);
          end;
          inc(px, fs.cx);
        end;
        inc(py, fs.cy);

        if Assigned(FOnPrintProgress) then
          if not FOnPrintProgress(Self, y - AFirstLine + 1, ALastLine - AFirstLine + 1) then
          begin
            Abort;
            SysUtils.Abort;
          end;
      end;

      EndDoc;

    end;

  finally

    Enabled := true;

    RemoveNotification(EN_PRINTING);

    if Assigned(FOnPrintEnd) then
      FOnPrintEnd(Self);

  end;

end;

procedure TTextEditor.MenuPopup(Sender: TObject);
var
  i, j: Integer;
  subitem: TMenuItem;
  URL: string;
begin
  for i := 0 to FPopupMenu.Items.Count - 1 do
  begin
    FPopupMenu.Items[i].Enabled := CommandEnabled(FPopupMenu.Items[i].Tag);
    FPopupMenu.Items[i].Visible := CommandVisible(FPopupMenu.Items[i].Tag);

    case FPopupMenu.Items[i].Tag of
      EDITOR_COMMAND_OPEN_URL_AT_CARET:
        if GetURLAtCaret(URL) then
          FPopupMenu.Items[i].Hint := Format(SMenuOpenURLHint, [URL]);
      EDITOR_COMMAND_SEL_TRANSFORM_MENU:
        for j := 0 to FPopupMenu.Items[i].Count - 1 do
        begin
          FPopupMenu.Items[i].Items[j].Enabled := CommandEnabled(FPopupMenu.Items[i].Items[j].Tag);
          FPopupMenu.Items[i].Items[j].Visible := CommandVisible(FPopupMenu.Items[i].Items[j].Tag);
        end;
      EDITOR_COMMAND_BOOKMARK_SET_MENU:
        begin
          FPopupMenu.Items[i].Clear;
          for j := 0 to BookmarkCount - 1 do
          begin
            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := GetBookmarkDescr(j);
            subitem.Hint := SMenuSetBookmarkItemHint;
            if InRange(j, 1, 9) then
              subitem.ShortCut := ShortCut(ord('0') + j, [ssShift, ssCtrl]);
            subitem.OnClick := MenuItemMessage;
            subitem.Tag := EDITOR_COMMAND_BOOKMARK_SET or (j shl 16);
            FPopupMenu.Items[i].Add(subitem);
          end;
        end;
      EDITOR_COMMAND_BOOKMARK_GO_MENU:
        begin
          FPopupMenu.Items[i].Clear;
          for j := 0 to BookmarkCount - 1 do
          begin
            if not BookmarkUsed(j) then Continue;
            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := GetBookmarkDescr(j);
            subitem.Hint := SMenuGotoBookmarkItemHint;
            if InRange(j, 1, 9) then
              subitem.ShortCut := ShortCut(ord('0') + j, [ssCtrl]);
            subitem.OnClick := MenuItemMessage;
            subitem.Tag := EDITOR_COMMAND_BOOKMARK_GO or (j shl 16);
            FPopupMenu.Items[i].Add(subitem);
          end;
          if UsedBookmarkCount = 0 then
          begin
            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := SMenuNoBookmarksSetParen;
            subitem.Enabled := false;
            FPopupMenu.Items[i].Add(subitem);
          end;
        end;
      EDITOR_COMMAND_BOOKMARK_CLEAR_MENU:
        begin
          FPopupMenu.Items[i].Clear;
          for j := 0 to BookmarkCount - 1 do
          begin
            if not BookmarkUsed(j) then Continue;
            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := GetBookmarkDescr(j);
            subitem.Hint := SMenuClearBookmarkItemHint;
            subitem.OnClick := MenuItemMessage;
            subitem.Tag := EDITOR_COMMAND_BOOKMARK_CLEAR or (j shl 16);
            FPopupMenu.Items[i].Add(subitem);
          end;
          if UsedBookmarkCount = 0 then
          begin
            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := SMenuNoBookmarksSetParen;
            subitem.Enabled := false;
            FPopupMenu.Items[i].Add(subitem);
          end
          else
          begin
            subitem := TMenUItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := '-';
            FPopupMenu.Items[i].Add(subitem);

            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := SMenuClearAllBookmarks;
            subitem.Hint := SMenuClearAllBookmarksHint;
            subitem.OnClick := MenuItemMessage;
            subitem.Tag := EDITOR_COMMAND_BOOKMARK_CLEAR_ALL;
            FPopupMenu.Items[i].Add(subitem);
          end;
        end;
      EDITOR_COMMAND_CLASS_MENU:
        begin
          FPopupMenu.Items[i].Clear;
          subitem := TMenuItem.Create(FPopupMenu.Items[i]);
          subitem.Caption := SMenuUseNoClass;
          subitem.Hint := SMenuUseNoClassHint;
          subitem.Checked := Length(LineClasses[CaretPos.Y]) = 0;
          subitem.OnClick := MenuItemMessage;
          subitem.Tag := EDITOR_COMMAND_CLASS_REMOVE;
          FPopupMenu.Items[i].Add(subitem);
          subitem := TMenuItem.Create(FPopupMenu.Items[i]);
          subitem.Caption := '-';
          FPopupMenu.Items[i].Add(subitem);
          for j := 0 to ClassCount - 1 do
          begin
            subitem := TMenuItem.Create(FPopupMenu.Items[i]);
            subitem.Caption := Classes[j].Name;
            subitem.Hint := SMenuClassesItemHint;
            subitem.Checked := SameStr(LineClasses[CaretPos.Y], Classes[j].Name);
            subitem.OnClick := MenuItemMessage;
            subitem.Tag := EDITOR_COMMAND_CLASS_USE or (j shl 16);
            FPopupMenu.Items[i].Add(subitem);
          end;
        end;
    end;

  end;
end;

function TTextEditor.MakeLinesUnique: boolean;
begin
  TypeTimerEnd;
  result := FTextFile.MakeLinesUnique;
  if result then
    AddUndoRecord(SUndoMadeLinesUnique, UID_UNKNOWN);
end;

procedure TTextEditor.MakeUndoRoot;
begin
  FTypeTimer.Enabled := false;
  FTextFile.ClearUndoHistory;
  AddUndoRecord(SUndoInitialText, UID_UNKNOWN);
end;

function TTextEditor.MaxLineWidth: integer; // in px, ctrl aware
var
  i: Integer;
begin
  result := 0;
  for i := 0 to FTextFile.LineCount - 1 do
    if LineWidths(i) > result then
      result := LineWidths(i);
end;

procedure TTextEditor.MenuItemMessage(Sender: TObject);
begin
  if not Enabled then Exit;
  if Sender is TMenuItem then
    with Sender as TMenuItem do
      EditorCommand(Tag);
end;

procedure TTextEditor.CreateParams(var Params: TCreateParams);
begin
  inherited;
  Params.Style := Params.Style or WS_HSCROLL or WS_VSCROLL or 0*WS_CLIPCHILDREN;
  ControlStyle := ControlStyle - [csNeedsBorderPaint];
  case FBorderType of
    btNone: ;
    btWin32ThinLine:
      Params.Style := Params.Style or WS_BORDER;
    btWin32SunkenEdge:
      Params.ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE;
    btThemeBorder:
      begin
        Params.ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE;
        ControlStyle := ControlStyle + [csNeedsBorderPaint];
      end;
    btSimpleColor: ;
  end;
end;

procedure TTextEditor.CreateWnd;
begin

  inherited;

  FHintWindow := CreateWindowEx(0, TOOLTIPS_CLASS, nil, WS_POPUP or TTS_ALWAYSTIP
    or TTS_NOPREFIX or TTS_BALLOON, Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT),
    Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT), Handle, 0, HInstance, nil);

  if FHintWindow <> 0 then
  begin
    FToolInfo.cbSize := sizeof(FToolInfo);
    FToolInfo.uFlags := TTF_TRANSPARENT or TTF_CENTERTIP or TTF_IDISHWND or
      TTF_TRACK or TTF_ABSOLUTE;
    FToolInfo.hwnd := Handle;
    FToolInfo.uId := Handle;
    FToolInfo.hInst := 0;
    FToolInfo.lpszText := '';
    SendMessage(FHintWindow, TTM_ADDTOOL, 0, LParam(@FToolInfo));
  end;

  OleCheck(RegisterDragDrop(Handle, Self));

end;

function TTextEditor.GetTotalVerticalExtent: integer;
begin
  if FMultiSize then
    result := FAccumLineHeights[FTextFile.LineCount - 1] + FFontSizes[FTextFile.LineCount - 1].cy
  else
    result := FFontSize.cy * FTextFile.LineCount;
end;

function TTextEditor.GetURLAtCaret(out AURL: string): boolean;
begin
  result := FTextFile.GetURLAtCaret(AURL);
end;

function TTextEditor.GetUsedBookmarkCount: integer;
begin
  result := FTextFile.UsedBookmarkCount;
end;

function TTextEditor.GetTotalHorizontalExtent: integer;
begin
  if FMultiSize then
    result := FCachedHorizontalExtent
  else
    result := FFontSize.cx * FTextFile.MaxLineWidth
end;

function TTextEditor.IsCaretVisible: boolean;
begin
  result := FCaretVisible and PtInRect(TextContentRect, PhysicalPixelAtChar(GetCaretPos));
end;

{ BMSB, BMSCROLLBAR }
procedure TTextEditor.UpdateScrollBars;
var
  ScrollInfo: TScrollInfo;
  OldVScroll, NewVScroll, OldHScroll, NewHScroll, OldCaretVisible: boolean;
begin

  if SingleLine then
  begin
    ShowScrollBar(Handle, SB_BOTH, false);
    Exit;
  end;

  OldVScroll := GetWindowLong(Handle, GWL_STYLE) and WS_VSCROLL <> 0;
  OldHScroll := GetWindowLong(Handle, GWL_STYLE) and WS_HSCROLL <> 0;
  OldCaretVisible := IsCaretVisible;

  ScrollInfo.cbSize := sizeof(TScrollInfo);
  ScrollInfo.fMask := SIF_ALL;
  ScrollInfo.nMin := 0;
  ScrollInfo.nMax := max(GetTotalVerticalExtent, FScrollPos.Y + ClientHeight - FMarginTop - FMarginBottom - 1);
  ScrollInfo.nPage := max(0, ClientHeight - FMarginTop - FMarginBottom);
  ScrollInfo.nPos := FScrollPos.Y;
  SetScrollInfo(Handle, SB_VERT, ScrollInfo, true);

  ScrollInfo.cbSize := sizeof(TScrollInfo);
  ScrollInfo.fMask := SIF_ALL;
  ScrollInfo.nMin := 0;
  ScrollInfo.nMax := max(GetTotalHorizontalExtent, FScrollPos.X - FMarginLeft - FMarginRight + ClientWidth - 1);
  ScrollInfo.nPage := max(0, ClientWidth - FMarginLeft - FMarginRight);
  ScrollInfo.nPos := FScrollPos.X;
  SetScrollInfo(Handle, SB_HORZ, ScrollInfo, true);

  NewVScroll := GetWindowLong(Handle, GWL_STYLE) and WS_VSCROLL <> 0;
  NewHScroll := GetWindowLong(Handle, GWL_STYLE) and WS_HSCROLL <> 0;

  if OldCaretVisible and ((OldVScroll xor NewVScroll) or (OldHScroll xor NewHScroll)) then
    ScrollToCaret;
end;

procedure TTextEditor.UpdateScrollMode;
var
  OldScrollMode: boolean;
begin
  FScrollMode := GetScrollMode;
  OldScrollMode := HasNotificationMessage(EN_SCROLL_MODE);
  if FScrollMode and not OldScrollMode then
    NotifyApp(EN_SCROLL_MODE)
  else if OldScrollMode and not FScrollMode then
    RemoveNotification(EN_SCROLL_MODE);
end;

procedure TTextEditor.CutToClipboard;
begin
  TypeTimerEnd;
  FTextFile.CutToClipboard;
  AddUndoRecord(SUndoCutToClipboard, UID_CUT);
end;

function TTextEditor.FPFileChangeNotification(ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: Integer): TChangeRecord;
var
  TC1, TC2: cardinal;
begin
  TC1 := GetTickCount;
  result := FFormattingProcessor.FileChangeNotification(ChangeType, Data1, Data2, Data3, Data4);
  TC2 := GetTickCount;
  if TC2 - TC1 > 5000 then
    if MessageBox(0, PChar(SFPSlowText), PChar(SFPSlowTitle), MB_ICONQUESTION or MB_YESNO) = ID_YES then
      FormattingProcessor := nil;
end;

function TTextEditor.FPFromString(
  const FPClassName: string): TFormattingProcessor;
begin
  if not FPDict.TryGetValue(FPClassName, result) then
    result := nil;
end;

procedure TTextEditor.TextFileChange(Sender: TObject; ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: Integer);
var
  IFCR: TChangeRecord;
begin
  if Assigned(FFormattingProcessor) then
  begin
    IFCR := FPFileChangeNotification(ChangeType, Data1, Data2, Data3, Data4);
    with ChangeUnion(IFCR, MakeChangeRecord(ChangeType, Data1, Data2, Data3, Data4)) do
      VisualUpdate(ChangeType, Data1, Data2, Data3, Data4);
  end
  else
    VisualUpdate(ChangeType, Data1, Data2, Data3, Data4);

  if FMultiSize then
    RecomputeHorizontalExtent;
  UpdateScrollBars;
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

procedure TTextEditor.TextFileInputError(Sender: TObject);
begin
  if FBeepOnInputError then
    beep;
  NotifyAppWithTimer(EN_INPUT_ERROR);
end;

procedure TTextEditor.TextFileReadOnlyError(Sender: TObject);
begin
  if FErrorMessageOnReadOnlyError then
    MessageBox(Handle, PChar(SReadOnlyErrorText),
      PChar(SReadOnlyErrorTitle), MB_ICONINFORMATION or MB_OK);
  NotifyAppWithTimer(EN_READ_ONLY_ERROR);
end;


procedure TTextEditor.TextFileModified(Sender: TObject);
begin
  if BalloonVisible and (ord(FBalloonPersistence) <= ord(bpModify)) then
    HideBalloon;
  if Assigned(FOnModified) then
    FOnModified(Self);
end;

function TTextEditor.TransformSelection(
  Transformation: TTextTransformFunc; const TransformName: string): boolean;
begin
  result := FTextFile.HasSelection and (SelectionType = stLineBased);
  if result then
  begin
    TypeTimerEnd;
    FTextFile.InsertText(Transformation(SelText));
    AddUndoRecord(Format(SUndoSelectionTransformed, [TransformName]), UID_UNKNOWN);
  end;
end;

procedure TTextEditor.TransformText(Transformation: TTextTransformFunc;
  const TransformName: string);
begin
  TypeTimerEnd;
  PlainText := Transformation(PlainText);
  AddUndoRecord(Format(SUndoTextTransformed, [TransformName]), UID_UNKNOWN);
end;

procedure TTextEditor.TrimRight;
begin
  TypeTimerEnd;
  FTextFile.TrimRight;
  AddUndoRecord(SUndoTrimRight, UID_UNKNOWN);
end;

procedure TTextEditor.TruncateAt(AIndex: integer; AChar: char;
  PreserveChar: boolean; AReverse: boolean);
begin
  TruncateAt(0, LineCount - 1, AIndex, AChar, PreserveChar, AReverse);
end;

procedure TTextEditor.TruncateAtInSelection(AIndex: integer; AChar: char;
  PreserveChar: boolean; AReverse: boolean);
var
  FirstLine, SecondLine: integer;
begin
  FirstLine := min(CaretPos.Y, SelEndPos.Y);
  SecondLine := max(CaretPos.Y, SelEndPos.Y);
  TruncateAt(FirstLine, SecondLine, AIndex, AChar, PreserveChar, AReverse);
end;

procedure TTextEditor.TruncateAt(AFirstLine, ALastLine, AIndex: integer;
  AChar: char; PreserveChar: boolean; AReverse: boolean);
begin
  TypeTimerEnd;
  FTextFile.TruncateAt(AFirstLine, ALastLine, AIndex, AChar, PreserveChar, AReverse);
  AddUndoRecord(SUndoLinesTruncated, UID_UNKNOWN);
end;

function TTextEditor.GetLineComparer: TLineComparer;
begin
  result := FTextFile.LineComparer;
end;

function TTextEditor.GetLineControlSize(LineIndex: integer): TSize;
var
  i: Integer;
  ID: integer;
begin
  result := FFontSize;
  if not (LineIsControl(LineIndex) and TryStrToInt(Copy(FTextFile.Lines[LineIndex],
    Length(LINE_CONTROL_PREFIX) + 1), ID)) then
    Exit;
  for i := 0 to high(FLineControls) do
    if (FLineControls[i].ID = ID) and Assigned(FLineControls[i].Control) then
    begin
      result.cx := FLineControls[i].Control.Width + 2*CARET_WIDTH;
      result.cy := FLineControls[i].Control.Height;
      break;
    end;
end;

function TTextEditor.GetLineCount: integer;
begin
  result := FTextFile.LineCount;
end;

function TTextEditor.GetLineFromControlID(ID: integer): integer;
var
  i: Integer;
  IDStr: string;
begin
  result := -1;
  IDStr := IntToStr(ID);
  for i := 0 to FTextFile.LineCount - 1 do
    if LineIsControl(i) and SameStr(Copy(FTextFile.Lines[i], Length(LINE_CONTROL_PREFIX) + 1), IDStr) then
      Exit(i);
end;

procedure TTextEditor.ReapplyFont(ATo: TCanvas);
begin
  if ATo = nil then ATo := Canvas;
  ATo.Font.Size := FCurrentFormat.Size;
  ATo.Font.Color := FCurrentFormat.Color;
  ATo.Font.Style := FCurrentFormat.Style;
end;

procedure TTextEditor.RebuildLineCache;
var
  nLines: integer;
  i: integer;
  ci: integer;
begin
  NeedValidPaintState;
  nLines := FTextFile.LineCount;
  SetLength(FFontSizes, nLines);
  for i := 0 to nLines - 1 do
  begin
    if SameStr(FTextFile.Classes[i], LINE_CONTROL_CLASS) then
      FFontSizes[i] := GetLineControlSize(i)
    else
    begin
      ci := GetClassIndex(FTextFile.Classes[i]);
      if ci <> -1 then
        FFontSizes[i] := FClassArray[ci].Format.BoxSize
      else
        FFontSizes[i] := FFontSize;
    end;
  end;
  SetLength(FAccumLineHeights, nLines);
  FAccumLineHeights[0] := 0;
  for i := 1 to nLines - 1 do
    FAccumLineHeights[i] := FAccumLineHeights[i - 1] + FFontSizes[i - 1].cy;
end;

procedure TTextEditor.RecomputeHorizontalExtent;
begin
  if FMultiSize then
    FCachedHorizontalExtent := MaxLineWidth
  else
    FCachedHorizontalExtent := FFontSize.cx * FTextFile.MaxLineWidth;
end;

procedure TTextEditor.TextFileLineChange(Sender: TObject;
  LineChangeType: TLineChangeType; From: integer);
begin
  if FMultiSize then
  begin
    RebuildLineCache;
    UpdateLineControls;
  end;
  if RulerVisible then
    if LineChangeType = lctAppend then
      UpdateRulerLine(LineCount - 1)
    else
      UpdateRuler;
end;

procedure TTextEditor.TextFileLineClassChange(Sender: TObject;
  LineIndex: integer);
begin
  if FMultiSize then
  begin
    RebuildLineCache;
    RecomputeHorizontalExtent;
    UpdateScrollBars;
    VisualUpdate(ctLineRange, LineIndex, FTextFile.LineCount - 1, 0, 0);
    VisualUpdate(ctPostFile, 0, 0, 0, 0);
    UpdateLineControls;
    UpdateRuler;
  end
  else
    VisualUpdate(ctLine, LineIndex, 0, 0, 0);

  if CaretPos.Y = LineIndex then
    UpdateCaret
  else
    DoSetCaretPos;
end;

procedure TTextEditor.TextFileControlRemoved(Sender: TObject;
  ControlID: integer);
var
  i: Integer;
  j: Integer;
begin
  Exit; // it is nice to be able to undo the removal
  for i := 0 to high(FLineControls) do
    if FLineControls[i].ID = ControlID then
    begin
      FLineControls[i].Control.Free;
      for j := i to high(FLineControls) - 1 do
        FLineControls[j] := FLineControls[j + 1];
      SetLength(FLineControls, Length(FLineControls) - 1);
      break;
    end;
end;

function TTextEditor.ClassExists(const AClassName: string): boolean;
begin
  result := GetClassIndex(AClassName) <> -1;
end;

function TTextEditor.ClassExists(const AClassName: string;
  out Index: integer): boolean;
begin
  Index := GetClassIndex(AClassName);
  result := Index <> -1;
end;

procedure TTextEditor.Clear;
begin
  Escape(true);
  TypeTimerEnd;
  FTextFile.Clear;
  FTextFile.ControlAware := false;
  AddUndoRecord(SUndoTextCleared, UID_UNKNOWN);
end;

procedure TTextEditor.ClearBookmarks;
begin
  TypeTimerEnd;
  FTextFile.ClearBookmarks;
  AddUndoRecord(SUndoBookmarksCleared, UID_UNKNOWN);
  UpdateRuler;
end;

procedure TTextEditor.ClearBracketHighlight;
begin
  if FBracketHighlight then
  begin
    FBracketHighlight := false;
    VisualUpdate(ctTwoChars, FBracketPos1.Y, FBracketPos1.X, FBracketPos2.Y,
      FBracketPos2.X);
  end;
end;

procedure TTextEditor.ClearClasses;
begin
  SetLength(FClassArray, 0);
end;

procedure TTextEditor.ClearControls;
var
  i: Integer;
begin
  for i := 0 to high(FLineControls) do
    FLineControls[i].Control.Free;
  SetLength(FLineControls, 0);
end;

procedure TTextEditor.SetBracketHighlight(const PointA, PointB: TPoint);
begin
  if FBracketHighlight then
    ClearBracketHighlight;
  FBracketHighlight := true;
  FBracketPos1 := PointA;
  FBracketPos2 := PointB;
  VisualUpdate(ctTwoChars, FBracketPos1.Y, FBracketPos1.X, FBracketPos2.Y,
    FBracketPos2.X);
end;

procedure TTextEditor.HighlightCurrentBracket;
var
  BracketPos: TPoint;
begin
  ClearBracketHighlight;
  BracketPos := FTextFile.MatchBracket(FTextFile.CaretPos.Data);
  if BracketPos.Y <> -1 then
    SetBracketHighlight(CaretPos, BracketPos);
end;

{ pre-BMCARET }
procedure TTextEditor.TextFileCaretPosChange(Sender: TObject);
begin
  if (not FPreserveDesiredColumn) and FMultiSize then
    FDesiredColumn :=  FTextFile.CaretPos.X * FFontSizes[FTextFile.CaretPos.Y].cx;
  if BalloonVisible and (ord(FBalloonPersistence) <= ord(bpCaretPos)) then
    HideBalloon;
  ChangeCursor;
  if FMultiSize and (FTextFile.CaretPos.Y <> FOldCaretPosY) then
    UpdateCaret;
  if FTextFile.CaretPos.Y <> FOldCaretPosY then
  begin
    UpdateRulerLine(FTextFile.CaretPos.Y);
    UpdateRulerLine(FOldCaretPosY);
  end;
  if (not ScrollToCaret) and Focused then
    DoSetCaretPos;
  if FLineHighlight and (FTextFile.CaretPos.Y <> FOldCaretPosY) then
  begin
    VisualUpdate(ctLine, FOldCaretPosY, 0, 0, 0);
    VisualUpdate(ctLine, FTextFile.CaretPos.Y, 0, 0, 0);
  end;
  if FMatchBrackets then
    HighlightCurrentBracket;
  if FListBoxMode and (FTextFile.CaretPos.Y <> FOldCaretPosY) then
    if Assigned(FOnListBoxChange) then
      FOnListBoxChange(Self);
  FOldCaretPosY := FTextFile.CaretPos.Y;
  if FMultiCharSelect and HasNotificationMessage(EN_MULTICHAR) then
    RemoveNotification(EN_MULTICHAR);
  if Assigned(FOnSelChange) then
    FOnSelChange(Self);
end;

function TTextEditor.ScrollToCaret: boolean;
var
  CaretPixel: TPoint;
  NewX, NewY: integer;
  _ScrollExtra: integer;
begin
  if FNoScrollToCaret then Exit(false);

  CaretPixel := VirtualPixelAtChar(FTextFile.CaretPos.Data);

  if (SCROLL_EXTRA < ClientWidth div 2) and not SingleLine then
    _ScrollExtra := SCROLL_EXTRA
  else
    _ScrollExtra := 0;

  if FScrollPos.X + ClientWidth - FMarginLeft - FMarginRight < CaretPixel.X + CARET_WIDTH then
    NewX := CaretPixel.X - ClientWidth + FMarginLeft + FMarginRight + CARET_WIDTH + _ScrollExtra
  else if FScrollPos.X > CaretPixel.X then
    NewX := Max(CaretPixel.X - _ScrollExtra, 0)
  else
    NewX := FScrollPos.X;

  if FScrollPos.Y + ClientHeight - FMarginTop - FMarginBottom < CaretPixel.Y + FFontSize.cy then
    NewY := CaretPixel.Y - ClientHeight + FMarginTop + FMarginBottom + FFontSize.cy
  else if FScrollPos.Y > CaretPixel.Y then
    NewY := CaretPixel.Y
  else
    NewY := FScrollPos.Y;

  result := (NewX <> FScrollPos.X) or (NewY <> FScrollPos.Y);

  if result then
    SetScrollPosXY(NewX, NewY);
end;

procedure TTextEditor.TextFileCaretPosSelChange(Sender: TObject;
  ChangeType: TChangeType; Data1, Data2, Data3, Data4: Integer);
begin
  VisualUpdate(ChangeType, Data1, Data2, Data3, Data4);
end;

procedure TTextEditor.WMContextMenu(var Message: TWMContextMenu);
var
  p: TPoint;
  PmMain: TPopupMenu;
  PmRuler: TPopupMenu;
  ctl: TControl;
begin

  if Assigned(PopupMenu) then
    PmMain := PopupMenu
  else
    PmMain := FPopupMenu;

  if Assigned(RulerPopupMenu) then
    PmRuler := RulerPopupMenu
  else
    PmRuler := FRulerMenu;

  if (Message.XPos = -1) and (Message.YPos = -1) then // menu key or Shift+F10
    if Windows.GetCaretPos(p) then
      with ClientToScreen(p) do
        if FMultiSize then
          PmMain.Popup(x, y + FFontSizes[CaretPos.Y].cy)
        else
          PmMain.Popup(x, y + FFontSize.cy)
    else
      with ClientToScreen(Point(ClientWidth div 2, ClientHeight div 2)) do
        PmMain.Popup(x, Y)
  else // RMB
  begin
    p := ScreenToClient(SmallPointToPoint(Message.Pos));
    if (p.X >= ClientWidth) or (p.Y >= ClientHeight) then
    begin
      inherited;
      Exit;
    end
    else if p.X >= GetFunctionalSelectionBarWidth then
    begin
      ctl := ControlAtPos(p, true);
      if ctl <> nil then
        Message.Result := ctl.Perform(WM_CONTEXTMENU, TMessage(Message).WParam, TMessage(Message).LParam);
      if Message.Result = 0 then
        PmMain.Popup(Message.XPos, Message.YPos)
    end
    else if p.X < FRulerWidth then
      PmRuler.Popup(Message.XPos, Message.YPos);
  end;

  Message.Result := 1;

end;

procedure TTextEditor.WMEnable(var Message: TWMEnable);
begin
  inherited;
  SetupColors;
  Invalidate;
end;

procedure TTextEditor.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
  Message.Result := 1;
end;

procedure TTextEditor.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
  inherited;
  Message.Result := Message.Result or DLGC_WANTCHARS or DLGC_WANTARROWS or
    IfThen(FWantTab, DLGC_WANTTAB) or IfThen(FWantReturn, DLGC_WANTALLKEYS);
end;

procedure TTextEditor.WMHScroll(var Message: TWMHScroll);
var
  ScrollInfo: TScrollInfo;
begin
  inherited;
  case Message.ScrollCode of
    SB_LEFT:
      SetScrollPosX(0);
    SB_RIGHT:
      SetScrollPosX(FFontSize.cx * FTextFile.MaxLineWidth);
    SB_LINELEFT:
      SetScrollPosX(FScrollPos.X - FFontSize.cx);
    SB_LINERIGHT:
      SetScrollPosX(FScrollPos.X + FFontSize.cx);
    SB_PAGELEFT:
      SetScrollPosX(FScrollPos.X - ClientWidth + FMarginLeft + FMarginRight);
    SB_PAGERIGHT:
      SetScrollPosX(FScrollPos.X + ClientWidth - FMarginLeft - FMarginRight);
    SB_THUMBTRACK:
      begin
        ScrollInfo.cbSize := sizeof(TScrollInfo);
        ScrollInfo.fMask := SIF_TRACKPOS;
        GetScrollInfo(Handle, SB_HORZ, ScrollInfo);
        SetScrollPosX(ScrollInfo.nTrackPos);
      end;
  end;
end;

{ BMSCROLL }
procedure TTextEditor.SetScrollPosX(Value: integer);
var
  OldScrollPos, diff: integer;
  TCR: TRect;
begin
  if Value < 0 then Value := 0;
  OldScrollPos := FScrollPos.X;
  FScrollPos.X := Value;
  diff := OldScrollPos - Value;
  if diff = 0 then Exit;
  UpdateScrollBars;
  TCR := TextContentRect;
  if abs(diff) < ClientWidth - FMarginLeft - FMarginRight then
    ScrollWindowEx(Handle, diff, 0, @TCR, @TCR, 0, nil, SW_INVALIDATE or SW_SCROLLCHILDREN)
  else
    Invalidate;
  DoSetCaretPos;
  if FTextFile.ControlAware then
    UpdateLineControls;
  MoveBalloonPostScroll;
end;

procedure TTextEditor.WMKillFocus(var Message: TWMKillFocus);
begin
  inherited;
  Escape(true);
  DestroyCaret;
  FCaretVisible := false;
  if SingleLine and FLabelStyle then Invalidate;
end;

procedure TTextEditor.WMMouseHWheel(var Message: TWMMouseWheel);
begin
  if (GetKeyState(VK_LMENU) and $8000) <> 0 then
  begin
    if Message.WheelDelta < 0 then
      FTextFile.Left
    else
      FTextFile.Right;
    Exit;
  end;

  if (Message.Keys and MK_SHIFT) <> 0 then
    SetScrollPosX(FScrollPos.X + Sign(Message.WheelDelta))
  else
    SetScrollPosX(FScrollPos.X + round(FFontSize.cx * Message.WheelDelta / WHEEL_DELTA));

  Message.Result := 0;
end;

procedure TTextEditor.WMMouseWheel(var Message: TWMMouseWheel);
var
  ShiftState: TShiftState;
begin

  ShiftState := [];
  if Message.Keys and MK_CONTROL <> 0 then
    Include(ShiftState, ssCtrl);
  if Message.Keys and MK_LBUTTON <> 0 then
    Include(ShiftState, ssLeft);
  if Message.Keys and MK_MBUTTON <> 0 then
    Include(ShiftState, ssMiddle);
  if Message.Keys and MK_RBUTTON <> 0 then
    Include(ShiftState, ssRight);
  if Message.Keys and MK_SHIFT <> 0 then
    Include(ShiftState, ssShift);
  if IsKeyDown(VK_LMENU) then
    Include(ShiftState, ssAlt);

  if ssCtrl in ShiftState then
  begin
    if Message.WheelDelta < 0 then
      ZoomOut
    else
      ZoomIn;
    Exit;
  end;

  if ssAlt in ShiftState then
  begin
    if Message.WheelDelta < 0 then
      FTextFile.Down
    else
      FTextFile.Up;
    Update;
    Exit;
  end;

  if (ssShift in ShiftState) or (FScrollBehaviour = sbPixel) then
    SetScrollPosY(FScrollPos.Y - Sign(Message.WheelDelta), true)
  else if FScrollBehaviour = sbLine then
    SetScrollPosY(FScrollPos.Y - round(FFontSize.cy * Message.WheelDelta / WHEEL_DELTA), true)
  else
    if FSPIScrollLines >= 0 then
      SetScrollPosY(FScrollPos.Y - round(FFontSize.cy * FSPIScrollLines * Message.WheelDelta / WHEEL_DELTA), true)
    else if FSPIScrollLines = -1 then
      SetScrollPosY(FScrollPos.Y - round(ClientHeight * Message.WheelDelta / WHEEL_DELTA), true);

  Message.Result := 0;

  with ScreenToClient(Message.Pos) do
    ChangeCursor(ShiftState, Y, X);

end;

procedure TTextEditor.WMNCActivate(var Message: TWMNCActivate);
begin
  inherited;
end;

procedure TTextEditor.WMNCCalcSize(var Message: TWMNCCalcSize);
var
  R: TRect;
begin
  DefaultHandler(Message);
  R := Message.CalcSize_Params.rgrc0;
  InflateRect(R, -BorderWidth, -BorderWidth);
  Message.CalcSize_Params.rgrc0 := R;
  Message.Result := 0;
end;

procedure TTextEditor.WMNCHitTest(var Message: TWMNCHitTest);
var
  pnt: TPoint;
  WS: integer;
  R: TRect;
  ClientWidth, ClientHeight: integer;
begin
  if FBorderType = btSimpleColor then
  begin
    Windows.GetClientRect(Handle, R);
    ClientWidth := R.Right - R.Left;
    ClientHeight := R.Bottom - R.Top;
    pnt := ScreenToClient(SmallPointToPoint(Message.Pos));
    WS := GetWindowLong(Handle, GWL_STYLE);
    if PtInRect(R, pnt) then
      Message.result := HTCLIENT
    else if ((WS and WS_VSCROLL) <> 0) and
      InRange(pnt.X, ClientWidth, ClientWidth + GetSystemMetrics(SM_CXVSCROLL)) and
      InRange(pnt.Y, 0, ClientHeight) then
      Message.Result := HTVSCROLL
    else if ((WS and WS_HSCROLL) <> 0) and
      InRange(pnt.Y, ClientHeight, ClientHeight + GetSystemMetrics(SM_CYHSCROLL)) and
      InRange(pnt.X, 0, ClientWidth) then
      Message.Result := HTHSCROLL
    else
      Message.Result := HTBORDER;
  end
  else
    inherited;
end;

procedure TTextEditor.WMNCPaint(var Message: TWMNCPaint);
var
  dc: HDC;
  WS: integer;
  OldColor: TColor;
  R: TRect;
  Width, Height: integer;
begin
  if FBorderType = btSimpleColor then
  begin
    DefaultHandler(Message);
    GetWindowRect(Handle, R);
    Width := R.Right - R.Left;
    Height := R.Bottom - R.Top; // Self.Width and Self.Height are not up to date at this time
    OldColor := Brush.Color;
    dc := GetWindowDC(Handle);
    try
      WS := GetWindowLong(Handle, GWL_STYLE);
      if ((WS and WS_VSCROLL) <> 0) and ((WS and WS_HSCROLL) <> 0) then
      begin
        Brush.Color := clBtnFace;
        FillRect(dc, Rect(Width - BorderWidth - GetSystemMetrics(SM_CXVSCROLL),
          Height - BorderWidth - GetSystemMetrics(SM_CXHSCROLL),
          Width - BorderWidth,
          Height - BorderWidth),
          Brush.Handle);
      end;
      ExcludeClipRect(dc, BorderWidth, BorderWidth,
        Width - BorderWidth, Height - BorderWidth);
      Brush.Color := FBorderColor;
      FillRect(dc, Rect(0, 0, Width, Height), Brush.Handle);
      Message.Result := 0;
    finally
      ReleaseDC(Handle, dc);
      Brush.Color := OldColor;
    end;
  end
  else
    inherited;
end;

procedure TTextEditor.WMPaint(var Message: TWMPaint);
begin
  if Assigned(FDropTargetHelper) and Assigned(FDragDataObj) then
    FDropTargetHelper.Show(false);
  inherited;
  if Assigned(FDropTargetHelper) and Assigned(FDragDataObj) then
    FDropTargetHelper.Show(true);
end;

procedure TTextEditor.WMSetFocus(var Message: TWMSetFocus);
begin
  inherited;
  NeedValidPaintState;
  UpdateCaret;
  UpdateScrollMode;
  if SingleLine and FLabelStyle then
    Invalidate;
end;

procedure TTextEditor.WMSize(var Message: TWMSize);
begin
  inherited;
  UpdateScrollBars;
  DoSetCaretPos;
end;

procedure TTextEditor.WMVScroll(var Message: TWMVScroll);
var
  ScrollInfo: TScrollInfo;
begin
  inherited;
  case Message.ScrollCode of
    SB_TOP:
      SetScrollPosY(0);
    SB_BOTTOM:
      SetScrollPosY(FFontSize.cy * FTextFile.LineCount);
    SB_LINEUP:
      SetScrollPosY(FScrollPos.Y - FFontSize.cy);
    SB_LINEDOWN:
      SetScrollPosY(FScrollPos.Y + FFontSize.cy);
    SB_PAGEUP:
      SetScrollPosY(FScrollPos.Y - ClientHeight + FMarginTop + FMarginBottom);
    SB_PAGEDOWN:
      SetScrollPosY(FScrollPos.Y + ClientHeight - FMarginTop - FMarginBottom);
    SB_THUMBTRACK:
      begin
        ScrollInfo.cbSize := sizeof(TScrollInfo);
        ScrollInfo.fMask := SIF_TRACKPOS;
        GetScrollInfo(Handle, SB_VERT, ScrollInfo);
        SetScrollPosY(ScrollInfo.nTrackPos);
      end;
  end;
end;

procedure TTextEditor.WndProc(var Message: TMessage);
  function REFontInc(Old, Delta: integer): integer;
    function rnd(x: real): integer;
    begin
      if Delta > 0 then
        result := ceil(x)
      else
        result := floor(x);
    end;
  begin
    result := Old + Delta;
    if result < 1 then
      result := 1
    else if result <= 28 then
      result := 2*rnd(result / 2)
    else if result <= 36 then
      result := 36
    else if result <= 48 then
      result := 48
    else if result <= 72 then
      result := 72
    else if result <= 80 then
      result := 80
    else
      result := 10*rnd(result / 10);
    if result > 1638 then
      result := 1638;
  end;
const
  ECM_FIRST = $1500;
  EM_SETCUEBANNER = ECM_FIRST + 1;
  EM_GETCUEBANNER = ECM_FIRST + 2;
  EM_SHOWBALLOONTIP = ECM_FIRST + 3;
  EM_HIDEBALLOONTIP = ECM_FIRST + 4;
  EM_GETSCROLLPOS = WM_USER + 221;
  EM_SETSCROLLPOS = WM_USER + 222;
  EM_GETTOUCHOPTIONS = WM_USER + 310;
  EM_GETZOOM = WM_USER + 224;
  EM_SETZOOM = WM_USER + 225;
  EM_SETFONTSIZE = WM_USER + 223;
type
  PCHARRANGE = ^CHARRANGE;
  PTEXTRANGE = ^TEXTRANGE;
var
  s: string;
  i: integer;
begin
  inherited;
  case Message.Msg of
    WM_TIMER:
      if Message.WParam and EDITOR_NOTIFY <> 0 then
      begin
        RemoveNotification(Message.WParam and $FFFF);
        if not KillTimer(Handle, Message.WParam) then
          RaiseLastOSError;
        Message.Result := 0;
        Exit;
      end;
  end;
  if not FMessageInterface then Exit;
  case Message.Msg of
    WM_UNDO:
      Message.Result := B(Undo);
    EM_UNDO:
      Message.Result := B(Undo);
    EM_REDO:
      Message.Result := B(Redo);
    EM_CANUNDO:
      Message.Result := B(CanUndo);
    EM_CANREDO:
      Message.Result := B(CanRedo);
    WM_CUT:
      CutToClipboard;
    WM_COPY:
      CopyToClipboard;
    WM_PASTE:
      PasteFromClipboard;
    WM_CLEAR:
      ClearSelection;
    EM_SETSEL:
      begin
        if Message.WParam = NativeUInt(-1) then
          SelectNone
        else if (Message.WParam = 0) and (Message.LParam = -1) then
          SelectAll
        else if (Integer(Message.WParam) >= 0) and (Message.LParam >= 0) then
        begin
          FTextFile.CaretPos.SetPoint(FTextFile.GetPointOfIndex(Message.WParam));
          FTextFile.CaretPos.SetPoint(FTextFile.GetPointOfIndex(Message.LParam), true);
        end;
      end;
    EM_CHARFROMPOS:
      Message.Result := FTextFile.GetIndexOfPoint(CaretPosAtPhysicalPixel(Point(PPOINTL(Message.LParam)^.x, PPOINTL(Message.LParam)^.y)));
    EM_EMPTYUNDOBUFFER:
      ClearUndoHistory;
    EM_GETCUEBANNER:
      Message.Result := 0;
    EM_GETFIRSTVISIBLELINE:
      Message.Result := FirstVisibleLine;
    EM_GETHANDLE:
      Message.Result := 0;
    EM_GETLINE:
      begin
        if InRange(Message.WParam, 0, FTextFile.LineCount - 1) then
        begin
          s := FTextFile.Lines[Message.WParam];
          i := Min(PWord(Message.LParam)^, Length(s));
          Move(s, PChar(Message.LParam)^, i * sizeof(Char));
          Message.Result := i;
        end
        else
          Message.Result := 0;
      end;
    EM_GETLINECOUNT:
      Message.Result := FTextFile.LineCount;
    EM_GETMARGINS:
      Message.Result := 0;
    EM_GETMODIFY:
      Message.Result := B(FTextFile.FileModified);
    EM_GETPASSWORDCHAR:
      Message.Result := ord(FPasswordChar);
    EM_GETSEL:
      begin
        if FTextFile.HasSelection then
        begin
          if Message.WParam <> 0 then
            PDWORD(Message.WParam)^ := FTextFile.GetIndexOfPoint(FTextFile.CaretPos.FirstPoint);
          if Message.LParam <> 0 then
            PDWORD(Message.LParam)^ := FTextFile.GetIndexOfPoint(FTextFile.CaretPos.LastPoint) + 1;
        end
        else
        begin
          if Message.WParam <> 0 then
            PDWORD(Message.WParam)^ := SelStart;
          if Message.LParam <> 0 then
            PDWORD(Message.LParam)^ := SelStart;
        end;
      end;
    EM_GETTHUMB:
      Message.Result := FScrollPos.Y;
    EM_GETWORDBREAKPROC:
      Message.Result := 0;
    EM_HIDEBALLOONTIP:
      begin
        HideBalloon;
        Message.Result := 1;
      end;
    EM_LINEFROMCHAR:
      if Message.WParam = NativeUInt(-1) then
        Message.Result := FTextFile.CaretPos.FirstPoint.Y
      else if InRange(Message.WParam, 0, FTextFile.NumCharacters - 1) then
        Message.Result := FTextFile.GetPointOfIndex(Message.WParam).Y
      else
        Message.Result := -1;
    EM_LINEINDEX:
      if Message.WParam = NativeUInt(-1) then
        Message.Result := FTextFile.GetIndexOfPoint(Point(0, FTextFile.CaretPos.FirstPoint.Y))
      else if InRange(Message.WParam, 0, FTextFile.LineCount - 1) then
        Message.Result := FTextFile.GetIndexOfPoint(Point(0, Message.WParam))
      else
        Message.Result := -1;
    EM_LINELENGTH:
      if Message.WParam = NativeUInt(-1) then
        with FTextFile.CaretPos.LastPoint do
          Message.Result := FTextFile.CaretPos.FirstPoint.X + (FTextFile.VirtualLineWidths[Y] - X)
      else if InRange(Message.WParam, 0, FTextFile.LineCount - 1) then
        Message.Result := FTextFile.VirtualLineWidths[Message.WParam]
      else
        Message.Result := 0;
    EM_LINESCROLL:
      begin
        SetScrollPosXY(FScrollPos.X + FFontSize.cx * NativeInt(Message.WParam), FScrollPos.Y + FFontSize.cy * Message.LParam);
        Message.Result := IfThen(SingleLine, 0, 1);
      end;
    EM_POSFROMCHAR:
      with VirtualPixelAtChar(FTextFile.GetPointOfIndex(Message.LParam)) do
      begin
        PPOINTL(Message.WParam)^.x := X;
        PPointL(Message.WParam)^.y := Y;
      end;
    EM_REPLACESEL:
      begin
        InsertText(PChar(Message.LParam)^);
        if Message.WParam = 0 then
          ClearUndoHistory;
      end;
    EM_SCROLL:
      begin
        if (Message.WParam  = SB_LINEDOWN) or (Message.WParam = SB_LINEUP) then
          Message.Result := (1 shr 16) or 1
        else if (Message.WParam = SB_PAGEDOWN) or (Message.WParam = SB_PAGEUP) then
          Message.Result := (1 shr 16) or (ClientHeight div FFontSize.cy)
        else
          Message.Result := 0;
        if Message.Result <> 0 then
          Perform(WM_VSCROLL, Message.wParam, 0);
      end;
    EM_SCROLLCARET:
      Message.Result := B(ScrollToCaret);
    EM_SETCUEBANNER:
      Message.Result := 0;
    EM_SETMODIFY:
      FTextFile.FileModified := Message.WParam <> 0;
    EM_SETPASSWORDCHAR:
      SetPasswordChar(chr(Message.WParam));
    EM_SETREADONLY:
      begin
        if Message.WParam <> 0 then
          EditMode := emReadOnly
        else if EditMode = emReadOnly then
          EditMode := emText;
        Message.Result := 1;
      end;
    EM_SETTABSTOPS:
      Message.Result := 0;
    EM_SHOWBALLOONTIP:
      with PEDITBALLOONTIP(Message.LParam)^ do
      begin
        if cbStruct = sizeof(TEditBalloonTip) then
          Message.Result := B(ShowBalloon(pszTitle, pszText,
            TBalloonIconKind(ttiIcon), bpRemain, CaretPos))
        else
          Message.Result := 0;
      end;
    EM_CANPASTE:
      if Message.WParam = 0 then
        Message.Result := B(Clipboard.HasFormat(CF_TEXT) or (Clipboard.HasFormat(CF_BITMAP) and not SingleLine))
      else
        Message.Result := B((Message.WParam = CF_TEXT) or (Message.WParam = CF_UNICODETEXT) or ((Message.WParam = CF_BITMAP) and not SingleLine));
    EM_EXGETSEL:
      begin
        if FTextFile.AllSelected then
        begin
          PCHARRANGE(Message.LParam)^.cpMin := 0;
          PCHARRANGE(Message.LParam)^.cpMax := -1;
        end
        else if FTextFile.HasSelection then
        begin
          PCHARRANGE(Message.LParam)^.cpMin := FTextFile.GetIndexOfPoint(FTextFile.CaretPos.FirstPoint);
          PCHARRANGE(Message.LParam)^.cpMin := FTextFile.GetIndexOfPoint(FTextFile.CaretPos.LastPoint) + 1
        end
        else
        begin
          PCHARRANGE(Message.LParam)^.cpMin := FTextFile.GetIndexOfPoint(FTextFile.CaretPos.FirstPoint);
          PCHARRANGE(Message.LParam)^.cpMin := PCHARRANGE(@Message.LParam)^.cpMin;
        end;
      end;
    EM_EXLINEFROMCHAR:
      Message.Result := FTextFile.GetPointOfIndex(Message.LParam).Y;
    EM_FINDTEXT:
      {TODO};
    EM_FINDTEXTEX:
      {TODO};
    EM_GETREDONAME:
      if CanRedo then
        Message.Result := FTextFile.HistoryManager.UndoData[FTextFile.HistoryManager.HistoryIndex + 1].UID
      else
        Message.Result := 0;
    EM_GETSCROLLPOS:
      begin
        PPOINT(Message.LParam)^ := FScrollPos;
        Message.Result := 1;
      end;
    EM_GETSELTEXT:
      begin
        s := SelText;
        i := Length(SelText);
        Move(s, PChar(Message.LParam), i * sizeof(Char));
        Message.Result := i;
      end;
    EM_GETTEXTLENGTHEX:
      if (PDWORD(Message.WParam)^ and GTL_USECRLF) <> 0 then
        Message.Result := FTextFile.VirtualTextLength
      else
        Message.Result := FTextFile.NumCharacters;
    EM_GETTEXTMODE:
      Message.Result := TM_PLAINTEXT or TM_MULTILEVELUNDO or TM_MULTICODEPAGE;
    EM_GETTEXTRANGE:
      with PTEXTRANGE(Message.LParam)^ do
      begin
        if (chrg.cpMin = 0) and (chrg.cpMax = -1) then
          s := PlainText + #0
        else
          s := Copy(PlainText, chrg.cpMin + 1, chrg.cpMax - chrg.cpMin) + #0;
          Move(s[1], lpstrText^, Length(s))
      end;
    EM_GETTOUCHOPTIONS:
      Message.Result := 0;
    EM_GETUNDONAME:
      if CanUndo then
        Message.Result := FTextFile.HistoryManager.UndoData[FTextFile.HistoryManager.HistoryIndex].UID
      else
        Message.Result := 0;
    EM_GETZOOM:
      begin
        Message.WParam := FZoom;
        Message.LParam := 100;
        Message.Result := 1;
      end;
    EM_HIDESELECTION:
      {TODO};
    EM_SELECTIONTYPE:
      if FTextFile.HasSelection then
        Message.Result := SEL_TEXT or IfThen(SelLength > 1, SEL_MULTICHAR)
      else
        Message.Result := SEL_EMPTY;
    EM_SETBKGNDCOLOR:
      begin
        Message.Result := FBkColor;
        SetUseSystemColors(Message.WParam <> 0);
        if not FUseSystemColors then
          SetBackgroundColor(Message.LParam);
      end;
    EM_SETCHARFORMAT:
      {TODO};
    EM_SETFONTSIZE:
      begin
        Message.Result := B(InRange(Message.WParam, -1637, 1638));
        if Message.Result <> 0 then
          FFont.Size := REFontInc(FFont.Size, Message.WParam);
      end;
    EM_SETSCROLLPOS:
      begin
        Message.Result := 1;
        with PPoint(Message.LParam)^ do
          SetScrollPosXY(X, Y);
      end;
    EM_SETZOOM:
      begin
        Message.Result := B((Message.WParam > 0) and (Message.LParam > 0));
        if Message.Result <> 0 then
          SetZoom(100 * NativeInt(Message.WParam) div Message.LParam);
      end;
    EM_STOPGROUPTYPING:
      if FTypeTimer.Enabled then
        TypeTimerTimer(Self);
  end;
end;

procedure TTextEditor.WordWrap(ALineLength: integer; ANice: boolean;
  AChr: char);
begin
  TypeTimerEnd;
  FTextFile.WordWrap(ALineLength, ANice, AChr);
  AddUndoRecord(SUndoWordWrap, UID_UNKNOWN);
end;

procedure TTextEditor.TextFileFindDataClear(Sender: TObject);
begin
  Invalidate;
  if Assigned(FOnFindDataClear) then
    FOnFindDataClear(Self);
end;

procedure TTextEditor.TextFileLockVisualUpdates(Sender: TObject);
begin
  inc(FVisualUpdateLock);
end;

procedure TTextEditor.BeginVisualUpdate;
begin
  inc(FVisualUpdateLock);
end;

procedure TTextEditor.TextFileUnlockVisualUpdates(Sender: TObject);
begin
  dec(FVisualUpdateLock);
  if FVisualUpdateLock = 0 then
    DoSetCaretPos;
  // But the client is responsible for what to redraw
end;

procedure TTextEditor.EndVisualUpdate(AUpdate: boolean = false);
begin
  dec(FVisualUpdateLock);
  if FVisualUpdateLock = 0 then
  begin
    Invalidate;
    DoSetCaretPos;
    if AUpdate then Update;
  end;
end;

procedure TTextEditor.ConnectTextFileToEditor;
begin
  FTextFile.OnChange := TextFileChange;
  FTextFile.OnCaretPosChange := TextFileCaretPosChange;
  FTextFile.OnCaretPosSelChange := TextFileCaretPosSelChange;
  FTextFile.OnInputError := TextFileInputError;
  FTextFile.OnReadOnlyError := TextFileReadOnlyError;
  FTextFile.OnFileModified := TextFileModified;
  FTextFile.OnLineChange := TextFileLineChange;
  FTextFile.OnLineClassChange := TextFileLineClassChange;
  FTextFile.OnControlRemoved := TextFileControlRemoved;
  FTextFile.OnGetControlText := TextFileGetControlText;
  FTextFile.OnBookmarksMoved := TextFileBookmarksMoved;
  FTextFile.OnFindDataClear := TextFileFindDataClear;
  FTextFile.OnLockVisualUpdates := TextFileLockVisualUpdates;
  FTextFile.OnUnlockVisualUpdates := TextFileUnlockVisualUpdates;
  FTextFile.IndentSize := Self.IndentSize;
  FTextFile.AutoIndent := Self.AutoIndent;
  FTextFile.CaretAfterEOL := FCaretAfterEOL {important!};
end;

procedure TTextEditor.DisconnectTextFileFromEditor;
begin
  FTextFile.OnChange := nil;
  FTextFile.OnCaretPosChange := nil;
  FTextFile.OnCaretPosSelChange := nil;
  FTextFile.OnInputError := nil;
  FTextFile.OnFileModified := nil;
  FTextFile.OnLineChange := nil;
  FTextFile.OnLineClassChange := nil;
  FTextFile.OnControlRemoved := nil;
  FTextFile.OnGetControlText := nil;
  FTextFile.OnBookmarksMoved := nil;
  FTextFile.OnLockVisualUpdates := nil;
  FTextFile.OnUnlockVisualUpdates := nil;
end;

procedure TTextEditor.ZoomIn;
begin
  Zoom := Zoom + 10;
end;

procedure TTextEditor.ZoomOut;
begin
  Zoom := Max(Zoom - 10, 10);
end;

{ BMSCROLL }
procedure TTextEditor.SetScrollPosY(Value: integer; Lim: boolean = false);
var
  OldScrollPos, diff: integer;
  TCR: TRect;
begin
  if (Value < 0) or SingleLine then Value := 0;
  if Lim then
  begin
    if GetLineBottomVirtual(LineCount - 1) < (ClientHeight - FMarginTop - FMarginBottom) then
      Value := 0
    else if Value > GetLineBottomVirtual(LineCount - 1) - (ClientHeight - FMarginTop - FMarginBottom) then
      Value := GetLineBottomVirtual(LineCount - 1) - (ClientHeight - FMarginTop - FMarginBottom);
  end;
  OldScrollPos := FScrollPos.Y;
  FScrollPos.Y := Value;
  diff := OldScrollPos - Value;
  if diff = 0 then Exit;
  UpdateScrollBars;
  TCR := TextContentRect;
  TCR.Left := 0; // ruler should scroll with the text (in pure vertical scrolling)
  if abs(diff) < ClientHeight - FMarginTop - FMarginBottom then
    ScrollWindowEx(Handle, 0, diff, @TCR, @TCR, 0, nil, SW_INVALIDATE or SW_SCROLLCHILDREN)
  else
    Invalidate;
  UpdateRuler;
  DoSetCaretPos;
  if FTextFile.ControlAware then
    UpdateLineControls;
  MoveBalloonPostScroll;
end;

{ BMSCROLL }
procedure TTextEditor.SetScrollPosXY(X, Y: integer; Lim: boolean = false);
var
  OldScrollPos: TPoint;
  diffX, diffY: integer;
  TCR: TRect;
begin

  if SingleLine then Y := 0;

  if X < 0 then X := 0;
  if Y < 0 then Y := 0;

  if Lim then
  begin
    if GetLineBottomVirtual(LineCount - 1) < (ClientHeight - FMarginTop - FMarginBottom) then
      Y := 0
    else if Y > GetLineBottomVirtual(LineCount - 1) - (ClientHeight - FMarginTop - FMarginBottom) then
      Y := GetLineBottomVirtual(LineCount - 1) - (ClientHeight - FMarginTop - FMarginBottom);
  end;

  // Special case: optimize?
  if (X = FScrollPos.X) then
  begin
    SetScrollPosY(Y);
    Exit;
  end
  else if (Y = FScrollPos.Y) then
  begin
    SetScrollPosX(X);
    Exit;
  end;

  OldScrollPos := FScrollPos;
  FScrollPos := Point(X, Y);
  diffX := OldScrollPos.X - X;
  diffY := OldScrollPos.Y - Y;
  UpdateScrollBars;
  TCR := TextContentRect;
  if (abs(diffY) < ClientHeight - FMarginTop - FMarginBottom) and (abs(diffX) < ClientWidth - FMarginLeft - FMarginRight) then
    ScrollWindowEx(Handle, diffX, diffY, @TCR, @TCR, 0, nil, SW_INVALIDATE or SW_SCROLLCHILDREN)
  else
    Invalidate;
  UpdateRuler;
  DoSetCaretPos;
  if FTextFile.ControlAware then
    UpdateLineControls;
  MoveBalloonPostScroll;

end;

procedure TTextEditor.UpdateLineControls;
var
  i: Integer;
  LineIndex: integer;
begin
  for i := 0 to high(FLineControls) do
  begin
    if not Assigned(FLineControls[i].Control) then Continue;
    LineIndex := GetLineFromControlID(FLineControls[i].ID);
    if LineIndex = -1 then
    begin
      FLineControls[i].Control.Visible := false;
      Continue;
    end;
    FLineControls[i].Control.Visible := true;
    FLineControls[i].Control.SetBounds(FMarginLeft - FScrollPos.X + CARET_WIDTH,
      FMarginTop + FAccumLineHeights[LineIndex] - FScrollPos.Y,
      FLineControls[i].Control.Width,
      FLineControls[i].Control.Height);
  end;
end;

procedure TTextEditor.FontChange(Sender: TObject);
begin
  VerifyFont;
  SetupFontMetrics;
  BuildFontDataArray;
  AdjustHeight;
  Invalidate;
end;

procedure TTextEditor.UpdateRuler;
begin
  InvalidateRect(Handle, RulerRect, false);
end;

procedure TTextEditor.RulerFontChange(Sender: TObject);
begin
  UpdateRuler;
end;

function TTextEditor.GetCaretAfterEOL: boolean;
begin
  FCaretAfterEOL := FTextFile.CaretAfterEOL;
  result := FCaretAfterEOL;
end;

function TTextEditor.GetCaretPos: TPoint;
begin
  result := FTextFile.CaretPos.Data;
end;

function TTextEditor.GetCharAtCaret: char;
begin
  if (SelLength = 1) and (SafeSelLength = 1) then
    result := SelText[1]
  else if FTextFile.CaretPos.X < FTextFile.VirtualLineWidths[FTextFile.CaretPos.Y] then
    result := FTextFile.Lines[FTextFile.CaretPos.Y][FTextFile.CaretPos.X + 1]
  else
    result := #0;
end;

function TTextEditor.GetCharBeforeCaret: char;
begin
  if (SelLength = 1) and (SafeSelLength = 1) then
    result := SelText[1]
  else if FTextFile.CharacterExists(FTextFile.CaretPos.Y, FTextFile.CaretPos.X - 1) then
    result := FTextFile.Lines[FTextFile.CaretPos.Y][FTextFile.CaretPos.X]
  else
    result := #0;
end;

function TTextEditor.GetClassRecord(Index: integer): TClassRecord;
begin
  result := FClassArray[Index];
end;

function TTextEditor.GetCliHistory(Index: integer): string;
begin
  result := FCliHistory[Index];
end;

function TTextEditor.GetCliHistoryCount: integer;
begin
  result := Length(FCliHistory);
end;

function TTextEditor.GetCliHistoryIndex: integer;
begin
  result := FCliHistoryIndex;
end;

function TTextEditor.GetControlFromID(ID: integer): TControl;
var
  i: Integer;
begin
  result := nil;
  for i := low(FLineControls) to high(FLineControls) do
    if FLineControls[i].ID = ID then
      Exit(FLineControls[i].Control);
end;

function TTextEditor.GetControlFromLine(LineIndex: integer): TControl;
begin
  result := GetControlFromID(GetControlIDFromLine(LineIndex));
end;

function TTextEditor.GetControlIDFromLine(LineIndex: integer): integer;
var
  tmp: integer;
begin
  result := -1;
  if LineIsControl(LineIndex) and TryStrToInt(Copy(FTextFile.Lines[LineIndex],
    Length(LINE_CONTROL_PREFIX) + 1), tmp) then result := tmp;
end;

function TTextEditor.GetEditMode: TEditMode;
begin
  result := FTextFile.EditMode;
end;

function TTextEditor.GetClass(Index: integer): string;
begin
  result := FTextFile.Classes[Index];
end;

function TTextEditor.GetClassFromName(const AClassName: string;
  out AClassRecord: TClassRecord): boolean;
var
  i: Integer;
begin
  for i := low(FClassArray) to high(FClassArray) do
    if SameStr(AClassName, FClassArray[i].Name) then
    begin
      AClassRecord := FClassArray[i];
      Exit(true);
    end;
  result := false;
end;

function TTextEditor.GetClassIndex(const AClassName: string): integer;
var
  i: Integer;
begin
  if not AClassName.IsEmpty then
    for i := low(FClassArray) to high(FClassArray) do
      if SameStr(AClassName, FClassArray[i].Name) then
        Exit(i);
  result := -1;
end;

function TTextEditor.GetFalse: boolean;
begin
  result := false;
end;

function TTextEditor.GetFontChrs(const AFontName: TFontName;
  out GlyphSet: PGlyphSet): boolean;
var
  size: integer;
begin
  FGLYPHBM.Canvas.Font.Name := AFontName;
  size := GetFontUnicodeRanges(FGLYPHBM.Canvas.Handle, nil);
  GetMem(GlyphSet, size);
  result := GetFontUnicodeRanges(FGLYPHBM.Canvas.Handle, GlyphSet) > 0;
end;

function TTextEditor.GetIDFromControl(AControl: TControl): integer;
var
  i: Integer;
begin
  for i := low(FLineControls) to high(FLineControls) do
    if FLineControls[i].Control = AControl then
      Exit(i);
  result := -1;
end;

function TTextEditor.GetNotification(AIndex: integer): integer;
begin
  result := FNotifications[AIndex];
end;

function TTextEditor.GetNotificationCount: integer;
begin
  result := Length(FNotifications);
end;

function TTextEditor.GetNotificationStr(MsgID: integer): string;
begin
  result := FNotificationStrs[MsgID];
end;

function TTextEditor.GetNumClasses: integer;
begin
  result := Length(FClassArray);
end;

function TTextEditor.GetRulerVisible: boolean;
begin
  result := FRulerWidth > 0;
end;

function TTextEditor.GetSelEndPos: TPoint;
begin
  result := FTextFile.CaretPos.SelEnd;
end;

function TTextEditor.GetSelLength: integer;
begin
  result := FTextFile.SelLength;
end;

function TTextEditor.GetSelStart: integer;
begin
  result := FTextFile.SelStart;
end;

function TTextEditor.GetSelText: string;
begin
  result := FTextFile.SelText;
end;

function TTextEditor.GetSelType: TSelectionType;
begin
  result := FTextFile.CaretPos.SelectionType;
end;

function TTextEditor.GetSingleLine: boolean;
begin
  result := FTextFile.SingleLine;
end;

function TTextEditor.GetSortReverseOrder: boolean;
begin
  result := FTextFile.SortReverseOrder;
end;

function TTextEditor.GetText: string;
begin
  result := FTextFile.PlainText;
end;

function TTextEditor.GetWord: string;
begin
  result := FTextFile.GetWord;
end;

function TTextEditor.GetWord(const Point: TPoint): string;
begin
  result := FTextFile.GetWord(Point);
end;

function TTextEditor.GetWordBoundary(out StartPos, EndPos: integer): boolean;
begin
  result := FTextFile.GetWordBoundary(StartPos, EndPos);
end;

function TTextEditor.GetWrapAt: string;
begin
  result := FTextFile.WrapAt;
end;

function TTextEditor.GiveFeedback(dwEffect: Longint): HRESULT;
begin
  result := DRAGDROP_S_USEDEFAULTCURSORS;
end;

function TTextEditor.GotoBookmark(AIndex: integer): boolean;
begin
  result := FTextFile.GotoBookmark(AIndex);
end;

function TTextEditor.GotoHistoryVersion(Index: integer): boolean;
begin
  if FTypeTimer.Enabled then
    TypeTimerTimer(Self);
  FNoScrollToCaret := true;
  try
    result := FTextFile.GotoHistoryVersion(Index);
    if FTextFile.ControlAware then
      FixRemovedLineControlLines;
  finally
    FNoScrollToCaret := false;
  end;
  if result then
    CenterOnSelection(true);
end;

procedure TTextEditor.GotoSamePixelAtNextLine(Shift: boolean);
var
  px: TPoint;
begin

  if FTextFile.AtLastLine then
  begin
    TextFileInputError(Self);
    Exit;
  end;

  if not FMultiSize then
  begin
    FTextFile.Down(Shift);
    Exit;
  end;

  px := VirtualPixelAtChar(CaretPos);
  if FDesiredColumn <> 0 then
    px.X := FDesiredColumn;
  inc(px.Y, FFontSizes[CaretPos.Y].cy + FFontSizes[CaretPos.Y + 1].cy div 2);

  FPreserveDesiredColumn := true;
  try
    FTextFile.CaretPos.SetPoint(CaretPosAtVirtualPixel(px), Shift);
  finally
    FPreserveDesiredColumn := false;
  end;

end;

procedure TTextEditor.GotoSamePixelAtPrevLine(Shift: boolean);
var
  px: TPoint;
begin

  if CaretPos.Y = 0 then
  begin
    TextFileInputError(Self);
    Exit;
  end;

  if not FMultiSize then
  begin
    FTextFile.Up(Shift);
    Exit;
  end;

  px := VirtualPixelAtChar(CaretPos);
  if FDesiredColumn <> 0 then
    px.X := FDesiredColumn;
  dec(px.Y, FFontSizes[CaretPos.Y - 1].cy div 2);

  FPreserveDesiredColumn := true;
  try
    FTextFile.CaretPos.SetPoint(CaretPosAtVirtualPixel(px), Shift);
  finally
    FPreserveDesiredColumn := false;
  end;

end;

function TTextEditor.HasNotificationMessage(MsgID: integer): boolean;
var
  i: Integer;
begin
  for i := low(FNotifications) to high(FNotifications) do
    if FNotifications[i] = MsgID then
      Exit(true);
  result := false;
end;

procedure TTextEditor.HideBalloon;
begin
  if FHintWindow <> 0 then
    SendMessage(FHintWindow, TTM_TRACKACTIVATE, 0, LParam(@FToolInfo));
end;

function TTextEditor.GetWordBoundary(const Point: TPoint; out StartPos,
  EndPos: integer): boolean;
begin
  result := FTextFile.GetWordBoundary(Point, StartPos, EndPos);
end;

function UnicodeSuperscript(const AChar: char): char;
begin
  result := AChar;
  case AChar of
    '0':
      result := '⁰';
    '1':
      result := '¹';
    '2':
      result := '²';
    '3':
      result := '³';
    '4':
      result := '⁴';
    '5':
      result := '⁵';
    '6':
      result := '⁶';
    '7':
      result := '⁷';
    '8':
      result := '⁸';
    '9':
      result := '⁹';
    '+':
      result := '⁺';
    '-', '−':
      result := '⁻';
    '=':
      result := '⁼';
    '(':
      result := '⁽';
    ')':
      result := '⁾';
    'n':
      result := 'ⁿ';
  end;
end;

function UnicodeSubscript(const AChar: char): char;
begin
  result := AChar;
  case AChar of
    '0':
      result := '₀';
    '1':
      result := '₁';
    '2':
      result := '₂';
    '3':
      result := '₃';
    '4':
      result := '₄';
    '5':
      result := '₅';
    '6':
      result := '₆';
    '7':
      result := '₇';
    '8':
      result := '₈';
    '9':
      result := '₉';
    '+':
      result := '₊';
    '-', '−':
      result := '₋';
    '=':
      result := '₌';
    '(':
      result := '₍';
    ')':
      result := '₎';
  end;
end;

function UnicodeCircled(const AChar: char): char;
begin
  result := AChar;
  if InRange(ord(AChar), ord('A'), ord('Z')) then
    result := chr($24B6 + ord(AChar) - ord('A'))
  else if InRange(ord(AChar), ord('a'), ord('z')) then
    result := chr($24D0 + ord(AChar) - ord('a'))
  else if InRange(ord(AChar), ord('1'), ord('9')) then
    result := chr($2460 + ord(AChar) - ord('1'))
  else if AChar = '0' then
    result := #$24EA;
end;

function UnicodeParenthesized(const AChar: char): char;
begin
  result := AChar;
  if InRange(ord(AChar), ord('a'), ord('z')) then
    result := chr($249C + ord(AChar) - ord('a'))
  else if InRange(ord(AChar), ord('1'), ord('9')) then
    result := chr($2474 + ord(AChar) - ord('1'))
end;

function UnicodeFullStop(const AChar: char): char;
begin
  result := AChar;
  if InRange(ord(AChar), ord('1'), ord('9')) then
    result := chr($2488 + ord(AChar) - ord('1'))
end;

function UnicodeDoublyCircled(const AChar: char): char;
begin
  result := AChar;
  if InRange(ord(AChar), ord('1'), ord('9')) then
    result := chr($24F5 + ord(AChar) - ord('1'))
end;

function TTextEditor.GetBalloonPosition: TPoint;
begin
  result := ClientToScreen(PhysicalPixelAtChar(FBalloonPoint));
  inc(result.Y, FFontSize.cy);
  inc(result.X, CARET_WIDTH div 2);
end;

function TTextEditor.GetBookmark(Index: integer): TPoint;
begin
  result := FTextFile.Bookmarks[Index];
end;

function TTextEditor.GetBookmarkCount: integer;
begin
  result := FTextFile.BookmarkCount;
end;

function TTextEditor.GetBookmarkDescr(BookmarkIndex: integer): string;
begin
  if not InRange(BookmarkIndex, 0, BookmarkCount - 1) then
    Exit(SBookmarkDescriptionInvalid);

  if BookmarkUsed(BookmarkIndex) then
    result := Format(SBookmarkDescription,
      [BookmarkIndex, Bookmarks[BookmarkIndex].Y + 1, Bookmarks[BookmarkIndex].X + 1])
  else
    result := Format(SBookmarkDescriptionEmpty, [BookmarkIndex]);
end;

procedure TTextEditor.InsertChar(const AChar: Char; AOverwrite: boolean = false);
var
  BChar: char;
begin

  if FTextFile.ControlAware and LineIsControl(FTextFile.CaretPos.Y) then
  begin
    TextFileInputError(Self);
    ShowBalloon(SControlLineInputTitle, SControlLineInputText, bikError, bpCaretPos,
      GetCaretPos);
    Exit;
  end;

  if FNumbersOnly and not AChar.IsDigit and (FHintWindow <> 0) then
  begin
    TextFileInputError(Self);
    ShowBalloon(SNumOnlyErrorTitle, SNumOnlyErrorText, bikError, bpCaretPos,
      GetCaretPos);
    Exit;
  end;

  BChar := AChar;
  case FInputTransform of
    itUpperCase:
      BChar := AnsiUpperCase(AChar)[1];
    itLowerCase:
      BChar := AnsiLowerCase(AChar)[1];
    itSuperscript:
      BChar := UnicodeSuperscript(AChar);
    itSubscript:
      BChar := UnicodeSubscript(AChar);
    itCircled:
      BChar := UnicodeCircled(AChar);
    itParenthesized:
      BChar := UnicodeParenthesized(AChar);
    itFullStop:
      BChar := UnicodeFullStop(AChar);
    itDoublyCircled:
      BChar := UnicodeDoublyCircled(AChar);
  end;

  if FMultipleCarets then
    FTextFile.MultiInsertChar(FCarets, BChar, Overwrite)
  else
    FTextFile.InsertChar(BChar, AOverwrite);

  PostType;

  if FMatchBrackets and ((BChar = '❩') or (BChar = ')') or (BChar = '}') or (BChar = ']')) then
    BlinkBracket;

end;

procedure TTextEditor.InsertGraphic(AGraphic: TGraphic; LineIndex: integer);
var
  img: TImage;
begin
  img := TImage.Create(Self);
  try
    img.AutoSize := true;
    img.Stretch := false;
    img.Proportional := true;
    img.Center := true;
    img.Cursor := crArrow;
    img.Picture.Graphic := AGraphic;
    img.PopupMenu := FImagePopup;
    InsertLineControl(img, LineIndex);
  except {read-only mode, for instance}
    img.Free;
    raise;
  end;
end;

procedure TTextEditor.InsertLine(const AText, AClassName: string;
  LineIndex: integer);
begin
  FTextFile.InsertLine(AText, AClassName, LineIndex);
end;

procedure TTextEditor.InsertLine(const AText: string; LineIndex: integer);
begin
  FTextFile.InsertLine(AText, LineIndex);
end;

procedure TTextEditor.InsertLine(LineIndex: integer);
begin
  FTextFile.InsertLine('', LineIndex);
end;

procedure TTextEditor.RemoveAllMargins;
begin
  if FMarginLeft + FMarginRight + FMarginTop + FMarginBottom > 0 then
  begin
    FMarginLeft := 0;
    FMarginRight := 0;
    FMarginTop := 0;
    FMarginBottom := 0;
    FRulerWidth := 0;
    UpdateScrollBars;
    Invalidate;
    DoSetCaretPos;
  end;
end;

procedure TTextEditor.InsertLineControl(AControl: TControl; LineIndex: integer);
begin
  RemoveAllMargins;

  MultiSize := true;
  FTextFile.ControlAware := true;

  SetLength(FLineControls, Length(FLineControls) + 1);
  FLineControls[high(FLineControls)].ID := FNextControlID;
  FLineControls[high(FLineControls)].Control := AControl;

  InsertLine(LINE_CONTROL_PREFIX + IntToStr(FNextControlID), LINE_CONTROL_CLASS, LineIndex);

  inc(FNextControlID);

  AControl.Parent := Self;
  AControl.Visible := true;
end;

procedure TTextEditor.BlinkBracket;
var
  start: TPoint;
  NewBracket: TPoint;
begin
  NewBracket := Point(FTextFile.CaretPos.X - 1, FTextFile.CaretPos.Y);
  start := FTextFile.MatchBracket(NewBracket);
  if start.Y <> -1 then
  begin
    SetBracketHighlight(NewBracket, start);
    FBlinkRemover.Enabled := false;
    FBlinkRemover.Enabled := true;
  end;
end;

procedure TTextEditor.InsertText(const AText: string);
begin
  TypeTimerEnd;
  FTextFile.InsertText(AText);
  AddUndoRecord(SUndoTextInserted, UID_UNKNOWN);
end;

procedure TTextEditor.InsertTextAsBlock(const AText: string);
begin
  TypeTimerEnd;
  FTextFile.InsertTextAsBlock(AText);
  AddUndoRecord(SUndoTextInserted, UID_UNKNOWN);
end;

function TTextEditor.Undo: boolean;
begin
  if FTypeTimer.Enabled then
    TypeTimerTimer(Self);
  FNoScrollToCaret := true;
  try
    result := FTextFile.Undo;
    if result and FTextFile.ControlAware then
      FixRemovedLineControlLines;
  finally
    FNoScrollToCaret := false;
  end;
  if result then
    CenterOnSelection(true);
end;

function TTextEditor.TextContentRect: TRect;
begin
  result := ClientRect;
  inc(result.Left, FMarginLeft);
  inc(result.Top, FMarginTop);
  dec(result.Right, FMarginRight);
  dec(result.Bottom, FMarginBottom);
end;

{ pre-BMCARET }
procedure TTextEditor.UpdateCaret;
begin
  if not Focused then Exit;
  if FListBoxMode then Exit;
  if FMultiSize then
    CreateCaret(Handle, IfThen(FTextFile.EditMode = emReadOnly, 1, 0), IfThen(FOverwrite, FFontSizes[FTextFile.CaretPos.Y].cx, CARET_WIDTH), FFontSizes[FTextFile.CaretPos.Y].cy)
  else
    CreateCaret(Handle, IfThen(FTextFile.EditMode = emReadOnly, 1, 0), IfThen(FOverwrite, FFontSize.cx, CARET_WIDTH), FFontSize.cy);
  ShowCaret(Handle);
  FCaretVisible := true;
  DoSetCaretPos;
end;

procedure TTextEditor.MultiCharSelectDlgResize(Sender: TObject);
begin
  if Sender is TForm then
    with TForm(Sender) do
      SetWindowPos(Flv, HWND_TOP, 0, 0, ClientWidth, ClientHeight,
        SWP_NOOWNERZORDER or SWP_NOZORDER or SWP_SHOWWINDOW);
end;

procedure TTextEditor.MultiCharSelectDlgWndProc(var Message: TMessage);
type
  LPNMLVKEYDOWN = ^NMLVKEYDOWN;
  NMLVKEYDOWN = packed record
    hdr: NMHDR;
    wVKey: WORD;
    flags: UINT;
  end;
var
  index: integer;
  buf: array[0..32] of char;
begin
  FMultiCharSelectDlgDefaultWndProc(Message);
  case Message.Msg of
    WM_NOTIFY:
      if PNMHDR(Message.LParam).hwndFrom = Flv then
        case PNMHDR(Message.LParam).code of
          LVN_KEYDOWN:
            if LPNMLVKEYDOWN(Message.LParam).wVKey = VK_ESCAPE then
              FMultiCharSelectDlgFrm.ModalResult := mrCancel;
          NM_RETURN, NM_DBLCLK:
            begin
              index := ListView_GetNextItem(Flv, -1, LVNI_SELECTED);
              if index <> -1 then
              begin
                ListView_GetItemText(Flv, index, 1, @buf[0], Length(buf));
                if (buf[0] = 'U') and (buf[1]= '+') then
                  FMultiCharSelectDlgFrm.Tag := StrToInt('$' + Copy(PChar(@buf[0]), 3));
              end;
              FMultiCharSelectDlgFrm.ModalResult := mrOk;
            end;
        end;
  end;
end;

procedure TTextEditor.MultiCharSelectDlgActivate(Sender: TObject);
begin
  Windows.SetFocus(Flv);
end;

procedure TTextEditor.DoMultiCharSelect(AChrs: array of char);
var
  frm: TForm;
  lv: HWND;
  c: char;
  tvi: TLVTileViewInfo;
  li: TLVItem;
  cl: TLVColumn;
  index: integer;
  il: TImageList;
  bm: TBitmap;
  i: integer;
  R: TRect;
  S: string;
const
  colinfo: array[0..1] of integer = (1, 2);
begin

  frm := TForm.Create(nil);
  lv := 0;
  try
    frm.Caption := SMultiSelectCaption;
    frm.BorderStyle := bsSizeToolWin;
    frm.Width := 600;
    frm.Height := 400;
    frm.OnActivate := MultiCharSelectDlgActivate;
    frm.OnResize := MultiCharSelectDlgResize;
    FMultiCharSelectDlgFrm := frm;
    FMultiCharSelectDlgDefaultWndProc := frm.WindowProc;
    frm.WindowProc := MultiCharSelectDlgWndProc;
    with ClientToScreen(Point(ClientWidth div 2 - frm.ClientWidth div 2,
      ClientHeight div 2 - frm.ClientHeight div 2)) do
    begin
      frm.Left := X;
      frm.Top := Y;
    end;

    // Image list
    il := TImageList.Create(frm);
    il.Width := 64;
    il.Height := 64;

    bm := TBitmap.Create;
    try
      bm.SetSize(64, 64);
      R := Rect(0, 0, bm.Width, bm.Height);
      bm.Canvas.Font.Assign(Self.Font);
      bm.Canvas.Font.Height := 64;
      bm.Canvas.Font.Color := clBlack;
      for c in AChrs do
      begin
        bm.Canvas.Brush.Color := clWhite;
        bm.Canvas.FillRect(R);
        S := c;
        bm.Canvas.TextRect(R, S, [tfSingleLine, tfCenter, tfVerticalCenter]);
        il.Add(bm, nil);
      end;
    finally
      bm.Free;
    end;

    lv := CreateWindowEx(0, WC_LISTVIEW, nil,
      WS_CHILD or WS_VISIBLE or LVS_REPORT or LVS_NOSORTHEADER or LVS_SINGLESEL or LVS_AUTOARRANGE,
      0, 0, frm.ClientWidth, frm.ClientHeight, frm.Handle, 0, HInstance, nil);

    Flv := lv;

    ListView_SetExtendedListViewStyle(lv, LVS_EX_AUTOSIZECOLUMNS or LVS_EX_FULLROWSELECT);
    ListView_SetImageList(lv, il.Handle, LVSIL_NORMAL);

    // Enter tile mode
    if not FMultiCharReportView then
    begin
      ListView_SetView(lv, LV_VIEW_TILE);

      tvi.cbSize := sizeof(tvi);
      tvi.dwMask := LVTVIM_COLUMNS;
      tvi.cLines := 2;
      ListView_SetTileViewInfo(lv, tvi);
    end;

    // Columns
    cl.mask := LVCF_SUBITEM or LVCF_TEXT or LVCF_ORDER or LVCF_WIDTH;
    cl.iSubItem := 0;
    cl.pszText := PChar(SMultiCharDlgLvColumnTitleDescription);
    cl.iOrder := 0;
    cl.cx := 200;
    ListView_InsertColumn(lv, 0, cl);

    cl.iSubItem := 1;
    cl.pszText := PChar(SMultiCharDlgLvColumnTitleCodepoint);
    cl.iOrder := 1;
    cl.cx := 75;
    ListView_InsertColumn(lv, 1, cl);

    cl.iSubItem := 2;
    cl.pszText := PChar(SMultiCharDlgLvColumnTitleBlock);
    cl.iOrder := 2;
    cl.cx := 200;
    ListView_InsertColumn(lv, 2, cl);

    // Items
    li.mask := LVIF_TEXT or LVIF_IMAGE or LVIF_STATE or LVIF_COLUMNS;
    li.stateMask := 0;
    li.iSubItem := 0;
    li.state := 0;
    li.iImage := 0;
    li.cColumns := 2;
    li.puColumns := PUINT(@colinfo[0]);

    ListView_SetItemCount(lv, Length(AChrs));
    i := 0;
    for c in AChrs do
    begin
      li.iImage := i;
      inc(i);
      li.pszText := PChar(UCD.GetChrName(c));
      index := ListView_InsertItem(lv, li);
      ListView_SetItemText(lv, index, 1, PChar(UCD.GetChrCodepointStr(c)));
      ListView_SetItemText(lv, index, 2, PChar(UCD.GetChrBlock(c)));
    end;

    frm.Tag := 0;
    if frm.ShowModal = mrOk then
      if frm.Tag <> 0 then
      begin
        Backspace;
        InsertChar(Chr(frm.Tag));
      end;

  finally
    if lv <> 0 then DestroyWindow(lv);
    frm.Free;
  end;

end;

{ effect-BMCARET }
procedure TTextEditor.DoSetCaretPos;
var
  pt: TPoint;
begin

  if FVisualUpdateLock > 0 then Exit;

  if FListBoxMode or not Focused then Exit;

  if FMultiSize then
    pt := Point(FMarginLeft +
      FTextFile.CaretPos.X * FFontSizes[FTextFile.CaretPos.Y].cx - FScrollPos.X,
      FMarginTop + FAccumLineHeights[FTextFile.CaretPos.Y] - FScrollPos.Y)
  else
    pt := Point(FMarginLeft + FTextFile.CaretPos.X * FFontSize.cx - FScrollPos.X,
      FMarginTop + FTextFile.CaretPos.Y * FFontSize.cy - FScrollPos.Y);

  if PtInRect(TextContentRect, pt) then
  begin
    BinaryShowCaret;
    Windows.SetCaretPos(pt.X, pt.Y)
  end
  else
    BinaryHideCaret;

end;

procedure TTextEditor.BinaryHideCaret;
begin
  if FCaretVisible then
  begin
    HideCaret(Handle);
    FCaretVisible := false;
  end;
end;

procedure TTextEditor.BinaryShowCaret;
begin
  if not FCaretVisible then
  begin
    ShowCaret(Handle);
    FCaretVisible := true;
  end;
end;

function TTextEditor.GetLineTop(LineIndex: integer): integer;
begin
  if FMultiSize then
    result := FMarginTop + FAccumLineHeights[LineIndex] - FScrollPos.Y
  else
    result := FMarginTop + FFontSize.cy * LineIndex - FScrollPos.Y;
end;

function TTextEditor.GetListBoxItemIndex: integer;
begin
  result := CaretPos.Y;
end;

function TTextEditor.GetLastMultiCaret: TPoint;
begin
  if Length(FCarets) > 0 then
    result := FCarets[high(FCarets)]
  else
    result := CaretPos;
end;

function TTextEditor.GetLine(Index: integer): string;
begin
  result := FTextFile.Lines[Index];
end;

function TTextEditor.GetLineBookmark(ALineIndex: integer): integer;
var
  i: Integer;
begin
  for i := 0 to FTextFile.BookmarkCount - 1 do
    if FTextFile.Bookmarks[i].Y = ALineIndex then
      Exit(i);
  result := -1;
end;

function TTextEditor.GetLineBottom(LineIndex: integer): integer;
begin
  if FMultiSize then
    result := FMarginTop + FAccumLineHeights[LineIndex] + FFontSizes[LineIndex].cy - FScrollPos.Y
  else
    result := FMarginTop + FFontSize.cy * (LineIndex + 1) - FScrollPos.Y;
end;

function TTextEditor.GetLineBottomVirtual(LineIndex: integer): integer;
begin
  if FMultiSize then
    result := FMarginTop + FAccumLineHeights[LineIndex] + FFontSizes[LineIndex].cy
  else
    result := FMarginTop + FFontSize.cy * (LineIndex + 1);
end;

function TTextEditor.GetCharLeft(LineIndex, ColIndex: integer): integer;
begin
  if FMultiSize then
    result := FMarginLeft + FFontSizes[LineIndex].cx * ColIndex - FScrollPos.X
  else
    result := FMarginLeft + FFontSize.cx * ColIndex - FScrollPos.X;
end;

function TTextEditor.GetCharRight(LineIndex, ColIndex: integer): integer;
begin
  if FMultiSize then
    result := FMarginLeft + FFontSizes[LineIndex].cx * (ColIndex + 1) - FScrollPos.X
  else
    result := FMarginLeft + FFontSize.cx * (ColIndex + 1) - FScrollPos.X;
end;

procedure TTextEditor.VisualUpdate(ChangeType: TChangeType; Data1, Data2, Data3,
  Data4: integer);
var
  i: Integer;
begin

  if (FVisualUpdateLock > 0) or not (FValidPaintState and Visible) then Exit;
  begin
    case ChangeType of
      ctFile:
        Invalidate;
      ctLineRange:
        InvalidateRect(Handle, Rect(0, GetLineTop(Data1), ClientWidth, GetLineBottom(Data2)), false);
      ctBlock:
        if FMultiSize then
          for i := max(FirstVisibleLine, Data1) to min(LastVisibleLine, Data2) do
            InvalidateRect(Handle, Rect(GetCharLeft(i, Data3), GetLineTop(i), GetCharRight(i, Data4), GetLineBottom(i)), false)
        else
          InvalidateRect(Handle, Rect(GetCharLeft(Data1, Data3), GetLineTop(Data1), GetCharRight(Data1, Data4), GetLineBottom(Data2)), false);
      ctLine:
        InvalidateRect(Handle, Rect(0, GetLineTop(Data1), ClientWidth, GetLineBottom(Data1)), false);
      ctLineFrom:
        InvalidateRect(Handle, Rect(GetCharLeft(Data1, Data2), GetLineTop(Data1), ClientWidth, GetLineBottom(Data1)), false);
      ctChar:
        InvalidateRect(Handle, Rect(GetCharLeft(Data1, Data2), GetLineTop(Data1), GetCharRight(Data1, Data2), GetLineBottom(Data1)), false);
      ctTwoChars:
        begin
          InvalidateRect(Handle, Rect(GetCharLeft(Data1, Data2), GetLineTop(Data1), GetCharRight(Data1, Data2), GetLineBottom(Data1)), false);
          InvalidateRect(Handle, Rect(GetCharLeft(Data3, Data4), GetLineTop(Data3), GetCharRight(Data3, Data4), GetLineBottom(Data3)), false);
        end;
      ctPostFile:
        InvalidateRect(Handle, Rect(0, GetLineBottom(FTextFile.LineCount - 1), ClientWidth, ClientHeight), false);
    end;
    Update;
  end

end;

function TTextEditor.EditorCommand(Command, Param1, Param2, Param3,
  Param4: integer): integer;
var
  S: string;
  i: integer;
begin
  result := 0;

  // Param in Command?
  if (Command and $FFFF0000) <> 0 then
  begin
    Param1 := Command shr 16;
    Command := Command and $0000FFFF;
  end;

  case Command of
    EDITOR_COMMAND_RIGHT:
      FTextFile.Right(Param1 <> 0, Param2 <> 0, Param3 <> 0);
    EDITOR_COMMAND_LEFT:
      FTextFile.Left(Param1 <> 0, Param2 <> 0, Param3 <> 0);
    EDITOR_COMMAND_DOWN:
      FTextFile.Down(Param1 <> 0, Param2 <> 0);
    EDITOR_COMMAND_UP:
      FTextFile.Up(Param1 <> 0, Param2 <> 0);
    EDITOR_COMMAND_HOME:
      FTextFile.Home(Param1 <> 0, Param2 <> 0);
    EDITOR_COMMAND_END:
      FTextFile.KEnd(Param1 <> 0, Param2 <> 0);
    EDITOR_COMMAND_PAGE_UP:
      PageUp(Param1 <> 0);
    EDITOR_COMMAND_PAGE_DOWN:
      PageDown(Param1 <> 0);
    EDITOR_COMMAND_BACKSPACE:
      Backspace(Param1 <> 0);
    EDITOR_COMMAND_DELETE:
      Delete(Param1 <> 0);
    EDITOR_COMMAND_CLEAR_SELECTION:
      ClearSelection;
    EDITOR_COMMAND_SELECT_ALL:
      SelectAll;
    EDITOR_COMMAND_SELECT_NONE:
      SelectNone;
    EDITOR_COMMAND_SELECT_ALL_NONE:
      SelectAllNone;
    EDITOR_COMMAND_SELECT_WORD:
      result := B(SelectWord);
    EDITOR_COMMAND_SELECT_LINE:
      SelectLine;
    EDITOR_COMMAND_CLEAR_LINE:
      ClearLine(Param1);
    EDITOR_COMMAND_CUT:
      CutToClipboard;
    EDITOR_COMMAND_COPY:
      CopyToClipboard;
    EDITOR_COMMAND_PASTE:
      PasteFromClipboard;
    EDITOR_COMMAND_UNDO:
      result := B(Undo);
    EDITOR_COMMAND_REDO:
      result := B(Redo);
    EDITOR_COMMAND_CLEAR_UNDO_BUFFER:
      ClearUndoHistory;
    EDITOR_COMMAND_GOTO_SOF:
      FTextFile.GotoSOF(Param1 <> 0);
    EDITOR_COMMAND_GOTO_EOF:
      FTextFile.GotoEOF(Param1 <> 0);
    EDITOR_COMMAND_RETURN:
      Return;
    EDITOR_COMMAND_CHAR:
      InsertChar(Char(Param1), Param2 <> 0);
    EDITOR_COMMAND_GET_AT_SOF:
      result := B(FTextFile.AtSOF);
    EDITOR_COMMAND_GET_AT_EOL:
      result := B(FTextFile.AtEOL);
    EDITOR_COMMAND_GET_BEYOND_EOL:
      result := B(FTextFile.AtOrBeyondEOL);
    EDITOR_COMMAND_GET_AT_EOF:
      result := B(FTextFile.AtEOF);
    EDITOR_COMMAND_GET_AT_LAST_LINE:
      result := B(FTextFile.AtLastLine);
    EDITOR_COMMAND_GET_HAS_SELECTION:
      result := B(FTextFile.HasSelection);
    EDITOR_COMMAND_GET_LINE_NUMBER_0:
      result := FTextFile.CaretPos.Y;
    EDITOR_COMMAND_GET_COL_NUMBER_0:
      result := FTextFile.CaretPos.X;
    EDITOR_COMMAND_GET_CHR_INDEX:
      result := SelStart;
    EDITOR_COMMAND_GOTO_POINT:
      FTextFile.CaretPos.SetPoint(Param1, Param2, Param3 <> 0);
    EDITOR_COMMAND_GOTO_INDEX:
      SelStart := Param1;
    EDITOR_COMMAND_GET_SEL_LENGTH:
      result := SelLength;
    EDITOR_COMMAND_SET_SEL_LENGTH:
      SelLength := Param1;
    EDITOR_COMMAND_GET_EDIT_MODE:
      result := ord(FTextFile.EditMode);
    EDITOR_COMMAND_SET_EDIT_MODE:
      SetEditMode(TEditMode(Param1));
    EDITOR_COMMAND_GET_SELECTION_MODE:
      result := ord(GetSelType);
    EDITOR_COMMAND_SET_SELECTION_MODE:
      SetSelType(TSelectionType(Param1));
    EDITOR_COMMAND_GET_OVERWRITE:
      result := B(FOverwrite);
    EDITOR_COMMAND_SET_OVERWRITE:
      SetOverwrite(Param1 <> 0);
    EDITOR_COMMAND_GET_AUTO_REPLACE:
      result := B(FAutoReplace);
    EDITOR_COMMAND_SET_AUTO_REPLACE:
      AutoReplace := Param1 <> 0;
    EDITOR_COMMAND_GET_CHAR:
      result := Integer(GetCharAtCaret);
    EDITOR_COMMAND_ADD_INDENT:
      AddIndent;
    EDITOR_COMMAND_REMOVE_INDENT:
      RemoveIndent;
    EDITOR_COMMAND_TRIM_INDENT:
      RemoveAllIndent;
    EDITOR_COMMAND_SWAP_UP:
      SwapLinesAbove;
    EDITOR_COMMAND_SWAP_DOWN:
      SwapLinesBelow;
    EDITOR_COMMAND_GET_AUTO_INDENT:
      result := B(FAutoIndent);
    EDITOR_COMMAND_SET_AUTO_INDENT:
      SetAutoIndent(Param1 <> 0);
    EDITOR_COMMAND_GET_CARET_BEYOND_EOL:
      result := B(FTextFile.CaretAfterEOL);
    EDITOR_COMMAND_SET_CARET_BEYOND_EOL:
      SetCaretAfterEOL(Param1 <> 0);
    EDITOR_COMMAND_GET_NUM_CHARACTERS:
      result := FTextFile.NumCharacters;
    EDITOR_COMMAND_GET_TEXT_SIZE:
      result := FTextFile.VirtualTextLength;
    EDITOR_COMMAND_GET_NUM_LINES:
      result := FTextFile.LineCount;
    EDITOR_COMMAND_GET_MAX_WIDTH:
      result := FTextFile.MaxLineWidth;
    EDITOR_COMMAND_SCROLL_TO_CARET:
      result := B(ScrollToCaret);
    EDITOR_COMMAND_CENTER_ON_SELECTION:
      CenterOnSelection(Param1 <> 0);
    EDITOR_COMMAND_REPLACE_TOKEN:
      DoAutoReplace;
    EDITOR_COMMAND_REPLACE_CODEPOINT:
      FTextFile.ReplaceCodepoint;
    EDITOR_COMMAND_UPDATE_SCROLLBARS:
      UpdateScrollBars;
    EDITOR_COMMAND_UPDATE_CARET:
      UpdateCaret;
    EDITOR_COMMAND_UPDATE_CURSOR:
      ChangeCursor;
    EDITOR_COMMAND_REDRAW:
      Invalidate;
    EDITOR_COMMAND_REDRAW_LINE:
      VisualUpdate(ctLine, Param1, 0, 0, 0);
    EDITOR_COMMAND_REDRAW_LINE_RANGE:
      VisualUpdate(ctLineRange, Param1, Param2, 0, 0);
    EDITOR_COMMAND_REDRAW_BLOCK:
      VisualUpdate(ctBlock, Param1, Param2, Param3, Param4);
    EDITOR_COMMAND_GET_MODIFIED:
      result := B(FTextFile.FileModified);
    EDITOR_COMMAND_SET_MODIFIED:
      FTextFile.FileModified := Param1 <> 0;
    EDITOR_COMMAND_NEW:
      NewFile;
    EDITOR_COMMAND_CLEAR:
      FTextFile.Clear;
    EDITOR_COMMAND_OPEN:
      LoadFromFile(PChar(Param1), TEncoding.UTF8);
    EDITOR_COMMAND_SAVE:
      SaveToFile(PChar(Param1));
    EDITOR_COMMAND_GET_HIDDEN:
      result := B(FShowHiddenCharacters);
    EDITOR_COMMAND_SET_HIDDEN:
      SetShowHiddenCharacters(Param1 <> 0);
    EDITOR_COMMAND_SET_SELECTION:
      begin
        FTextFile.CaretPos.SetPoint(Param1, Param2, false);
        FTextFile.CaretPos.SetPoint(Param3, Param4, true);
      end;
    EDITOR_COMMAND_GET_MATCH_BRACKETS:
      result := B(FMatchBrackets);
    EDITOR_COMMAND_SET_MATCH_BRACKETS:
      SetMatchBrackets(Param1 <> 0);
    EDITOR_COMMAND_GET_BRACKET_HIGHLIGHT:
      result := B(FBracketHighlight);
    EDITOR_COMMAND_GET_SCROLL_POS_X:
      result := FScrollPos.X;
    EDITOR_COMMAND_GET_SCROLL_POS_Y:
      result := FScrollPos.Y;
    EDITOR_COMMAND_SET_SCROLL_POS:
      SetScrollPosXY(Param1, Param2);
    EDITOR_COMMAND_REDRAW_CHAR:
      VisualUpdate(ctChar, Param1, Param2, 0, 0);
    EDITOR_COMMAND_REDRAW_CHARS:
      VisualUpdate(ctChar, Param1, Param2, Param3, Param4);
    EDITOR_COMMAND_GET_INDENT:
      result := FIndentSize;
    EDITOR_COMMAND_SET_INDENT:
      SetIndentSize(Param1);
    EDITOR_COMMAND_GET_TAB_LENGTH:
      result := FTabLength;
    EDITOR_COMMAND_SET_TAB_LENGTH:
      FTabLength := Param1;
    EDITOR_COMMAND_GET_SINGLE_LINE:
      result := B(SingleLine);
    EDITOR_COMMAND_SET_SINGLE_LINE:
      SetSingleLine(Param1 <> 0);
    EDITOR_COMMAND_GET_LABEL_MODE:
      result := B(FLabelStyle);
    EDITOR_COMMAND_SET_LABEL_MODE:
      SetLabelStyle(Param1 <> 0);
    EDITOR_COMMAND_GET_ELLIPSIS_MODE:
      result := B(FLabelEllipsis);
    EDITOR_COMMAND_SET_ELLIPSIS_MODE:
      SetLabelEllipsis(Param1 <> 0);
    EDITOR_COMMAND_GET_INPUT_TRANSFORM:
      result := ord(FInputTransform);
    EDITOR_COMMAND_SET_INPUT_TRANSFORM:
      FInputTransform := TInputTransform(Param1);
    EDITOR_COMMAND_GET_NUMBERS_ONLY:
      result := B(FNumbersOnly);
    EDITOR_COMMAND_SET_NUMBERS_ONLY:
      FNumbersOnly := Param1 <> 0;
    EDITOR_COMMAND_GET_PASSWORD_CHAR:
      result := ord(FPasswordChar);
    EDITOR_COMMAND_SET_PASSWORD_CHAR:
      SetPasswordChar(Chr(Param1));
    EDITOR_COMMAND_GET_UNICODE_FALLBACK:
      result := B(FUnicodeFallback);
    EDITOR_COMMAND_SET_UNICODE_FALLBACK:
      SetUnicodeFallback(Param1 <> 0);
    EDITOR_COMMAND_ESCAPE:
      Escape(Param1 <> 0);
    EDITOR_COMMAND_USE_DEFAULT_FALLBACK_FONTS:
      UseDefaultFallbackFonts;
    EDITOR_COMMAND_SHOW_BALLOON:
      result := B(ShowBalloon(PChar(Param1), PChar(Param2), TBalloonIconKind(Param3),
        TBalloonPersistence(Param4), CaretPos));
    EDITOR_COMMAND_HIDE_BALLOON:
      HideBalloon;
    EDITOR_COMMAND_SHOW_BALLOON_POS:
      result := B(ShowBalloon(PChar(Param1), PChar(Param2), TBalloonIconKind(Byte(Param3)),
        TBalloonPersistence(Byte(Param3 shr 8)), FTextFile.GetPointOfIndex(Param4)));
    EDITOR_COMMAND_IS_BALLOON_VISIBLE:
      result := B(BalloonVisible);
    EDITOR_COMMAND_ADJUST_HEIGHT:
      begin
        result := B(SingleLine);
        if result <> 0 then
          ClientHeight := FFontSize.cy + AUTO_HEIGHT_PADDING;
      end;
    EDITOR_COMMAND_GET_UNDO_LENGTH:
      result := FTextFile.HistoryManager.Count;
    EDITOR_COMMAND_GET_UNDO_SIZE:
      result := FTextFile.HistoryManager.Size;
    EDITOR_COMMAND_GET_UNDO_MAX_SIZE:
      result := FTextFile.HistoryManager.MaxSize;
    EDITOR_COMMAND_SET_UNDO_MAX_SIZE:
      FTextFile.HistoryManager.MaxSize := Param1;
    EDITOR_COMMAND_GET_UNDO_FIRST_INDEX:
      result := FTextFile.HistoryManager.FirstItem;
    EDITOR_COMMAND_GET_UNDO_LAST_INDEX:
      result := FTextFile.HistoryManager.LastItem;
    EDITOR_COMMAND_GET_UNDO_POSITION:
      result := FTextFile.HistoryManager.HistoryIndex;
    EDITOR_COMMAND_WINDOWS_MESSAGE:
      result := Perform(Param1, Param2, Param3);
    EDITOR_COMMAND_COPY_ALL:
      CopyAll;
    EDITOR_COMMAND_FIND:
      result := Find(MakeFindQuery(PChar(Param1), Param2 <> 0, Param3 <> 0,
        Param4 <> 0));
    EDITOR_COMMAND_GET_FIND_COUNT:
      result := FTextFile.FindCount;
    EDITOR_COMMAND_FIND_NEXT:
      result := FindNext;
    EDITOR_COMMAND_FIND_PREV:
      result := FindPrevious;
    EDITOR_COMMAND_FIND_FROM_TOP:
      result := FindFromTop;
    EDITOR_COMMAND_GET_START_OVER:
      result := B(FStartOver);
    EDITOR_COMMAND_SET_START_OVER:
      FStartOver := Param1 <> 0;
    EDITOR_COMMAND_REPLACE_ALL:
      result := ReplaceAll(MakeFindQuery(PChar(Param1), (Param3 and 1) <> 0,
        (Param3 and 2) <> 0, (Param3 and 4) <> 0), PChar(Param2));
    EDITOR_COMMAND_ADD_UNDO_RECORD:
      AddUndoRecord(PChar(Param1), UNDONAMEID(Param2));
    EDITOR_COMMAND_POSTTYPE:
      PostType;
    EDITOR_COMMAND_TYPE_TIMER_EMD:
      TypeTimerEnd;
    EDITOR_COMMAND_TYPE_TIMER_DISABLE:
      FTypeTimer.Enabled := false;
    EDITOR_COMMAND_TYPE_TIMER_DISCONNECT:
      FTypeTimer.OnTimer := nil;
    EDITOR_COMMAND_TYPE_TIMER_CONNECT:
      FTypeTimer.OnTimer := TypeTimerTimer;
    EDITOR_COMMAND_GET_ENABLED:
      result := B(Enabled);
    EDITOR_COMMAND_SET_ENABLED:
      Enabled := Param1 <> 0;
    EDITOR_COMMAND_IS_FOCUSED:
      result := B(Focused);
    EDITOR_COMMAND_TRY_FOCUS:
      begin
        result := B(CanFocus);
        if result <> 0 then
          SetFocus;
      end;
    EDITOR_COMMAND_GET_FIRST_VISIBLE_LINE:
      result := FirstVisibleLine(true);
    EDITOR_COMMAND_GET_LAST_VISIBLE_LINE:
      result := LastVisibleLine(true);
    EDITOR_COMMAND_RECOMPUTE_HOR_EXTENT:
      begin
        RecomputeHorizontalExtent;
        result := FCachedHorizontalExtent;
      end;
    EDITOR_COMMAND_ACTIVATE_CONTROL:
      result := ActivateControl;
    EDITOR_COMMAND_REMOVE_LINE_CONTROL:
      result := B(FTextFile.DeleteControlAtLine(Param1));
    EDITOR_COMMAND_ADD_LINE_CONTROL:
      AddLineControl(TControl(Param1));
    EDITOR_COMMAND_ADD_GRAPHICS:
      AddGraphic(TGraphic(Param1));
    EDITOR_COMMAND_INSERT_LINE_CONTROL:
      InsertLineControl(TControl(Param1), Param2);
    EDITOR_COMMAND_INSERT_GRAPHICS:
      InsertGraphic(TGraphic(Param1), Param2);
    EDITOR_COMMAND_TRIM_RIGHT:
      TrimRight;
    EDITOR_COMMAND_BOOKMARK_SET:
      AddBookmark(Param1);
    EDITOR_COMMAND_BOOKMARK_GO:
      GotoBookmark(Param1);
    EDITOR_COMMAND_BOOKMARK_CLEAR:
      AddBookmark(Param1, EMPTY_BOOKMARK);
    EDITOR_COMMAND_BOOKMARK_CLEAR_ALL:
      ClearBookmarks;
    EDITOR_COMMAND_CLASS_USE:
      SetClass(CaretPos.Y, Classes[Param1].Name);
    EDITOR_COMMAND_CLASS_REMOVE:
      SetClass(CaretPos.Y, '');
    EDITOR_COMMAND_SET_FP:
      SetFormattingProcessor(TFormattingProcessor(Param1));
    EDITOR_COMMAND_EXPORT_HTML:
      ExportToHTML(PChar(Param1));
    EDITOR_COMMAND_OPEN_URL_AT_CARET:
      OpenURLAtCaret;
    EDITOR_COMMAND_SELECT_LINE_INDEX:
      SelectLine(Param1);
    EDITOR_COMMAND_SELECT_LINE_RANGE:
      SelectLines(Param1, Param2);
    EDITOR_COMMAND_DISABLE_SCROLL_TO_CARET:
      FNoScrollToCaret := true;
    EDITOR_COMMAND_ENABLE_SCROLL_TO_CARET:
      FNoScrollToCaret := false;
    EDITOR_COMMAND_CREATE_SELECTION:
      FTextFile.CaretPos.CreateSelection(Point(Param1, Param2),
        Point(Param3, Param4), stLineBased);
    EDITOR_COMMAND_CREATE_BLOCK_SELECTION:
      FTextFile.CaretPos.CreateSelection(Point(Param1, Param2),
        Point(Param3, Param4), stBlock);
    EDITOR_COMMAND_GET_LINE_HIGHLIGHT:
      result := B(FLineHighlight);
    EDITOR_COMMAND_SET_LINE_HIGHLIGHT:
      SetLineHighlight(Param1 <> 0);
    EDITOR_COMMAND_REDRAW_RULER:
      UpdateRuler;
    EDITOR_COMMAND_REDRAW_RULER_LINE:
      UpdateRulerLine(Param1);
    EDITOR_COMMAND_PRINT:
      if Param1 <> 0 then
        Print(PChar(Param1), Param2, Param3)
      else
        Print(Param2, Param3);
    EDITOR_COMMAND_PRINT_SELECTION:
      if Param1 <> 0 then
        PrintSelection(PChar(Param1))
      else
        PrintSelection;
    EDITOR_COMMAND_SET_PRINT_MARGINS:
      begin
        FPrintSettings.HorizontalMargin := Param1;
        FPrintSettings.VerticalMargin := Param2;
      end;
    EDITOR_COMMAND_SET_PRINT_WW_OPTIONS:
      begin
        FPrintSettings.WordWrap := Param1 <> 0;
        FPrintSettings.NiceWordWrap := Param2 <> 0;
        if Param3 = 0 then
          FPrintSettings.ShowWordWrapIcon := false
        else
        begin
          FPrintSettings.ShowWordWrapIcon := true;
          FPrintSettings.WordWrapIcon := Char(Param3);
          FPrintSettings.WordWrapIconColor := TColor(Param4);
        end;
      end;
    EDITOR_COMMAND_PRINT_DIALOG:
      begin
        with TPrintDialog.Create(nil) do
          try
            if FTextFile.HasSelection then
              Options := [poSelection, poWarning]
            else
              Options := [poWarning];
            if Execute then
              if PrintRange = prSelection then
                PrintSelection(SDefaultPrintJobTitle)
              else
                Print(SDefaultPrintJobTitle);
          finally
            Free;
          end;
      end;
    EDITOR_COMMAND_GET_PRINT_VMARGIN:
      result := FPrintSettings.VerticalMargin;
    EDITOR_COMMAND_GET_PRINT_HMARGIN:
      result := FPrintSettings.HorizontalMargin;
    EDITOR_COMMAND_GET_PRINT_WW_OPTIONS:
      result := B(FPrintSettings.WordWrap) or
        (B(FPrintSettings.NiceWordWrap) shl 16);
    EDITOR_COMMAND_GET_PRINT_WW_CHAR:
      if FPrintSettings.ShowWordWrapIcon then
        result := ord(FPrintSettings.WordWrapIcon)
      else
        result := 0;
    EDITOR_COMMAND_GET_PRINT_WW_COLOR:
      result := FPrintSettings.WordWrapIconColor;
    EDITOR_COMMAND_WORDWRAP:
      WordWrap(Param1, Param2 <> 0, Char(Param3));
    EDITOR_COMMAND_UPPER_CASE:
      ChrTransformText(ChrUpperCase, STransformNameUpperCase);
    EDITOR_COMMAND_LOWER_CASE:
      ChrTransformText(ChrLowerCase, STransformNameLowerCase);
    EDITOR_COMMAND_INVERT_CASE:
      ChrTransformText(ChrInvertCase, STransformNameInvertCase);
    EDITOR_COMMAND_SEL_UPPER_CASE:
      ChrTransformSelection(ChrUpperCase, STransformNameUpperCase);
    EDITOR_COMMAND_SEL_LOWER_CASE:
      ChrTransformSelection(ChrLowerCase, STransformNameLowerCase);
    EDITOR_COMMAND_SEL_INVERT_CASE:
      ChrTransformSelection(ChrInvertCase, STransformNameInvertCase);
    EDITOR_COMMAND_CAMEL_CASE:
      TransformText(TxtCamelCase, STransformNameCamelCase);
    EDITOR_COMMAND_SENTENCE_CASE:
      TransformText(TxtSentenceCase, STransformNameSentenceCase);
    EDITOR_COMMAND_SEL_CAMEL_CASE:
      TransformSelection(TxtCamelCase, STransformNameCamelCase);
    EDITOR_COMMAND_SEL_SENTENCE_CASE:
      TransformSelection(TxtSentenceCase, STransformNameSentenceCase);
    EDITOR_COMMAND_SEL_REVERSE:
      TransformSelection(ReverseText, STransformNameReverse);
    EDITOR_COMMAND_ROT13:
      ChrTransformText(ChrRot13, STransformNameRot13);
    EDITOR_COMMAND_SEL_ROT13:
      ChrTransformSelection(ChrRot13, STransformNameRot13);
    EDITOR_COMMAND_CAESAR:
      if (Param1 <> 0) or TMultiInputBox.NumInputBox(GetParentForm(Self), SCaesarNTitle, SCaesarNText, Param1, ord('A') - ord('Z') - 1, ord('Z') - ord('A') + 1) then
        ChrTransformText(ChrCaesar(Param1), Format(STransformNameCaesarN, [Param1]));
    EDITOR_COMMAND_SEL_CAESAR:
      if (Param1 <> 0) or TMultiInputBox.NumInputBox(GetParentForm(Self), SCaesarNTitle, SCaesarNText, Param1, ord('A') - ord('Z') - 1, ord('Z') - ord('A') + 1) then
        ChrTransformSelection(ChrCaesar(Param1), Format(STransformNameCaesarN, [Param1]));
    EDITOR_COMMAND_VIGENERE:
      if Param2 <> 0 then
        TransformText(TxtVigenère(PChar(Param2), Param1 <> 0), STransformNameVigenere)
      else
        if TMultiInputBox.TextInputBox(GetParentForm(Self), SVigenereTitle, SVigenereText, S, ecUpperCase, false, [aoCapitalAZ]) then
          TransformText(TxtVigenère(S, Param1 <> 0), STransformNameVigenere);
    EDITOR_COMMAND_SEL_VIGENERE:
      if Param2 <> 0 then
        TransformSelection(TxtVigenère(PChar(Param2), Param1 <> 0), STransformNameVigenere)
      else
        if TMultiInputBox.TextInputBox(GetParentForm(Self), SVigenereTitle, SVigenereText, S, ecUpperCase, false, [aoCapitalAZ]) then
          TransformSelection(TxtVigenère(S, Param1 <> 0), STransformNameVigenere);
    EDITOR_COMMAND_UPDATE_SCROLL_MODE:
      UpdateScrollMode;
    EDITOR_COMMAND_GET_SCROLL_MODE:
      result := B(FScrollMode);
    EDITOR_COMMAND_SORT:
      result := B(Sort(Param1, Param2));
    EDITOR_COMMAND_SORT_ALL:
      result := B(Sort);
    EDITOR_COMMAND_SORT_SEL:
      result := B(SortSelection);
    EDITOR_COMMAND_SET_LINE_COMPARER:
      SetLineComparer(TLineComparer(Param1));
    EDITOR_COMMAND_GET_LINE_COMPARER:
      result := integer(@LineComparer);
    EDITOR_COMMAND_SET_SORT_REVERSE:
      SortReverseOrder := Param1 <> 0;
    EDITOR_COMMAND_GET_SORT_REVERSE:
      result := B(SortReverseOrder);
    EDITOR_COMMAND_MAKE_LINES_UNIQUE:
      result := B(MakeLinesUnique);
    EDITOR_COMMAND_CLI_NEW_PROMPT:
      CliNewPrompt;
    EDITOR_COMMAND_CLI_WRITELN:
      CliWriteLn(PChar(Param1), PChar(Param2));
    EDITOR_COMMAND_ABORT_SCRIPT:
      FAbortScript := true;
    EDITOR_COMMAND_WRITE_INT:
      SelText := IntToStr(Param1);
    EDITOR_COMMAND_ABORT_SCRIPT_IF_EOL:
      if FTextFile.AtOrBeyondEOL then
        FAbortScript := true;
    EDITOR_COMMAND_ABORT_SCRIPT_IF_LL:
      if FTextFile.AtLastLine then
        FAbortScript := true;
    EDITOR_COMMAND_ABORT_SCRIPT_IF_EOF:
      if FTextFile.AtOrBeyondEOF then
        FAbortScript := true;
    EDITOR_COMMAND_ABORT_SCRIPT_IF_SOF:
      if FTextFile.AtSOF then
        FAbortScript := true;
    EDITOR_COMMAND_SET_SCRIPT_COUNTER:
      FScriptCounter := Param1;
    EDITOR_COMMAND_GET_SCRIPT_COUNTER:
      result := FScriptCounter;
    EDITOR_COMMAND_GET_LINE_NUMBER_1:
      result := FTextFile.CaretPos.Y + 1;
    EDITOR_COMMAND_GET_COL_NUMBER_1:
      result := FTextFile.CaretPos.X + 1;
    EDITOR_COMMAND_WRITE_DATE:
      SelText := DateToStr(Date);
    EDITOR_COMMAND_WRITE_TIME:
      SelText := TimeToStr(Time);
    EDITOR_COMMAND_WRITE_DATETIME:
      SelText := DateTimeToStr(Now);
    EDITOR_COMMAND_GET_TICKCOUNT:
      result := GetTickCount;
    EDITOR_COMMAND_GET_RANDOM_INTEGER:
      if Param2 > Param1 then
        result := RandomRange(Param1, Param2)
      else
        result := RandomRange(0, MaxInt);
    EDITOR_COMMAND_FIX_REMOVED_LINE_CONTROLS:
      FixRemovedLineControlLines;
    EDITOR_COMMAND_CLI_HISTORY_UP:
      result := B(CliHistoryUp);
    EDITOR_COMMAND_CLI_HISTORY_DOWN:
      result := B(CliHistoryDown);
    EDITOR_COMMAND_CLI_HISTORY_CLEAR:
      CliClearHistory;
    EDITOR_COMMAND_CLI_HISTORY_ADD:
      CliAddHistory(PChar(Param1));
    EDITOR_COMMAND_CLI_GET_HISTORY_LENGTH:
      result := CliHistoryCount;
    EDITOR_COMMAND_CLI_GET_HISTORY_INDEX:
      result := CliHistoryIndex;
    EDITOR_COMMAND_CLI_HISTORY_RECALL:
      result := B(CliHistoryRecall(Param1));
    EDITOR_COMMAND_BEGIN_ADD_LINES:
      BeginAddLine;
    EDITOR_COMMAND_END_ADD_LINES:
      EndAddLine;
    EDITOR_COMMAND_GET_LISTBOX_MODE:
      result := B(ListBoxMode);
    EDITOR_COMMAND_SET_LISTBOX_MODE:
      ListBoxMode := Param1 <> 0;
    EDITOR_COMMAND_WRITE_STRING:
      SelText := PChar(Param1);
    EDITOR_COMMAND_WRITE_INPUT_DIALOG:
      begin
        S := PChar(Param3);
        if TMultiInputBox.TextInputBox(GetParentForm(Self), PChar(Param1), PChar(Param2), S) then
          SelText := S;
      end;
    EDITOR_COMMAND_SET_AS_HYPHEN_ASTERISK_TOGGLE:
      FASHyphenAsteriskToggle := Param1 <> 0;
    EDITOR_COMMAND_SET_MULTI_CHAR_SELECT:
      MultiCharSelect := Param1 <> 0;
    EDITOR_COMMAND_GET_MULTI_CHAR_SELECT:
      result := B(FMultiCharSelect);
    EDITOR_COMMAND_SET_MULTI_CHAR_REPORT_VIEW:
      MultiCharReportView := Param1 <> 0;
    EDITOR_COMMAND_GET_MULTI_CHAR_REPORT_VIEW:
      result := B(FMultiCharReportView);
    EDITOR_COMMAND_SET_NO_VERIFY_FONT:
      FNoVerifyFont := Param1 <> 0;
    EDITOR_COMMAND_SET_DOUBLE_BUFFERING:
      DoubleBuffered := Param1 <> 0;
    EDITOR_COMMAND_REPLACE_ALL_IN_SELECTION:
      result := ReplaceAll(MakeFindQuery(PChar(Param1), (Param3 and 1) <> 0,
        (Param3 and 2) <> 0, (Param3 and 4) <> 0), PChar(Param2), true);
    EDITOR_COMMAND_SET_BITMAP_EFFECT:
      if InRange(Param1, ord(low(TBitmapEffect)), ord(high(TBitmapEffect))) then
      begin
        result := 1;
        BitmapEffect := TBitmapEffect(Param1);
      end
      else
        result := 0;
    EDITOR_COMMAND_GET_BITMAP_EFFECT:
      result := ord(FBitmapEffect);
    EDITOR_COMMAND_SET_DISABLED_EFFECT:
      if InRange(Param1, ord(low(TBitmapEffect)), ord(high(TBitmapEffect))) then
      begin
        result := 1;
        DisabledEffect := TBitmapEffect(Param1);
      end
      else
        result := 0;
    EDITOR_COMMAND_GET_DISABLED_EFFECT:
      result := ord(FDisabledEffect);
    EDITOR_COMMAND_REPEAT:
      for i := 1 to trunc(Param1) do
        EditorCommand(Param2, Param3, Param4);
    EDITOR_COMMAND_REPEAT_EX_SET_NUM:
      FRepeatExNum := trunc(Param1);
    EDITOR_COMMAND_REPEAT_EX_SET_COMMAND:
      FRepeatExCommand := trunc(Param1);
    EDITOR_COMMAND_REPEAT_EX:
      for i := 1 to FRepeatExNum do
        EditorCommand(FRepeatExCommand, Param1, Param2, Param3, Param4);
    EDITOR_COMMAND_RESTORE_MARGINS:
      RestoreAllMargins;
    EDITOR_COMMAND_FILL_WITH_CHAR:
      result := B(FillWithChar(char(Param1)));
    EDITOR_COMMAND_PASTE_AS_BLOCK:
      result := B(PasteFromClipboardAsBlock);
    EDITOR_COMMAND_TRUNCATE_AT:
      TruncateAt(Param1, Param2, Param3, Char(Word(Param4)), Param4 and $FFFF0000 <> 0);
    EDITOR_COMMAND_TRUNCATE_AT_IN_FILE:
      TruncateAt(Param1, Char(Word(Param2)), Param3 <> 0);
    EDITOR_COMMAND_TRUNCATE_AT_IN_SELECTION:
      TruncateAtInSelection(Param1, Char(Word(Param2)), Param3 <> 0);
    EDITOR_COMMAND_GET_JUST_OPENED:
      result := B(FTextFile.RecentlyOpened);
    EDITOR_COMMAND_LOAD_DEFAULT_CLASSES:
      LoadDefaultClasses;
    EDITOR_COMMAND_BEGIN_VISUAL_UPDATE:
      BeginVisualUpdate;
    EDITOR_COMMAND_END_VISUAL_UPDATE:
      EndVisualUpdate(Param1 <> 0);
    EDITOR_COMMAND_SURROUND_SEL:
      SurroundText(PChar(Param1), PChar(Param2));
    EDITOR_COMMAND_FILTER_LINES:
      if Param1 = SizeOf(TFilterOptions) then
      begin
        Filter(PFilterOptions(Param2)^);
        result := 1;
      end
      else
        result := 0;
    EDITOR_COMMAND_UPDATE_SPI:
      UpdateSPI;
    EDITOR_COMMAND_SET_STRICT_READONLY:
      FTextFile.StrictReadOnly := Param1 <> 0;
    EDITOR_COMMAND_REMOVE_GHOST_BOOKMARKS:
      result := B(FTextFile.RemoveGhostBookmarks);
    EDITOR_COMMAND_CHARACTER_FIND:
      result := Find(MakeFindQuery(Param1));
  end;
end;

procedure TTextEditor.EndAddLine;
begin
  FTextFile.EndAddLine;
end;

procedure TTextEditor.AbortScript;
begin
  FAbortScript := true;
end;

function TTextEditor.ActivateControl: HWND;
var
  ctl: TControl;
begin
  result := 0;
  ctl := GetControlFromLine(CaretPos.Y);
  if Assigned(ctl) and (ctl is TWinControl) then
  begin
    TWinControl(ctl).SetFocus;
    result := TWinControl(ctl).Handle;
  end
  else if Assigned(ctl) and (ctl is TImage) and Assigned(TImage(ctl).PopupMenu) then
  begin
    TImage(ctl).PopupMenu.PopupComponent := TImage(ctl);
    with ClientToScreen(Point(0, GetLineTop(CaretPos.Y))) do
      TImage(ctl).PopupMenu.Popup(X, Y);
    result := Handle;
  end;
end;

procedure TTextEditor.Escape(AAll: boolean);
begin
  if FMultipleCarets then
  begin
    FMultipleCarets := false;
    SetLength(FCarets, 0);
    Invalidate;
    RemoveNotification(EN_MULTICARET);
    if not AAll then Exit;
  end;
  if BalloonVisible then
  begin
    HideBalloon;
    if not AAll then Exit;
  end;
  if (EditMode = emConsole) and FTextFile.AtLastLine and not AAll then
    ClearLine;
end;

procedure TTextEditor.ExportToHTML(const FileName: TFileName);

  function Q(const S: string): string;
  begin
    if Pos(#32, S) > 0 then
      result := '"' + S + '"'
    else
      result := S;
  end;

  function MakeClassName(const S: string): string;
  var
    i: Integer;
  begin
    result := '';
    for i := 1 to Length(S) do
      if S[i].IsLetterOrDigit then
        result := result + S[i];
  end;

  function HtmlEscape(const C: char): string;
  begin
    if C = '<' then
      result := '&lt;'
    else if C = '>' then
      result := '&gt;'
    else if C = '&' then
      result := '&amp;'
    else
      result := C;
  end;

var
  SL: TStringList;
  DocumentName, FPName: string;
  Indent: string;
  rules: TCSSRules;
  oldc, c: Integer;
  i: Integer;
  j: Integer;
  L: string;
begin

  Indent := DupeString(#32, FIndentSize);
  DocumentName := FTextFile.FileName;
  if DocumentName = '' then
    DocumentName := SDefaultFileName;
  if Assigned(FFormattingProcessor) then
    FPName := FFormattingProcessor.ClassName
  else
    FPName := SNoInteractiveFormattingParen;

  SL := TStringList.Create;
  try
    SL.Add('<!DOCTYPE html>');
    SL.Add('');
    SL.Add('<html xmlns="http://www.w3.org/1999/xhtml">');
    SL.Add('<head>');
    SL.Add('');
    SL.Add('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');
    SL.Add('<title>' + ExtractFileName(DocumentName) + '</title>');
    SL.Add('');
    SL.Add('<style>');
    SL.Add('main {');
    SL.Add(Indent + 'background-color: ' + CSSColor(FBackgroundColor) + ';');
    SL.Add(Indent + 'color: ' + CSSColor(FForegroundColor) + ';');
    SL.Add('}');
    SL.Add('pre {');
    SL.Add(Indent + 'font-family: ' + Q(FFont.Name) + ';');
    SL.Add(Indent + 'font-size: ' + IntToStr(FFont.Size) + 'pt;');
    SL.Add('}');

    if (Length(FClassArray) > 0) and FTextFile.UseLineClasses then
    begin
      SL.Add('');
      for i := 0 to high(FClassArray) do
      begin
        SL.Add('.' + MakeClassName(FClassArray[i].Name) + ' {');
        SL.Add(Indent + 'font-size: ' + IntToStr(FClassArray[i].Format.Size) + 'pt;');
        SL.Add(Indent + 'color: ' + CSSColor(FClassArray[i].Format.Color) + ';');
        if fsBold in FClassArray[i].Format.Style then
          SL.Add(Indent + 'font-weight: ' + 'bold;');
        if fsItalic in FClassArray[i].Format.Style then
          SL.Add(Indent + 'font-style: ' + 'italic;');
        if fsUnderline in FClassArray[i].Format.Style then
          SL.Add(Indent + 'text-decoration: ' + 'underline;');
        SL.Add('}');
      end;
    end;

    if Assigned(FFormattingProcessor) then
    begin
      SL.Add('');
      rules := FFormattingProcessor.GetCSSRules;
      for i := low(rules) to high(rules) do
      begin
        SL.Add('.' + rules[i].Selector + ' {');
        for j := low(rules[i].Declarations) to high(rules[i].Declarations) do
          SL.Add(Indent + rules[i].Declarations[j].CSSProperty + ': ' + rules[i].Declarations[j].Value + ';');
        SL.Add('}');
      end;
    end;

    SL.Add('</style>');
    SL.Add('');
    SL.Add('</head>');
    SL.Add('');
    SL.Add('<body>');
    SL.Add('');
    SL.Add('<header>');
    SL.Add('');
    SL.Add(Indent + '<h1>' + ExtractFileName(DocumentName) + '</h1>');
    SL.Add('');
    SL.Add(Indent + '<dl>');
    SL.Add(Indent + Indent + '<dt>' + SHTMLExportFileName + '</dt>');
    SL.Add(Indent + Indent + '<dd>' + DocumentName + '</dd>');
    SL.Add(Indent + Indent + '<dt>' + SHTMLExportDate + '</dt>');
    SL.Add(Indent + Indent + '<dd><time>' + FormatDateTime('yyyy"-"mm"-"dd', Date) + '</time></dd>');
    SL.Add(Indent + Indent + '<dt>' + SHTMLExportTime + '</dt>');
    SL.Add(Indent + Indent + '<dd><time>' + FormatDateTime('hh":"mm":"ss', Time) + '</time></dd>');
    SL.Add(Indent + Indent + '<dt>' + SHTMLExportFP + '</dt>');
    SL.Add(Indent + Indent + '<dd>' + FPName + '</dd>');
    SL.Add(Indent + '</dl>');
    SL.Add('');
    SL.Add('</header>');
    SL.Add('');
    SL.Add('<main>');
    SL.Add('');
    SL.Add(Indent + '<pre>');
    oldc := -1;
    c := -1;
    for i := 0 to FTextFile.LineCount - 1 do
    begin
      L := '';
      if LineClasses[i] <> '' then
        L := '<span class="' + MakeClassName(LineClasses[i]) + '">';
      if c <> -1 then
        L := L + '<span class="' + rules[c].Selector + '">';

      for j := 0 to FTextFile.PhysicalLineWidths[i] - 1 do
      begin
        if Assigned(FFormattingProcessor) then
          c := FFormattingProcessor.GetCharCSSClass(i, j, FTextFile.Character[i, j]);
        if c <> oldc then
        begin
          if oldc <> -1 then
            L := L + '</span>';
          if c shr 16 = 0 then
            L := L + '<span class="' + rules[c].Selector + '">'
          else
            L := L + '<span class="' + rules[c and $FFFF].Selector + ' ' + rules[c shr 16].Selector + '">'
        end;
        L := L + HtmlEscape(FTextFile.Character[i, j]);
        oldc := c;
      end;
      if c <> -1 then
        L := L + '</span>';
      if LineClasses[i] <> '' then
        L := L + '</span>';
      SL.Add(L);
    end;
    SL.Add('</pre>');
    SL.Add('');
    SL.Add('</main>');
    SL.Add('');
    SL.Add('</body>');
    SL.Add('</html>');
    SL.SaveToFile(FileName, TEncoding.UTF8);
  finally
    SL.Free;
  end;

end;

function TTextEditor.CharInSet(AChar: char; ASet: array of char): boolean;
var
  i: Integer;
begin
  result := false;
  for i := low(ASet) to high(ASet) do
    if AChar = ASet[i] then
      Exit(true);
end;

function TTextEditor.CharInAnyMultiCharSet(AChar: char): boolean;
begin
  result := CharInSet(AChar, MultiCharHyphen) or CharInSet(AChar, MultiCharAsterisk) or
    CharInSet(AChar, MultiCharDoubleQuote) or CharInSet(AChar, MultiCharSingleQuote);
end;

procedure TTextEditor.KeyDown(var Key: Word; Shift: TShiftState);
var
  c: char;
begin
  inherited;

  UpdateScrollMode;

  // Cursor
  if Key in [VK_SHIFT, VK_CONTROL, VK_MENU, VK_SCROLL] then
    ChangeCursor(Shift);

  if (EditMode = emConsole) and (Key = VK_F7) then
  begin
    CliHistoryDialogSelect;
    Exit;
  end;

  if (Key = VK_F9) and FMultiCharSelect then
  begin
    c := GetCharBeforeCaret;
    if CharInSet(c, MultiCharHyphen) then
      DoMultiCharSelect(MultiCharHyphen)
    else if CharInSet(c, MultiCharAsterisk) then
      DoMultiCharSelect(MultiCharAsterisk)
    else if CharInSet(c, MultiCharDoubleQuote) then
      DoMultiCharSelect(MultiCharDoubleQuote)
    else if CharInSet(c, MultiCharSingleQuote) then
      DoMultiCharSelect(MultiCharSingleQuote);
    Exit;
  end;

  // Special case: scroll mode
  if FScrollMode then
  begin
    case Key of
      VK_UP:
        SetScrollPosY(FScrollPos.Y - IfThen(ssCtrl in Shift, 1, FFontSize.cy));
      VK_DOWN:
        SetScrollPosY(FScrollPos.Y + IfThen(ssCtrl in Shift, 1, FFontSize.cy));
      VK_LEFT:
        SetScrollPosX(FScrollPos.X - IfThen(ssCtrl in Shift, 1, FFontSize.cx));
      VK_RIGHT:
        SetScrollPosX(FScrollPos.X + IfThen(ssCtrl in Shift, 1, FFontSize.cx));
      VK_PRIOR:
        SetScrollPosY(FScrollPos.Y - ClientHeight);
      VK_NEXT:
        SetScrollPosY(FScrollPos.Y + ClientHeight);
      VK_HOME:
        SetScrollPosY(0);
      VK_END:
        SetScrollPosY(FTextFile.LineCount * FFontSize.cy - ClientHeight);
    end;
    Exit;
  end;

  if [ssShift, ssCtrl] <= Shift then
    case Key of
      VK_UP:
        begin
          SwapLinesAbove;
          Exit;
        end;
      VK_DOWN:
        begin
          SwapLinesBelow;
          Exit;
        end;
      ord('1')..ord('9'):
        if FHandleBookmarkHotkeys then
        begin
          AddBookmark(Key - ord('0'));
          Exit;
        end;
    end;

  if (ssCtrl in Shift) and (FTextFile.EditMode = emText) then
    case Key of
      VK_UP:
        begin
          with GetLastMultiCaret do
            if Y > 0 then
              CreateNewCaretAt(Point(X, Y - 1));
          Exit;
        end;
      VK_DOWN:
        begin
          with GetLastMultiCaret do
            if Y < LineCount - 1 then
              CreateNewCaretAt(Point(X, Y + 1));
          Exit;
        end;
    end;

  if FHandleBookmarkHotkeys and (Shift = [ssCtrl]) and
    (Key in [ord('1')..ord('9')]) then
  begin
    GotoBookmark(ord(key) - ord('0'));
    Exit;
  end;

  case Key of
    VK_BACK:
      Backspace(ssCtrl in Shift);
    VK_DELETE:
      begin
        Delete(ssCtrl in Shift);
        if FMatchBrackets then
          TextFileCaretPosChange(Self);
      end;
    VK_LEFT:
      FTextFile.Left(ssCtrl in Shift, ssShift in Shift, ssAlt in Shift);
    VK_RIGHT:
      FTextFile.Right(ssCtrl in Shift, ssShift in Shift, ssAlt in Shift);
    VK_UP:
      if (FTextFile.EditMode = emConsole) and FTextFile.AtLastLine and not (ssCtrl in Shift) then
        CliHistoryUp
      else if FMultiSize and not (ssAlt in Shift) then
        GotoSamePixelAtPrevLine(ssShift in Shift)
      else
        FTextFile.Up(ssShift in Shift, ssAlt in Shift);
    VK_DOWN:
      if (FTextFile.EditMode = emConsole) and FTextFile.AtLastLine and not (ssCtrl in Shift) then
        CliHistoryDown
      else if FMultiSize and not (ssAlt in Shift) then
        GotoSamePixelAtNextLine(ssShift in Shift)
      else
        FTextFile.Down(ssShift in Shift, ssAlt in Shift);
    VK_RETURN:
      begin
        if FAutoReplace then DoAutoReplace;
        Return;
      end;
    VK_HOME:
      FTextFile.Home(ssCtrl in Shift, ssShift in Shift);
    VK_END:
      FTextFile.KEnd(ssCtrl in Shift, ssShift in Shift);
    VK_PRIOR:
      PageUp(ssShift in Shift);
    VK_NEXT:
      PageDown(ssShift in Shift);
    VK_INSERT:
        SetOverwrite(not FOverwrite);
    VK_ESCAPE:
      Escape;
    VK_PAUSE:
      case EditMode of
        emText:
          EditMode := emReadOnly;
        emConsole: ;
        emReadOnly:
          EditMode := emText;
      end;
  end;

  if FHandleHotkeys then
  begin
    if [ssShift, ssCtrl] <= Shift then
      case Key of
        ord('A'):
          begin
            if not FTextFile.SelectWord then
              TextFileInputError(Self);
            Exit;
          end;
      end;
    if Shift = [ssCtrl] then
      case Key of
        ord('Z'):
          Undo;
        ord('Y'):
          Redo;
        ord('X'):
          CutToClipboard;
        ord('C'):
          CopyToClipboard;
        ord('V'):
          PasteFromClipboard;
        ord('D'):
          ClearLine;
        ord('A'):
          SelectAllNone;
        ord('L'):
          SelectLine;
        ord('U'):
          ReplaceCodepoint;
        ord('M'):
          EnterMultiCaretMode;
        ord('H'):
          Backspace;
        ord('J'):
          InsertChar(#9, FOverwrite);
        VK_OEM_PLUS, VK_ADD:
          ZoomIn;
        VK_OEM_MINUS, VK_SUBTRACT:
          ZoomOut;
        ord('0'), VK_NUMPAD0:
          ResetZoom;
      end;
  end;
end;

procedure TTextEditor.EnterMultiCaretMode;
begin
  if EditMode <> emText then Exit;

  if not FMultipleCarets then
  begin
    NotifyApp(EN_MULTICARET);
    FMultipleCarets := true;
    CreateNewCaretAt(CaretPos);
  end;
end;

procedure TTextEditor.CreateNewCaretAt(const APoint: TPoint);
var
  i: Integer;
begin
  if EditMode <> emText then Exit;

  EnterMultiCaretMode;

  for i := low(FCarets) to high(FCarets) do
    if SamePoint(FCarets[i], APoint) then
      Exit;

  SetLength(FCarets, Length(FCarets) + 1);
  FCarets[high(FCarets)] := APoint;
  Invalidate;
end;

function TTextEditor.ReplaceAll(const FindQuery: TFindQuery;
  const ReplaceText: string; SelOnly: boolean = false): integer;
begin
  if FTextFile.SingleLine and FindQuery.Linebreak then
    Exit(0);

  TypeTimerEnd;
  FTextFile.Find(FindQuery, true);
  result := FTextFile.ReplaceAll(ReplaceText, SelOnly);
  if result > 0 then AddUndoRecord(Format(SUndoReplacedAll,
    [result, FindQuery.SearchString, ReplaceText]), UID_UNKNOWN);
end;

procedure TTextEditor.ReplaceCodepoint;
begin
  TypeTimerEnd;
  if FTextFile.ReplaceCodepoint then
    AddUndoRecord(SUndoUnicodeReplacedCodepoint, UID_UNKNOWN);
end;

procedure TTextEditor.ResetZoom;
begin
  Zoom := 100;
end;

procedure TTextEditor.RestoreAllMargins;
begin
  if TextFile.ControlAware then Exit;

  FMarginLeft := DEFAULT_MARGIN_LEFT;
  FMarginRight := DEFAULT_MARGIN_RIGHT;
  FMarginTop := DEFAULT_MARGIN_TOP;
  FMarginBottom := DEFAULT_MARGIN_BOTTOM;
  FRulerWidth := DEFAULT_RULER_WIDTH;
  UpdateScrollBars;
  Invalidate;
  DoSetCaretPos;
end;

procedure TTextEditor.RestoreWrapAt(const Value: boolean);
begin
  if csDesigning in ComponentState then
  begin
    if MessageBox(0, PChar(SRestoreWrapAtText), PChar(SRestoreWrapAtCaption), MB_ICONQUESTION or MB_YESNOCANCEL) = ID_YES then
      WrapAt := DEFAULT_WRAP_AT
  end
  else
    WrapAt := DEFAULT_WRAP_AT;
end;

procedure TTextEditor.MoveBalloonPostScroll;
var
  p: TPoint;
begin
  if BalloonVisible then
    if ord(FBalloonPersistence) <= ord(bpScroll) then
      HideBalloon
    else
    begin
      p := GetBalloonPosition;
      if PtInRect(TextContentRect, ScreenToClient(p)) then
        SendMessage(FHintWindow, TTM_TRACKPOSITION, 0, MakeLParam(p.x, p.y))
      else
        HideBalloon;
    end;
end;

procedure TTextEditor.MoveSelection(const ANewPos: TPoint);
var
  S: string;
begin
  if FTextFile.IsCharSel(ANewPos) then Exit;
  TypeTimerEnd;
  S := SelText;
  FTextFile.AddBookmark(INTERNAL_BOOKMARK, ANewPos);
  try
    FTextFile.ClearSelection;
    FTextFile.GotoBookmark(INTERNAL_BOOKMARK);
    FTextFile.InsertText(S);
    AddUndoRecord(SUndoMouseMove, UID_DRAGDROP);
  finally
    FTextFile.AddBookmark(INTERNAL_BOOKMARK, EMPTY_BOOKMARK);
  end;
end;

procedure TTextEditor.Return;
var
  accept: boolean;
  S: string;
begin

  if FMultipleCarets then
  begin
    TextFileInputError(Self);
    Exit;
  end;

  if FListBoxMode then
  begin
    if Assigned(FOnListBoxSelect) then
      FOnListBoxSelect(Self);
    Exit;
  end;

  if (EditMode = emConsole) and FTextFile.AtLastLine then
  begin
    S :=  Lines[LineCount - 1];
    accept := true;
    if Assigned(FOnCliInput) then
      FOnCliInput(Self, S, accept);
    if accept then
    begin
      CliAddHistory(S);    // now S might differ from Lines[LineCount - 1]!!
      CliNewPrompt;
    end;

    Exit;
  end;

  FTextFile.Return;
  PostType;

end;

procedure TTextEditor.Backspace(Word: boolean = false);
begin

  if FMultipleCarets then
    FTextFile.MultiBackspace(FCarets)
  else
    FTextFile.Backspace(Word);

  PostType;

end;

function TTextEditor.BalloonVisible: boolean;
begin
  result := (FHintWindow <> 0) and
    (SendMessage(FHintWindow, TTM_GETCURRENTTOOL, 0, 0) <> 0);
end;

procedure TTextEditor.BeginAddLine;
begin
  FTextFile.BeginAddLine;
end;

procedure TTextEditor.SwapLinesAbove;
begin
  TypeTimerEnd;
  if FTextFile.SwapLinesAbove then
    AddUndoRecord(SUndoLinesSwapped, UID_UNKNOWN);
end;

procedure TTextEditor.SwapLinesBelow;
begin
  TypeTimerEnd;
  if FTextFile.SwapLinesBelow then
    AddUndoRecord(SUndoLinesSwapped, UID_UNKNOWN);
end;

procedure TTextEditor.DoAutoReplace;
var
  StartPos, Index: integer;
begin
  if FTextFile.CanAutoReplace(StartPos, Index) then
  begin
    TypeTimerEnd;
    FTextFile.DoAutoReplace(StartPos, Index);
    AddUndoRecord(SUndoAutoReplaced, UID_UNKNOWN);
  end;
end;

procedure TTextEditor.KeyPress(var Key: Char);
var
  PrevCh: char;
begin

  inherited;

  if Key = #9 then
  begin
    InsertText(DupeString(#32, FTabLength));
    Exit;
  end;

  if Key.IsControl or FScrollMode then Exit;
  if FAutoReplace and not Key.IsLetterOrDigit then
    DoAutoReplace;

  if FASHyphenAsteriskToggle then
  begin
    PrevCh := GetCharBeforeCaret;
    if (PrevCh = '-') and (Key = '-') then
    begin
      FTextFile.Character[CaretPos.Y, CaretPos.X - 1] := #$2212;
      Exit;
    end;
    if (PrevCh = #$2212) and (Key = '-') then
    begin
      FTextFile.Character[CaretPos.Y, CaretPos.X - 1] := '-';
      Exit;
    end;
    if (PrevCh = #$22C5) and (Key = '*') then
    begin
      FTextFile.Character[CaretPos.Y, CaretPos.X - 1] := #$00D7;
      Exit;
    end;
    if (PrevCh = #$00D7) and (Key = '*') then
    begin
      FTextFile.Character[CaretPos.Y, CaretPos.X - 1] := '*';
      Exit;
    end;
    if (PrevCh = '*') and (Key = '*') then
    begin
      FTextFile.Character[CaretPos.Y, CaretPos.X - 1] := #$22C5;
      Exit;
    end;
  end;

  InsertChar(Key, FOverwrite);

  if FMultiCharSelect and not FScriptRunning then
    if CharInAnyMultiCharSet(Key) then
      NotifyAppWithTimer(EN_MULTICHAR);

end;

procedure TTextEditor.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited;
  if Key in [VK_SHIFT, VK_CONTROL, VK_MENU, VK_SCROLL] then
    ChangeCursor(Shift);
  if Key = VK_MENU then
    UpdateScrollMode;
end;

function TTextEditor.GetFunctionalSelectionBarWidth: integer;
begin
  result := FRulerWidth;
  case FSelectionBarBehaviour of
    sbbAlwaysSelect:
      result := FMarginLeft;
    sbbNeverSelect:
      result := FRulerWidth;
    sbbAuto:
      if FRulerWidth > 0 then
        result := FRulerWidth
      else
        result := FMarginLeft;
    sbbAutoMixed:
      if FRulerWidth > 0 then
        result := FRulerWidth
      else
        result := FMarginLeft div 2;
  end;
end;

procedure TTextEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  ChSel: boolean;
  R: TRect;
begin

  inherited;

  FExpectDragDrop := false;
  FDragButton := mbLeft;
  FMouseContSel := false;

  FPrevCursorX := X;
  FPrevCursorY := Y;

  FMouseDownX := X;
  FMouseDownY := Y;

  if CanFocus and not Focused then
    SetFocus;

  ChangeCursor(Shift, Y, X);

  if FMultipleCarets then
  begin
    CreateNewCaretAt(CharAtPhysicalPixelEx(Point(X, Y), true));
    Exit;
  end;

  if FScrollMode then
  begin
    // Not much to do here, really.
    Exit;
  end;

  if FDoubleClicking then
  begin
    FDoubleClicking := false;
    ControlState := ControlState - [csLButtonDown];
    Exit;
  end;

  // Selection bar
  if X < GetFunctionalSelectionBarWidth then
  begin
    FRegion := terSelectionBar;
    if Button = mbLeft then
    begin
      SelectLine(CaretPosAtPhysicalPixel(Point(X, Y)).Y);
      FSelectionBarInitialLine := CaretPos.Y;
      R := LeftColumnRect;
      with ClientToScreen(Point(0, 0)) do OffsetRect(R, X, Y);
      ClipCursor(@R);
    end;
    Exit;
  end;

  FRegion := terText;

  ChSel := (X >= FMarginLeft) and FTextFile.IsCharSel(CharAtPhysicalPixel(Point(X, Y)));

  // Special case: grab selection
  if ChSel and (Button in [mbLeft, mbRight]) and not SingleLine then
  begin
    FExpectDragDrop := true;
    FDragButton := Button;
    Exit;
  end;

  if ((Button in [mbLeft, mbRight]) and not ChSel) or (SingleLine and (Button = mbLeft)) then
  begin
    FTextFile.CaretPos.SetPoint(CaretPosAtPhysicalPixel(Point(X,Y)), ssShift in Shift);
    FMouseContSel := true;
  end;

end;

procedure TTextEditor.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  ΔX, ΔY: integer;
  P: TPoint;
  OLEDidDrop: boolean;
  DropEffect: integer;
begin

  inherited;

  if FOLEDragging then
    Exit;

  ΔX := X - FPrevCursorX;
  ΔY := Y - FPrevCursorY;
  FPrevCursorX := X;
  FPrevCursorY := Y;

  ChangeCursor(Shift, Y, X);

  // Special case: scroll mode
  if FScrollMode and (csLButtonDown in ControlState) then
  begin
    SetScrollPosXY(FScrollPos.X - ΔX, FScrollPos.Y - ΔY);
    Exit;
  end;

  // Special case: grab selection
  if FExpectDragDrop and
    ((Abs(X - FMouseDownX) > FXDRAG) or (Abs(Y - FMouseDownY) > FYDRAG)) and
    (((FDragButton = mbLeft) and IsKeyDown(VK_LBUTTON)) or ((FDragButton = mbRight) and IsKeyDown(VK_RBUTTON))) and
    not SingleLine then
  begin

    FExpectDragDrop := false;

    if ControlInSelection then
    begin
      TextFileInputError(Self);
      Exit;
    end;

    OLEDidDrop := false;
    FOLEDragging := true;
    FOLEInternalDrop := false;
    FDragButtonOLE := IfThen(FDragButton = mbRight, MK_RBUTTON, MK_LBUTTON);
    try
      OLEDidDrop := DoDragDrop(
        TTextEditorDataObject.Create(Self),
        Self,
        DROPEFFECT_COPY or DROPEFFECT_MOVE,
        DropEffect
      ) = DRAGDROP_S_DROP;
    finally
      FOLEDragging := false;
      FMouseContSel := false;
      if not IsKeyDown(VK_LBUTTON) then
        ControlState := ControlState - [csLButtonDown];
      if OLEDidDrop then
      begin
        if FOLEInternalDrop then
        begin
          case DropEffect of
            DROPEFFECT_MOVE:
              MoveSelection(FDropLocation);
            DROPEFFECT_COPY:
              CopySelection(FDropLocation);
          end;
        end
        else
          if DropEffect = DROPEFFECT_MOVE then
          begin
            TypeTimerEnd;
            FTextFile.ClearSelection;
            AddUndoRecord(SUndoMouseMoveExtDst, UID_DRAGDROP);
          end;
      end;
    end;

    Exit;

  end;

  if FMouseContSel and IsKeyDown(VK_LBUTTON) and (FRegion = terText) then
  begin
    if ssCtrl in Shift then
      SelectionType := stBlock;
    p := CaretPosAtPhysicalPixel(Point(X, Y));
    if (not FTextFile.HasSelection) and (FTextFile.CaretPos.Y = p.Y) and
      (FTextFile.CaretPos.X >= FTextFile.VirtualLineWidths[FTextFile.CaretPos.Y]) and
      (p.X >= FTextFile.VirtualLineWidths[FTextFile.CaretPos.Y]) and
      (FTextFile.CaretPos.SelectionType = stLineBased) then // BMFIXSEL
      FTextFile.CaretPos.SetPoint(p, false)
    else
      FTextFile.CaretPos.SetPoint(p, true);
  end;

  if (csLButtonDown in ControlState) and (FRegion = terSelectionBar) then
    SelectLines(FSelectionBarInitialLine, CaretPosAtPhysicalPixel(Point(X, Y)).Y);

end;

procedure TTextEditor.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin

  inherited;

  FExpectDragDrop := false;
  FDragButton := mbLeft;
  FMouseContSel := false;

  if FOLEDragging then
    Exit;

  ClipCursor(nil);

end;

procedure TTextEditor.NewFile;
var
  WasControlAware: boolean;
begin
  Escape(true);
  WasControlAware := FTextFile.ControlAware;
  FTypeTimer.Enabled := false;
  FTextFile.NewFile;
  ClearControls; // no ghosts
//  FNextControlID := 0;
  CliClearHistory;
  FMultiSize := false;
  AddUndoRecord(SUndoNewFile, UID_UNKNOWN);
  UpdateCaret;
  if WasControlAware then
    RestoreAllMargins;
end;

function TTextEditor.NonRulerRect: TRect;
begin
  result := ClientRect;
  inc(result.Left, FRulerWidth);
end;

function TTextEditor.NotifyApp(const MsgID: integer): boolean;
var
  i: Integer;
  j: Integer;
begin
  result := Assigned(FOnNotification) or Assigned(FOnSimpleNotification);
  for i := 0 to high(FNotifications) do
    if FNotifications[i] = MsgID then
    begin
      for j := i to high(FNotifications) - 1 do
        FNotifications[j] := FNotifications[j + 1];
      SetLength(FNotifications, high(FNotifications));
    end;
  SetLength(FNotifications, Length(FNotifications) + 1);
  FNotifications[High(FNotifications)] := MsgID;
  if Assigned(FOnNotification) then
    FOnNotification(Self, MsgID);
  if Assigned(FOnSimpleNotification) then
    FOnSimpleNotification(Self, MsgID, FNotificationStrs[MsgID]);
end;

function TTextEditor.NotifyAppWithTimer(const MsgID: integer): boolean;
begin
  result := NotifyApp(MsgID);
  if SetTimer(Handle, EDITOR_NOTIFY or MsgID, FNotifyMsgDuration, nil) = 0 then
    RaiseLastOSError;
end;

function TTextEditor.OpenURLAtCaret: boolean;
var
  URL: string;
begin
  result := GetURLAtCaret(URL) and
    (ShellExecute(0, nil, PChar(URL), nil, nil, SW_SHOWNORMAL) > 32);
end;

procedure TTextEditor.DblClick;
begin

  inherited;
  FDoubleClicking := true;

  if FListBoxMode then
  begin
    if Assigned(FOnListBoxSelect) then
      FOnListBoxSelect(Self);
    Exit;
  end;

  if not SelectWord then
    TextFileInputError(Self);

end;

procedure TTextEditor.Delete(Word: boolean);
begin
  FTextFile.Delete(Word);
  PostType;
end;

procedure TTextEditor.DeleteAllLineControls;
var
  i: Integer;
begin
  for i := 0 to FTextFile.LineCount - 1 do
    if FTextFile.Classes[i] = LINE_CONTROL_CLASS then
    begin
      FTextFile.Classes[i] := ''; { internal, no repaint }
      FTextFile.Lines[i] := '';   { -"- }
    end;
  if FMultiSize then
  begin
    RebuildLineCache;
    RecomputeHorizontalExtent;
    UpdateScrollBars;
  end;
  Invalidate;
  UpdateCaret;
  for i := 0 to high(FLineControls) do
    FLineControls[i].Control.Free;
  SetLength(FLineControls, 0);
  FTextFile.ControlAware := false;
  CheckCaretBeyondEOL;
end;

function TTextEditor.DeleteControlAtLine(const LineIndex: integer): boolean;
begin
  result := FTextFile.DeleteControlAtLine(LineIndex);
  if Length(FLineControls) = 0 then
    FTextFile.ControlAware := false;
end;

procedure TTextEditor.CheckCaretBeyondEOL;
begin
  if (not CaretAfterEOL) and (not FTextFile.HasSelection) and (CaretPos.X > FTextFile.VirtualLineWidths[CaretPos.Y]) then
    FTextFile.KEnd;
end;

destructor TTextEditor.Destroy;
begin
  OleUninitialize;
  FBlinkRemover.Free;
  FTypeTimer.Free;
  FDropMenu.Free;
  FRulerFont.Free;
  FRulerMenu.Free;
  FImagePopup.Free;
  FPopupMenu.Free;
  FFont.Free;
  if FTextFileOwner = tfoEditor then
    FreeAndNil(FTextFile);
  FFONTBM.Free;
  FGLYPHBM.Free;
  FFallbackFonts.Free;
  FreeFontDataArray;
  FBalloonTimer.Free;
  FPrintSettings.Free;
  FPDict.Free;
  inherited;
end;

procedure TTextEditor.DestroyWnd;
begin
  RevokeDragDrop(Handle);
  inherited;
end;

function TTextEditor.FileIsEmpty: boolean;
begin
  result := (FTextFile.LineCount = 1) and FTextFile.LineIsEmpty(0) and (FTextFile.Classes[0] = '');
end;

function TTextEditor.FillWithChar(const AChar: char): boolean;
begin
  TypeTimerEnd;
  result := FTextFile.FillWithChar(AChar);
  if result then
    AddUndoRecord(Format(SUndoFillWithChar, [AChar]), UID_UNKNOWN);
end;

procedure TTextEditor.Filter(const Contains, Starts, Ends: string;
  CaseSensitive, RemoveMatches: boolean);
var
  FilterOptions: TFilterOptions;
begin
  FilterOptions.RemoveMatchingLines := RemoveMatches;
  FilterOptions.Contains := Contains;
  FilterOptions.StartsWith := Starts;
  FilterOptions.EndsWith := Ends;
  FilterOptions.MatchCase := CaseSensitive;
  Filter(FilterOptions);
end;

procedure TTextEditor.Filter(const AFilterOptions: TFilterOptions);
begin
  TypeTimerEnd;
  FTextFile.Filter(AFilterOptions);
  AddUndoRecord(SUndoLinesFiltered, UID_UNKNOWN);
end;

procedure TTextEditor.AddLine(const AText: string; const AClassName: string);
begin
  if FListBoxMode then EditMode := emText;

  if FileIsEmpty then
  begin
    Lines[0] := AText;
    if AClassName <> '' then
      LineClasses[0] := AClassName;
  end
  else
    FTextFile.AddLine(AText, AClassName);

  if FListBoxMode then EditMode := emReadOnly;
end;

procedure TTextEditor.UpdateFontBoxSize(ClassIndex: integer);
begin
  FFONTBM.Canvas.Font.Assign(FFont);
  FFONTBM.Canvas.Font.Size := Ceil(FClassArray[ClassIndex].Format.Size * FZoom / 100);
  FFONTBM.Canvas.Font.Style := FClassArray[ClassIndex].Format.Style;
  FFONTBM.Canvas.Font.Color := FClassArray[ClassIndex].Format.Color; // seriously?
  FClassArray[ClassIndex].Format.BoxSize := FFONTBM.Canvas.TextExtent('M');
end;

procedure TTextEditor.UpdateFontBoxSizes;
var
  i: integer;
begin
  for i := 0 to high(FClassArray) do
    UpdateFontBoxSize(i);
end;

procedure TTextEditor.BookmarkHistoryRecord(const APoint: TPoint);
begin
  if SamePoint(APoint, EMPTY_BOOKMARK) then
    AddUndoRecord(SUndoBookmarkCleared, UID_UNKNOWN)
  else
    AddUndoRecord(SUndoBookmarkAdded, UID_UNKNOWN)
end;

procedure TTextEditor.UpdateRulerLine(const ALineIndex: integer);
begin
  if InRange(ALineIndex, 0, LineCount - 1) then
    InvalidateRect(Handle,
      Rect(0, GetLineTop(ALineIndex), FRulerWidth, GetLineBottom(ALineIndex)),
      false);
end;

function TTextEditor.AddBookmark(const APoint: TPoint): integer;
begin
  TypeTimerEnd;
  result := FTextFile.AddBookmark(APoint);
  if result <> -1 then
  begin
    BookmarkHistoryRecord(APoint);
    UpdateRulerLine(APoint.Y);
  end;
end;

procedure TTextEditor.AddBookmark(AIndex: integer);
var
  OldLine: integer;
begin
  OldLine := Bookmarks[AIndex].Y;
  TypeTimerEnd;
  FTextFile.AddBookmark(AIndex);
  AddUndoRecord(SUndoBookmarkAdded, UID_UNKNOWN);
  UpdateRulerLine(OldLine);
  UpdateRulerLine(CaretPos.Y);
end;

procedure TTextEditor.AddBookmark(AIndex: integer; const APoint: TPoint);
var
  OldLine: integer;
begin
  OldLine := Bookmarks[AIndex].Y;
  TypeTimerEnd;
  FTextFile.AddBookmark(AIndex, APoint);
  BookmarkHistoryRecord(APoint);
  UpdateRulerLine(OldLine);
  UpdateRulerLine(APoint.Y);
end;

function TTextEditor.AddBookmark: integer;
begin
  TypeTimerEnd;
  result := FTextFile.AddBookmark;
  if result <> -1 then
  begin
    AddUndoRecord(SUndoBookmarkAdded, UID_UNKNOWN);
    UpdateRulerLine(CaretPos.Y);
  end;
end;

procedure TTextEditor.AddClass(const AClassRecord: TClassRecord);
var
  i: integer;
begin

  for i := low(FClassArray) to high(FClassArray) do
    if SameStr(AClassRecord.Name, FClassArray[i].Name) then
    begin
      FCLassArray[i].Format := AClassRecord.Format;
      UpdateFontBoxSize(i);
      Exit;
    end;

  SetLength(FClassArray, Length(FClassArray) + 1);
  FClassArray[high(FClassArray)] := AClassRecord;
  UpdateFontBoxSize(high(FClassArray));

end;

procedure TTextEditor.AddGraphic(AGraphic: TGraphic);
begin
  InsertGraphic(AGraphic, LineCount - 1);
end;

procedure TTextEditor.AddIndent;
begin
  TypeTimerEnd;
  FTextFile.AddIndent;
  AddUndoRecord(SUndoIndentIncreased, UID_UNKNOWN);
end;

procedure TTextEditor.AddLine;
begin
  AddLine('', '');
end;

procedure TTextEditor.AddLineControl(AControl: TControl);
begin
  InsertLineControl(AControl, LineCount);
end;

procedure TTextEditor.AddLine(const AText: string);
begin
  AddLine(AText, '');
end;

procedure TTextEditor.AddUndoRecord(const AComment: string; UID: UNDONAMEID);
begin
  Assert(not FTypeTimer.Enabled);
  if FScriptRunning then Exit;
  FTextFile.AddUndoRecord(AComment, UID);
end;

procedure TTextEditor.ApplyFont(const AClassName: string; ATo: TCanvas = nil);
var
  UseDefFont: boolean;
  ClassIndex: integer;
begin
  if ATo = nil then ATo := Canvas;

  UseDefFont := (AClassName = '') or (Length(FClassArray) = 0) or
    not ClassExists(AClassName, ClassIndex);

  if UseDefFont then
  begin
    ATo.Font.Name := FFont.Name;
    ATo.Font.Size := Ceil(FFont.Size * FZoom / 100);
    ATo.Font.Style := FFont.Style;
    ATo.Font.Color := FFgColor;
  end
  else
  begin
    ATo.Font.Name := FFont.Name;
    ATo.Font.Size := Ceil(IfThen(FMultiSize, FClassArray[ClassIndex].Format.Size, FFont.Size) * FZoom / 100);
    ATo.Font.Style := FClassArray[ClassIndex].Format.Style;
    ATo.Font.Color := FClassArray[ClassIndex].Format.Color;
  end;

  FCurrentFormat.Size := ATo.Font.Size;
  FCurrentFormat.Style := ATo.Font.Style;
  FCurrentFormat.Color := ATo.Font.Color;
end;

procedure TTextEditor.ApplyInteractiveFormatting(const X, Y: integer; ATo: TCanvas = nil);
var
  FontRecord: TFontRecord;
  TC1, TC2: cardinal;
begin
  if not Assigned(FFormattingProcessor) then Exit;
  if ATo = nil then ATo := Canvas;
  FontRecord := FCurrentFormat;
  TC1 := GetTickCount;
  FFormattingProcessor.GetCharFormat(Y, X, FTextFile.Character[Y, X], FontRecord);
  TC2 := GetTickCount;
  ATo.Font.Color := FontRecord.Color;
  ATo.Font.Style := FontRecord.Style;
  if TC2 - TC1 > 500 then
    if MessageBox(0, PChar(SFPSlowText), PChar(SFPSlowTitle), MB_ICONQUESTION or MB_YESNO) = ID_YES then
      FormattingProcessor := nil;
end;

function TTextEditor.IsBracketHighlight(const X, Y: integer): boolean;
begin
  result := FBracketHighlight and
    (((X=FBracketPos1.X) and (Y=FBracketPos1.Y)) or ((X=FBracketPos2.X) and (Y=FBracketPos2.Y)));
end;

procedure TTextEditor.ApplyCharacterColors(const X, Y: integer; AForceFindHighlight: boolean = false);
begin
  if FTextFile.IsCharSel(X, Y) then
  begin
    Canvas.Brush.Color := FSelBkColor;
    Canvas.Font.Color := FSelFgColor;
  end
  else if AForceFindHighlight then // replacement, see .Paint
  begin
    Canvas.Brush.Color := FFndBkColor;
    Canvas.Font.Color := FFndFgColor;
  end
  else
    Canvas.Brush.Color := IfThen(IsBracketHighlight(X, Y),
      FBracketHighlightColor,
      IfThen(FLineHighlight and (Y = FTextFile.CaretPos.Y),
        FLineHighlightColor,
        FBkColor));
end;

const
  UNICODE_NULL = #0;
  UNICODE_BACKSPACE = #8;
  UNICODE_LF = #$000A;
  UNICODE_CR = #$000D;
  UNICODE_SPACE = ' ' {U+0020: SPACE};
  UNICODE_HORIZONTAL_TAB = #$09 {U+0009: Character Tabulation (HT)};
  UNICODE_NO_BREAK_SPACE = #$A0 {U+00A0: NO-BREAK SPACE};
  UNICODE_NARROW_NO_BREAK_SPACE = #$202F {U+202F: NARROW NO-BREAK SPACE};
  UNICODE_ZERO_WIDTH_SPACE = #$200B {U+200B: ZERO WIDTH SPACE};
  UNICODE_ZERO_WIDTH_NON_JOINER = #$200C {U+200C: ZERO-WIDTH NON-JOINER};
  UNICODE_EN_SPACE = #$2002 {U+2002: EN SPACE};
  UNICODE_EM_SPACE = #$2003 {U+2003: EM SPACE};
  UNICODE_THIN_SPACE = #$2009 {U+2009: THIN SPACE};
  UNICODE_HAIR_SPACE = #$200A {U+200A: HAIR SPACE};
  UNICODE_MEDIUM_MATHEMATICAL_SPACE = #$205F {U+205F: MEDIUM MATHEMATICAL SPACE};
  UNICODE_FIGURE_SPACE = #$2007 {U+2007: FIGURE SPACE};
  UNICODE_PUNCTUATION_SPACE = #$2008 {U+2008: PUNCTUATION SPACE};
  UNICODE_THREE_PER_EM_SPACE = #$2004 {U+2004: THREE-PER-EM SPACE};
  UNICODE_FOUR_PER_EM_SPACE = #$2005 {U+2005: FOUR-PER-EM SPACE};
  UNICODE_SIX_PER_EM_SPACE = #$2006 {U+2065: FOUR-PER-EM SPACE};
  UNICODE_MIDDLE_DOT = '·' {U+00B7: MIDDLE DOT};
  UNICODE_WHITE_CIRCLE = '○' {U+25CB: WHITE CIRCLE};
  UNICODE_DOTTED_CIRCLE = '◌' {U+25CC: DOTTED CIRCLE};
  UNICODE_CIRCLE_WITH_VERTICAL_FILL = '◍' {U+25CD: CIRCLE WITH VERTICAL FILL};
  UNICODE_BLACK_CIRCLE = '●' {U+25CF: BLACK CIRCLE};
  UNICODE_WHITE_BULLET = '◦' {U+25E6: WHITE BULLET};
  UNICODE_LOWER_HALF_CIRCLE = '◡' {U+25E1: LOWER HALF CIRCLE};
  UNICODE_CIRCLE_WITH_UPPER_RIGHT_QUADRANT_BLACK = '◔' {U+25D4: CIRCLE WITH UPPER RIGHT QUADRANT BLACK};
  UNICODE_CIRCLE_WITH_RIGHT_HALF_BLACK = '◑' {U+25D1: CIRCLE WITH RIGHT HALF BLACK};
  UNICODE_CIRCLE_WITH_ALL_BUT_UPPER_LEFT_QUADRANT_BLACK = '◕' {U+25D5: CIRCLE WITH ALL BUT UPPER LEFT QUADRANT BLACK};
  UNICODE_BLACK_RIGHTPOINTING_POINTER = '►' {U+25BA: BLACK RIGHT-POINTING POINTER};
  UNICODE_WHITE_SMALL_SQUARE = '▫' {U+25AB: WHITE SMALL SQUARE};
  UNICODE_WHITE_DIAMOND = '◇' {U+25C7: WHITE DIAMOND};
  UNICODE_WHITE_SQUARE = '□' {U+25A1: WHITE SQUARE};
  UNICODE_BULLSEYE = '◎' {U+25CE: BULLSEYE};
  UNICODE_FISHEYE = '◉' {U+25C9: FISHEYE};
  UNICODE_LIGHT_VERTICAL_BAR = '❘' {U+2758: LIGHT VERTICAL BAR};
  UNICODE_LOZENGE = '◊' {U+25CA: LOZENGE};
  UNICODE_WHITE_VERTICAL_RECTANGLE = '▯' {U+25AF: WHITE VERTICAL RECTANGLE};
  UNICODE_WHITE_RECTANGLE = '▭' {U+25AD: WHITE RECTANGLE};
  UNICODE_SUBSCRIPT_THREE = '₃' {U+2083: SUBSCRIPT THREE};
  UNICODE_SUBSCRIPT_FOUR = '₄' {U+2084: SUBSCRIPT FOUR};
  UNICODE_SUBSCRIPT_SIX = '₆' {U+2086: SUBSCRIPT SIX};
  UNICODE_SYMBOL_FOR_NULL = '␀' {U+2400: SYMBOL FOR NULL};
  UNICODE_SYMBOL_FOR_BACKSPACE = '␈' {U+2408: SYMBOL FOR BACKSPACE};
  UNICODE_SYMBOL_FOR_LINE_FEED = #$240A {U+240A: SYMBOL FOR LINE FEED};
  UNICODE_SYMBOL_FOR_CARRIAGE_RETURN = #$240D {U+240D: SYMBOL FOR CARRIAGE RETURN};

function TTextEditor.Reveal(const C: char): char;
begin
  result := C;
  if FPasswordChar <> #0 then
    Exit(FPasswordChar);
  if not FShowHiddenCharacters then Exit;
  case C of
    UNICODE_NULL:
      result := UNICODE_SYMBOL_FOR_NULL;
    UNICODE_BACKSPACE:
      result := UNICODE_SYMBOL_FOR_BACKSPACE;
    UNICODE_SPACE:
      result := UNICODE_MIDDLE_DOT;
    UNICODE_HORIZONTAL_TAB:
      result := UNICODE_BLACK_RIGHTPOINTING_POINTER;
    UNICODE_NO_BREAK_SPACE:
      result := UNICODE_WHITE_DIAMOND;
    UNICODE_NARROW_NO_BREAK_SPACE:
      result := UNICODE_LOZENGE;
    UNICODE_ZERO_WIDTH_SPACE:
      result := UNICODE_LOWER_HALF_CIRCLE;
    UNICODE_HAIR_SPACE:
      result := UNICODE_CIRCLE_WITH_UPPER_RIGHT_QUADRANT_BLACK;
    UNICODE_THIN_SPACE:
      result := UNICODE_CIRCLE_WITH_RIGHT_HALF_BLACK;
    UNICODE_EN_SPACE:
      result := UNICODE_CIRCLE_WITH_ALL_BUT_UPPER_LEFT_QUADRANT_BLACK;
    UNICODE_EM_SPACE:
      result := UNICODE_BLACK_CIRCLE;
    UNICODE_MEDIUM_MATHEMATICAL_SPACE:
      result := UNICODE_WHITE_SMALL_SQUARE;
    UNICODE_FIGURE_SPACE:
      result := UNICODE_BULLSEYE;
    UNICODE_PUNCTUATION_SPACE:
      result := UNICODE_FISHEYE;
    UNICODE_ZERO_WIDTH_NON_JOINER:
      result := UNICODE_LIGHT_VERTICAL_BAR;
    UNICODE_THREE_PER_EM_SPACE:
      result := UNICODE_SUBSCRIPT_THREE;
    UNICODE_FOUR_PER_EM_SPACE:
      result := UNICODE_SUBSCRIPT_FOUR;
    UNICODE_SIX_PER_EM_SPACE:
      result := UNICODE_SUBSCRIPT_SIX;
    UNICODE_LF:
      result := UNICODE_SYMBOL_FOR_LINE_FEED;
    UNICODE_CR:
      result := UNICODE_SYMBOL_FOR_CARRIAGE_RETURN;
  end;
  if result <> C then
    Canvas.Font.Color := $00BBBBFF;
end;

function TTextEditor.RulerRect: TRect;
begin
  result := Rect(0, 0, FRulerWidth, ClientHeight);
end;

procedure TTextEditor.RunScript(const AScript: TEditorScript; AIterations: integer = 1;
  ACounterInit: integer = 1; ACounterInc: integer = 1);

  function PP(AParam: TScriptParam): integer;
  begin
    result := AParam.ParamValue;
    case AParam.ParamType of
      ptConstant:
        result := AParam.ParamValue;
      ptCommand:
        result := EditorCommand(AParam.ParamValue);
    end;
  end;

var
  i: Integer;
  j: Integer;
label
  Done;
begin

  if FScriptRunning then Exit;

  TypeTimerEnd;
  NotifyApp(EN_SCRIPT);
  FScriptRunning := true;
  ChangeCursor;
  FAbortScript := false;
  try
    FScriptCounter := ACounterInit;
    for j := 1 to AIterations do
    begin
      for i := low(AScript) to high(AScript) do
        with AScript[i] do
        begin
          EditorCommand(Verb, PP(Param1), PP(Param2), PP(Param3), PP(Param4));
          Application.ProcessMessages;
          if IsKeyDown(VK_ESCAPE) and Application.Active then
            FAbortScript := true;
          if FAbortScript then
            goto Done;
        end;
        inc(FScriptCounter, ACounterInc);
      end;
    Done:
  finally
    FScriptRunning := false;
    RemoveNotification(EN_SCRIPT);
    ChangeCursor;
    FTypeTimer.Enabled := false;
    if FAbortScript then
      AddUndoRecord(SUndoScriptAbort, UID_UNKNOWN)
    else
      AddUndoRecord(SUndoScript, UID_UNKNOWN);
  end;

end;

procedure TTextEditor.DrawVisibleLine(LineIndex: Integer; From: Integer = 0);
begin
  // LineIndex MUST be a visible line
  if LineIndex <= FTextFile.LineCount - 1 then
    DrawLine(LineIndex, From, FTextFile.VirtualLineWidths[LineIndex] - 1);
end;

function TTextEditor.DropTargetDragEnter(const dataObj: IDataObject;
  grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT;
var
  helperptt: TPoint;
begin

  if Assigned(FDropTargetHelper) then
  begin
    helperptt := pt;
    FDropTargetHelper.DragEnter(Handle, dataObj, helperptt, dwEffect);
  end;

  FDragDataObj := dataObj;
  FDragCompatFmt := dataObj.QueryGetData(FORMATETC_UNICODETEXT) = S_OK;
  FRightDrag := (grfKeyState and MK_RBUTTON) <> 0;
  GetDragDropEffect(dwEffect, grfKeyState);
  FLastDropEffect := -1;
  FDragScrollFirstChance := 0;
  result := S_OK;

end;

function TTextEditor.DropTargetDragLeave: HRESULT;
begin

  if Assigned(FDropTargetHelper) then
    FDropTargetHelper.DragLeave;

  FDragCompatFmt := false;
  FRightDrag := false;
  FDragDataObj := nil;
  result := S_OK;
  RemoveInsertionPoint;
  try
    RemoveNotification(EN_DRAG_MOVE);
    RemoveNotification(EN_DRAG_COPY);
  except
  end;
  FLastDropEffect := -1;
  FDragScrollFirstChance := 0;

end;

function TTextEditor.DropTargetDragOver(grfKeyState: Longint; pt: TPoint;
  var dwEffect: Longint): HRESULT;
var
  helperptt, PhysCP: TPoint;
  Δx, Δy: integer;
begin

  if Assigned(FDropTargetHelper) then
  begin
    helperptt := pt;
    FDropTargetHelper.DragOver(helperptt, dwEffect);
  end;

  GetDragDropEffect(dwEffect, grfKeyState);

  PhysCP := Self.ScreenToClient(pt);

  if PhysCP.y < 2 * FFontSize.cy then
    Δy := -2*FFontSize.cy
  else if PhysCP.y > ClientHeight - 2 * FFontSize.cy then
    Δy := 2*FFontSize.cy
  else
    Δy := 0;

  if PhysCP.x < FMarginLeft + 2 * FFontSize.cx then
    Δx := -2*FFontSize.cx
  else if PhysCP.x > ClientWidth - 2 * FFontSize.cx then
    Δx := 2*FFontSize.cx
  else
    Δx := 0;

  if (dwEffect <> DROPEFFECT_NONE) and ((Δx <> 0) or (Δy <> 0)) then
  begin
    if FDragScrollFirstChance = 0 then
      FDragScrollFirstChance := GetTickCount{64}
    else if GetTickCount{64} - FDragScrollFirstChance > 1000 then
      SetScrollPosXY(FScrollPos.X + Δx, FScrollPos.Y + Δy, true);
  end;

  IndicateInsertionPoint(CaretPosAtPhysicalPixel(PhysCP));
  DragDropNotify(dwEffect);

  result := S_OK;

end;

function TTextEditor.DropTargetDrop(const dataObj: IDataObject;
  grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT;
var
  medium: TStgMedium;
  txtbuf: PChar;
  helperptt, PhysCurPos: TPoint;
  ctxidx: cardinal;
  OldForegroundWindow: HWND;
begin

  result := S_OK;

  try

    try

      if Assigned(FDropTargetHelper) then
      begin
        helperptt := pt;
        FDropTargetHelper.Drop(dataObj, helperptt, dwEffect);
      end;

      FDragCompatFmt := dataObj.QueryGetData(FORMATETC_UNICODETEXT) = S_OK;

      PhysCurPos := Self.ScreenToClient(pt);
      FDropLocation := CaretPosAtPhysicalPixel(PhysCurPos);

      if FOLEDragging then
      begin
        // Internal drag and drop
        FOLEInternalDrop := true;
        if FTextFile.IsCharSel(FDropLocation) then
        begin
          dwEffect := DROPEFFECT_NONE;
          Exit;
        end;
      end;

      if FRightDrag and FDragCompatFmt then
      begin
        OldForegroundWindow := 0;
        if Assigned(FDropMenuMove) then
          FDropMenuMove.Enabled := (dwEffect and DROPEFFECT_MOVE) <> 0;
        if Assigned(FDropMenuCopy) then
          FDropMenuCopy.Enabled := (dwEffect and DROPEFFECT_COPY) <> 0;
        if Application.MainForm <> nil then
        begin
          OldForegroundWindow := GetForegroundWindow;
          SetForegroundWindow(Application.MainForm.Handle); // important -- if we don't do (something like) this, the menu (and the DD op) will not be dismissed on Esc or external app activation
        end;
        ctxidx := Cardinal(TrackPopupMenu(FDropMenu.Handle, TPM_RETURNCMD or TPM_NONOTIFY or TPM_RIGHTBUTTON, pt.X, pt.Y, 0, Handle, nil));
        if ctxidx = GetMenuItemID(FDropMenu.Handle, 0) then
          dwEffect := DROPEFFECT_MOVE
        else if ctxidx = GetMenuItemID(FDropMenu.Handle, 1) then
          dwEffect := DROPEFFECT_COPY
        else
        begin
          dwEffect := DROPEFFECT_NONE;
          if OldForegroundWindow <> 0 then
            SetForegroundWindow(OldForegroundWindow);
        end;
      end
      else
        GetDragDropEffect(dwEffect, grfKeyState);

      if (dwEffect <> DROPEFFECT_NONE) then
      begin

        if FOLEDragging then
        begin

          // Internal drag and drop
          // Handled by the caller of DoDragDrop

        end
        else
        begin

          // Drop external source
          if dataObj.GetData(FORMATETC_UNICODETEXT, medium) = S_OK then
            try
              if medium.tymed = TYMED_HGLOBAL then
              begin
                txtbuf := GlobalLock(medium.hGlobal);
                if Assigned(txtbuf) then
                  try
                    TypeTimerEnd;
                    FTextFile.CaretPos.SetPoint(FDropLocation);
                    FTextFile.InsertText(txtbuf);

                    case dwEffect of
                      DROPEFFECT_MOVE:
                        AddUndoRecord(SUndoMouseMoveExtSrc, UID_DRAGDROP);
                      DROPEFFECT_COPY:
                        AddUndoRecord(SUndoMouseCopyExtSrc, UID_DRAGDROP);
                    else
                      AddUndoRecord(SUndoTextInserted, UID_DRAGDROP);
                    end;

                  finally
                    GlobalUnlock(medium.hGlobal);
                  end
                else
                  result := E_UNEXPECTED;
              end
              else
                result := E_UNEXPECTED;
            finally
              ReleaseStgMedium(medium);
            end
          else
            result := E_UNEXPECTED;

        end;

      end;

    finally
      FDragCompatFmt := false;
      FDragDataObj := nil;
      RemoveInsertionPoint;
      RemoveNotification(EN_DRAG_MOVE);
      RemoveNotification(EN_DRAG_COPY);
    end;

  except
    result := E_UNEXPECTED;
  end;

end;

procedure TTextEditor.IndicateInsertionPoint(const APoint: TPoint);
begin
  if FInsertionPoint <> APoint then
  begin
    if FInsertionPoint.Y <> -1 then
      InvalidateCharAndPrev(FInsertionPoint);
    FInsertionPoint := APoint;
    InvalidateCharAndPrev(FInsertionPoint);
  end;
end;

function TTextEditor.SafeSelLength: integer;
begin
  result := Length(SelText);
end;

procedure TTextEditor.SaveToFile(const FileName: TFileName; TrimRight: boolean = false);
begin
  FTextFile.SaveToFile(FileName, TrimRight);
end;

{ BMDRAW }                                               // **Including** ATo
procedure TTextEditor.DrawLine(LineIndex: Integer; From, ATo: integer; AForceFindHighlight: boolean = false);
var
  i: Integer;
  x, y: Integer;
  FontSize: TSize;
  C: char;
begin
  // LineIndex MUST be a visible line
  if LineIndex >= FTextFile.LineCount then
    Exit;

  HideCaret(Handle);
  try
    IntersectClipRect(Canvas.Handle, FMarginLeft, FMarginTop, ClientWidth - FMarginRight, ClientHeight - FMarginBottom);
    ApplyFont(FTextFile.Classes[LineIndex]);

    if FMultiSize then
    begin
      y := FAccumLineHeights[LineIndex];
      FontSize.cx := FFontSizes[LineIndex].cx;
      FontSize.cy := FFontSizes[LineIndex].cy;
    end
    else
    begin
      y := LineIndex * FFontSize.cy;
      FontSize.cx := FFontSize.cx;
      FontSize.cy := FFontSize.cy;
    end;

    Canvas.Brush.Color := IfThen(FLineHighlight and (LineIndex = FTextFile.CaretPos.Y), FLineHighlightColor, FBkColor);
    Canvas.FillRect(Rect(FMarginLeft + From * FontSize.cx - FScrollPos.X,
      FMarginTop + y - FScrollPos.y,
      IfThen(ATo = FTextFile.VirtualLineWidths[LineIndex] - 1, ClientWidth - FMarginRight, FMarginLeft + (ATo+1) * FontSize.cx - FScrollPos.X),
      FMarginTop + y + FontSize.cy - FScrollPos.y));

    if FTextFile.ControlAware and LineIsControl(LineIndex) then
    begin
      Canvas.Brush.Color := IfThen(FTextFile.IsCharSel(0, LineIndex), FSelBkColor, Canvas.Brush.Color);
      Canvas.FillRect(Rect(FMarginLeft - FScrollPos.X, FMarginTop + y - FScrollPos.Y,
        FMarginLeft + FontSize.cx - FScrollPos.X, FMarginTop + y + FontSize.cy - FScrollPos.Y));
      InvalidateLineControl(LineIndex);
      Exit;
    end;

    From := Max(From, (FScrollPos.X + Max(0, Canvas.ClipRect.Left - FMarginLeft)) div FontSize.cx);
    ATo := Min(ATo, (FScrollPos.X + ClientWidth - FMarginLeft - FMarginRight - Max(0, ClientWidth - Canvas.ClipRect.Right - FMarginRight) + 1) div FontSize.cx);
    for i := From to Min(ATo, FTextFile.VirtualLineWidths[LineIndex] - 1) do
    begin
      x := i * FontSize.cx;
      ReapplyFont;
      ApplyInteractiveFormatting(i, LineIndex);
      ApplyCharacterColors(i, LineIndex, AForceFindHighlight);
      C := Reveal(FTextFile.Character[LineIndex, i]);
      if FUnicodeFallback then UseBestFont(C);
      Canvas.FillRect(Rect(FMarginLeft + x - FScrollPos.X,
        FMarginTop + y - FScrollPos.Y,
        FMarginLeft + x + FontSize.cx - FScrollPos.X,
        FMarginTop + y + FontSize.cy - FScrollPos.Y));
      Canvas.TextRect(Rect(FMarginLeft + x - FScrollPos.X,
                           FMarginTop + y - FScrollPos.Y,
                           FMarginLeft + x - FScrollPos.X + FontSize.cx,
                           FMarginTop + y - FScrollPos.Y + FontSize.cy),
                       FMarginLeft + x - FScrollPos.X,
                       FMarginTop + y - FScrollPos.Y,
                       C);
    end;
  finally
    ShowCaret(Handle);
  end;
end;

procedure TTextEditor.InvalidateLineControl(LineIndex: integer);
var
  ctl: TControl;
begin Exit;
  ctl := GetControlFromLine(LineIndex);
  if Assigned(ctl) then
    ctl.Invalidate;
end;

procedure TTextEditor.UseBestFont(const AChar: Char);

  function ChrFits: boolean;
  begin
    with Canvas.TextExtent(AChar) do
      result := (cx <= FFontSize.cx) and (cy <= FFontSize.cy);
  end;

var
  i: Integer;
  Changed: boolean;
begin
  Changed := false;

  if not SameStr(Canvas.Font.Name, FFont.Name) then
    Canvas.Font.Name := FFont.Name;  // reset
  if Canvas.Font.Size <> FCurrentFormat.Size then
    Canvas.Font.Size := FCurrentFormat.Size; // reset

  if ChrInGlyphSet(FGlyphSets[0], AChar) then Exit;

  for i := 0 to FFallbackFonts.Count - 1 do
    if ChrInGlyphSet(FGlyphSets[i + 1], AChar) then
    begin
      Canvas.Font.Name := FFallbackFonts[i];
      Changed := true;
      break;
    end;

  if Changed then
    while not ChrFits do
      Canvas.Font.Size := Canvas.Font.Size - 1;

end;

procedure TTextEditor.UseDefaultFallbackFonts;
begin
  FFallbackFonts.Clear;
  FFallbackFonts.Add('Arial Unicode MS');
  FFallbackFonts.Add('Lucida Sans Unicode');
  FFallbackFonts.Add('DejaVu Sans Mono');
  FFallbackFonts.Add('Consolas');
  FFallbackFonts.Add('Segoe UI');
end;

procedure TTextEditor.PageDown(Selection: boolean);
var
  NewY: integer;
begin
  NewY := EnsureRange(FTextFile.CaretPos.Y + (ClientHeight - FMarginTop - FMarginBottom) div FFontSize.cy, 0, FTextFile.LineCount - 1);
  if NewY = FTextFile.CaretPos.Y then
  begin
    TextFileInputError(Self);
    Exit;
  end;
  if FTextFile.CaretAfterEOL then
    FTextFile.CaretPos.SetY(NewY, Selection)
  else
    FTextFile.CaretPos.SetPoint(Min(FTextFile.CaretPos.X, FTextFile.VirtualLineWidths[NewY]), NewY, Selection);
end;

procedure TTextEditor.PageUp(Selection: boolean);
var
  NewY: integer;
begin
  NewY := EnsureRange(FTextFile.CaretPos.Y - (ClientHeight - FMarginTop - FMarginBottom) div FFontSize.cy, 0, FTextFile.LineCount - 1);
  if NewY = FTextFile.CaretPos.Y then
  begin
    TextFileInputError(Self);
    Exit;
  end;
  if FTextFile.CaretAfterEOL then
    FTextFile.CaretPos.SetY(NewY, Selection)
  else
    FTextFile.CaretPos.SetPoint(Min(FTextFile.CaretPos.X, FTextFile.VirtualLineWidths[NewY]), NewY, Selection);
end;

procedure TTextEditor.DrawRuler;
var
  R: TRect;
  S: string;
  y: integer;
  bm: integer;
  RulerBkColor, RulerFgColor: TColor;
begin

  if not RulerVisible then Exit;

  if FRulerColor = clDefault then
  begin
    RulerBkColor := FBkColor;
    RulerFgColor := FFgColor;
  end
  else
  begin
    RulerBkColor := FRulerColor;
    RulerFgColor := FRulerFont.Color;
  end;

  SelectClipRgn(Canvas.Handle, 0);
  Canvas.Brush.Color := RulerBkColor;
  Canvas.FillRect(RulerRect);
  Canvas.Font.Assign(FRulerFont);
  Canvas.Font.Size := Ceil(Canvas.Font.Size * FZoom / 100);
  for y := FirstVisibleLine to LastVisibleLine do
  begin
    R := Rect(0, GetLineTop(y), FRulerWidth, GetLineBottom(y));
    S := IntToStr(y + 1);
    if CaretPos.Y = y then
    begin
      Canvas.Brush.Color := FSelBkColor;
      Canvas.FillRect(R);
      Canvas.Font.Color := FSelFgColor;
    end
    else
    begin
      Canvas.Brush.Color := RulerBkColor;
      Canvas.Font.Color := RulerFgColor;
    end;
    Canvas.TextRect(R, S, [tfSingleLine, tfVerticalCenter, tfRight]);
    bm := GetLineBookmark(y);
    if bm <> -1 then
    begin
      S := 'BM' + IntToStr(bm);
      Canvas.Brush.Color := FSelBkColor;
      Canvas.Font.Color := FSelFgColor;
      Canvas.TextRect(R, S, [tfSingleLine, tfVerticalCenter, tfLeft]);
    end;
  end;

end;

procedure TTextEditor.DrawSpan(const ATextSpan: TTextSpan;
  AForceFindHighlight: boolean);
var
  y: Integer;
begin
  if ATextSpan.A.Y = ATextSpan.B.Y then
    DrawLine(ATextSpan.A.Y, ATextSpan.A.X, ATextSpan.B.X - 1, true)
  else
  begin
    DrawLine(ATextSpan.A.Y, ATextSpan.A.X, FTextFile.PhysicalLineWidths[ATextSpan.A.Y] - 1, true);
    for y := ATextSpan.A.Y + 1 to ATextSpan.B.Y - 1 do
      DrawLine(y, 0, FTextFile.PhysicalLineWidths[y] - 1, true);
    DrawLine(ATextSpan.B.Y, 0, ATextSpan.B.X - 1, true);
  end;
end;

procedure TTextEditor.NeedValidPaintState;
begin
  if not FValidPaintState then
  begin
    SetupFontMetrics;
    AdjustHeight;
  end;
  FValidPaintState := true;
end;

procedure TTextEditor.InvalidateChar(const AChar: TPoint);
begin
  if InRange(AChar.Y, 0, LineCount - 1) then
    InvalidateRect(
      Handle,
      Rect(
        GetCharLeft(AChar.Y, AChar.X),
        GetLineTop(AChar.Y),
        GetCharRight(AChar.Y, AChar.X + 1),
        GetLineBottom(AChar.Y)
      ),
      false
    )
  else
    Invalidate;
end;

procedure TTextEditor.InvalidateCharAndPrev(const AChar: TPoint);
begin
  if InRange(AChar.Y, 0, LineCount - 1) then
    InvalidateRect(
      Handle,
      Rect(
        GetCharLeft(AChar.Y, AChar.X - 1),
        GetLineTop(AChar.Y),
        GetCharRight(AChar.Y, AChar.X + 1),
        GetLineBottom(AChar.Y)
      ),
      false
    )
  else
    Invalidate;
end;

procedure TTextEditor.Paint;
var
  i: Integer;
  R: TRect;
  OCR: TRect;
  FVL, LVL: integer;
begin
  inherited;

  NeedValidPaintState;

  OCR := Canvas.ClipRect;

  // Text client area
  if OCR.Right > FRulerWidth then
  begin

    Canvas.Brush.Color := FBkColor;
    Canvas.FillRect(NonRulerRect);
    Canvas.Font.Assign(FFont);
    Canvas.Font.Color := FFgColor;

    FVL := FirstVisibleLine;
    LVL := LastVisibleLine;

    if SingleLine and (not Focused) and FLabelStyle then
    begin
      R := ClientRect;
      DrawText(Canvas.Handle, FTextFile.Lines[0], FTextFile.VirtualLineWidths[0],
        R, DT_SINGLELINE or DT_NOPREFIX or DT_VCENTER or
        IfThen(FLabelEllipsis, DT_END_ELLIPSIS))
    end
    else
      for i := FVL to LVL do
        DrawVisibleLine(i);

    // Find highlight (moved from ApplyCharacterColors 20160728)
    for i := low(FTextFile.FFindData) to high(FTextFile.FFindData) do
      if (FTextFile.FFindData[i].A.Y <= LVL) and (FTextFile.FFindData[i].B.Y >= FVL) then
        DrawSpan(FTextFile.FFindData[i], true);

  end;

  // Ruler
  if OCR.Left < FRulerWidth then
    DrawRuler;

  // Right line
  if FRightLine then
  begin
    SelectClipRgn(Canvas.Handle, 0);
    Canvas.Pen.Color := FRightLineColor;
    Canvas.MoveTo(FMarginLeft + FRightLinePos - FScrollPos.X, FMarginTop);
    Canvas.LineTo(FMarginLeft + FRightLinePos - FScrollPos.X,
      ClientHeight - FMarginBottom);
  end;

  // Multi-caret mode
  if FMultipleCarets then
  begin
    IntersectClipRect(Canvas.Handle, FMarginLeft, FMarginTop, ClientWidth - FMarginRight, ClientHeight - FMarginBottom);
    Canvas.Pen.Color := FFgColor;
    Canvas.Pen.Width := CARET_WIDTH;
    for i := low(FCarets) to high(FCarets) do
    begin
      with PhysicalPixelAtChar(FCarets[i]) do
        Canvas.MoveTo(X, Y);
      Canvas.LineTo(Canvas.PenPos.X, GetLineBottom(FCarets[i].Y) - 1);
    end;
  end;

  // Insertion point (for OLE Drag and Drop)
  if FInsertionPoint.Y <> -1 then
  begin
    IntersectClipRect(Canvas.Handle, FMarginLeft, FMarginTop, ClientWidth - FMarginRight, ClientHeight - FMarginBottom);
    Canvas.Pen.Color := FFgColor;
    Canvas.Pen.Width := CARET_WIDTH;
    with PhysicalPixelAtChar(FInsertionPoint) do
      Canvas.MoveTo(X, Y);
    Canvas.LineTo(Canvas.PenPos.X, GetLineBottom(FInsertionPoint.Y) - 1);
  end;

  // Raster post processing
  BitmapEffects.BitmapEffect(Self, Canvas, FBitmapEffect);

  if not Enabled then
    BitmapEffects.BitmapEffect(Self, Canvas, FDisabledEffect);

end;

function TTextEditor.Find(AFindQuery: TFindQuery): integer;
begin
  result := FTextFile.Find(AFindQuery);
  FStartOver := true;
  Invalidate;
end;

procedure TTextEditor.SelectFindItem(ItemIndex: integer);
begin
  FNoScrollToCaret := true;
  try
    with FTextFile do
    begin
      CaretPos.SetPoint(FindData[ItemIndex].B);
      CaretPos.SetPoint(FindData[ItemIndex].A, true);
    end;
  finally
    FNoScrollToCaret := false;
  end;
  CenterOnSelection(true);
  FStartOver := false;
end;

function TTextEditor.LeftColumnRect: TRect;
begin
  result := Rect(0, 0, FMarginLeft, ClientHeight);
end;

procedure TTextEditor.SelectLine(ALineIndex: integer);
begin
  FTextFile.SelectLine(ALineIndex);
end;

function TTextEditor.FindFromTop: integer;
begin
  if FTextFile.FindCount = 0 then
    Exit(-1);
  if FStartOver then
  begin
    SelectFindItem(0);
    result := 0;
  end
  else
    result := FindNext;
end;

function TTextEditor.FindNext: integer;
var
  i: Integer;
begin
  result := -1;
  for i := 0 to FTextFile.FindCount - 1 do
    if (FTextFile.FindData[i].A.Y > FTextFile.CaretPos.Y) or
        ((FTextFile.FindData[i].A.Y = FTextFile.CaretPos.Y) and
        (FTextFile.FindData[i].A.X > FTextFile.CaretPos.X)) then
    begin
      SelectFindItem(i);
      result := i;
      break;
    end;
end;

function TTextEditor.FindPrevious: integer;
var
  i: Integer;
begin
  result := -1;
  for i := FTextFile.FindCount - 1 downto 0 do
    if (FTextFile.FindData[i].A.Y < FTextFile.CaretPos.Y) or
        ((FTextFile.FindData[i].A.Y = FTextFile.CaretPos.Y) and
        (FTextFile.FindData[i].A.X < FTextFile.CaretPos.X)) then
    begin
      SelectFindItem(i);
      result := i;
      break;
    end;
end;

function TTextEditor.FirstVisibleLine(TrueValue: boolean = false): integer;
var
  i: Integer;
  ClipRectTop, MX: Integer;
begin
  if TrueValue then
    ClipRectTop := 0
  else
    ClipRectTop := Canvas.ClipRect.Top;
  MX := Max(0, ClipRectTop - FMarginTop);
  if FMultiSize then
  begin
    result := FTextFile.LineCount - 1;
    for i := 0 to FTextFile.LineCount - 1 do
      if FAccumLineHeights[i] + FFontSizes[i].cy > FScrollPos.Y + MX then
        Exit(i);
  end
  else
    result := EnsureRange((FScrollPos.Y + MX) div FFontSize.cy, 0, FTextFile.LineCount - 1);
end;

procedure TTextEditor.FixRemovedLineControlLines;
var
  i: Integer;
begin
  for i := 0 to LineCount - 1 do
    if LineIsControl(i) and not Assigned(GetControlFromLine(i)) then
    begin
      Lines[i] := '[' + SRemovedControl + ']';
      ForceSetClass(i, '');
    end;
end;

function TTextEditor.LastVisibleLine(TrueValue: boolean = false): integer;
var
  i: Integer;
  ClipRectBottom, MN: Integer;
begin
  if TrueValue then
    ClipRectBottom := ClientHeight - FMarginBottom
  else
    ClipRectBottom := Canvas.ClipRect.Bottom;
  MN := Min(ClipRectBottom - FMarginTop, ClientHeight - FMarginTop - FMarginBottom);
  if FMultiSize then
  begin
    result := FTextFile.LineCount - 1;
    for i := 1 to FTextFile.LineCount - 1 do
      if FAccumLineHeights[i] > FScrollPos.Y + MN then
        Exit(i - 1);
  end
  else
    result := EnsureRange((FScrollPos.Y + MN + 1) div FFontSize.cy, 0, FTextFile.LineCount - 1);
end;

function TTextEditor.LineIsControl(LineIndex: integer): boolean;
begin
  result := SameStr(FTextFile.Classes[LineIndex], LINE_CONTROL_CLASS);
end;

function TTextEditor.LineIsWinControlOrHasPopup(LineIndex: integer): boolean;
var
  ctl: TControl;
begin
  ctl := GetControlFromLine(LineIndex);
  result := Assigned(ctl) and
    ((ctl is TWinControl) or ((ctl is TImage) and Assigned(TImage(ctl).PopupMenu)));
end;

function TTextEditor.LineWidths(LineIndex: integer): integer; {in px, control aware}
begin
  if FMultiSize and LineIsControl(LineIndex) then
    result := GetLineControlSize(LineIndex).cx
  else
    result := FTextFile.VirtualLineWidths[LineIndex] * FFontSizes[LineIndex].cx;
end;

procedure TTextEditor.LoadDefaultClasses;
var
  HeadingColor: TColor;
begin

  if GetSysColor(COLOR_WINDOW) = DWORD(clWhite) then
    HeadingColor := clNavy
  else
    HeadingColor := clWindowText;

  AddClass(MakeClass('Heading 1', 28, [], HeadingColor));
  AddClass(MakeClass('Heading 2', 16, [], HeadingColor));
  AddClass(MakeClass('Heading 3', 12, [], HeadingColor));
  AddClass(MakeClass('Heading 4', 10, [fsBold], HeadingColor));
  AddClass(MakeClass('Heading 5', 10, [fsItalic], HeadingColor));
  AddClass(MakeClass('Heading 6', 10, [], HeadingColor));

end;

procedure TTextEditor.DragDropNotify(dwEffect: Integer);
begin
  if dwEffect <> FLastDropEffect then
  begin
    case dwEffect of
      DROPEFFECT_COPY:
        begin
          RemoveNotification(EN_DRAG_MOVE);
          NotifyApp(EN_DRAG_COPY);
        end;
      DROPEFFECT_MOVE:
        begin
          RemoveNotification(EN_DRAG_COPY);
          NotifyApp(EN_DRAG_MOVE);
        end;
    else
      RemoveNotification(EN_DRAG_MOVE);
      RemoveNotification(EN_DRAG_COPY);
    end;
    FLastDropEffect := dwEffect;
  end;
end;

procedure TTextEditor.GetDragDropEffect(var dwEffect: Integer; grfKeyState: Integer);
begin
  if FDragCompatFmt then
    if ((grfKeyState and MK_CONTROL) <> 0) and ((dwEffect and DROPEFFECT_COPY) <> 0) then
      dwEffect := DROPEFFECT_COPY
    else if ((dwEffect and DROPEFFECT_MOVE) <> 0) then
      dwEffect := DROPEFFECT_MOVE
    else if ((dwEffect and DROPEFFECT_COPY) <> 0) then
      dwEffect := DROPEFFECT_COPY
    else
      dwEffect := DROPEFFECT_NONE
  else
    dwEffect := DROPEFFECT_NONE
end;

procedure TTextEditor.RemoveInsertionPoint;
begin
  if FInsertionPoint.Y <> -1 then
  begin
    InvalidateCharAndPrev(FInsertionPoint);
    FInsertionPoint := Point(-1, -1);
  end;
end;

procedure TTextEditor.Loaded;
begin
  inherited;
end;

procedure TTextEditor.LoadFromFile(const FileName: TFileName;
  const Encoding: TEncoding);
var
  WasControlAware: boolean;
begin
  try
    WasControlAware := FTextFile.ControlAware;
    Escape(true);
    FTypeTimer.Enabled := false;
    FMultiSize := false;
    FTextFile.LoadFromFile(FileName, Encoding);
    AddUndoRecord(SUndoDocumentLoaded, UID_UNKNOWN);
    UpdateCaret;
    if WasControlAware then
      RestoreAllMargins;
  except
    // Unknown (and thus unrecoverable) error during file load:
    // create a new document just to have a valid state.
    NewFile;
    raise;
  end;
end;

function TTextEditor.PasteFromClipboard: boolean;
var
  gr: TBitmap;
begin
  TypeTimerEnd;
  if Clipboard.HasFormat(CF_TEXT) and FMultipleCarets then
  begin
    FTextFile.MultiInsertText(FCarets, Clipboard.AsText);
    result := true;
  end
  else if Clipboard.HasFormat(CF_TEXT) then
    result := FTextFile.PasteFromClipboard
  else if FAllowBitmapPaste and Clipboard.HasFormat(CF_BITMAP) and not SingleLine then
  begin
    gr := TBitmap.Create;
    try
      gr.Assign(Clipboard);
      InsertGraphic(gr, CaretPos.Y);
    finally
      gr.Free;
    end;
    result := true;
  end
  else
    result := false;
  if result then
    AddUndoRecord(SUndoPastedFromClipboard, UID_PASTE);
end;

function TTextEditor.PasteFromClipboardAsBlock: boolean;
begin
  TypeTimerEnd;
  result := FTextFile.PasteFromClipboardAsBlock;
  if result then
    AddUndoRecord(SUndoPastedFromClipboard, UID_PASTE);
end;

function TTextEditor.PhysicalPixelAtChar(const Point: TPoint): TPoint;
begin
  result := VirtualPixelAtChar(Point);
  dec(result.X, FScrollPos.X);
  dec(result.Y, FScrollPos.Y);
  inc(result.X, FMarginLeft);
  inc(result.Y, FMarginTop);
end;

function TTextEditor.VirtualPixelAtChar(const Point: TPoint): TPoint;
begin
  if FMultiSize then
  begin
    result.X := Point.X * FFontSizes[Point.Y].cx;
    result.Y := FAccumLineHeights[Point.Y];
  end
  else
  begin
    result.X := Point.X * FFontSize.cx;
    result.Y := Point.Y * FFontSize.cy;
  end;
end;

function TTextEditor.Redo: boolean;
begin
  if FTypeTimer.Enabled then
    TypeTimerTimer(Self);
  FNoScrollToCaret := true;
  try
    result := FTextFile.Redo;
    if FTextFile.ControlAware then
      FixRemovedLineControlLines;
  finally
    FNoScrollToCaret := false;
  end;
  if result then
    CenterOnSelection(true);
end;

procedure TTextEditor.RegisterFP(FormattingProcessor: TFormattingProcessor);
begin
  FPDict.AddOrSetValue(FormattingProcessor.ClassName, FormattingProcessor);
end;

procedure TTextEditor.RemoveAllIndent;
begin
  TypeTimerEnd;
  FTextFile.RemoveAllIndent;
  AddUndoRecord(SUndoIndentRemoved, UID_UNKNOWN);
end;

function TTextEditor.RemoveClass(const AClassName: string): boolean;
var
  i: Integer;
  j: Integer;
begin
  result := false;
  for i := 0 to high(FClassArray) do
    if SameStr(AClassName, FClassArray[i].Name) then
    begin
      for j := i to high(FClassArray) - 1 do
        FClassArray[j] := FClassArray[j + 1];
      SetLength(FClassArray, Length(FClassArray) - 1);
      Exit(true);
    end;
end;

procedure TTextEditor.RemoveIndent;
begin
  TypeTimerEnd;
  FTextFile.RemoveIndent;
  AddUndoRecord(SUndoIndentDecreased, UID_UNKNOWN);
end;

procedure TTextEditor.RemoveNotification(const MsgID: integer);

  function GetMostRecentNotification(out AMsg: cardinal; out AStr: string): boolean;
  begin
    result := Length(FNotifications) > 0;
    if result then
    begin
      AMsg := FNotifications[high(FNotifications)];
      AStr := FNotificationStrs[AMsg];
    end
    else
    begin
      AMsg := 0;
      AStr := '';
    end;
  end;

var
  i: Integer;
  j: Integer;
  LastMsg: cardinal;
  LastStr: string;
begin
  for i := high(FNotifications) downto 0 do
    if FNotifications[i] = MsgID then
    begin
      for j := i to high(FNotifications) - 1 do
        FNotifications[j] := FNotifications[j + 1];
      SetLength(FNotifications, high(FNotifications));
      if Assigned(FOnNotification) then
        FOnNotification(Self, MsgID, true);
      if Assigned(FOnSimpleNotification) then
      begin
        GetMostRecentNotification(LastMsg, LastStr);
        FOnSimpleNotification(Self, LastMsg, LastStr);
      end;
      break;
    end;
end;

procedure TTextEditor.SelectAll;
begin
  FNoScrollToCaret := true;
  try
    FTextFile.SelectAll;
  finally
    FNoScrollToCaret := false;
  end;
end;

procedure TTextEditor.SelectAllNone;
begin
  FNoScrollToCaret := true;
  try
    FTextFile.SelectAllNone;
  finally
    FNoScrollToCaret := false;
  end;
end;

procedure TTextEditor.SelectLine;
begin
  FTextFile.SelectLine;
end;

procedure TTextEditor.SelectLines(const ALineA, ALineB: integer);
begin
  FNoScrollToCaret := true;
  try
    FTextFile.SelectLines(ALineA, ALineB);
  finally
    FNoScrollToCaret := false;
  end;
end;

procedure TTextEditor.SelectNone;
begin
  FTextFile.SelectNone;
end;

function TTextEditor.SelectWord: boolean;
begin
  result := FTextFile.SelectWord;
end;

procedure TTextEditor.AdjustHeight;
begin
  if SingleLine and FAutoHeight then
    ClientHeight := FFontSize.cy + AUTO_HEIGHT_PADDING;
end;

procedure TTextEditor.SetAutoHeight(const Value: boolean);
begin
  if FAutoHeight <> Value then
  begin
    FAutoHeight := Value;
    AdjustHeight;
  end;
end;

procedure TTextEditor.SetAutoIndent(const Value: boolean);
begin
  FAutoIndent := Value;
  FTextFile.AutoIndent := Value;
end;

procedure TTextEditor.SetBackgroundColor(const Value: TColor);
begin
  if FBackgroundColor <> Value then
  begin
    FBackgroundColor := Value;
    SetupColors;
    Invalidate;
  end;
end;

procedure TTextEditor.SetBitmapEffect(const Value: TBitmapEffect);
begin
  if FBitmapEffect <> Value then
  begin
    FBitmapEffect := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetBorderColor(const Value: TColor);
begin
  FBorderColor := Value;
  if (FBorderColor <> Value) and (FBorderType = btSimpleColor) then
    Invalidate;
end;

procedure TTextEditor.SetBorderType(const Value: TBorderType);
begin
  if FBorderType <> Value then
  begin
    if Value <> btSimpleColor then
      BorderWidth := 0;
    FBorderType := Value;
    HideBalloon;
    RecreateWnd;
  end;
end;

procedure TTextEditor.SetBracketHighlightColor(const Value: TColor);
begin
  if FBracketHighlightColor <> Value then
  begin
    FBracketHighlightColor := Value;
    if FBracketHighlight then
      VisualUpdate(ctTwoChars, FBracketPos1.Y, FBracketPos1.X, FBracketPos2.Y, FBracketPos2.X) // update
  end;
end;

procedure TTextEditor.SetCaretAfterEOL(const Value: boolean);
begin
  FTextFile.CaretAfterEOL := Value;
  FCaretAfterEOL := FTextFile.CaretAfterEOL; // could have been rejected by the text file
end;

procedure TTextEditor.SetCaretPos(const Value: TPoint);
var
  X, Y: integer;
begin
  Y := EnsureRange(Value.Y, 0, LineCount - 1);
  if CaretAfterEOL then
    X := Max(Value.X, 0)
  else
    X := EnsureRange(Value.X, 0, FTextFile.VirtualLineWidths[Y]);
  FTextFile.CaretPos.SetPoint(X, Y);
end;

procedure TTextEditor.SetClass(Index: integer; const Value: string);
begin
  if LineIsControl(Index) then Exit;
  FTextFile.Classes[Index] := Value;
  TextFileLineClassChange(Self, Index);
end;

procedure TTextEditor.SetCliHistory(Index: integer; const Value: string);
begin
  FCliHistory[Index] := Value;
end;

procedure TTextEditor.SetDisabledEffect(const Value: TBitmapEffect);
begin
  if FDisabledEffect <> Value then
  begin
    FDisabledEffect := Value;
    if not Enabled then
      Invalidate;
  end;
end;

procedure TTextEditor.SetEditMode(const Value: TEditMode);
begin
  if (FTextFile.EditMode = emReadOnly) and FTextFile.StrictReadOnly then
    Exit;

  if (Value = emReadOnly) and (FTextFile.EditMode <> emReadOnly) then
    NotifyApp(EN_READONLY)
  else if (Value <> emReadOnly) and (FTextFile.EditMode = emReadOnly) then
    RemoveNotification(EN_READONLY);
  FTextFile.EditMode := Value;

  UpdateCaret;
end;

procedure TTextEditor.SetFallbackFonts(const Value: TStringList);
begin
  FFallbackFonts.Assign(Value);
  BuildFontDataArray;
  Invalidate;
end;

procedure TTextEditor.SetFindBackgroundColor(const Value: TColor);
begin
  if FFndBkColor <> Value then
  begin
    FFndBkColor := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetFindForegroundColor(const Value: TColor);
begin
  if FFndFgColor <> Value then
  begin
    FFndFgColor := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.VerifyFont;
const
  GoodFonts: array[0..5] of string = ('DejaVu Sans Mono', 'Consolas',
    'Lucida Console', 'Courier New', 'Courier', 'Fixedsys');
var
  i: integer;
begin
  if FNoVerifyFont then Exit;
  if FixedWidthFonts.IndexOf(FFont.Name) = -1 then
  begin
    for i := low(GoodFonts) to high(GoodFonts) do
      if FixedWidthFonts.IndexOf(GoodFonts[i]) <> -1 then
      begin
        FFont.Name := GoodFonts[i];
        Exit;
      end;
    if FixedWidthFonts.Count > 0 then
      FFont.Name := FixedWidthFonts[0];
  end;
end;

procedure TTextEditor.SetFont(const Value: TFont);
begin
  FFont.Assign(Value);
  VerifyFont;
  SetupFontMetrics;
  BuildFontDataArray;
  AdjustHeight;
  Invalidate;
end;

procedure TTextEditor.SetForegroundColor(const Value: TColor);
begin
  if FForegroundColor <> Value then
  begin
    FForegroundColor := Value;
    SetupColors;
    Invalidate;
  end;
end;

procedure TTextEditor.ForceSetClass(Index: integer; const Value: string);
begin
  FTextFile.Classes[Index] := Value;
  TextFileLineClassChange(Self, Index);
end;

procedure TTextEditor.FormattingProcessorChanged(Sender: TObject);
begin
  Invalidate;
end;

function TTextEditor.FormattingProcessorGetLineWidth(ALineIndex: integer): integer;
begin
  result := FTextFile.PhysicalLineWidths[ALineIndex]
end;

function TTextEditor.FormattingProcessorGetChar(ALineIndex, ACol: integer): char;
begin
  result := FTextFile.UnsafeGetChar(ALineIndex, ACol);
end;

function TTextEditor.FormattingProcessorGetLineCount: integer;
begin
  result := FTextFile.LineCount;
end;

function TTextEditor.FormattingProcessorGetWord(const APoint: TPoint; APascalIdent: boolean = false): string;
begin
  result := FTextFile.GetWord(APoint, APascalIdent);
end;

function TTextEditor.FormattingProcessorGetWordBoundary(const APoint: TPoint; out SP, EP: integer): boolean;
begin
  result := FTextFile.GetWordBoundary(APoint, SP, EP);
end;

procedure TTextEditor.SetFormattingProcessor(const Value: TFormattingProcessor; AInitialize: boolean = true);
begin
  if FFormattingProcessor <> Value then
  begin
    FFormattingProcessor := Value;
    if Assigned(FFormattingProcessor) then
    begin
      FFormattingProcessor.OnGetLineWidth := FormattingProcessorGetLineWidth;
      FFormattingProcessor.OnGetChar := FormattingProcessorGetChar;
      FFormattingProcessor.OnGetLineCount := FormattingProcessorGetLineCount;
      FFormattingProcessor.OnGetWord := FormattingProcessorGetWord;
      FFormattingProcessor.OnGetWordBoundary := FormattingProcessorGetWordBoundary;
      FFormattingProcessor.OnChange := FormattingProcessorChanged;
      if AInitialize then
        FPFileChangeNotification(ctFile, 0, 0, 0, 0);
    end;
    Invalidate;
  end;
end;

procedure TTextEditor.SetFormattingProcessorSmple(
  const Value: TFormattingProcessor);
begin
  SetFormattingProcessor(Value, true);
end;

procedure TTextEditor.SetIndentSize(const Value: integer);
begin
  FIndentSize := Value;
  FTextFile.IndentSize := Value;
end;

procedure TTextEditor.SetLabelEllipsis(const Value: boolean);
begin
  if FLabelEllipsis <> Value then
  begin
    FLabelEllipsis := Value;
    if SingleLine and (not Focused) and FLabelStyle then
      Invalidate;
  end;
end;

procedure TTextEditor.SetLabelStyle(const Value: boolean);
begin
  if FLabelStyle <> Value then
  begin
    FLabelStyle := Value;
    if SingleLine and not Focused then
      Invalidate;
  end;
end;

procedure TTextEditor.SetLetterSpacing(const Value: integer);
begin
  if FLetterSpacing <> Value then
  begin
    FLetterSpacing := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetLine(Index: integer; const Value: string);
begin
  FTextFile.Lines[Index] := Value;
  TextFileChange(Self, ctLine, Index, 0, 0, 0);
  with FTextFile do
    if (CaretPos.Y = Index) and (not CaretAfterEOL) and
      (CaretPos.X > VirtualLineWidths[CaretPos.Y]) then
      KEnd;
end;

procedure TTextEditor.SetLineComparer(const Value: TLineComparer);
begin
  FTextFile.LineComparer := Value;
end;

procedure TTextEditor.SetLineHighlight(const Value: boolean);
begin
  if FLineHighlight <> Value then
  begin
    FLineHighlight := Value;
    VisualUpdate(ctLine, FTextFile.CaretPos.Y, 0, 0, 0);
  end;
end;

procedure TTextEditor.SetLineHighlightColor(const Value: TColor);
begin
  if FLineHighlightColor <> Value then
  begin
    FLineHighlightColor := Value;
    VisualUpdate(ctLine, FTextFile.CaretPos.Y, 0, 0, 0);
  end;
end;

procedure TTextEditor.SetLineSpacing(const Value: integer);
begin
  if FLineSpacing <> Value then
  begin
    FLineSpacing := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetListBoxItemIndex(const Value: integer);
begin
  FTextFile.CaretPos.SetPoint(0, Value);
end;

procedure TTextEditor.SetListBoxMode(const Value: boolean);
begin
  if FListBoxMode <> Value then
  begin
    FListBoxMode := Value;
    if FListBoxMode then
    begin
      RemoveAllMargins;
      EditMode := emReadOnly;
      LineHighlight := true;
      DestroyCaret;
    end
    else
    begin
      EditMode := emText;
      UpdateCaret;
      DoSetCaretPos;
    end;
  end;
end;

procedure TTextEditor.SetMarginBottom(const Value: integer);
begin
  if (Value < 0) or SingleLine then Exit;
  if FTextFile.ControlAware then Exit;
  if FMarginBottom <> Value then
  begin
    FMarginBottom := Value;
    UpdateScrollBars;
    Invalidate;
    if FTextFile.ControlAware then
      UpdateLineControls;
    DoSetCaretPos;
  end;
end;

procedure TTextEditor.SetMarginLeft(const Value: integer);
begin
  if (Value < 0) or SingleLine then Exit;
  if FTextFile.ControlAware then Exit;
  if FMarginLeft <> Value then
  begin
    FMarginLeft := Value;
    FRulerWidth := Min(FRulerWidth, FMarginLeft);
    UpdateScrollBars;
    Invalidate;
    if FTextFile.ControlAware then
      UpdateLineControls;
    DoSetCaretPos;
  end;
end;

procedure TTextEditor.SetMarginRight(const Value: integer);
begin
  if (Value < 0) or SingleLine then Exit;
  if FTextFile.ControlAware then Exit;
  if FMarginRight <> Value then
  begin
    FMarginRight := Value;
    UpdateScrollBars;
    Invalidate;
    if FTextFile.ControlAware then
      UpdateLineControls;
    DoSetCaretPos;
  end;
end;

procedure TTextEditor.SetMarginTop(const Value: integer);
begin
  if (Value < 0) or SingleLine then Exit;
  if FTextFile.ControlAware then Exit;
  if FMarginTop <> Value then
  begin
    FMarginTop := Value;
    UpdateScrollBars;
    Invalidate;
    if FTextFile.ControlAware then
      UpdateLineControls;
    DoSetCaretPos;
  end;
end;

procedure TTextEditor.SetMatchBrackets(const Value: boolean);
begin
  if FMatchBrackets <> Value then
  begin
    FMatchBrackets := Value;
    if (not FMatchBrackets) and FBracketHighlight then
    begin
      FBracketHighlight := false;
      VisualUpdate(ctTwoChars, FBracketPos1.Y, FBracketPos1.X, FBracketPos2.Y, FBracketPos2.X); // turn off old ones
    end;
    if FMatchBrackets then
      TextFileCaretPosChange(Self); // possibly turn on new ones
  end;
end;

procedure TTextEditor.SetMultiSize(const Value: boolean);
begin

  if not FMultiSize and not Value then
    Exit;

  FMultiSize := Value;

  if FMultiSize then
  begin
    RebuildLineCache;
    RecomputeHorizontalExtent;
  end
  else
    DeleteAllLineControls;

  Invalidate;

end;

procedure TTextEditor.SetOverwrite(const Value: boolean);
begin
  if FOverwrite <> Value then
  begin
    FOverwrite := Value;
    UpdateCaret;
    if Assigned(FOnOverwriteChange) then
      FOnOverwriteChange(Self);
  end;
end;

procedure TTextEditor.SetPasswordChar(const Value: char);
begin
  if FPasswordChar <> Value then
  begin
    FPasswordChar := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetRightLine(const Value: boolean);
begin
  if FRightLine <> Value then
  begin
    FRightLine := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetRightLineColor(const Value: TColor);
begin
  FRightLineColor := Value;
  if FRightLine and (FRightLineColor <> Value) then
    Invalidate;
end;

procedure TTextEditor.SetRightLinePos(const Value: integer);
begin
  FRightLinePos := Value;
  if FRightLine and (FRightLinePos <> Value) then
    Invalidate;
end;

procedure TTextEditor.SetRulerColor(const Value: TColor);
begin
  if FRulerColor <> Value then
  begin
    FRulerColor := Value;
    if RulerVisible then
      UpdateRuler;
  end;
end;

procedure TTextEditor.SetRulerVisible(const Value: boolean);
begin
  if SingleLine then Exit;
  if FTextFile.ControlAware then Exit;
  if Value and not RulerVisible then
    SetRulerWidth(DEFAULT_RULER_WIDTH)
  else if RulerVisible and not Value then
    SetRulerWidth(0);
end;

procedure TTextEditor.SetRulerWidth(const Value: integer);
begin
  if (Value < 0) or SingleLine then Exit;
  if FTextFile.ControlAware then Exit;
  if FRulerWidth <> Value then
  begin
    inc(FMarginLeft, Value - FRulerWidth);
    FRulerWidth := Value;
    UpdateScrollBars;
    Invalidate;
    DoSetCaretPos;
    if FTextFile.ControlAware then
      UpdateLineControls;
  end;
end;

procedure TTextEditor.SetSelBackgroundColor(const Value: TColor);
begin
  if FSelBackgroundColor <> Value then
  begin
    FSelBackgroundColor := Value;
    SetupColors;
    Invalidate;
  end;
end;

procedure TTextEditor.SetSelEndPos(const Value: TPoint);
begin
  FTextFile.CaretPos.SetPoint(Value, true);
end;

procedure TTextEditor.SetSelForegroundColor(const Value: TColor);
begin
  if FSelForegroundColor <> Value then
  begin
    FSelForegroundColor := Value;
    SetupColors;
    Invalidate;
  end;
end;

procedure TTextEditor.SetSelLength(const Value: integer);
begin
  FTextFile.SelLength := Value;
end;

procedure TTextEditor.SetSelStart(const Value: integer);
begin
  FTextFile.SelStart := Value;
end;

procedure TTextEditor.SetSelType(const Value: TSelectionType);
begin
  FTextFile.CaretPos.SelectionType := Value;
end;

procedure TTextEditor.SetShowHiddenCharacters(const Value: boolean);
begin
  if FShowHiddenCharacters <> Value then
  begin
    FShowHiddenCharacters := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetSingleLine(const Value: boolean);
begin
  FTextFile.SingleLine := Value;
  if Value then
  begin
    FRulerWidth := 0;
    FMarginLeft := 0;
    FMarginRight := 0;
    FMarginTop := 0;
    FMarginBottom := 0;
  end;
  FWantTab := not Value;
  FWantReturn := not Value;
  AdjustHeight;
  Invalidate;
end;

procedure TTextEditor.SetSortReverseOrder(const Value: boolean);
begin
  FTextFile.SortReverseOrder := Value;
end;

procedure TTextEditor.SetText(const Value: string);
begin
  FTextFile.PlainText := Value;
end;

procedure TTextEditor.SetTextFile(const Value: TTextFile);
var
  WasControlAware: boolean;
  ptr: PByte;
begin

  if (not Enabled) or FScriptRunning then
    Exit;

  Escape(true);
  TypeTimerEnd;

  if FTextFile <> Value then
  begin
    ClearBracketHighlight;
    WasControlAware := TextFile.ControlAware;
    DeleteAllLineControls;
    DisconnectTextFileFromEditor;
    if FTextFileOwner = tfoEditor then
      FreeAndNil(FTextFile)
    else
    begin
      if Assigned(FFormattingProcessor) then
        FTextFile.EditorState.FormattingProcessor := FFormattingProcessor.ClassName
      else
        FTextFile.EditorState.FormattingProcessor := '';
      FTextFile.EditorState.ScrollPos := FScrollPos;
      FTextFile.EditorState.MultiSize := FMultiSize;
      FTextFile.EditorState.Overwrite := FOverwrite;
      FTextFile.EditorState.HiddenChrs := FShowHiddenCharacters;
      FTextFile.EditorState.RulerVisible := RulerVisible;
      FTextFile.EditorState.ZoomLevel := FZoom;
      if FFormattingProcessor <> nil then
      begin
        if Assigned(FTextFile.EditorState.FPCache) then
        begin
          FreeMem(FTextFile.EditorState.FPCache);
          FTextFile.EditorState.FPCache := nil;
          FTextFile.EditorState.FPCacheLen := 0;
        end;
        FTextFile.EditorState.FPCacheLen := FFormattingProcessor.GetCache(ptr);
        FTextFile.EditorState.FPCache := ptr;
        FFormattingProcessor.ClearCache;
      end;
      FTextFile.EditorState.Valid := true;
    end;
    if Assigned(Value) then
      FTextFile := Value
    else
    begin
      FTextFileOwner := tfoEditor;
      FTextFile := TTextFile.Create;
    end;
    FOldCaretPosY := FTextFile.CaretPos.Y;
    ConnectTextFileToEditor;
    if FTextFile.EditorState.Valid then
    begin
      MultiSize := FTextFile.EditorState.MultiSize; // important to set the FMultiSize flag first
      Overwrite := FTextFile.EditorState.Overwrite;
      ShowHiddenCharacters := FTextFile.EditorState.HiddenChrs;
      RulerVisible := FTextFile.EditorState.RulerVisible;
      Zoom := FTextFile.EditorState.ZoomLevel;
      FFormattingProcessor := nil; // otherwise the setter will not send a change notification to the FP
      SetFormattingProcessor(
        FPFromString(FTextFile.EditorState.FormattingProcessor),
        FTextFile.EditorState.FPCache = nil);
      if Assigned(FFormattingProcessor) and Assigned(FTextFile.EditorState.FPCache) then
      begin
        if not FFormattingProcessor.RestoreCache(FTextFile.EditorState.FPCache,
          FTextFile.EditorState.FPCacheLen) then
          FPFileChangeNotification(ctFile, 0, 0, 0, 0);
        FreeMem(FTextFile.EditorState.FPCache);
        FTextFile.EditorState.FPCache := nil;
        FTextFile.EditorState.FPCacheLen := 0;
      end;
      SetScrollPosXY(FTextFile.EditorState.ScrollPos.X,
        FTextFile.EditorState.ScrollPos.Y);
    end
    else
    begin
      MultiSize := FTextFile.ControlAware; // default only
      FFormattingProcessor := nil;
      SetScrollPosXY(0, 0);
    end;
    UpdateCaret;
    UpdateScrollBars;
    Invalidate;

    // Some notification messages are per-file, not per-control, such as read-only mode
    if HasNotificationMessage(EN_READONLY) and (EditMode <> emReadOnly) then
      RemoveNotification(EN_READONLY)
    else if (EditMode = emReadOnly) and not HasNotificationMessage(EN_READONLY) then
      NotifyApp(EN_READONLY);

    if WasControlAware then
      RestoreAllMargins;
  end;
end;

procedure TTextEditor.SetUnicodeFallback(const Value: boolean);
begin
  if FUnicodeFallback <> Value then
  begin
    FUnicodeFallback := Value;
    Invalidate;
  end;
end;

procedure TTextEditor.SetupColors;
begin
  if FUseSystemColors then
  begin
    FBkColor := clWindow;
    FFgColor := IfThen(Enabled, clWindowText, clGrayText);
    FSelBkColor := clHighlight;
    FSelFgColor := clHighlightText;
  end
  else
  begin
    FBkColor := FBackgroundColor;
    FFgColor := FForegroundColor;
    FSelBkColor := FSelBackgroundColor;
    FSelFgColor := FSelForegroundColor;
  end;
end;

procedure TTextEditor.SetupFontMetrics;
begin
  Canvas.Font.Assign(FFont);
  Canvas.Font.Size := Ceil(Canvas.Font.Size * FZoom / 100);
  FFontSize := Canvas.TextExtent('M');
  Inc(FFontSize.cx, LetterSpacing);
  Inc(FFontSize.cy, LineSpacing);
end;

procedure TTextEditor.SetUseSystemColors(const Value: boolean);
begin
  if FUseSystemColors <> Value then
  begin
    FUseSystemColors := Value;
    SetupColors;
    Invalidate;
  end;
end;

procedure TTextEditor.SetWrapAt(const Value: string);
begin
  FTextFile.WrapAt := Value;
end;

procedure TTextEditor.SetZoom(const Value: integer);
begin
  if FZoom <> Value then
  begin
    FZoom := Value;
    SetupFontMetrics;
    if FMultiSize then
    begin
      UpdateFontBoxSizes;
      RebuildLineCache;
      RecomputeHorizontalExtent;
    end;
    UpdateScrollBars;
    DoSetCaretPos;
    if FTextFile.ControlAware then
      UpdateLineControls;
    Invalidate;
    UpdateCaret;
    if Assigned(FOnZoomChange) then
      FOnZoomChange(Self);
  end;
end;

function TTextEditor.ShowBalloon(const ATitle, AText: string; AKind: TBalloonIconKind;
  APersistence: TBalloonPersistence; const APoint: TPoint): boolean;
var
  p: TPoint;
begin
  result := FHintWindow <> 0;
  if result then
  begin
    FBalloonPoint := APoint;
    FBalloonPersistence := APersistence;
    p := GetBalloonPosition;
    FToolInfo.lpszText := PChar(AText);
    result := result and (SendMessage(FHintWIndow, TTM_SETTITLE, ord(AKind),
      lParam(PChar(ATitle))) <> 0);
    SendMessage(FHintWindow, TTM_UPDATETIPTEXT, 0, lParam(@FToolInfo));
    SendMessage(FHintWindow, TTM_TRACKACTIVATE, 1, LParam(@FToolInfo));
    SendMessage(FHintWindow, TTM_TRACKPOSITION, 0, MakeLParam(p.x, p.y));
    if ord(APersistence) <= ord(bpTime) then
    begin
      FBalloonTimer.Enabled := false;
      FBalloonTimer.Enabled := true;
    end;
  end;
end;

function TTextEditor.Sort(AFirstLine, ALastLine: integer): boolean;
begin
  TypeTimerEnd;
  result := FTextFile.Sort(AFirstLine, ALastLine, FTextFile.HasBookmarks);
  if result then AddUndoRecord(SUndoSorted, UID_UNKNOWN);
end;

function TTextEditor.Sort: boolean;
begin
  result := Sort(0, LineCount - 1);
end;

function TTextEditor.SortSelection: boolean;
var
  FirstPoint, SecondPoint: TPoint;
begin
  result := false;
  if not FTextFile.HasSelection then Exit;
  FTextFile.CaretPos.GetSelBdry(FirstPoint, SecondPoint);
  result := Sort(FirstPoint.Y, SecondPoint.Y);
end;

procedure TTextEditor.SurroundText(const APrefix, APostfix: string);
begin
  TypeTimerEnd;
  FTextFile.SurroundText(APrefix, APostfix);
  AddUndoRecord(Format(SUndoTextSurrounded, [APrefix, APostfix]), UID_UNKNOWN);
end;

function TTextEditor.CanRedo: boolean;
begin
  result := FTextFile.CanRedo;
end;

function TTextEditor.CanUndo: boolean;
begin
  result := FTextFile.CanUndo or FTypeTimer.Enabled;
end;

procedure TTextEditor.ChangeCursor;
var
  ShiftState: TShiftState;
begin
  ShiftState := [];
  if IsKeyDown(VK_SHIFT) then
    Include(ShiftState, ssShift);
  if IsKeyDown(VK_CONTROL) then
    Include(ShiftState, ssCtrl);
  if IsKeyDown(VK_MENU) then
    Include(ShiftState, ssAlt);
  ChangeCursor(ShiftState);
end;

function TTextEditor.CharAtPhysicalPixel(Pixel: TPoint): TPoint;
begin
  result := CharAtPhysicalPixelEx(Pixel);
end;

function TTextEditor.CharAtVirtualPixel(Pixel: TPoint): TPoint;
begin
  result := CharAtVirtualPixelEx(Pixel);
end;

function TTextEditor.CharAtPhysicalPixelEx(Pixel: TPoint; const CP: boolean = false): TPoint;
begin
  inc(Pixel.Y, FScrollPos.Y - FMarginTop);
  inc(Pixel.X, FScrollPos.X - FMarginLeft);

  result := CharAtVirtualPixelEx(Pixel, CP);
end;

function TTextEditor.CharAtVirtualPixelEx(Pixel: TPoint; const CP: boolean = false): TPoint;
var
  FontSizecx: integer;
  i: Integer;
begin

  if FMultiSize then
  begin
    result.Y := FTextFile.LineCount - 1;
    for i := 0 to high(FAccumLineHeights) do
      if FAccumLineHeights[i] > Pixel.Y then
      begin
        result.Y := i - 1;
        break;
      end;
    if result.Y < 0 then // should be impossible
      result.Y := 0;

    FontSizecx := FFontSizes[result.Y].cx;
  end
  else
  begin
    result.Y := EnsureRange(Pixel.Y div FFontSize.cy, 0, FTextFile.LineCount - 1);
    FontSizecx := FFontSize.cx;
  end;

  if FTextFile.CaretAfterEOL then
    result.X := Max(0, (Pixel.X + IfThen(CP, 1) * FontSizecx div 2) div FontSizecx)
  else
    result.X := EnsureRange((Pixel.X + IfThen(CP, 1) * FontSizecx div 2) div FontSizecx, 0, FTextFile.VirtualLineWidths[result.Y]);
end;

{ TTextFile }

procedure TTextFile.AddLine(const ALine: string);
begin
  AddLine(ALine, '');
end;

procedure TTextFile.GotoSOF(Selection: boolean = false);
begin
  FCaretPos.SetPoint(0, 0, Selection);
end;

procedure TTextFile.GotoEOF(Selection: boolean = false);
begin
  FCaretPos.SetPoint(VirtualLineWidths[LineCount - 1], LineCount - 1, Selection);
end;

function TTextFile.GotoHistoryVersion(Index: integer): boolean;
var
  UndoData: TUndoDataItem;
begin
  result := FHistoryManager.GotoVersion(Index, UndoData);
  if not result then Exit;
  ApplyUndoRecord(UndoData);
end;

function TTextFile.GotoBookmark(AIndex: integer): boolean;
begin
  result := InRange(AIndex, low(FBookmarks), high(FBookmarks)) and
    (not SamePoint(FBookmarks[AIndex], EMPTY_BOOKMARK)) and
    ValidCaretPos(FBookmarks[AIndex]);
  if result then
    FCaretPos.SetPoint(FBookmarks[AIndex]);
end;

procedure TTextFile.GotoBottomRight(Selection: Boolean = False);
begin
  FCaretPos.SetPoint(GetMaxLineWidth, LineCount - 1, Selection);
end;

function TTextFile.HasQueryResult(const AFindQuery: TFindQuery): boolean;
begin
  result := CompareFindQuery(AFindQuery) and FFindResultValid;
end;

function TTextFile.HasSelection: boolean;
begin
  result := not SamePoint(FCaretPos.Data, FCaretPos.SelEnd);
end;

procedure TTextFile.Home(AFile: boolean = false; Selection: boolean = false);
begin
  if AFile then
    GotoSOF(Selection)
  else
  begin
    if FCaretPos.X > 0 then
      FCaretPos.SetX(0, Selection)
    else
      FCaretPos.SetX(GetIndent, Selection);
  end;
end;

procedure TTextFile.KEnd(AFile: boolean = false; Selection: boolean = false);
begin
  if AFile then
    GotoEOF(Selection)
  else
    FCaretPos.SetX(VirtualLineWidths[FCaretPos.Y], Selection);
end;

const
  FIND_DATA_ALLOC_BY = 4096;

procedure TTextFile.AddBookmark(AIndex: integer);
begin
  AddBookmark(AIndex, FCaretPos.Data);
end;

procedure TTextFile.AddBookmark(AIndex: integer; const APoint: TPoint);
begin
  Assert(InRange(AIndex, low(FBookmarks), high(FBookmarks)));
  FBookmarks[AIndex] := APoint;
end;

function TTextFile.AddBookmark: integer;
begin
  result := AddBookmark(FCaretPos.Data);
end;

procedure TTextFile.AddFindData(const A: TPoint);
var
  B: TPoint;
begin
  B.Y := A.Y;
  B.X := A.X + 1;
  AddFindData(A, B);
end;

function TTextFile.AddBookmark(const APoint: TPoint): integer;
begin
  result := GetEmptyBookmarkIndex;
  if result > -1 then
    AddBookmark(result, APoint);
end;

procedure TTextFile.AddFindData(const A, B: TPoint);
begin
  if FFindDataActualLength = Length(FFindData) then
    SetLength(FFindData, Length(FFindData) + FIND_DATA_ALLOC_BY);
  FFindData[FFindDataActualLength].A := A;
  FFindData[FFindDataActualLength].B := B;
  inc(FFindDataActualLength);
end;

procedure TTextFile.AddIndent;
var
  FirstPoint, SecondPoint: TPoint;
  i: Integer;
  IndentStep: string;
begin
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FirstPoint.Y < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  IndentStep := DupeString(#32, FIndentSize);
  for i := FirstPoint.Y to SecondPoint.Y do
    if not (FControlAware and IsControlLine(i)) then
      FLines[i] := IndentStep + FLines[i];
  FCaretPos.InternalPush(FIndentSize);
  Changed(ctLineRange, FirstPoint.Y, SecondPoint.Y);
  Modified;

  PushBookmarksEx(FirstPoint.Y, SecondPoint.Y, FIndentSize);
end;

procedure TTextFile.AddLine(const ALine: string; const AClassName: string);
begin
  if EditMode = emReadOnly then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FSingleLine then
    raise EInvalidOperation.Create(SInvalidOpMsgSingleLineModeInsertLine);

  InternalAddLine(ALine, AClassName);

  if not FMultiAddLineMode then
  begin
    LineArrayChanged;
    Changed(ctLine, High(FLines), 0);
    GotoEOF;
    Modified;
  end;
end;

procedure TTextFile.AddUndoRecord(const AComment: string; UID: UNDONAMEID);
begin
  FHistoryManager.Add(GetText, GetClassesAsText, FCaretPos.Data,
    FCaretPos.SelEnd, FCaretPos.SelectionType, Now, AComment, FBookmarks, ord(UID));
end;

procedure TTextFile.AddUndoRecord;
begin
  FHistoryManager.Add(GetText, GetClassesAsText, FCaretPos.Data,
    FCaretPos.SelEnd, FCaretPos.SelectionType, Now, '', FBookmarks);
end;

function TTextFile.AllSelected: boolean;
var
  FirstPoint, SecondPoint: TPoint;
begin
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  result := (FirstPoint.Y = 0) and (FirstPoint.X = 0) and (SecondPoint.Y = LineCount - 1) and (SecondPoint.X >= VirtualLineWidths[LineCount - 1]);
end;

procedure TTextFile.Backspace(Word: boolean = false);
var
  LW, PWB: integer;
  Len: integer; // Num chars to be removed (possibly > 1 if Word, as in Ctrl+Backspace)
begin

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and not AtLastLine) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  // Special case: has selection
  if HasSelection then
  begin
    ClearSelection;
    Exit;
  end;

  // Special case: SOF
  if AtSOF then
  begin
    IssueInputError;
    Exit;
  end;

  // Special case: control line
  if FControlAware and IsControlLine then
  begin
    if FCaretPos.X > 1 then
      Left
    else if FCaretPos.X = 1 then
    begin
      DeleteControlAtLine(FCaretPos.Y);
      FCaretPos.SetX(0);
      Modified;
    end
    else if FCaretPos.X = 0 then
    begin
      if (FCaretPos.Y > 0) and LineIsEmpty(FCaretPos.Y - 1) then
      begin
        InternalDeleteLine(FCaretPos.Y - 1);
        QushBookmarks(FCaretPos.Y - 1, 1);
        LineArrayChanged;
        FCaretPos.SetPoint(0, FCaretPos.Y - 1);
        Changed(ctLineRange, FCaretPos.Y, LineCount - 1);
        PostFileChanged(1);
        Modified;
      end
      else
        IssueInputError;
    end;
    Exit;
  end;

  // Special case: remove line break
  if (EditMode = emConsole) and (FCaretPos.X = 0) then
    Exit {silently};

  // Sub-special case: previous line is control line
  if FControlAware and (FCaretPos.X = 0) and (FCaretPos.Y > 0) and
    IsControlLine(FCaretPos.Y - 1) and not LineIsEmpty(FCaretPos.Y) then
  begin
    IssueInputError;
    Exit;
  end;

  if (FCaretPos.X = 0) and (FCaretPos.Y > 0) then
  begin
    LW := VirtualLineWidths[FCaretPos.Y - 1];
    if LineIsEmpty(FCaretPos.Y - 1) and not SameStr(FClasses[FCaretPos.Y - 1], FClasses[FCaretPos.Y]) then
    begin
      FClasses[FCaretPos.Y - 1] := FClasses[FCaretPos.Y];
      LineClassChanged(FCaretPos.Y - 1);
    end;
    FLines[FCaretPos.Y - 1] := FLines[FCaretPos.Y - 1] + FLines[FCaretPos.Y];
    InternalDeleteLine(FCaretPos.Y);
    QushBookmarks(FCaretPos.Y - 1, LW);
    LineArrayChanged;
    FCaretPos.SetPoint(LW, FCaretPos.Y - 1);
    Changed(ctLineRange, FCaretPos.Y, LineCount - 1, 2);
    PostFileChanged(1);
    Modified;
    Exit;
  end;

  // General case
  if Word then
    PWB := PrevWordBoundary
  else
    PWB := FCaretPos.X - 1;
  Len := FCaretPos.X - PWB;

  if AtEOL then
  begin
    SetLength(FLines[FCaretPos.Y], Length(FLines[FCaretPos.Y]) - Len);
    FCaretPos.SetX(PWB);
    if Len = 1 then
      Changed(ctChar, FCaretPos.Y, FCaretPos.X)
    else
      Changed(ctLineFrom, FCaretPos.Y, FCaretPos.X);
  end
  else
  begin
    // Important: The code below must work as VK_LEFT beyond EOL
    // (except possibly for bookmark pushing)
    System.Delete(FLines[FCaretPos.Y], PWB + 1, Len);
    FCaretPos.SetX(PWB);
    Changed(ctLineFrom, FCaretPos.Y, FCaretPos.X);
  end;
  PushBookmarks(FCaretPos.Y, FCaretPos.X + 1, -Len);
  Modified;
end;

procedure TTextFile.Left(Word: boolean = false; Selection: boolean = false;
  Block: boolean = false);
begin

  if Selection and (not HasSelection) and BeyondEOL and (not Block) then // BMFIXSEL
    Selection := false;

  if Selection and Block then
    FCaretPos.SelectionType := stBlock;

  if (FCaretPos.SelectionType = stBlock) and (FCaretPos.X = 0) then
  begin
    IssueInputError;
    Exit;
  end;

  if FCaretPos.X > 0 then
    if Word then
      FCaretPos.SetX(PrevWordBoundary, Selection)
    else
      FCaretPos.SetX(FCaretPos.X - 1, Selection)
  else if FCaretPos.Y > 0 then
    FCaretPos.SetPoint(VirtualLineWidths[FCaretPos.Y - 1], FCaretPos.Y - 1, Selection)
  else
    IssueInputError;
end;

procedure TTextFile.Right(Word: boolean = false; Selection: boolean = false;
  Block: boolean = false);
begin

  if Selection and (not HasSelection) and AtOrBeyondEOL and (not Block) then // BMFIXSEL
    Selection := false;

  if Selection and Block then
    FCaretPos.SelectionType := stBlock;

  if (FCaretPos.X < VirtualLineWidths[FCaretPos.Y]) or (FCaretAfterEOL and not Word) then
    if Word then
      FCaretPos.SetX(NextWordBoundary, Selection)
    else
      FCaretPos.SetX(FCaretPos.X + 1, Selection)
  else if (FCaretPos.Y < LineCount - 1) then
    FCaretPos.SetPoint(0, FCaretPos.Y + 1, Selection)
  else
    IssueInputError;
end;

function TTextFile.RushBookmarks(const FirstPoint: TPoint): boolean; // e.g. Return
begin
  result := RushBookmarksInternal(FirstPoint);
  if result then BookmarksMoved;
end;

function TTextFile.RushBookmarksEx(const FirstPoint, // e.g. InsertText
  SecondPoint: TPoint): boolean;
var
  i: Integer;
  Δy, Δx: integer;
begin
  result := false;
  Δy := SecondPoint.Y - FirstPoint.Y;
  Δx := SecondPoint.X - FirstPoint.X;
  for i := low(FBookmarks) to high(FBookmarks) do
    if (FBookmarks[i].Y = FirstPoint.Y) and (FBookmarks[i].X >= FirstPoint.X) then
    begin
      result := true;
      inc(FBookmarks[i].Y, Δy);
      inc(FBookmarks[i].X, Δx);
    end
    else if (FBookmarks[i].Y > FirstPoint.Y) then
    begin
      result := true;
      inc(FBookmarks[i].Y, Δy);
    end;
  if result then BookmarksMoved;
end;

function TTextFile.RushBookmarksInternal(const FirstPoint: TPoint): boolean;
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if (FBookmarks[i].Y = FirstPoint.Y) and (FBookmarks[i].X >= FirstPoint.X) then
    begin
      result := true;
      inc(FBookmarks[i].Y, 1);
      dec(FBookmarks[i].X, FirstPoint.X);
    end
    else if (FBookmarks[i].Y > FirstPoint.Y) then
    begin
      result := true;
      inc(FBookmarks[i].Y, 1);
    end;
end;

function TTextFile.Undo: boolean;
var
  UndoData: TUndoDataItem;
begin
  result := FHistoryManager.Undo(UndoData);
  if not result then Exit;
  ApplyUndoRecord(UndoData);
end;

function TTextFile.UnsafeGetChar(Y, X: integer): char;
begin
  result := FLines[Y][X+1];
end;

procedure TTextFile.Up(Selection: boolean = false; Block: boolean = false);
begin
  if Selection and Block then
    FCaretPos.SelectionType := stBlock;

  if FCaretPos.Y > 0 then
    if FCaretAfterEOL then
      FCaretPos.SetY(FCaretPos.Y - 1, Selection)
    else
    begin
      FPreserveDesiredCol := true;
      try
        FCaretPos.SetPoint(Min(IfThen(FDesiredCol <> 0, FDesiredCol, FCaretPos.X),
          VirtualLineWidths[FCaretPos.Y - 1]), FCaretPos.Y - 1, Selection)
      finally
        FPreserveDesiredCol := false;
      end;
    end
  else
    IssueInputError;
end;

function TTextFile.ValidCaretPos(APoint: TPoint): boolean;
begin
  result := InRange(APoint.Y, 0, LineCount - 1) and
    (InRange(APoint.X, 0, VirtualLineWidths[APoint.Y]) or FCaretAfterEOL);
end;

procedure TTextFile.WordWrap(ALineLength: integer; ANice: boolean; AChr: char);
var
  NewFile: TTextFile;
  y: integer;
  WrapList: TIntegerDynArray;
  i: Integer;
  SChr: string;
  HasBookmarks, BMCh: boolean;
  BMLastWrap, BMc: integer;
begin

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  HasBookmarks := Self.HasBookmarks;
  BMCh := false;

  if ALineLength <= 0 then Exit;
  if AChr = #0 then
    SChr := ''
  else
    SChr := AChr;
  NewFile := TTextFile.Create;
  try
    BMc := 0;
    for y := 0 to LineCount - 1 do
    begin
      if ANice then
        FindWhereToWrap(y, ALineLength, WrapList)
      else
      begin
        if VirtualLineWidths[y] = 0 then
          SetLength(WrapList, 0)
        else
          SetLength(WrapList, ceil(VirtualLineWidths[y] / ALineLength) - 1);
        for i := 0 to high(WrapList) do WrapList[i] := (i+1) * ALineLength;
      end;
      if Length(WrapList) > 0 then
      begin
        BMLastWrap := 0;

        NewFile.AddLine(SysUtils.TrimRight(Copy(FLines[y], 1, WrapList[0])) + SChr, FClasses[y]);
        for i := 0 to high(WrapList) - 1 do
        begin
          NewFile.AddLine(SysUtils.TrimRight(Copy(FLines[y], WrapList[i] + 1,
            WrapList[i+1] - WrapList[i])) + SChr, FClasses[y]);
          if HasBookmarks then
          begin
            BMCh := RushBookmarksInternal(Point(WrapList[i] - BMLastWrap, y + BMc)) or BMCh;
            BMLastWrap := WrapList[i];
            inc(BMc);
          end;
        end;
        NewFile.AddLine(Copy(FLines[y], WrapList[high(WrapList)] + 1), FClasses[y]);
        if HasBookmarks then
        begin
          BMCh := RushBookmarksInternal(Point(WrapList[high(WrapList)] - BMLastWrap, y + BMc)) or BMCh;
          inc(BMc);
        end;
      end
      else
        NewFile.AddLine(FLines[y], FClasses[y]);
    end;

    SetLength(FLines, NewFile.LineCount - 1);
    SetLength(FClasses, NewFile.LineCount - 1);
    for y := 1 to NewFile.LineCount - 1 do
    begin
      FLines[y - 1] := NewFile.Lines[y];
      FClasses[y - 1] := NewFile.Classes[y];
    end;
  finally
    NewFile.Free;
  end;
  LineArrayChanged;
  Changed(ctFile);
  GotoSOF;
  Modified;

  if BMCh then BookmarksMoved;
end;

procedure TTextFile.Delete(Word: boolean);
var
  NWB: integer;
  Len: integer; // Num chars to be removed (possibly > 1 if Word, as in Ctrl+Del)
begin

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and not AtLastLine) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  // Special case: has selection
  if HasSelection then
  begin
    ClearSelection;
    Exit;
  end;

  // Special case: EOF
  if AtOrBeyondEOF then
  begin
    IssueInputError;
    Exit;
  end;

  // Special case: line control
  if FControlAware and IsControlLine then
  begin
    if FCaretPos.X = 0 then
    begin
      DeleteControlAtLine(FCaretPos.Y);
      Modified;
    end
    else if FCaretPos.X = 1 then
    begin
      if (not AtLastLine) and LineIsEmpty(FCaretPos.Y + 1) then
      begin
        InternalDeleteLine(FCaretPos.Y + 1);
        QushBookmarks(FCaretPos.Y, 1);
        LineArrayChanged;
        Changed(ctLineRange, FCaretPos.Y, LineCount - 1);
        PostFileChanged(1);
        Modified;
      end
      else
        IssueInputError;
    end
    else
      IssueInputError;
    Exit;
  end;

  // Special case: remove line break
  if AtOrBeyondEOL and not AtLastLine then
  begin

    // Sub-special case: next line is control line
    if FControlAware and IsControlLine(FCaretPos.Y + 1) then
    begin
      if LineIsEmpty(FCaretPos.Y) then
        FClasses[FCaretPos.Y] := LINE_CONTROL_CLASS
      else
      begin
        IssueInputError;
        Exit;
      end;
    end;

    FLines[FCaretPos.Y] := FLines[FCaretPos.Y] + GetVirtualSpace + FLines[FCaretPos.Y + 1];
    InternalDeleteLine(FCaretPos.Y + 1);
    QushBookmarks(FCaretPos.Y, FCaretPos.X);
    LineArrayChanged;
    Changed(ctLineRange, FCaretPos.Y, LineCount - 1, 2);
    PostFileChanged(1);
    Modified;
    Exit;
  end;

  // General case
  if Word then
    NWB := NextWordBoundary
  else
    NWB := FCaretPos.X + 1;
  Len := NWB - FCaretPos.X;

  System.Delete(FLines[FCaretPos.Y], FCaretPos.X + 1, Len);
  PushBookmarks(FCaretPos.Y, FCaretPos.X, -Len);
  Changed(ctLineFrom, FCaretPos.Y, FCaretPos.X);
  Modified;
end;

function TTextFile.DeleteControlAtLine(const LineIndex: integer): boolean;
var
  CID: integer;
begin
  result := IsControlLine(LineIndex) and TryStrToInt(Copy(FLines[LineIndex],
    Length(LINE_CONTROL_PREFIX) + 1), CID);
  if result then
  begin
    FLines[LineIndex] := '';
    FClasses[LineIndex] := '';
    if Assigned(FOnControlRemoved) then
      FOnControlRemoved(Self, CID);
    LineClassChanged(LineIndex);
  end;
end;

destructor TTextFile.Destroy;
begin
  FHistoryManager.Free;
  FCaretPos.Free;
  FEditorState.Free;
  inherited;
end;

procedure TTextFile.Down(Selection: boolean = false; Block: boolean = false);
begin
  if Selection and Block then
    FCaretPos.SelectionType := stBlock;

  if FCaretPos.Y < LineCount - 1 then
    if FCaretAfterEOL then
      FCaretPos.SetY(FCaretPos.Y + 1, Selection)
    else
    begin
      FPreserveDesiredCol := true;
      try
        FCaretPos.SetPoint(Min(IfThen(FDesiredCol <> 0, FDesiredCol, FCaretPos.X),
          VirtualLineWidths[FCaretPos.Y + 1]), FCaretPos.Y + 1, Selection)
      finally
        FPreserveDesiredCol := false;
      end;
    end
  else
    IssueInputError;
end;

function TTextFile.Empty: boolean;
begin
  result := (length(FLines) = 1) and (length(FLines[0]) = 0);
end;

procedure TTextFile.ApplyUndoRecord(const UndoData: TUndoDataItem);
begin
  SetText(UndoData.Text, UndoData.Classes);
  FBookmarks := UndoData.Bookmarks;
  FCaretPos.CreateSelection(UndoData.SelStartPos, UndoData.CaretPos, UndoData.SelType);
end;

procedure TTextFile.EndAddFindData;
begin
  SetLength(FFindData, FFindDataActualLength);
end;

procedure TTextFile.EndAddLine;
begin
  FMultiAddLineMode := false;
  LineArrayChanged;
  Changed(ctFile);
  GotoEOF;
  Modified;
end;

function TTextFile.FillWithChar(const AChar: char): boolean;
begin
  result := ChrTransform(function(C: char): char begin result := AChar end);
end;

function TTextFile.LineMatches(LineIndex: integer; const ACriteria: TFilterOptions): boolean;
begin
  result := true;
  if ACriteria.MatchCase then
  begin
    if ACriteria.Contains <> '' then
      result := result and ContainsStr(FLines[LineIndex], ACriteria.Contains);
    if ACriteria.StartsWith <> '' then
      result := result and StartsStr(ACriteria.StartsWith, FLines[LineIndex]);
    if ACriteria.EndsWith <> '' then
      result := result and EndsStr(ACriteria.EndsWith, FLines[LineIndex]);
  end
  else
  begin
    if ACriteria.Contains <> '' then
      result := result and ContainsText(FLines[LineIndex], ACriteria.Contains);
    if ACriteria.StartsWith <> '' then
      result := result and StartsText(ACriteria.StartsWith, FLines[LineIndex]);
    if ACriteria.EndsWith <> '' then
      result := result and EndsText(ACriteria.EndsWith, FLines[LineIndex]);
  end
end;

procedure TTextFile.Filter(const AFilterOptions: TFilterOptions);
var
  SL: TStringList;
  i: Integer;
  HasBookmarks, BMCh: boolean;
  BMc: integer;
begin

  if EditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FControlAware then
  begin
    IssueInputError;
    Exit;
  end;

  HasBookmarks := Self.HasBookmarks;
  BMCh := false;
  BMc := 0;

  SL := TStringList.Create;
  try
    SL.Capacity := LineCount;
    SL.BeginUpdate;

    for i := 0 to LineCount - 1 do
      if LineMatches(i, AFilterOptions) xor AFilterOptions.RemoveMatchingLines then
        SL.Add(FLines[i])
      else if HasBookmarks then
      begin
        BMCh := DeleteBookmarksOnLine(i - BMc) or BMCh;
        BMCh := TushBookmarksInternal(i - BMc, -1) or BMCh;
        inc(BMc);
      end;

    SL.EndUpdate;

    SetLength(FLines, SL.Count);
    SetLength(FClasses, SL.Count);

    for i := 0 to SL.Count - 1 do
    begin
      FLines[i] := SL.Strings[i];
      FClasses[i] := '';
    end;

    if Length(FLines) = 0 then
      InternalAddLine('', '');

    LineArrayChanged;
    Changed(ctFile);
    GotoSOF;
    Modified;

    if BMCh then BookmarksMoved;

  finally
    SL.Free;
  end;

end;

function IsNoncharacter(C: char): boolean;
begin
  result := InRange(ord(C), $FDD0, $FDEF) or (ord(C) = $FFFE) or (ord(C) = $FFFF);
end;

function TTextFile.Find(AFindData: TFindQuery; AInternal: boolean = false): integer;

  procedure CheckWordAndAddFindData(const A, B: TPoint);
  begin
    if

      (not AFindData.MatchWord)

      or
      (
        ({word sep at A}

          (A.X = 0) or not FLines[A.Y][A.X-1+1].IsLetterOrDigit

        )

        and

        ({word sep at B}

          (B.X = VirtualLineWidths[B.Y]) or not FLines[B.Y][B.X+1].IsLetterOrDigit

        )
      )

    then
      AddFindData(A, B);
  end;

var
  WithinLines, NoMatch: boolean;
  len, i, j, p, y, x: Integer;
  SearchLines: DynStringArray;
  LowerCaseLines: array of string;
label
  Finish;
begin
  result := 0;

  if HasQueryResult(AFindData) then Exit(Length(FFindData));

  FFindQuery := AFindData;

  ClearFindData;

  if AFindData.UCBlock <> FQ_NULL then
  begin
    if not InRange(AFindData.UCBlock, FQ_MIN, UCD.BlockCount - 1) then
      Exit;

    for y := 0 to Length(FLines) - 1 do
    begin
      if IsControlLine(y) then
        Continue;

      for x := 1 to Length(FLines[y]) do
        case AFindData.UCBlock of
          FQ_NONASCII:
            if ord(FLines[y][x]) > 127 then
              AddFindData(Point(x - 1, y));
          FQ_CONTROL:
            if FLines[y][x].IsControl then
              AddFindData(Point(x - 1, y));
          FQ_NONCHAR:
            if IsNoncharacter(FLines[y][x]) then
              AddFindData(Point(x - 1, y));
        else
          with UCD.Blocks[AFindData.UCBlock - 1] do
            if InRange(ord(FLines[y][x]), BlockBegin, BlockEnd) then
              AddFindData(Point(x - 1, y));
        end;
    end;

    goto Finish;
  end;

  len := Length(AFindData.SearchString);
  WithinLines := (not AFindData.Linebreak) or (Pos('\n', AFindData.SearchString) = 0);

  if AFindData.MatchCase then
    DynStringArray(LowerCaseLines) := DynStringArray(FLines)
  else
  begin
    AFindData.SearchString := AnsiLowerCase(AFindData.SearchString);
    SetLength(LowerCaseLines, LineCount);
    for i := 0 to LineCount - 1 do
      LowerCaseLines[i] := AnsiLowerCase(FLines[i]);
  end;

  if WithinLines then
  begin
    for i := 0 to GetLineCount - 1 do
    begin
      if FControlAware and IsControlLine(i) then Continue;
      p := 1 - Length(AFindData.SearchString);
      repeat
        p := PosEx(AFindData.SearchString, LowerCaseLines[i], p + Length(AFindData.SearchString));
        if p > 0 then
          CheckWordAndAddFindData(Point(p-1, i), Point(p-1+len, i));
      until p = 0;
    end;
  end
  else
  begin
    SearchLines := Split(AFindData.SearchString, '\n');
    for i := 0 to GetLineCount - 1 do
    begin
      p := PhysicalLineWidths[i] - Length(SearchLines[0]) + 1;
      if SameStr(SearchLines[0], Copy(LowerCaseLines[i], p)) then
      begin
        if IsControlLine(i) then Continue;
        NoMatch := false;
        for j := 1 to High(SearchLines) do
          if (i + j >= LineCount)
                  or
             ((j < High(SearchLines)) and not SameStr(SearchLines[j], LowerCaseLines[i + j]))
                  or
             ((j = High(SearchLines)) and not SameStr(SearchLines[j], Copy(LowerCaseLines[i + j], 1, Length(SearchLines[j]))))
                  or
             IsControlLine(i + j) then
          begin
            NoMatch := true;
            break;
          end;
        if not NoMatch then
          CheckWordAndAddFindData(Point(p-1, i), Point(Length(SearchLines[High(SearchLines)]), i + High(SearchLines)));
      end;
    end;
  end;

Finish:

  EndAddFindData;
  result := Length(FFindData);
  FFindResultValid := true;

end;

function TTextFile.IsWrappable(const AChar: char): boolean;
var
  i: Integer;
begin
  result := false;
  for i := 1 to Length(FWrapAt) do
    if AChar = FWrapAt[i] then
      Exit(true);
end;

procedure TTextFile.FindWhereToWrap(ALineIndex, MaxLength: integer;
  var AWrapList: TIntegerDynArray);
const
  ALLOC_BY = 32;
var
  ActualLength: integer;
  procedure Add(X: integer);
  begin
    if ActualLength = Length(AWrapList) then
      SetLength(AWrapList, Length(AWrapList) + ALLOC_BY);
    AWrapList[ActualLength] := X;
    inc(ActualLength);
  end;

  procedure Trim;
  begin
    SetLength(AWrapList, ActualLength);
  end;

  function LastBreak: integer;
  begin
    if ActualLength > 0 then
      result := AWrapList[ActualLength - 1]
    else
      result := 0;
  end;

var
  OpportunityFound: boolean;
  x: integer;
  LineLength: integer;

begin
  SetLength(AWrapList, 0);
  if MaxLength <= 0 then Exit;
  ActualLength := 0;

  LineLength := VirtualLineWidths[ALineIndex];

  while LineLength > LastBreak + MaxLength do
  begin
    OpportunityFound := false;
    for x := LastBreak + MaxLength downto LastBreak + 1 do
      if IsWrappable(Character[ALineIndex, x]) then
      begin
        if (x = LastBreak + MaxLength) and (Character[ALineIndex, x] <> #32) then Continue;
        Add(x + 1);
        OpportunityFound := true;
        break;
      end;
    if not OpportunityFound then
      Add(LastBreak + MaxLength);
  end;

  Trim;
end;

function TTextFile.GetIndent(LineIndex: integer): integer;
var
  i: Integer;
begin
  // Special case: virtual space
  if FCaretAfterEOL and LineIsEmpty(LineIndex) then
    Exit(FCaretPos.X);

  // General case
  for i := 1 to VirtualLineWidths[LineIndex] do
    if FLines[LineIndex][i] <> #32 then
      Exit(i - 1);
  result := VirtualLineWidths[LineIndex];
end;

function TTextFile.LineIsEmpty(const LineIndex: integer): boolean;
begin
  result := Length(FLines[LineIndex]) = 0;
end;

function TTextFile.Redo: boolean;
var
  UndoData: TUndoDataItem;
begin
  result := FHistoryManager.Redo(UndoData);
  if not result then Exit;
  ApplyUndoRecord(UndoData);
end;

procedure TrimLeftInplace(var S: string; out Len: integer);
begin
  Len := 0;
  while (Len + 1 <= Length(S)) and (S[Len + 1] = #32) do inc(Len);
  if Len > 0 then Delete(S, 1, Len);
end;

procedure TTextFile.RemoveAllIndent;
var
  FirstPoint, SecondPoint: TPoint;
  i, len: Integer;
  HasBookmarks, BMCh: boolean;
begin
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FirstPoint.Y < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  HasBookmarks := Self.HasBookmarks;
  BMCh := false;

  for i := FirstPoint.Y to SecondPoint.Y do
  begin
    TrimLeftInplace(FLines[i], len);
    if HasBookmarks and (len > 0) then
      BMCh := PushBookmarksInternal(i, -len) or BMCh;
  end;
  FCaretPos.SetX(0);
  Changed(ctLineRange, FirstPoint.Y, SecondPoint.Y);
  Modified;

  if BMCh then BookmarksMoved;
end;

procedure TTextFile.RemoveIndent;
var
  FirstPoint, SecondPoint: TPoint;
  i: Integer;
  IndentStep: string;
  LastLinePushed: boolean;
  HasBookmarks, BMCh: boolean;
begin
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FirstPoint.Y < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  HasBookmarks := Self.HasBookmarks;
  BMCh := false;

  IndentStep := DupeString(#32, FIndentSize);
  LastLinePushed := SameStr(Copy(FLines[SecondPoint.Y], 1, FIndentSize), IndentStep);
  for i := FirstPoint.Y to SecondPoint.Y do
    if not (FControlAware and IsControlLine(i)) then
      if SameStr(Copy(FLines[i], 1, FIndentSize), IndentStep) then
      begin
        System.Delete(FLines[i], 1, FIndentSize);
        if HasBookmarks then
          BMCh := PushBookmarksInternal(i, -FIndentSize) or BMCh;
      end;
  FCaretPos.InternalPush(-FIndentSize, LastLinePushed);
  Changed(ctLineRange, FirstPoint.Y, SecondPoint.Y);
  Modified;

  if BMCh then BookmarksMoved;
end;

procedure TTextFile.ReplaceInLineSameWidth(const ReplaceText: string);
var
  i: Integer;
begin
  for i := low(FFindData) to high(FFindData) do
    Move(ReplaceText[1], FLines[FFindData[i].A.Y][FFindData[i].A.X + 1],
      Length(ReplaceText) * SizeOf(char));
end;

procedure TTextFile.ReplaceInLineDiffWidth(const ReplaceText: string);
var
  LineMatches: array of integer;
  diff, i: Integer;
  PrevCurLine: integer;
  NewLine: string;
  OriginalOffset, NewOffset: integer;
begin

  diff := Length(ReplaceText) - Length(FFindQuery.SearchString);

  // Step 1: count matches per line
  SetLength(LineMatches, LineCount);
  for i := 0 to LineCount - 1 do
    LineMatches[i] := 0;
  for i := low(FFindData) to high(FFindData) do
    inc(LineMatches[FFindData[i].A.Y]);

  // Step 2: build new lines
  PrevCurLine := -1;
  OriginalOffset := 0;  // zero-based index of next char to be read
  NewOffset := 0;       // zero-based index of next char to be set
  for i := low(FFindData) to high(FFindData) do
  begin
    if PrevCurLine <> FFindData[i].A.Y then
    begin
      // Complete and set previous line
      if PrevCurLine <> -1 then
      begin
        Move(FLines[PrevCurLine][OriginalOffset + 1], NewLine[NewOffset + 1], (VirtualLineWidths[PrevCurLine] - OriginalOffset) * SizeOf(char));
        FLines[PrevCurLine] := NewLine;
      end;
      // Begin new line
      SetLength(NewLine, Length(FLines[FFindData[i].A.Y]) + LineMatches[FFindData[i].A.Y] * diff);
      NewOffset := 0;
      Move(FLines[FFindData[i].A.Y][1], NewLine[NewOffset + 1], FFindData[i].A.X * SizeOf(char));
      NewOffset := FFindData[i].A.X;
      Move(ReplaceText[1], NewLine[NewOffset + 1], Length(ReplaceText) * SizeOf(char));
      inc(NewOffset, Length(ReplaceText));
      OriginalOffset := FFindData[i].A.X + Length(FFindQuery.SearchString);
      PrevCurLine := FFindData[i].A.Y;
    end
    else
    begin
      Move(FLines[FFindData[i].A.Y][OriginalOffset + 1], NewLine[NewOffset + 1], (FFindData[i].A.X - OriginalOffset) * SizeOf(char));
      inc(NewOffset, FFindData[i].A.X - OriginalOffset);
      Move(ReplaceText[1], NewLine[NewOffset + 1], Length(ReplaceText) * SizeOf(char));
      inc(NewOffset, Length(ReplaceText));
      OriginalOffset := FFindData[i].A.X + Length(FFindQuery.SearchString);
    end;
  end;
  // Complete and set last line
  if Length(FFindData) > 0 then
  begin
    Move(FLines[PrevCurLine][OriginalOffset + 1], NewLine[NewOffset + 1], (VirtualLineWidths[PrevCurLine] - OriginalOffset) * SizeOf(char));
    FLines[PrevCurLine] := NewLine;
  end;
end;

procedure TTextFile.ReplaceMultilineSameWidth(const ReplaceText: string);
var
  S: string;
  ParsedReplaceText: string;
  i: Integer;
  ALW: array of integer;
  LW: integer;
begin

  LW := 0;
  SetLength(ALW, Length(FLines));
  for i := 0 to Length(FLines) - 1 do
  begin
    ALW[i] := LW;
    inc(LW, Length(FLines[i]) + Length(#13#10));
  end;

  S := GetText;
  ParsedReplaceText := StringReplace(ReplaceText, '\n', #13#10, [rfReplaceAll]);
  for i := low(FFindData) to high(FFindData) do
    Move(ParsedReplaceText[1], S[ALW[FFindData[i].A.Y] + FFindData[i].A.X + 1],
      Length(ParsedReplaceText) * SizeOf(char));
  SetText(S);
end;

procedure TTextFile.ReplaceMultilineDiffWidth(const ReplaceText: string);
var
  S, S2: string;
  ParsedReplaceText: string;
  diff: integer;
  OriginalOffset, NewOffset: integer;
  i, index: Integer;
  ALW: array of integer;
  LW: integer;
begin

  LW := 0;
  SetLength(ALW, Length(FLines));
  for i := 0 to Length(FLines) - 1 do
  begin
    ALW[i] := LW;
    inc(LW, Length(FLines[i]) + Length(#13#10));
  end;

  S := GetText;
  ParsedReplaceText := StringReplace(ReplaceText, '\n', #13#10, [rfReplaceAll]);
  diff := Length(ReplaceText) - Length(FFindQuery.SearchString);
  SetLength(S2, Length(S) + Length(FFindData) * diff);
  OriginalOffset := 0;
  NewOffset := 0;
  for i := low(FFindData) to high(FFindData) do
  begin
    index := ALW[FFindData[i].A.Y] + FFindData[i].A.X;
    Move(S[OriginalOffset + 1], S2[NewOffset + 1], (index - OriginalOffset) * SizeOf(char));
    inc(NewOffset, index - OriginalOffset);
    Move(ParsedReplaceText[1], S2[NewOffset + 1], Length(ParsedReplaceText) * SizeOf(char));
    inc(NewOffset, Length(ParsedReplaceText));
    OriginalOffset := index + Length(FFindQuery.SearchString);
  end;
  Move(S[OriginalOffset + 1], S2[NewOffset + 1], (ALW[high(ALW)] + Length(FLines[high(FLines)]) - OriginalOffset) * SizeOf(char));
  SetText(S2);
end;

procedure TTextFile.IntersectFindDataWithSelection;
var
  i: integer;
  tmp: TFindData;
  ActualLength: integer;
  FirstPoint, SecondPoint: TPoint;

  function IsSel(const AChr: TPoint): boolean;
  begin
    result := IsCharInRgn(AChr, FCaretPos.SelectionType, FirstPoint, SecondPoint)
  end;

begin
  SetLength(tmp, Length(FFindData));
  ActualLength := 0;
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  for i := low(FFindData) to high(FFindData) do
    if IsSel(FFindData[i].A) and IsSel(PrevChar(FFindData[i].B)) then
    begin
      tmp[ActualLength] := FFindData[i];
      inc(ActualLength);
    end;
  SetLength(FFindData, ActualLength);
  Move(tmp[0], FFindData[0], ActualLength * sizeof(TTextSpan));
end;

function TTextFile.ReplaceAll(const ReplaceText: string; SelOnly: boolean = false): integer;
var
  FirstPoint, SecondPoint: TPoint;
begin

  result := -1;

  if FEditMode = emReadOnly then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FSingleLine and FFindQuery.Linebreak then
  begin
    IssueInputError;
    Exit;
  end;

  if SelOnly then
  begin
    FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
    IntersectFindDataWithSelection;
  end;

  result := Length(FFindData);

  if not FFindQuery.Linebreak then
  begin
    if Length(FFindQuery.SearchString) = Length(ReplaceText) then
      ReplaceInLineSameWidth(ReplaceText)
    else
      ReplaceInLineDiffWidth(ReplaceText);
  end
  else
  begin      { assumption: Length('\n') = Length(#13#10) }
    if Length(FFindQuery.SearchString) = Length(ReplaceText) then
      ReplaceMultilineSameWidth(ReplaceText)
    else
      ReplaceMultilineDiffWidth(ReplaceText);
  end;

  InternalClearFindData;

  if result > 0 then
  begin
    if FFindQuery.Linebreak then LineArrayChanged;

    if SelOnly then
    begin
      FCaretPos.SetPoint(FirstPoint);
      Changed(ctLineRange, FirstPoint.Y, SecondPoint.Y);
    end
    else
    begin
      Changed(ctFile);
      GotoSOF;
    end;

    Modified;
  end;
end;

function TTextFile.ReplaceCodepoint: boolean;
var
  PWB: integer;
  S: string;
  V: integer;
begin
  result := false;

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and not AtLastLine) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  PWB := PrevWordBoundary;
  S := Copy(FLines[FCaretPos.Y], PWB + 1, FCaretPos.X - PWB);
  if TryStrToInt('$' + S, V) then
  begin
    System.Delete(FLines[FCaretPos.Y], PWB + 1, Length(S));
    Insert(Chr(V), FLines[FCaretPos.Y], PWB + 1);
    FCaretPos.SetX(FCaretPos.X - Length(S) + 1);
    Changed(ctLineFrom, FCaretPos.Y, FCaretPos.X - 1);
    Modified;
    result := true;
  end
  else
    IssueInputError;
end;

function TTextFile.GetCurrentClass: string;
begin
  result := FClasses[FCaretPos.Y];
end;

function TTextFile.GetDecoratedControlText(LineIndex: integer): string;
begin
  result := '[' + GetControlText(LineIndex) + ']';
end;

function TTextFile.GetEmptyBookmarkIndex: integer;
var
  i: Integer;
begin
  result := -1;
  for i := 0{sic!} to high(FBookmarks) do
    if SamePoint(FBookmarks[i], EMPTY_BOOKMARK) then
      Exit(i);
end;

procedure TTextFile.Return;
var
  indentLength: integer;
begin
  if EditMode = emReadOnly then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FSingleLine or (EditMode = emReadOnly) or ((EditMode = emConsole) and not AtLastLine) then
  begin
    IssueInputError;
    Exit;
  end;

  if HasSelection then
    ClearSelection;

  if FControlAware and IsControlLine then
  begin
    if FCaretPos.X = 0 then
    begin
      InternalInsertLine(FCaretPos.Y, '', '');
      RushBookmarks(FCaretPos.Data);
      LineArrayChanged;
      FCaretPos.SetPoint(0, FCaretPos.Y + 1);
      Changed(ctLineRange, FCaretPos.Y - 1, LineCount - 1);
    end
    else
    begin
      InternalInsertLine(FCaretPos.Y + 1, '', '');
      RushBookmarks(FCaretPos.Data);
      LineArrayChanged;
      FCaretPos.SetPoint(0, FCaretPos.Y + 1);
      Changed(ctLineRange, FCaretPos.Y - 1, LineCount - 1);
    end;
    Modified;
    Exit;
  end;

  if AtEOF then
  begin
    InternalAddLine(GetIndentOnReturn(indentLength), GetCurrentClass);
    RushBookmarks(FCaretPos.Data);
    LineArrayChanged;
    FCaretPos.SetPoint(indentLength, FCaretPos.Y + 1);
    Changed(ctLine, LineCount - 1, 0);
  end
  else if AtLastLine then
  begin
    InternalAddLine(GetIndentOnReturn(indentLength) + LineToRight, GetCurrentClass);
    FLines[FCaretPos.Y] := Copy(FLines[FCaretPos.Y], 1, FCaretPos.X);
    RushBookmarks(FCaretPos.Data);
    LineArrayChanged;
    FCaretPos.SetPoint(indentLength, FCaretPos.Y + 1);
    Changed(ctLineRange, FCaretPos.Y - 1, FCaretPos.Y);
  end
  else
  begin
    InternalInsertLine(FCaretPos.Y + 1, GetIndentOnReturn(indentLength) + Copy(FLines[FCaretPos.Y], FCaretPos.X + 1), FClasses[FCaretPos.Y]);
    FLines[FCaretPos.Y] := Copy(FLines[FCaretPos.Y], 1, FCaretPos.X);
    RushBookmarks(FCaretPos.Data);
    LineArrayChanged;
    FCaretPos.SetPoint(indentLength, FCaretPos.Y + 1);
    Changed(ctLineRange, FCaretPos.Y - 1, LineCount - 1, 1);
  end;
  Modified;
end;

procedure TTextFile.InternalAddLine(const ALine: string; const AClassName: string);
begin
  SetLength(FLines, Length(FLines) + 1);
  SetLength(FClasses, Length(FClasses) + 1);
  FLines[High(FLines)] := ALine;
  FClasses[High(FClasses)] := AClassName;
end;

procedure TTextFile.InternalAddLines(const NumLines: integer);
var
  i: Integer;
begin
  SetLength(FLines, Length(FLines) + NumLines);
  SetLength(FClasses, Length(FClasses) + NumLines);
  for i := LineCount - NumLines to LineCount - 1 do
  begin
    FLines[i] := '';
    FClasses[i] := '';
  end;
end;

procedure TTextFile.InternalDeleteLine(const LineIndex: integer);
begin
  InternalDeleteLines(LineIndex, 1);
end;

procedure TTextFile.InternalDeleteLines(const LineIndex, NumLines: integer);
var
  i: Integer;
begin
  for i := LineIndex to LineCount - NumLines - 1 do
  begin
    FLines[i] := FLines[i + NumLines];
    FClasses[i] := FClasses[i + NumLines];
  end;
  SetLength(FLines, Length(FLines) - NumLines);
  SetLength(FClasses, Length(FClasses) - NumLines);
end;

procedure TTextFile.InternalInsertLine(const LineIndex: integer;
  const ALine: string; const AClassName: string);
var
  i: Integer;
begin
  InternalAddLine('', '');
  for i := LineCount - 1 downto LineIndex + 1 do
  begin
    FLines[i] := FLines[i - 1];
    FClasses[i] := FClasses[i - 1];
  end;
  FLines[LineIndex] := ALine;
  FClasses[LineIndex] := AClassName;
end;

procedure TTextFile.InternalInsertLines(const LineIndex, NumLines: integer);
var
  i: integer;
begin
  InternalAddLines(NumLines);
  for i := LineCount - 1 downto LineIndex + NumLines do
  begin
    FLines[i] := FLines[i - NumLines];
    FClasses[i] := FClasses[i - NumLines];
  end;
  for i := LineIndex to LineIndex + NumLines - 1 do
  begin
    FLines[i] := '';
    FClasses[i] := '';
  end;
end;

procedure TTextFile.InternalSwapLines(FirstLine, SecondLine: integer;
  BookmarkAware: boolean = true);
var
  tmpLine: string;
  tmpClass: string;
begin
  tmpLine := FLines[FirstLine];
  tmpClass := FClasses[FirstLine];
  FLines[FirstLine] := FLines[SecondLine];
  FClasses[FirstLine] := FClasses[SecondLine];
  FLines[SecondLine] := tmpLine;
  FClasses[SecondLine] := tmpClass;

  if BookmarkAware then
    SushBookmarks(FirstLine, SecondLine, true);
end;

function TTextFile.IsCharInRgn(X, Y: integer; SelectionType: TSelectionType; const FirstPoint, SecondPoint: TPoint): boolean;
begin
  case SelectionType of
    stLineBased:
      result := ((FirstPoint.Y = SecondPoint.Y) and (Y = FirstPoint.Y) and
                      InRange(X, FirstPoint.X, SecondPoint.X - 1))
                or
                ((FirstPoint.Y < SecondPoint.Y) and (
                      InRange(Y, FirstPoint.Y + 1, SecondPoint.Y - 1) or
                      ((Y = FirstPoint.Y) and (X >= FirstPoint.X)) or
                      ((Y = SecondPoint.Y) and (X < SecondPoint.X))
                      )
                );
    stBlock:
      result := InRange(X, FirstPoint.X, SecondPoint.X - 1) and InRange(Y, FirstPoint.Y, SecondPoint.Y);
  else
    result := false;
  end;
end;

function TTextFile.IsCharSel(const X, Y: integer): boolean;
var
  FirstPoint, SecondPoint: TPoint;
begin
  if not CharacterExistsEx(Y, X) then Exit(false); // typically beyond EOL
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  result := IsCharInRgn(X, Y, FCaretPos.SelectionType, FirstPoint, SecondPoint);
end;

function TTextFile.IsCharFound(const X, Y: integer): boolean;
var
  i: Integer;
begin
  result := false;
  for i := 0 to Length(FFindData) - 1 do
    if ((FFindData[i].A.Y = FFindData[i].B.Y) and (Y = FFindData[i].A.Y) and
             InRange(X, FFindData[i].A.X, FFindData[i].B.X - 1))
       or
       ((FFindData[i].A.Y < FFindData[i].B.Y) and (
             InRange(Y, FFindData[i].A.Y + 1, FFindData[i].B.Y - 1) or
             ((Y = FFindData[i].A.Y) and (X >= FFindData[i].A.X)) or
             ((Y = FFindData[i].B.Y) and (X < FFindData[i].B.X))
             )
       ) then
         Exit(true);
end;

function TTextFile.IsCharInRgn(const Point: TPoint; SelectionType: TSelectionType;
  const FirstPoint, SecondPoint: TPoint): boolean;
begin
  result := IsCharInRgn(Point.X, Point.Y, SelectionType, FirstPoint, SecondPoint);
end;

function TTextFile.IsCharSel(const Point: TPoint): boolean;
begin
  result := IsCharSel(Point.X, Point.Y);
end;

function TTextFile.IsControlLine(LineIndex: integer): boolean;
begin
  result := SameStr(FClasses[LineIndex], LINE_CONTROL_CLASS);
end;

function TTextFile.IsControlLine: boolean;
begin
  result := SameStr(FClasses[FCaretPos.Y], LINE_CONTROL_CLASS);
end;

procedure TTextFile.IssueInputError;
begin
  if Assigned(FOnInputError) then
    FOnInputError(Self);
  Abort;
end;

procedure TTextFile.IssueReadOnlyError;
begin
  if Assigned(FOnReadOnlyError) then
    FOnReadOnlyError(Self);
  Abort;
end;

function TTextFile.CurrentLine: string;
begin
  result := FLines[FCaretPos.Y];
end;

procedure TTextFile.CutToClipboard;
begin
  Clipboard.AsText := GetSelText;
  ClearSelection;
end;

function TTextFile.LineToLeft: string;
begin
  result := Copy(FLines[FCaretPos.Y], 1, FCaretPos.X);
end;

function TTextFile.LineToRight: string;
begin
  result := Copy(FLines[FCaretPos.Y], FCaretPos.X + 1);
end;

procedure TTextFile.InternalZero;
begin
  SetLength(FLines, 0);
  SetLength(FClasses, 0);
  ClearBookmarks;
  FHistoryManager.Clear;
  // This state is invalid and must be handled immediately.
end;

procedure TTextFile.LoadFromFile(const FileName: TFileName;
  Encoding: TEncoding; ClassAware: boolean = false);
var
  FS: TFileStream;
  SR: TStreamReader;
  ActualLength: integer;
  L: string;
  p: integer;
  LineHasClass: boolean;

  hresult: boolean;
  PositiveEncoding: TTextEncoding;
  PossibleEncodings, MagicWordsFound: TTextEncodings;
const
  ALLOC_BY = 2048;
begin

  try

    p := 0; // stupid compiler

    ClearFindData;
    InternalZero;
    ActualLength := 0;

    if Encoding = nil then
    begin
      hresult := GuessEncodingOfFile(FileName, PositiveEncoding, PossibleEncodings, MagicWordsFound);
      if not hresult then
        PositiveEncoding := teWindows8bitCodepage;
    end;

    FS := TFileStream.Create(FileName, fmOpenRead);
    try
      if Assigned(Encoding) then
        SR := TStreamReader.Create(FS, Encoding)
      else
        SR := TStreamReader.Create(FS, GetVCLEncoding(PositiveEncoding));
      try
        while not SR.EndOfStream do
        begin
          if Length(FLines) = ActualLength then
          begin
            SetLength(FLines, Length(FLines) + ALLOC_BY);
            SetLength(FClasses, Length(FClasses) + ALLOC_BY);
          end;

          if ClassAware then
          begin
            L := SR.ReadLine;

            LineHasClass := false;
            if (Length(L) > 0) and (L[1] = LINE_CLASS_INDICATOR) then
            begin
              p := PosEx(LINE_CLASS_INDICATOR, L, 2);
              if p > 0 then
                LineHasClass := true;
            end;

            if LineHasClass then
            begin
              FLines[ActualLength] := Copy(L, p + 1);
              FClasses[ActualLength] := Copy(L, 2, p - 2);
            end
            else
            begin
              FLines[ActualLength] := L;
              FClasses[ActualLength] := '';
            end;

          end
          else
          begin
            FLines[ActualLength] := SR.ReadLine;
            FClasses[ActualLength] := '';
          end;

          inc(ActualLength);
        end;
        SetLength(FLines, ActualLength);
        SetLength(FClasses, ActualLength);
      finally
        SR.Free;
      end;
    finally
      FS.Free;
    end;

    if Length(FLines) = 0 then
      InternalAddLine('', '');

    FFileName := FileName;
    FModified := false;
    FControlAware := false;
    FEncoding := DEFAULT_TEXT_FILE_FORMAT_INFO;
    if Assigned(Encoding) then
      FEncoding.TextEncoding := GetEncodingFromVCL(Encoding)
    else
    begin
      FEncoding.TextEncoding := PositiveEncoding;
      FEncoding.SetHasMagicWord(MagicWordsFound);
    end;
    FRecentlyOpened := true;

    FCaretPos.SetPoint(0, 0);
    Changed(ctFile);

  except
    // Unknown (and thus unrecoverable) error during file load:
    // create a new document just to have a valid state.
    NewFileAndInitUndo;
    raise;
  end;

end;

procedure TTextFile.LoadFromFileAndInitUndo(const FileName: TFileName;
  Encoding: TEncoding);
begin
  LoadFromFile(FileName, Encoding);
  AddUndoRecord(SUndoDocumentLoaded, UID_UNKNOWN);
end;

procedure TTextFile.LoadFromStream(AStream: TStream);
var
  Header: TStreamHeader;
  Counts: array of packed record
    LineText, LineClass: integer;
  end;
  i: Integer;
  data_dword: DWORD;
  data_char: char;
begin

  FillChar(Header, sizeof(Header), 0);
  AStream.ReadBuffer(Header, sizeof(Header));

  if Header.Signature <> TEXTFILE_SIGNATURE then
    raise Exception.Create('TTextFile.LoadFromStream: Invalid text file stream.');

  NewFileAndInitUndo;

  try

    SetLength(FLines, Header.LineCount);
    SetLength(FClasses, Header.LineCount);

    SetLength(Counts, Header.LineCount);
    if Length(Counts) > 0 then
      AStream.ReadBuffer(Counts[0], Length(Counts) * sizeof(Counts[0]));

    for i := 0 to Header.LineCount - 1 do
    begin
      SetLength(FLines[i], Counts[i].LineText);
      SetLength(FClasses[i], Counts[i].LineClass);
    end;

    for i := 0 to Header.LineCount - 1 do
    begin
      if not FLines[i].IsEmpty then
        AStream.ReadBuffer(FLines[i][1], FLines[i].Length * sizeof(char));
      if not FClasses[i].IsEmpty then
        AStream.ReadBuffer(FClasses[i][1], FClasses[i].Length * sizeof(char));
    end;

    AStream.ReadData(data_dword);
    if data_dword <> TEXTFILE_SIGNATURE_FPCACHE then
      raise Exception.Create('TTextFile.LoadFromStream: Invalid text file stream.');

    AStream.ReadData(FEditorState.FFPCacheLen);
    GetMem(FEditorState.FFPCache, FEditorState.FFPCacheLen);
    try
      AStream.ReadBuffer(FEditorState.FPCache^, FEditorState.FPCacheLen);
    except
      FreeMem(FEditorState.FFPCache);
      FEditorState.FFPCacheLen := 0;
      FEditorState.FFPCache := nil;
      raise;
    end;

    FHistoryManager.LoadFromStream(AStream);

    AStream.ReadData(data_dword);
    AStream.ReadData(data_char);
    if (data_dword <> TEXTFILE_SIGNATURE) or (data_char <> #0) then
      raise Exception.Create('TTextFile.LoadFromStream: Invalid text file stream.');

    FEditMode := Header.EditMode;
    FModified := Header.Modified;
    FFileName := Header.FileName;
    FBookmarks := Header.Bookmarks;
    FEditorState.ScrollPos := Header.ScrollPos;
    FEditorState.MultiSize := Header.MultiSize;
    FEditorState.Overwrite := Header.Overwrite;
    FEditorState.HiddenChrs := Header.HiddenChars;
    FEditorState.RulerVisible := Header.RulerVisible;
    FEditorState.ZoomLevel := Header.ZoomLevel;
    FEditorState.FormattingProcessor := Header.FPClassName;
    FEditorState.Valid := true;
    FEncoding := Header.Encoding;
    FRecentlyOpened := Header.RecentlyOpened;
    FStrictReadOnly := Header.StrictReadOnly;
    FUseLineClasses := Header.UseLineClasses;

    FCaretPos.CreateSelection(Header.CaretPos, Header.SelEndPos, Header.SelectionType);

    Changed(ctFile);
    BookmarksMoved;

  except
    NewFileAndInitUndo; // don't leave the text file in a possibly invalid state
    raise;
  end;

end;

procedure TTextFile.LoadFromBuffer(const Data: pointer; const Len: UInt64);
var
  MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  try
    MS.WriteBuffer(Data^, Len);
    MS.Position := 0;
    LoadFromStream(MS);
  finally
    MS.Free;
  end;
end;

function TTextFile.MakeLinesUnique: boolean;
var
  LC: integer;
  y: integer;
  i: integer;
  RemoveList: array of boolean;
  LinesRemoved: integer;
  NextExistingLine: integer;
  HasBookmarks: boolean;
  j: Integer;
label
  Done;

begin

  result := false;

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  LC := LineCount;

  HasBookmarks := Self.HasBookmarks;

  SetLength(RemoveList, LC);
  FillChar(RemoveList[0], Length(RemoveList) * Sizeof(Boolean), 0);

  LinesRemoved := 0;
  for y := 0 to LC - 1 do
    if not RemoveList[y] then
      for i := y + 1 to LC - 1 do
        if (not RemoveList[i]) and SameStr(FLines[y], FLines[i]) then
        begin
          RemoveList[i] := true;
          inc(LinesRemoved);

          if HasBookmarks then
            for j := low(FBookmarks) to high(FBookmarks) do
              if FBookmarks[j].Y = i then
                FBookmarks[j].Y := y;

        end;

  NextExistingLine := 0;
  for y := 0 to LC - 1 do
    if RemoveList[y] then
      for i := Max(y + 1, NextExistingLine) to LC - 1 do
      begin
        if not RemoveList[i] then
        begin
          FLines[y] := FLines[i];
          FClasses[y] := FClasses[i];
//          RemoveList[y] := false;
          if HasBookmarks then
            for j := low(FBookmarks) to high(FBookmarks) do
              if FBookmarks[j].Y = i then
                FBookmarks[j].Y := y;
          RemoveList[i] := true;
          NextExistingLine := i + 1;
          break;
        end;
        if i = LC - 1 then
          goto Done;
      end;

Done:

  result := LinesRemoved > 0;
  if not result then Exit;

  SetLength(FLines, LC - LinesRemoved);
  SetLength(FClasses, LC - LinesRemoved);

  LineArrayChanged;
  Changed(ctFile);
  CaretPos.SetPoint(0, 0);
  LineClassChanged(0);
  Modified;

  if HasBookmarks then BookmarksMoved;

end;

function TTextFile.MatchBracket(const BracketPoint: TPoint): TPoint;

const
  LeftBrackets: array[0..3] of char = ('(', '[', '{', '❨');
  RightBrackets: array[0..3] of char = (')', ']', '}', '❩');

var
  bracket: char;
  i, BracketType, direction, depth: Integer;
begin
  bracket := GetChar(BracketPoint);

  BracketType := -1;
  direction := 0;
  for i := low(LeftBrackets) to high(LeftBrackets) do
    if LeftBrackets[i] = bracket then
    begin
      direction := 1;
      BracketType := i;
      break;
    end
    else if RightBrackets[i] = bracket then
    begin
      direction := -1;
      BracketType := i;
      break;
    end;

  if BracketType = -1 then Exit(Point(0, -1));

  depth := 0;
  case direction of
    +1:
      begin
        result := NextChar(BracketPoint);
        while CharacterExistsEx(result) do
        begin
          if GetChar(result) = LeftBrackets[BracketType] then
            inc(depth)
          else if GetChar(result) = RightBrackets[BracketType] then
          begin
            dec(depth);
            if depth < 0 then
              Exit(result);
          end;
          result := NextChar(result);
        end;
      end;
    -1:
      begin
        result := PrevChar(BracketPoint);
        while CharacterExistsEx(result) do
        begin
          if GetChar(result) = RightBrackets[BracketType] then
            inc(depth)
          else if GetChar(result) = LeftBrackets[BracketType] then
          begin
            dec(depth);
            if depth < 0 then
              Exit(result);
          end;
          result := PrevChar(result);
        end;
      end;
  end;

  Exit(Point(0, -1));

end;

procedure TTextFile.Modified;
var
  OldModified: boolean;
begin
  OldModified := FModified;
  FModified := true;
  FRecentlyOpened := false;
  ClearFindData;
  if Assigned(FOnModified) and not OldModified then
    FOnModified(Self);
end;

procedure TTextFile.MultiBackspace(var ACarets: TPointArray);
var
  i: Integer;
  minln, maxln: integer;
begin

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  minln := LineCount - 1;
  maxln := 0;
  for i := low(ACarets) to high(ACarets) do
  begin

    if not InRange(ACarets[i].Y, 0, Length(FLines) - 1) then
      Continue;

    if ACarets[i].X > 0 then
    begin
      System.Delete(FLines[ACarets[i].Y], ACarets[i].X, 1);
      PushBookmarks(ACarets[i].Y, ACarets[i].X, -1);
      PushMultiCarets(ACarets, ACarets[i].Y, ACarets[i].X, -1);
      minln := min(minln, ACarets[i].Y);
      maxln := max(maxln, ACarets[i].Y);
    end;
  end;

  Changed(ctLineRange, minln, maxln);
  Modified;
end;

procedure TTextFile.MultiInsertChar(var ACarets: TPointArray;
  const AChar: char; const Overwrite: boolean);
var
  i: Integer;
  minln, maxln: integer;
begin

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  minln := LineCount - 1;
  maxln := 0;
  for i := low(ACarets) to high(ACarets) do
  begin

    if not InRange(ACarets[i].Y, 0, Length(FLines) - 1) then
      Continue;

    if ACarets[i].X < PhysicalLineWidths[ACarets[i].Y] then
      if Overwrite then
        FLines[ACarets[i].Y][ACarets[i].X + 1] := AChar
      else
        Insert(AChar, FLines[ACarets[i].Y], ACarets[i].X + 1)
    else
      FLines[ACarets[i].Y] := FLines[ACarets[i].Y] + GetVirtualSpace(ACarets[i].Y, ACarets[i].X) + AChar;

    if not Overwrite then
    begin
      PushBookmarks(ACarets[i].Y, ACarets[i].X);
      PushMultiCarets(ACarets, ACarets[i].Y, ACarets[i].X);
    end;

    minln := min(minln, ACarets[i].Y);
    maxln := max(maxln, ACarets[i].Y);
  end;

  Changed(ctLineRange, minln, maxln);
  Modified;
end;

procedure TTextFile.MultiInsertText(var ACarets: TPointArray;
  const AText: string);
var
  i, minln, maxln: integer;
begin

  if TextIsMultiline(AText) then
  begin
    IssueInputError;
    Exit;
  end;

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  minln := LineCount - 1;
  maxln := 0;
  for i := low(ACarets) to high(ACarets) do
  begin

    if not InRange(ACarets[i].Y, 0, Length(FLines) - 1) then
      Continue;

    if ACarets[i].X < PhysicalLineWidths[ACarets[i].Y] then
      Insert(AText, FLines[ACarets[i].Y], ACarets[i].X + 1)
    else
      FLines[ACarets[i].Y] := FLines[ACarets[i].Y] + GetVirtualSpace(ACarets[i].Y, ACarets[i].X) + AText;

    PushBookmarks(ACarets[i].Y, ACarets[i].X, Length(AText));
    PushMultiCarets(ACarets, ACarets[i].Y, ACarets[i].X, Length(AText));

    minln := min(minln, ACarets[i].Y);
    maxln := max(maxln, ACarets[i].Y);
  end;

  Changed(ctLineRange, minln, maxln);
  Modified;
end;

procedure TTextFile.NewFile;
begin
  ClearFindData;
  InternalZero;
  FModified := false;
  FRecentlyOpened := false;
  FControlAware := false;
  FFileName := Format(SNewFileName, [GlobalFileNumber]);
  FEncoding := DEFAULT_TEXT_FILE_FORMAT_INFO;
  if GlobalFileNumber = GlobalFileNumber.MaxValue then
    GlobalFileNumber := 1
  else
    Inc(GlobalFileNumber);
  InternalAddLine('', '');
  FCaretPos.Reset;
  LineArrayChanged;
  Changed(ctFile);
  GotoEOF;
end;

procedure TTextFile.NewFileAndInitUndo;
begin
  NewFile;
  AddUndoRecord(SUndoNewFile, UID_UNKNOWN);
end;

function TTextFile.NextChar(const APoint: TPoint): TPoint;
var
  i: Integer;
begin
  if APoint.X < VirtualLineWidths[APoint.Y] - 1 then
    Exit(Point(APoint.X + 1, APoint.Y))
  else
    for i := APoint.Y + 1 to LineCount - 1 do
      if VirtualLineWidths[i] > 0 then
        Exit(Point(0, i));
  Exit(Point(0, -1));
end;

function TTextFile.NextWordBoundary: integer;
begin
  result := NextWordBoundary(FCaretPos.Y, FCaretPos.X);
end;

function TTextFile.NextWordBoundary(Point: TPoint): integer;
begin
  result := NextWordBoundary(Point.Y, Point.X);
end;

function TTextFile.NextWordBoundary(Y, X: integer): integer;
var
  i: Integer;
begin
  result := VirtualLineWidths[FCaretPos.Y];
  for i := FCaretPos.X + 1 to result do
    if not FLines[FCaretPos.Y][i+1].IsLetterOrDigit then
      Exit(i);
end;

function TTextFile.PasteFromClipboard: boolean;
begin
  result := false;
  if Clipboard.HasFormat(CF_TEXT) then
  begin
    InsertText(Clipboard.AsText);
    result := true;
  end
  else
    IssueInputError;
end;

function TTextFile.PasteFromClipboardAsBlock: boolean;
begin
  result := false;
  if Clipboard.HasFormat(CF_TEXT) then
  begin
    InsertTextAsBlock(Clipboard.AsText);
    result := true;
  end
  else
    IssueInputError;
end;

procedure TTextFile.PostFileChanged(const NumLines: integer);
begin
  if Assigned(FOnChange) then
    FOnChange(Self, ctPostFile, NumLines, 0, 0, 0);
end;

function TTextFile.PrevWordBoundary(Point: TPoint): integer;
begin
  result := PrevWordBoundary(Point.Y, Point.X);
end;

function TTextFile.PrevChar(const APoint: TPoint): TPoint;
var
  i: Integer;
begin
  if APoint.X > 0 then
    Exit(Point(APoint.X - 1, APoint.Y))
  else
    for i := APoint.Y - 1 downto 0 do
      if VirtualLineWidths[i] > 0 then
        Exit(Point(VirtualLineWidths[i] - 1, i));
  Exit(Point(0, -1));
end;

function TTextFile.PrevWordBoundary: integer;
begin
  result := PrevWordBoundary(FCaretPos.Y, FCaretPos.X);
end;

function TTextFile.PushBookmarks(LineIndex, ColIndex: integer; NumChars: integer = 1): boolean; // e.g. InsertChar
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if (FBookmarks[i].Y = LineIndex) and (FBookmarks[i].X >= ColIndex) then
    begin
      result := true;
      inc(FBookmarks[i].X, NumChars);
    end;

  if result then BookmarksMoved;
end;

function TTextFile.PushMultiCarets(var ACarets: TPointArray;
  LineIndex, ColIndex: integer; NumChars: integer = 1): boolean;
var
  i: Integer;
begin
  result := false;
  for i := low(ACarets) to high(ACarets) do
    if (ACarets[i].Y = LineIndex) and (ACarets[i].X >= ColIndex) then
    begin
      result := true;
      inc(ACarets[i].X, NumChars);
    end;
end;

function TTextFile.PushBookmarksEx(FirstLine, LastLine,
  NumChars: integer): boolean;                                                   // e.g. AddIndent
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if InRange(FBookmarks[i].Y, FirstLine, LastLine) then
    begin
      result := true;
      inc(FBookmarks[i].X, NumChars);
    end;

  if result then BookmarksMoved;
end;

function TTextFile.PushBookmarksInternal(LineIndex, NumChars: integer): boolean;
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if FBookmarks[i].Y = LineIndex then
    begin
      result := true;
      inc(FBookmarks[i].X, NumChars);
      if FBookmarks[i].X < 0 then
        FBookmarks[i] := EMPTY_BOOKMARK;
    end;
end;

function TTextFile.QushBookmarks(LineIndex, ColIndex: integer): boolean; // e.g. Backspace #13#10
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if FBookmarks[i].Y > LineIndex then
    begin
      result := true;
      if FBookmarks[i].Y = LineIndex + 1 then
        inc(FBookmarks[i].X, ColIndex);
      dec(FBookmarks[i].Y);
    end;

  if result then BookmarksMoved;
end;

function TTextFile.QushBookmarksEx(SelectionType: TSelectionType;
  const FirstPoint, SecondPoint: TPoint): boolean;                               // e.g. ClearSelection
var
  i: Integer;
  Δx, Δy: integer;
begin

  result := false;

  for i := low(FBookmarks) to high(FBookmarks) do
    if IsCharInRgn(FBookmarks[i], SelectionType, FirstPoint, SecondPoint) then
    begin
      result := true;
      FBookmarks[i] := EMPTY_BOOKMARK;
    end;

  Δx := SecondPoint.X - FirstPoint.X;
  Δy := SecondPoint.Y - FirstPoint.Y;

  case SelectionType of
    stLineBased:
      for i := low(FBookmarks) to high(FBookmarks) do
        if (FBookmarks[i].Y = SecondPoint.Y) and (FBookmarks[i].X >= SecondPoint.X) then
        begin
          result := true;
          dec(FBookmarks[i].Y, Δy);
          dec(FBookmarks[i].X, ΔX);
        end
        else if FBookmarks[i].Y > SecondPoint.Y then
        begin
          result := true;
          dec(FBookmarks[i].Y, Δy);
        end;
    stBlock:
      for i := low(FBookmarks) to high(FBookmarks) do
        if InRange(FBookmarks[i].Y, FirstPoint.Y, SecondPoint.Y) and (FBookmarks[i].X >= SecondPoint.X) then
        begin
          result := true;
          dec(FBookmarks[i].X, Δx);
        end;
  end;

  if result then BookmarksMoved;

end;

function TTextFile.PrevWordBoundary(Y, X: integer): integer;
var
  i: Integer;
begin
  result := 0;
  if X > VirtualLineWidths[Y] then
    result := VirtualLineWidths[Y]
  else
    for i := FCaretPos.X - 1 downto 1 do
      if not FLines[FCaretPos.Y][(i - 1) + 1].IsLetterOrDigit then
        Exit(i);
end;

procedure TTextFile.Clear;
begin
  if EditMode <> emText then
  begin
    IssueInputError;
    Exit;
  end;
  ClearFindData;
  SetLength(FLines, 0);
  SetLength(FClasses, 0);
  ClearBookmarks;
  AddLine('');
  Changed(ctPostFile);
  Modified;
end;

procedure TTextFile.ClearFindData;
var
  OldLength: integer;
begin
  OldLength := Length(FFindData);
  InternalClearFindData;
  if OldLength > 0 then
  begin
    if Assigned(FOnFindDataClear) then
      FOnFindDataClear(Self);
  end;
end;

procedure TTextFile.InternalClearFindData;
begin
  SetLength(FFindData, 0);
  FFindDataActualLength := 0;
  FFindResultValid := false;
end;

procedure TTextFile.ClearBookmarks;
var
  i: Integer;
begin
  for i := low(FBookmarks) to high(FBookmarks) do
    FBookmarks[i] := EMPTY_BOOKMARK;
end;

procedure TTextFile.ClearLine(LineIndex: integer);
begin
  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (LineIndex < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if IsControlLine(LineIndex) then
  begin
    DeleteControlAtLine(LineIndex);
    FCaretPos.SetPoint(0, LineIndex);
    Changed(ctLine, LineIndex);
    Modified;
    Exit;
  end;

  if (VirtualLineWidths[LineIndex] = 0) and (LineIndex < LineCount - 1) then
  begin
    if EditMode = emConsole then
    begin
      IssueInputError;
      Exit;
    end;
    InternalDeleteLine(LineIndex);
    LineArrayChanged;
    FCaretPos.SetPoint(0, LineIndex);
    Changed(ctLineRange, LineIndex, LineCount);
  end
  else
  begin
    FLines[LineIndex] := '';
    FCaretPos.SetPoint(0, LineIndex);
    Changed(ctLine, LineIndex);
  end;
  Modified;
end;

procedure TTextFile.ClearLine;
begin
  ClearLine(FCaretPos.Y);
end;

procedure TTextFile.ClearSelection;
var
  FirstPoint, SecondPoint: TPoint;
  SelectionType: TSelectionType;
  i: Integer;
  xmin, xmax, wmax: integer;
begin
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  SelectionType := FCaretPos.SelectionType;

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FirstPoint.Y < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FirstPoint.Y = SecondPoint.Y then
  begin

    if FControlAware and IsControlLine then
    begin
      if (FirstPoint.X = 0) and (SecondPoint.X >= 1) then
        DeleteControlAtLine(FCaretPos.Y)
      else
        Exit {silently};
    end;

    System.Delete(FLines[FirstPoint.Y], FirstPoint.X + 1, SecondPoint.X - FirstPoint.X);
    FCaretPos.SetPoint(FirstPoint);
    Changed(ctLineFrom, FirstPoint.Y, FirstPoint.X);
  end
  else
  begin
    case FCaretPos.SelectionType of
      stLineBased:
        begin

          if FControlAware then
          begin

            if (IsControlLine(FirstPoint.Y) and (FirstPoint.X > 0)) or (IsControlLine(SecondPoint.Y) and (SecondPoint.X = 0)) then
            begin
              IssueInputError;
              Exit;
            end;

            if IsControlLine(FirstPoint.Y) and (FirstPoint.X = 0) then
              DeleteControlAtLine(FirstPoint.Y);
            for i := FirstPoint.Y + 1 to SecondPoint.Y - 1 do
              DeleteControlAtLine(i);
            if IsControlLine(SecondPoint.Y) and (SecondPoint.X >= 1) then
              DeleteControlAtLine(SecondPoint.Y);

          end;

          FLines[FirstPoint.Y] := Copy(FLines[FirstPoint.Y], 1, FirstPoint.X) +
            GetVirtualSpace(FirstPoint.Y, FirstPoint.X) +
            Copy(FLines[SecondPoint.Y], SecondPoint.X + 1);
          InternalDeleteLines(FirstPoint.Y + 1, SecondPoint.Y - FirstPoint.Y);
          LineArrayChanged;
          FCaretPos.SetPoint(FirstPoint);
          Changed(ctLineRange, FirstPoint.Y, LineCount - 1);
          PostFileChanged(SecondPoint.Y - FirstPoint.Y);
        end;
      stBlock:
        begin
          xmin := min(FirstPoint.X, SecondPoint.X);
          xmax := max(FirstPoint.X, SecondPoint.X);
          wmax := 0;
          for i := FirstPoint.Y to SecondPoint.Y do
          begin
            wmax := max(wmax, VirtualLineWidths[i]);
            if FControlAware and IsControlLine(i) then
              if FirstPoint.X = 0 then
                DeleteControlAtLine(i)
              else
                {Do nothing}
            else
              System.Delete(FLines[i], xmin + 1, xmax - xmin);
          end;
          LineArrayChanged;
          FCaretPos.SetPoint(xmin, FirstPoint.Y);
          Changed(ctBlock, FirstPoint.Y, SecondPoint.Y, xmin, wmax);
        end;
    end;
  end;
  Modified;
  QushBookmarksEx(SelectionType, FirstPoint, SecondPoint);
end;

procedure TTextFile.ClearUndoHistory;
begin
  FHistoryManager.Clear;
end;

function TTextFile.CompareFindQuery(const AFindQuery: TFindQuery): boolean;
begin
  result := (AFindQuery.MatchCase = FFindQuery.MatchCase) and
    (AFindQuery.MatchWord = FFindQuery.MatchWord) and
    (AFindQuery.Linebreak = FFindQuery.Linebreak) and
    SameStr(AFindQuery.SearchString, FFindQuery.SearchString) and
    (AFindQuery.UCBlock = FFindQuery.UCBlock);
end;

procedure TTextFile.CopyToClipboard;
begin
  Clipboard.AsText := GetSelText;
end;

procedure TTextFile.LoadAutoReplaceItems;
var
  ARFileName: TFileName;
  i, p: integer;
begin
  ARFileName := GetAutoReplaceDataFileName;
  if (Length(ARFileName) = 0) or not FileExists(ARFileName) then Exit;
  with TStringList.Create do
    try
      LoadFromFile(ARFileName, TEncoding.UTF8);
      SetLength(FAutoReplaceItems, Count);
      for i := 0 to Count - 1 do
      begin
        p := Pos(#32, Strings[i]);
        if p > 0 then
        begin
          FAutoReplaceItems[i].Token := Copy(Strings[i], 1, p - 1);
          FAutoReplaceItems[i].ReplacedValue := Copy(Strings[i], p + 1);
        end;
      end;
    finally
      Free;
    end;
end;

constructor TTextFile.Create;
begin
  FUseLineClasses := false;
  FStrictReadOnly := false;
  FIndentSize := 2;
  SetLength(FLines, 0);
  SetLength(FClasses, 0);
  FRecentlyOpened := false;
  FEncoding := DEFAULT_TEXT_FILE_FORMAT_INFO;
  FMultiAddLineMode := false;
  FPreserveDesiredCol := false;
  FSortReverseOrder := false;
  FLineComparer := AnsiCompareText;
  FEditorState := TEditorState.Create;
  FWrapAt := DEFAULT_WRAP_AT;
  FControlAware := false;
  FSingleLine := false;
  ClearFindData;
  ClearBookmarks;
  FHistoryManager := THistoryManager.Create;
  FCaretPos := TCaretPos.Create;
  FCaretPos.OnChange := CaretPosChange;
  FCaretPos.OnSelChange := CaretPosSelChange;
  FEditMode := emText;
  FModified := false;
  FCaretAfterEOL := true;
  LoadAutoReplaceItems;
  AddLine('');
end;

function TTextFile.CanRedo: boolean;
begin
  result := FHistoryManager.CanRedo;
end;

function TTextFile.CanUndo: boolean;
begin
  result := FHistoryManager.CanUndo;
end;

procedure TTextFile.CaretPosChange(Sender: TObject);
begin
  if not FPreserveDesiredCol then
    FDesiredCol := FCaretPos.X;
  if Assigned(FOnCaretPosChange) then
    FOnCaretPosChange(Self);
end;

procedure TTextFile.CaretPosSelChange(Sender: TObject; ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: integer);
begin
  // Merely pass on to visual editor control
  if Assigned(FOnCaretPosSelChange) then
    FOnCaretPosSelChange(Sender, ChangeType, Data1, Data2, Data3, Data4);
end;

procedure TTextFile.Changed(ChangeType: TChangeType; Data1: integer = 0;
  Data2: integer = 0; Data3: integer = 0; Data4: integer = 0);
begin
  if Assigned(FOnChange) then
    FOnChange(Self, ChangeType, Data1, Data2, Data3, Data4);
end;

function TTextFile.CharacterExists(APoint: TPoint): boolean;
begin
  result := InRange(APoint.Y, 0, LineCount - 1) and
    InRange(APoint.X, 0, VirtualLineWidths[APoint.Y] - 1) and
    not IsControlLine(APoint.Y);
end;

function TTextFile.CharacterExistsEx(Y, X: integer): boolean;
begin
  result := InRange(Y, 0, LineCount - 1) and InRange(X, 0, VirtualLineWidths[Y] - 1);
end;

function TTextFile.CharacterExistsEx(APoint: TPoint): boolean;
begin
  result := InRange(APoint.Y, 0, LineCount - 1) and
    InRange(APoint.X, 0, VirtualLineWidths[APoint.Y] - 1);
end;

function TTextFile.ChrTransform(Transformation: TChrTransformFunc): boolean;
var
  FirstPoint, SecondPoint: TPoint;
  i: Integer;
  j: Integer;
begin
  result := HasSelection;
  if result then
  begin

    if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FirstPoint.Y < LineCount - 1)) then
    begin
      IssueReadOnlyError;
      Exit;
    end;

    FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
    case FCaretPos.SelectionType of
      stLineBased:
          if FirstPoint.Y = SecondPoint.Y then
          begin
            for i := FirstPoint.X to SecondPoint.X - 1 do
              FLines[FirstPoint.Y][i + 1] := Transformation(FLines[FirstPoint.Y][i + 1]);
            Changed(ctBlock, FirstPoint.Y, SecondPoint.Y, FirstPoint.X, SecondPoint.X);
          end
          else
          begin
            for i := FirstPoint.X to GetVirtualLineWidth(FirstPoint.Y) - 1 do
              FLines[FirstPoint.Y][i + 1] := Transformation(FLines[FirstPoint.Y][i + 1]);
            for j := FirstPoint.Y + 1 to SecondPoint.Y - 1 do
              for i := 0 to GetVirtualLineWidth(j) - 1 do
              FLines[j][i + 1] := Transformation(FLines[j][i + 1]);
            for i := 0 to SecondPoint.X - 1 do
              FLines[SecondPoint.Y][i + 1] := Transformation(FLines[SecondPoint.Y][i + 1]);
            Changed(ctLineRange, FirstPoint.Y, SecondPoint.Y);
          end;
      stBlock:
        begin
          for j := FirstPoint.Y to SecondPoint.Y do
            for i := FirstPoint.X to SecondPoint.X - 1 do
              if CharacterExists(j, i) then
                FLines[j][i + 1] := Transformation(FLines[j][i + 1]);
          Changed(ctBlock, FirstPoint.Y, SecondPoint.Y, FirstPoint.X, SecondPoint.X);
        end;
    end;
    Modified;
  end;
end;

procedure TTextFile.ChrTransformText(Transformation: TChrTransformFunc);
var
  j: Integer;
  i: Integer;
begin
  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (LineCount > 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  for j := 0 to Length(FLines) - 1 do
  begin
    if IsControlLine(j) then
      Continue;
    for i := 0 to GetPhysicalLineWidth(j) - 1 do
      FLines[j][i + 1] := Transformation(FLines[j][i + 1]);
  end;
  Changed(ctFile);
  Modified;
end;

function TTextFile.CharacterExists(Y, X: integer): boolean;
begin
  result := InRange(Y, 0, LineCount - 1) and InRange(X, 0, VirtualLineWidths[Y] - 1)
    and not IsControlLine(Y);
end;

function TTextFile.GetChar(Y, X: Integer): Char;
begin
  if CharacterExists(Y, X) then
    result := FLines[Y][X+1]
  else
    result := #32;
end;

function TTextFile.GetAutoReplaceItem(Index: integer): TAutoReplaceItem;
begin
  result := FAutoReplaceItems[Index];
end;

function TTextFile.GetAutoReplaceItemCount: integer;
begin
  result := Length(FAutoReplaceItems);
end;

function TTextFile.GetBookmark(Index: Integer): TPoint;
begin
  Assert(InRange(Index, low(FBookmarks), high(FBookmarks)));
  result := FBookmarks[Index];
end;

function TTextFile.GetBookmarkCount: integer;
begin
  result := High(FBookmarks) + 1{sic!};
end;

function TTextFile.GetChar(APoint: TPoint): char;
begin
  result := GetChar(APoint.Y, APoint.X);
end;

function TTextFile.NumCharsOfType(CharTestFunction: TCharTestFunction): integer;
var
  i: Integer;
  j: Integer;
begin
  result := 0;
  for i := 0 to high(FLines) do
    for j := 1 to Length(FLines[i]) do
      if CharTestFunction(FLines[i][j]) then
        inc(result);
end;

function TTextFile.GetFileStatistics(AFileStatisticsFlags: TFileStatisticsFlags;
  AWordFreqs: TWordFreqDict): TFileStatistics;
var
  i: Integer;
  j: Integer;
  InProposedWord: boolean;
  start: integer;
  CurLineWidth: integer;
  c: char;

  procedure ConsiderPossibleWord(AStart, AEnd: integer);
  var
    WordLength: integer;
    Word, WordKey: string;
    WordFreqItem: TWordFreqItem;
    k: integer;
    HasLetter: boolean;
  begin

    // Preconditions:
    // FLines[i][AStart] exists and is the first character of the proposed word.
    // FLines[i][AEnd] exists and is the last character of the proposed word.
    // AStart <= AEnd

    {$IFDEF DEBUG}
    Assert(InRange(AStart, 1, FLines[i].Length));
    Assert(InRange(AEnd, 1, FLines[i].Length));
    Assert(AStart <= AEnd);
    {$ENDIF}

    while (AStart <= AEnd) and FLines[i][AStart].IsPunctuation do
      Inc(AStart);

    while (AEnd >= AStart) and FLines[i][AEnd].IsPunctuation do
      Dec(AEnd);

    HasLetter := False;
    for k := AStart to AEnd do
      if FLines[i][k].IsLetter then
      begin
        HasLetter := True;
        Break;
      end;

    if not HasLetter then
      Exit;

    if AEnd >= AStart then
    begin
      WordLength := AEnd - AStart + 1;
      if WordLength > result.MaxWordLength then
        Result.MaxWordLength := WordLength;
      if WordLength >= Length(Result.WordLengthDistr) then
        SetLength(Result.WordLengthDistr, WordLength + 1);
      Inc(Result.WordLengthDistr[WordLength]);
      Inc(Result.NumWords);
      if Assigned(AWordFreqs) then
      begin
        Word := Copy(FLines[i], AStart, WordLength);
        if fsCaseSensitive in AFileStatisticsFlags then
        begin
          if AWordFreqs.TryGetValue(Word, WordFreqItem) then
            Inc(WordFreqItem.Count)
          else
            AWordFreqs.Add(Word, TWordFreqItem.Create(Word));
        end
        else
        begin
          WordKey := Word.ToLower;
          if AWordFreqs.TryGetValue(WordKey, WordFreqItem) then
          begin
            Inc(WordFreqItem.Count);
            if not WordFreqItem.IsLower and (Word = WordKey) then
            begin
              WordFreqItem.InNaturalCase := Word;
              WordFreqItem.IsLower := True;
            end;
          end
          else
            AWordFreqs.Add(WordKey, TWordFreqItem.Create(Word, Word = WordKey));
        end;
      end;
    end;

  end;

  function IsWordSep(const C: char): boolean;
  const
    SourceCodeWordSeps = ['.', ',', ';', ':', '-', '+', '*', '/', '=', '(', ')',
      '[', ']', '{', '}', '<', '>', '|', '\', '%', '&', '@', '~', '!', '?'];
  begin
    Result := C.IsWhiteSpace or (C = '/') or (C = #$2014) or (C = '<') or (C = '>') or (C = '=');
    if (fsSourceCode in AFileStatisticsFlags) and not Result then
      Result := CharInSet(C, SourceCodeWordSeps) or (C.GetUnicodeCategory = TUnicodeCategory.ucMathSymbol);
  end;

begin

  Result.Flags := AFileStatisticsFlags;
  Result.Clear;
  if Assigned(AWordFreqs) then
    AWordFreqs.Clear;

  if fsfCharTypes in AFileStatisticsFlags then
  begin
    {$WARN SYMBOL_DEPRECATED OFF}
    Result.NumChars := NumCharacters;
    Result.NumLetters := NumCharsOfType(IsLetter);
    Result.NumDigits := NumCharsOfType(IsDigit);
    Result.NumWhitespace := NumCharsOfType(IsWhiteSpace);
    Result.NumPunctuation := NumCharsOfType(IsPunctuation);
    {$WARN SYMBOL_DEPRECATED DEFAULT}
  end;

  if fsfLines in AFileStatisticsFlags then
  begin
    Result.NumLines := LineCount;
    Result.MaxLineLength := GetMaxLineWidth;
    Result.AvgLineLength := 0;
    SetLength(Result.LineLengthDistr, Result.MaxLineLength + 1);
    for i := 0 to LineCount - 1 do
    begin
      Inc(Result.LineLengthDistr[Length(FLines[i])]);
      Result.AvgLineLength := Result.AvgLineLength + Length(FLines[i]) / Result.NumLines;
    end;
  end;

  if fsfWords in AFileStatisticsFlags then
  begin
    Result.NumWords := 0;
    Result.MaxWordLength := 0;
    SetLength(Result.WordLengthDistr, 1024);
    for i := 0 to LineCount - 1 do
    begin
      InProposedWord := false;
      start := 1; // So the compiler will not complain
      CurLineWidth := VirtualLineWidths[i];
      for j := 1 to CurLineWidth do
      begin
        c := FLines[i][j];
        if InProposedWord then
        begin
          if IsWordSep(c) then
          begin
            InProposedWord := False;
            ConsiderPossibleWord(start, j - 1);
          end;
        end
        else
        begin
          if not IsWordSep(c) then
          begin
            start := j;
            InProposedWord := True;
          end
        end
      end;
      if InProposedWord {at EOL} then
        ConsiderPossibleWord(start, CurLineWidth);
    end;
    SetLength(Result.WordLengthDistr, Result.MaxWordLength + 1);
    Result.AvgWordLength := 0;
    if Result.NumWords > 0 then
      for i := 0 to high(Result.WordLengthDistr) do
        Result.AvgWordLength := Result.AvgWordLength + Result.WordLengthDistr[i] * i / Result.NumWords;
  end;

end;

function TTextFile.GetFindCount: integer;
begin
  result := Length(FFindData);
end;

function TTextFile.GetFindData(Index: integer): TTextSpan;
begin
  result := FFindData[Index];
end;

function TTextFile.GetFirstLine(const AText: string): string;
begin
  result := Copy(AText, 1, Pos(#13#10, AText) - 1);
end;

function TTextFile.GetHasBookmarks: boolean;
begin
  result := UsedBookmarkCount > 0;
end;

function TTextFile.GetClass(Index: Integer): string;
begin
  result := FClasses[Index];
end;

function TTextFile.GetClassesAsText: string;
var
  i, p: Integer;
begin
  SetLength(result, GetClassLength);
  p := 1;
  for i := 0 to LineCount - 1 do
  begin
    if not FClasses[i].IsEmpty then
      Move(FClasses[i][1], result[p], Length(FClasses[i]) * SizeOf(Char));
    if i < LineCount - 1 then
    begin
      inc(p, Length(FClasses[i]) + 2);
      result[p-2] := #13;
      result[p-1] := #10;
    end;
  end;
end;

function TTextFile.GetClassLength: integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to LineCount - 1 do
    inc(result, Length(FClasses[i]) + length(#13#10));
  dec(result, length(#13#10));
end;

function TTextFile.GetIndent: integer;
begin
  result := GetIndent(FCaretPos.Y);
end;

function TTextFile.GetIndentOnReturn(out Len: integer): string;
begin
  Len := IfThen(FAutoIndent, Min(GetIndent, FCaretPos.X), 0);
  if FCaretAfterEOL and AtOrBeyondEOL then
    result := ''
  else
    result := DupeString(#32, Len); // = '' as well if not FAutoIndent
end;

function TTextFile.GetIndexOfPoint(const APoint: TPoint): integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to APoint.Y - 1 do
    inc(result, VirtualLineWidths[i]);
  inc(result, APoint.X);
end;

function TTextFile.GetLine(Index: Integer): string;
begin
  result := FLines[Index];
end;

function TTextFile.GetLineCount: integer;
begin
  result := Length(FLines);
end;

function TTextFile.GetPhysicalLineWidth(Index: Integer): integer;
begin
  result := Length(FLines[Index]);
end;

function TTextFile.GetPhysicalPhysicalIndexOfPoint(
  const APoint: TPoint): integer;
var
  i: integer;
begin
  result := 0;
  for i := 0 to APoint.Y - 1 do
    inc(result, PhysicalLineWidths[i] + Length(#13#10));
  inc(result, APoint.X);
end;

function TTextFile.GetVirtualLineWidth(Index: Integer): integer;
begin
  if SameStr(FClasses[Index], LINE_CONTROL_CLASS) then
    result := Min(1, Length(FLines[Index]))
  else
    result := Length(FLines[Index]);
end;

function TTextFile.GetVirtualSpace(LineIndex, Col: integer): string;
var
  LW: integer;
begin
  LW := VirtualLineWidths[LineIndex];
  if Col > LW then
    result := DupeString(' ', Col - LW)
  else
    result := '';
end;

function TTextFile.GetMaxLineWidth: integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to High(FLines) do
    if Length(FLines[i]) > result then
      result := Length(FLines[i]);
end;

function TTextFile.GetNoncharacterCount: integer; // NOT BMP-BEYOND AWARE!!
begin
  result := NumCharsOfType(IsNoncharacter)
end;

function TTextFile.GetNumCharacters: integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to LineCount - 1 do
    inc(result, VirtualLineWidths[i]);
end;

function TTextFile.GetPhysicalIndexOfPoint(const APoint: TPoint): integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to APoint.Y - 1 do
    inc(result, VirtualLineWidths[i] + Length(#13#10));
  inc(result, APoint.X);
end;

function TTextFile.GetPointOfIndex(const Index: integer): TPoint;
var
  acc: integer;
  i: Integer;
begin
  if Index < 0 then
    raise Exception.CreateFmt(SInvalidOpMsgInvalidChrIndex, [Index]);
  result.Y := -1;
  acc := 0;
  for i := 0 to LineCount - 1 do
  begin
    inc(acc, VirtualLineWidths[i]);
    if acc > Index then
    begin
      result.X := Index - acc + VirtualLineWidths[i];
      result.Y := i;
      break;
    end;
  end;
end;

function TTextFile.GetSelLength: integer;
var
  FirstPoint, SecondPoint: TPoint;
  i: Integer;
begin
  result := 0;
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  case FCaretPos.SelectionType of
    stLineBased:
        if FirstPoint.Y = SecondPoint.Y then
          result := SecondPoint.X - FirstPoint.X
        else
        begin
          result := VirtualLineWidths[FirstPoint.Y] - FirstPoint.X;
          for i := FirstPoint.Y + 1 to SecondPoint.Y - 1 do
            inc(result, VirtualLineWidths[i]);
          inc(result, SecondPoint.X);
        end;
    stBlock:
      result := (SecondPoint.Y - FirstPoint.Y + 1) * abs(SecondPoint.X - FirstPoint.X);
  end;
end;

function TTextFile.GetSelStart: integer;
begin
  result := GetIndexOfPoint(FCaretPos.Data)
end;

function TTextFile.GetControlCharCount: integer;
begin
  {$WARN SYMBOL_DEPRECATED OFF}
  result := NumCharsOfType(IsControl)
  {$WARN SYMBOL_DEPRECATED DEFAULT}
end;

function TTextFile.GetControlText(LineIndex: integer): string;
begin
  if Assigned(FOnGetControlText) then
    FOnGetControlText(Self, LineIndex, result)
  else
    result := SControl;
end;

function TTextFile.GetSelText: string;
var
  FirstPoint, SecondPoint: TPoint;
  xmin, xmax: integer;
  i: Integer;
begin
  result := '';
  if not HasSelection then Exit;
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);

  if FirstPoint.Y = SecondPoint.Y then
    if FControlAware and IsControlLine(FirstPoint.Y) then
      result := IfThen((FirstPoint.X = 0) and (SecondPoint.X >= 1), GetDecoratedControlText(FirstPoint.Y))
    else
      result := Copy(FLines[FirstPoint.Y], FirstPoint.X + 1, SecondPoint.X - FirstPoint.X)
  else
    case FCaretPos.SelectionType of
      stLineBased:
        begin
          if FControlAware and IsControlLine(FirstPoint.Y) then
            result := IfThen(FirstPoint.X = 0, GetDecoratedControlText(FirstPoint.Y)) + #13#10
          else
            result := Copy(FLines[FirstPoint.Y], FirstPoint.X + 1) + #13#10;
            for i := FirstPoint.Y + 1 to SecondPoint.Y - 1 do
              if FControlAware and IsControlLine(i) then
                result := result + GetDecoratedControlText(i) + #13#10
              else
                result := result + FLines[i] + #13#10;
          if FControlAware and IsControlLine(SecondPoint.Y) then
            result := result + IfThen(SecondPoint.X >= 1, GetDecoratedControlText(SecondPoint.Y))
          else
            result := result + Copy(FLines[SecondPoint.Y], 1, SecondPoint.X);
        end;
      stBlock:
        begin
          xmin := min(FirstPoint.X, SecondPoint.X);
          xmax := max(FirstPoint.X, SecondPoint.X);
          for i := FirstPoint.Y to SecondPoint.Y do
            result := result + Copy(FLines[i], xmin + 1, xmax - xmin) + IfThen(i < SecondPoint.Y, #13#10);
        end;
    end;
end;

function TTextFile.GetSingleLineText: string;
var
  i, p: Integer;
begin
  SetLength(result, GetPhysicalTextLength);
  p := 1;
  for i := 0 to LineCount - 1 do
  begin
    Move(FLines[i][1], result[p], PhysicalLineWidths[i] * SizeOf(Char));
    if i < LineCount - 1 then
    begin
      inc(p, PhysicalLineWidths[i] + 2);
      result[p-2] := '␍';
      result[p-1] := '␊';
    end;
  end;
end;

function TTextFile.GetVirtualTextLength: integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to LineCount - 1 do
    inc(result, VirtualLineWidths[i] + length(#13#10));
  dec(result, length(#13#10));
end;

function TTextFile.GetPhysicalTextLength: integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0 to LineCount - 1 do
    inc(result, PhysicalLineWidths[i] + length(#13#10));
  dec(result, length(#13#10));
end;

function TTextFile.AtEOL: boolean;
begin
  result := FCaretPos.X = VirtualLineWidths[FCaretPos.Y]
end;

function TTextFile.AtOrBeyondEOF: boolean;
begin
  result := (FCaretPos.Y = LineCount - 1) and (FCaretPos.X >= VirtualLineWidths[FCaretPos.Y]);
end;

function TTextFile.AtOrBeyondEOL: boolean;
begin
  result := FCaretPos.X >= VirtualLineWidths[FCaretPos.Y]
end;

procedure TTextFile.BeginAddLine;
begin
  FMultiAddLineMode := true;
end;

function TTextFile.BeyondEOL: boolean;
begin
  result := FCaretPos.X > VirtualLineWidths[FCaretPos.Y]
end;

procedure TTextFile.BookmarksMoved;
begin
  if Assigned(FOnBookmarksMoved) then
    FOnBookmarksMoved(Self);
end;

function TTextFile.AtEOF: boolean;
begin
  result := (FCaretPos.Y = LineCount - 1) and (FCaretPos.X = VirtualLineWidths[FCaretPos.Y]);
end;

function TTextFile.AtLastLine: boolean;
begin
  result := FCaretPos.Y = LineCount - 1;
end;

function TTextFile.AtSOF: boolean;
begin
  result := FCaretPos.X + FCaretPos.Y = 0;
end;

function TTextFile.CanAutoReplace(out StartPos, Index: integer): boolean;
var
  i: Integer;
  Token: string;
begin
  result := false;
  if BeyondEOL then Exit;

  StartPos := 1;
  for i := FCaretPos.X downto 1 do
    if FLines[FCaretPos.Y][i] = '\' then
    begin
      StartPos := i;
      break;
    end
    else if FLines[FCaretPos.Y][i].IsWhiteSpace then
    begin
      StartPos := i + 1;
      break;
    end;
  Token := Copy(FLines[FCaretPos.Y], StartPos, FCaretPos.X - StartPos + 1);
  Index := -1;
  for i := 0 to Length(FAutoReplaceItems) - 1 do
    if SameStr(FAutoReplaceItems[i].Token, Token) then
    begin
      Index := i;
      break;
    end;
  result := (Index <> -1) and (Length(Token) > 0);
end;

procedure TTextFile.DoAutoReplace(const StartPos, Index: integer);
begin
  System.Delete(FLines[FCaretPos.Y], StartPos, FCaretPos.X - StartPos + 1);
  System.Insert(FAutoReplaceItems[Index].ReplacedValue, FLines[FCaretPos.Y], StartPos);
  FCaretPos.SetX(StartPos + Length(FAutoReplaceItems[Index].ReplacedValue) - 1);
  Changed(ctLineFrom, FCaretPos.Y, StartPos - 1);
end;

function TTextFile.AutoReplace: boolean;
var
  StartPos: Integer;
  Index: integer;
begin
  result := CanAutoReplace(StartPos, Index);
  if result then
    DoAutoReplace(StartPos, Index);
end;

function TTextFile.GetVirtualSpace: string;
begin
  if FCaretPos.X > VirtualLineWidths[FCaretPos.Y] then
    result := DupeString(#32, FCaretPos.X - VirtualLineWidths[FCaretPos.Y])
  else
    result := '';
end;

function TTextFile.GetWordBoundary(const Point: TPoint; out StartPos,
  EndPos: integer; PascalIdent: boolean = false): boolean;
var
  i: Integer;
begin
  result := (CharacterExists(Point.Y, Point.X) and FLines[Point.Y][Point.X + 1].IsLetterOrDigit)
               or
            (CharacterExists(Point.Y, Point.X - 1) and FLines[Point.Y][Point.X - 1 + 1].IsLetterOrDigit);
  if not result then Exit;
  StartPos := 0;
  EndPos := VirtualLineWidths[Point.Y];
  for i := Point.X - 1 downto 0 do
    if not (FLines[Point.Y][i+1].IsLetterOrDigit or (PascalIdent and (FLines[Point.Y][i+1] = '_'))) then
    begin
      StartPos := i + 1;
      break;
    end;
  for i := Point.X to VirtualLineWidths[Point.Y] - 1 do
    if not (FLines[Point.Y][i+1].IsLetterOrDigit or (PascalIdent and (FLines[Point.Y][i+1] = '_'))) then
    begin
      EndPos := i;
      break;
    end;
end;

function TTextFile.GetWord(const Point: TPoint; PascalIdent: boolean = false): string;
var
  S, E: integer;
begin
  if GetWordBoundary(Point, S, E, PascalIdent) then
    result := Copy(FLines[Point.Y], S + 1, E - S);
end;

function TTextFile.GetWord(PascalIdent: boolean = false): string;
begin
  result := GetWord(FCaretPos.Data, PascalIdent);
end;

function TTextFile.GetWordBoundary(out StartPos, EndPos: integer; PascalIdent: boolean = false): boolean;
begin
  result := GetWordBoundary(FCaretPos.Data, StartPos, EndPos, PascalIdent);
end;

procedure TTextFile.InsertChar(const AChar: Char; const Overwrite: boolean = false);
var
  PrevLineEnd: integer;
begin
  if (EditMode = emReadOnly) or ((EditMode = emConsole) and not AtLastLine) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if HasSelection then
    ClearSelection;

  if FControlAware and IsControlLine then
  begin
    IssueInputError;
    Exit;
  end;

  if AtEOL then
  begin
    FLines[FCaretPos.Y] := FLines[FCaretPos.Y] + AChar;
    FCaretPos.SetX(FCaretPos.X + 1);
    Changed(ctChar, FCaretPos.Y, FCaretPos.X - 1);
  end
  else
  begin // Beyond EOL aware
    PrevLineEnd := VirtualLineWidths[FCaretPos.Y];
    FLines[FCaretPos.Y] := Copy(FLines[FCaretPos.Y], 1, FCaretPos.X) + GetVirtualSpace + AChar + Copy(FLines[FCaretPos.Y], FCaretPos.X + 1 + IfThen(Overwrite, 1));
    FCaretPos.SetX(FCaretPos.X + 1);
    Changed(ctLineFrom, FCaretPos.Y, Min(PrevLineEnd, FCaretPos.X - 1));
  end;
  PushBookmarks(FCaretPos.Y, FCaretPos.X - 1);
  Modified;
end;

procedure TTextFile.InsertLine(const ALine, AClassName: string;
  LineIndex: integer);
begin
  if (EditMode = emReadOnly) or (EditMode = emConsole) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FSingleLine then
    raise EInvalidOperation.Create(SInvalidOpMsgSingleLineModeInsertLine);

  InternalInsertLine(LineIndex, ALine, AClassName);

  TushBookmarks(LineIndex);

//  LineArrayChanged;  // included in LineClassChanged
  LineClassChanged(LineIndex);
  FCaretPos.SetPoint(VirtualLineWidths[LineIndex], LineIndex);
  Changed(ctLineRange, LineIndex, High(FLines));
  Modified;
end;

procedure TTextFile.InsertLine(const ALine: string; LineIndex: integer);
begin
  InsertLine(ALine, '', LineIndex);
end;

procedure TTextFile.InsertText(const AText: string);
var
  nlines, i: integer;
  indices: DynIntegerArray;
  pre, post: string;
  TML: boolean;
  PrevLineEnd: integer;
  OldCP, NewCP: TPoint;
  HadSel, HadMultiLineSel: boolean;
begin // Beyond EOL aware

  TML := TextIsMultiline(AText);

  if FSingleLine and TML then
  begin
    InsertText(GetFirstLine(AText));
    Exit;
  end;

  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (TML or not AtLastLine)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if FControlAware and IsControlLine then
  begin
    IssueInputError;
    Exit;
  end;

  HadSel := HasSelection;
  HadMultiLineSel := SelectionIsMultiline;

  if not TML then
  begin
    LockVisualUpdates;
    try
      if HadSel then ClearSelection;
      PushBookmarks(FCaretPos.Y, FCaretPos.X, Length(AText));
      PrevLineEnd := VirtualLineWidths[FCaretPos.Y];
      Insert(GetVirtualSpace + AText, FLines[FCaretPos.Y], FCaretPos.X + 1);
      FCaretPos.SetX(FCaretPos.X + Length(AText));
    finally
      UnlockVisualUpdates;
    end;
    if not HadMultiLineSel then
      Changed(ctLineFrom, FCaretPos.Y, Min(PrevLineEnd, FCaretPos.X - Length(AText)))
    else
    begin
      Changed(ctLineRange, FCaretPos.Y, LineCount - 1);
      PostFileChanged(100);
    end;
  end
  else
  begin
    LockVisualUpdates;
    try
      if HadSel then ClearSelection;
      nlines := Occurrences(AText, #13#10, indices) + 1;
      OldCP := FCaretPos.Data;
      InternalInsertLines(FCaretPos.Y + 1, nlines - 1);
      pre := LineToLeft;
      post := LineToRight;
      FLines[FCaretPos.Y] := pre + GetVirtualSpace + Copy(AText, 1, indices[0] - 1);
      FLines[FCaretPos.Y + nlines - 1] := Copy(AText, indices[high(indices)] + length(#13#10)) + post;
      for i := 0 to high(indices) - 1 do
        FLines[FCaretPos.Y + 1 + i] := Copy(AText, indices[i] + length(#13#10), indices[i+1] - indices[i] - length(#13#10));
      NewCP := Point(Length(AText) - indices[high(indices)] - 1, FCaretPos.Y + nlines - 1);
      LineArrayChanged;
      FCaretPos.SetPoint(NewCP);
      RushBookmarksEx(OldCP, FCaretPos.Data);
    finally
      UnlockVisualUpdates;
    end;
    Changed(ctLineRange, FCaretPos.Y - nlines + 1, LineCount - 1);
    if HadMultiLineSel then
      PostFileChanged(100);
  end;

  Modified;

end;

procedure TTextFile.LockVisualUpdates;
begin
  if Assigned(FOnLockVisualUpdates) then
    FOnLockVisualUpdates(Self);
end;

procedure TTextFile.UnlockVisualUpdates;
begin
  if Assigned(FOnUnlockVisualUpdates) then
    FOnUnlockVisualUpdates(Self);
end;

procedure TTextFile.InsertTextAsBlock(const AText: string);
var
  Lines: DynStringArray;
  nlines, i: integer;
  VirtualCP: TPoint;
  oldlen, newlen: integer;
  j: Integer;
  LAC: boolean;
  ML: integer;
begin

  if FSingleLine and (Pos(#13#10, AText) > 0) then
  begin
    IssueInputError;
    Exit;
  end;

  if EditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if HasSelection then
    ClearSelection;

  Lines := Split(AText, #13#10);
  nlines := Length(Lines);

  if FControlAware then
    for i := FCaretPos.Y to min(LineCount - 1, FCaretPos.Y + nlines - 1) do
      if IsControlLine(i) then
      begin
        IssueInputError;
        Exit;
      end;

  LAC := false;
  if CaretPos.Y + nlines - 1 >= Length(FLines) then
  begin
    InternalAddLines(CaretPos.Y + nlines - 1 + 1 - Length(FLines));
    LAC := true;
  end;

  VirtualCP := CaretPos.Data;
  ML := 0;
  for i := 0 to nlines - 1 do
  begin

    oldlen := Length(FLines[VirtualCP.Y]);
    SetLength(FLines[VirtualCP.Y],
      Max(Length(FLines[VirtualCP.Y]), VirtualCP.X + Length(Lines[i])));
    newlen := Length(FLines[VirtualCP.Y]);
    if newlen > oldlen + Length(Lines[i]) then
      for j := oldlen + 1  to VirtualCP.X do
        FLines[VirtualCP.Y][j] := #$20;

    Move(Lines[i][1], FLines[VirtualCP.Y][VirtualCP.X + 1], Length(Lines[i]) * sizeof(char));

    inc(VirtualCP.Y);

    ML := max(ML, Length(Lines[i]));

  end;

  if LAC then LineArrayChanged;

  with CaretPos.Data do
    Changed(ctBlock, Y, Y + nlines - 1, X, X + ML);

  Modified;
end;

procedure TTextFile.SaveToFile(const FileName: TFileName; TrimRight: boolean;
  AExport: boolean);
var
  FS: TFileStream;
  SW: TStreamWriter;
  i: Integer;
begin

  if FStrictReadOnly then Exit;

  FS := TFileStream.Create(FileName, fmCreate);
  try
    SW := TStreamWriter.Create(FS, FEncoding.GetVCLEncoding);
    try
      if not FEncoding.MagicWord then
        FS.Size := 0;
      case FEncoding.LineBreakType of
        lbtCRLF:
          SW.NewLine := #13#10;
        lbtCR:
          SW.NewLine := #13;
        lbtLF:
          SW.NewLine := #10;
      end;
      if TrimRight then
        for i := 0 to LineCount - 1 do
          if FControlAware and IsControlLine(i) then
            SW.WriteLine(GetDecoratedControlText(i))
          else
            SW.WriteLine(SysUtils.TrimRight(FLines[i]))
      else
        for i := 0 to LineCount - 1 do
          if FControlAware and IsControlLine(i) then
            SW.WriteLine(GetDecoratedControlText(i))
          else
            SW.WriteLine(FLines[i])
    finally
      SW.Free;
    end;
  finally
    FS.Free;
  end;

  if not AExport then
  begin
    FFileName := FileName;
    FModified := false;
    FRecentlyOpened := false;
  end;

end;

procedure TTextFile.SaveToStream(AStream: TStream);
var
  Header: TStreamHeader;
  i: Integer;
begin

  if AStream = nil then
    raise Exception.Create('TTextFile.SaveToStream: Stream is unassigned.');

  FillChar(Header, sizeof(Header), 0);
  Header.Signature := TEXTFILE_SIGNATURE;
  Header.CaretPos := FCaretPos.Data;
  Header.SelEndPos := FCaretPos.SelEnd;
  Header.SelectionType := FCaretPos.SelectionType;
  Header.EditMode := FEditMode;
  Header.Modified := FModified;
  Header.FileName := FFileName;
  Header.LineCount := LineCount;
  Header.Bookmarks := FBookmarks;
  if FEditorState.Valid then
  begin
    Header.ScrollPos := FEditorState.ScrollPos;
    Header.MultiSize := FEditorState.MultiSize;
    Header.Overwrite := FEditorState.Overwrite;
    Header.HiddenChars := FEditorState.HiddenChrs;
    Header.RulerVisible := FEditorState.RulerVisible;
    Header.ZoomLevel := FEditorState.ZoomLevel;
  end;
  Header.Encoding := FEncoding;
  Header.RecentlyOpened := FRecentlyOpened;
  Header.StrictReadOnly := FStrictReadOnly;
  Header.UseLineClasses := FUseLineClasses;
  Header.FPClassName := FEditorState.FormattingProcessor;

  AStream.WriteBuffer(Header, sizeof(Header));
  for i := 0 to Header.LineCount - 1 do
  begin
    AStream.WriteData(Integer(FLines[i].Length));
    AStream.WriteData(Integer(FClasses[i].Length));
  end;

  for i := 0 to Header.LineCount - 1 do
  begin
    if not FLines[i].IsEmpty then
      AStream.WriteBuffer(FLines[i][1], FLines[i].Length * sizeof(char));
    if not FClasses[i].IsEmpty then
      AStream.WriteBuffer(FClasses[i][1], FClasses[i].Length * sizeof(char));
  end;

  AStream.WriteData(TEXTFILE_SIGNATURE_FPCACHE);
  AStream.WriteData(FEditorState.FPCacheLen);
  if (FEditorState.FPCacheLen > 0) and Assigned(FEditorState.FPCache) then
    AStream.WriteBuffer(FEditorState.FPCache^, FEditorState.FPCacheLen);

  FHistoryManager.SaveToStream(AStream);

  AStream.WriteData(TEXTFILE_SIGNATURE);
  AStream.WriteData(#0);

end;

procedure TTextFile.CreateDataStream(out Data: pointer; out Len: UInt64);
var
  MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  try
    SaveToStream(MS);
    Len := MS.Size;
    GetMem(Data, Len);
    try
      CopyMemory(Data, MS.Memory, Len);
    except
      FreeMem(Data);
      raise;
    end;
  finally
    MS.Free;
  end;
end;

procedure TTextFile.SelectAll;
begin
  case FCaretPos.SelectionType of
    stLineBased:
      FCaretPos.CreateSelection(Point(VirtualLineWidths[LineCount - 1], LineCount - 1),
        Point(0, 0),
        stLineBased);
    stBlock:
      FCaretPos.CreateSelection(Point(GetMaxLineWidth, LineCount - 1),
        Point(0, 0),
        stBlock);
  end;
end;

procedure TTextFile.SelectAllNone;
begin
  if AllSelected then
    SelectNone
  else
    SelectAll;
end;

function TTextFile.SelectionIsMultiline: boolean;
begin
  result := FCaretPos.Data.Y <> FCaretPos.SelEnd.Y;
end;

procedure TTextFile.SelectLine(const ALineIndex: integer);
begin
  FCaretPos.CreateSelection(Point(VirtualLineWidths[ALineIndex], ALineIndex),
    Point(0, ALineIndex));
end;

procedure TTextFile.SelectLine;
begin
  FCaretPos.CreateSelection(Point(VirtualLineWidths[FCaretPos.Y], FCaretPos.Y),
    Point(0, FCaretPos.Y));
end;

procedure TTextFile.SelectLines(const ALineA, ALineB: integer);
begin
  if ALineA < ALineB then
    FCaretPos.CreateSelection(Point(0, ALineA),
      Point(VirtualLineWidths[ALineB], ALineB))
  else
    FCaretPos.CreateSelection(Point(VirtualLineWidths[ALineA], ALineA),
      Point(0, ALineB));
end;

procedure TTextFile.SelectNone;
begin
  FCaretPos.RemoveSelection;
end;

function TTextFile.SelectWord: boolean;
var
  S, E: integer;
begin
  result := GetWordBoundary(S, E);
  if result then
  begin
    FCaretPos.SetX(E);
    FCaretPos.SetX(S, true);
  end;
end;

procedure TTextFile.SetCaretAfterEOL(const Value: boolean);
begin
  if FSingleLine and Value then Exit;
  if FCaretAfterEOL <> Value then
  begin
    FCaretAfterEOL := Value;
    if not FCaretAfterEOL and (AtOrBeyondEOL and not AtEOL) then
      FCaretPos.SetX(VirtualLineWidths[FCaretPos.Y]);
  end;
end;

procedure TTextFile.SetChar(Y, X: Integer; const Value: char);
begin
  if CharacterExists(Y, X) then
  begin
    FLines[Y][X + 1] := Value;
    Changed(ctChar, Y, X);
    Modified;
  end;
end;

procedure TTextFile.SetClass(Index: Integer; const Value: string);
begin
  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (Index < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  FClasses[Index] := Value;
end;

procedure TTextFile.SetLine(Index: Integer; const Value: string);
begin
  if (EditMode = emReadOnly) or ((EditMode = emConsole) and (Index < LineCount - 1)) then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  FLines[Index] := Value;
end;

procedure TTextFile.SetSelLength(const Value: integer);
var
  SelEndPos: TPoint;
  FirstPoint, SecondPoint: TPoint;
begin
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  SelEndPos := GetPointOfIndex(GetIndexOfPoint(FirstPoint) + Value);
  if SelEndPos.Y = -1 then
    SelEndPos := Point(VirtualLineWidths[LineCount - 1], LineCount - 1);
  FCaretPos.SetPoint(SelEndPos, true);
end;

procedure TTextFile.SetSelStart(const Value: integer);
begin
  FCaretPos.SetPoint(GetPointOfIndex(Value));
end;

procedure TTextFile.SetSingleLine(const Value: boolean);
begin
  if FSingleLine <> Value then
  begin
    FSingleLine := Value;
    if FSingleLine and (Length(FLines) > 1) then
      SetText(GetSingleLineText);
    if FSingleLine then
      SetCaretAfterEOL(false);
  end;
end;

procedure TTextFile.SetText(const Value, Classes: string);
var
  i, nlines, prevsep: integer;
  indices: DynIntegerArray;
begin
  nlines := Occurrences(Value, #13#10, indices) + 1;
  SetLength(FLines, nlines);
  SetLength(indices, Length(indices) + 1);
  indices[high(indices)] := length(Value) + 1;
  prevsep := 1 - length(#13#10);
  for i := 0 to high(indices) do // high(indices) = nlines - 1 = LineCount - 1
  begin
    FLines[i] := Copy(Value, prevsep + length(#13#10), indices[i] - prevsep - length(#13#10));
    prevsep := indices[i];
  end;
  nlines := Occurrences(Classes, #13#10, indices) + 1;
  SetLength(FClasses, nlines);
  SetLength(indices, Length(indices) + 1);
  indices[high(indices)] := length(Classes) + 1;
  prevsep := 1 - length(#13#10);
  for i := 0 to high(indices) do // high(indices) = nlines - 1 = LineCount - 1
  begin
    FClasses[i] := Copy(Classes, prevsep + length(#13#10), indices[i] - prevsep - length(#13#10));
    prevsep := indices[i];
  end;
  LineArrayChanged;
  Changed(ctFile);
  GotoEOF;
  Modified;
end;

const
  SortTestStrA = 'baJbnHrkM7';
  SortTestStrB = 'jhn5V';

function TTextFile.Sort(AFirstLine, ALastLine: integer;
  BookmarkAware: boolean): boolean;
begin

  result := false;

  if not Assigned(FLineComparer) then
    raise EInvalidOperation.Create(SNoLineComparer);

  if FLineComparer(SortTestStrA, SortTestStrB) * FLineComparer(SortTestStrB, SortTestStrA) > 0 then
    raise EInvalidOperation.Create(SIllegalLineComparer);


  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if AFirstLine >= ALastLine then Exit;
  result := true;

  SortRecursive(AFirstLine, ALastLine, BookmarkAware);

  LineArrayChanged;
  CaretPos.SetPoint(0, AFirstLine);
  LineClassChanged(AFirstLine);
  Changed(ctLineRange, AFirstLine, ALastLine);
  Modified;

  if BookmarkAware then
    BookmarksMoved;
end;

procedure TTextFile.SortRecursive(AFirstLine, ALastLine: integer;
  BookmarkAware: boolean = true);

  function Partition(A, B: integer): integer;
  var
    pivot: string;
    i, j: integer;
    Rv: integer;
  begin
    Rv := IfThen(FSortReverseOrder, -1, 1);
    pivot := FLines[A + (B - A) div 2];
    i := A;
    j := B;
    repeat
      while Rv * FLineComparer(FLines[i], pivot) < 0 do inc(i);
      while Rv * FLineComparer(FLines[j], pivot) > 0 do dec(j);
      if i <= j then
      begin
        InternalSwapLines(i, j, BookmarkAware);
        inc(i);
        dec(j);
      end;
    until i > j;
    result := i;
  end;

var
  p: integer;

begin

  if AFirstLine < ALastLine then
  begin
    p := Partition(AFirstLine, ALastLine);
    SortRecursive(AFirstLine, p - 1);
    SortRecursive(p, ALastLine);
  end;

end;

function TTextFile.Sort(BookmarkAware: boolean): boolean;
begin
  result := Sort(0, LineCount - 1, BookmarkAware);
end;

function TTextFile.SortSelection(BookmarkAware: boolean): boolean;
var
  FirstPoint, SecondPoint: TPoint;
begin
  result := false;
  if not HasSelection then Exit;
  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
  result := Sort(FirstPoint.Y, SecondPoint.Y, BookmarkAware);
end;

procedure TTextFile.SurroundText(const APrefix, APostfix: string);
var
  FirstPoint, SecondPoint: TPoint;
begin
  if SelectionIsMultiline then
  begin
    if EditMode <> emText then
    begin
      IssueReadOnlyError;
      Exit;
    end;

    SanitizeSelection;

    FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
    if IsControlLine(FirstPoint.Y) or IsControlLine(SecondPoint.Y) then
    begin
      IssueInputError;
      Exit;
    end;

    Insert(APrefix, FLines[FirstPoint.Y], FirstPoint.X + 1);
    Insert(APostfix, FLines[SecondPoint.Y], SecondPoint.X + 1);

    PushBookmarks(FirstPoint.Y, FirstPoint.X, Length(APrefix));
    PushBookmarks(SecondPoint.Y, SecondPoint.X, Length(APostfix));

    inc(FirstPoint.X, Length(APrefix));
    LockVisualUpdates;
    try
      FCaretPos.CreateSelection(FirstPoint, SecondPoint);
    finally
      UnlockVisualUpdates;
      Changed(ctLineRange, FirstPoint.Y, SecondPoint.Y);
    end;

  end
  else if HasSelection then
  begin

    if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FCaretPos.Y <> LineCount - 1)) then
    begin
      IssueReadOnlyError;
      Exit;
    end;

    if IsControlLine(FCaretPos.Y) then
    begin
      IssueInputError;
      Exit;
    end;

    SanitizeSelection;

    FCaretPos.GetSelBdry(FirstPoint, SecondPoint);
    Insert(APrefix, FLines[FirstPoint.Y], FirstPoint.X + 1);
    Insert(APostfix, FLines[SecondPoint.Y], SecondPoint.X + Length(APrefix) + 1);

    PushBookmarks(FCaretPos.Y, FirstPoint.X, Length(APrefix));
    PushBookmarks(FCaretPos.Y, SecondPoint.X + Length(APrefix), Length(APostfix));

    inc(FirstPoint.X, Length(APrefix));
    inc(SecondPoint.X, Length(APrefix));
    LockVisualUpdates;
    try
      FCaretPos.CreateSelection(FirstPoint, SecondPoint);
    finally
      UnlockVisualUpdates;
      Changed(ctLine, FirstPoint.Y);
    end;

  end
  else
  begin

    if (EditMode = emReadOnly) or ((EditMode = emConsole) and (FCaretPos.Y <> LineCount - 1)) then
    begin
      IssueReadOnlyError;
      Exit;
    end;

    if IsControlLine(FCaretPos.Y) then
    begin
      IssueInputError;
      Exit;
    end;

    Insert(GetVirtualSpace(FCaretPos.Y, FCaretPos.X) + APrefix + APostfix, FLines[FCaretPos.Y], FCaretPos.X + 1);

    PushBookmarks(FCaretPos.Y, FCaretPos.X, Length(APrefix) + Length(APostfix));

    FCaretPos.SetX(FCaretPos.X + Length(APrefix));
    Changed(ctLine, FCaretPos.Y);
  end;

  Modified;
end;

procedure TTextFile.SanitizeSelection;
var
  FirstPoint, SecondPoint: TPoint;
begin
  if not (HasSelection and (FCaretPos.SelectionType = stLineBased)) then Exit;

  FCaretPos.GetSelBdry(FirstPoint, SecondPoint);

  if SecondPoint.X > VirtualLineWidths[SecondPoint.Y] then
    SecondPoint.X := VirtualLineWidths[SecondPoint.Y];

  if FirstPoint.X > VirtualLineWidths[FirstPoint.Y] then
    FirstPoint.X := VirtualLineWidths[FirstPoint.Y];

  FCaretPos.CreateSelection(FirstPoint, SecondPoint);

end;

function TTextFile.SushBookmarks(FirstLine, SecondLine: integer; Silent: boolean = false): boolean; // e.g. SwapLines
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if FBookmarks[i].Y = FirstLine then
    begin
      result := true;
      FBookmarks[i].Y := SecondLine;
    end
    else if FBookmarks[i].Y = SecondLine then
    begin
      result := true;
      FBookmarks[i].Y := FirstLine;
    end;
  if result and not Silent then BookmarksMoved;
end;

procedure TTextFile.SetText(const Value: string);
var
  i, nlines, prevsep: integer;
  indices: DynIntegerArray;
begin
  nlines := Occurrences(Value, #13#10, indices) + 1;
  SetLength(FLines, nlines);
  SetLength(FClasses, nlines);
  SetLength(indices, Length(indices) + 1);
  indices[high(indices)] := length(Value) + 1;
  prevsep := 1 - length(#13#10);
  for i := 0 to high(indices) do // high(indices) = nlines - 1 = LineCount - 1
  begin
    FLines[i] := Copy(Value, prevsep + length(#13#10), indices[i] - prevsep - length(#13#10));
    prevsep := indices[i];
    if FControlAware and SameStr(Copy(FLines[i], 1, Length(LINE_CONTROL_PREFIX)), LINE_CONTROL_PREFIX) then
      FClasses[i] := LINE_CONTROL_CLASS
    else
      FClasses[i] := '';
  end;
  LineArrayChanged;
  Changed(ctFile);
  GotoEOF;
  Modified;
end;

function TTextFile.SwapLines(FirstLine, SecondLine: integer): boolean;
var
  tmpLine: string;
  tmpClass: string;
begin

  result := false;

  if SingleLine then
    Exit;

  if EditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  if not (InRange(FirstLine, 0, LineCount - 1) and InRange(SecondLine, 0, LineCount - 1)) then
  begin
    IssueInputError;
    Exit;
  end;

  if FirstLine = SecondLine then Exit;

  tmpLine := FLines[FirstLine];
  tmpClass := FClasses[FirstLine];
  FLines[FirstLine] := FLines[SecondLine];
  FClasses[FirstLine] := FClasses[SecondLine];
  FLines[SecondLine] := tmpLine;
  FClasses[SecondLine] := tmpClass;

  SushBookmarks(FirstLine, SecondLine);

  LineArrayChanged;

  if FirstLine = FCaretPos.Y then
    FCaretPos.SetPoint(FCaretPos.X, SecondLine)
  else if SecondLine = FCaretPos.Y then
    FCaretPos.SetPoint(FCaretPos.X, FirstLine);


  Changed(ctLine, FirstLine);
  Changed(ctLine, SecondLine);
  Modified;

  result := true;
end;

procedure TTextFile.LineArrayChanged;
begin
  if Assigned(FOnLineChange) then
    FOnLineChange(Self, lctAll, 0);
end;

procedure TTextFile.LineClassChanged(LineIndex: integer);
begin
  if Assigned(FOnLineClassChange) then
    FOnLineClassChange(Self, LineIndex);
end;

function TTextFile.LineExists(LineIndex: integer): boolean;
begin
  result := InRange(LineIndex, 0, LineCount - 1);
end;

function TTextFile.SwapLinesAbove: boolean;
begin
  result := SwapLines(FCaretPos.Y, FCaretPos.Y - 1);
end;

function TTextFile.SwapLinesBelow: boolean;
begin
  result := SwapLines(FCaretPos.Y, FCaretPos.Y + 1);
end;

function TTextFile.TextIsMultiline(const AText: string): boolean;
begin
  result := Pos(#13#10, AText) > 0;
end;

procedure TTextFile.TrimRight;
var
  i: Integer;
begin

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  for i := 0 to Length(FLines) - 1 do
    FLines[i] := SysUtils.TrimRight(FLines[i]);
  if (not FCaretAfterEOL) and (FCaretPos.Data.X > VirtualLineWidths[FCaretPos.Data.Y]) then
    FCaretPos.SetX(VirtualLineWidths[FCaretPos.Data.Y]);
  Changed(ctFile); // the change *is* visible if hidden characters are displayed
  Modified;

end;

procedure TTextFile.TruncateAt(AFirstLine, ALastLine, AIndex: integer;
  AChar: char = #0; PreserveChar: boolean = false; AReverse: boolean = false);

  function NthPos(BLineIndex: integer; N: integer): integer;
  var
    i, c: integer;
  begin
    result := 0;
    c := 0;
    for i := 1 to Length(FLines[BLineIndex]) do
    begin
      if FLines[BLineIndex][i] = AChar then
        inc(c);
      if c = N then
        Exit(i);
    end;
  end;

  function NthPosRev(BLineIndex: integer; N: integer): integer;
  var
    i, c: integer;
  begin
    result := 0;
    c := 0;
    for i := Length(FLines[BLineIndex]) downto 1 do
    begin
      if FLines[BLineIndex][i] = AChar then
        inc(c);
      if c = N then
        Exit(i);
    end;
  end;

  procedure DoTruncate(BLineIndex: integer; N: integer);
  begin
    if AReverse then
      System.Delete(FLines[BLineIndex], 1, N - 1)
    else
      SetLength(FLines[BLineIndex], N);
  end;

var
  y, MLW: integer;
  p: integer;
  offset: integer;

begin

  if FEditMode <> emText then
  begin
    IssueReadOnlyError;
    Exit;
  end;

  MLW := 0;
  for y := AFirstLine to ALastLine do
    if Length(FLines[y]) > MLW then
      MLW := Length(FLines[y]);

  offset := IfThen(PreserveChar, 1, 0);
  if AReverse and not PreserveChar then inc(offset, 2);

  if AChar = #0 then
  begin
    for y := AFirstLine to ALastLine do
      if (Length(FLines[y]) > AIndex) or AReverse then
        DoTruncate(y, AIndex);
  end
  else if AIndex > 0 then
  begin
    for y := AFirstLine to ALastLine do
    begin
      p := NthPos(y, AIndex);
      if p > 0 then
        DoTruncate(y, p - 1 + Offset);
    end;
  end
  else if AIndex < 0 then
  begin
    for y := AFirstLine to ALastLine do
    begin
      p := NthPosRev(y, -AIndex);
      if p > 0 then
        DoTruncate(y, p - 1 + Offset);
    end;
  end;

  Changed(ctBlock, AFirstLine, ALastLine, AIndex, MLW);
  Modified;
  FCaretPos.SetPoint(0, AFirstLine);

  RemoveGhostBookmarks;
end;

function TTextFile.RemoveGhostBookmarks: boolean;
var
  i: integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if not SamePoint(FBookmarks[i], EMPTY_BOOKMARK) then
      if (FBookmarks[i].Y >= Length(FLines)) or (FBookmarks[i].X > VirtualLineWidths[FBookmarks[i].Y]) then
      begin
        FBookmarks[i] := EMPTY_BOOKMARK;
        result := true;
      end;
  if result then
    BookmarksMoved;
end;

function TTextFile.TushBookmarks(Line, NumLines: integer): boolean; // e.g. InsertLine
begin
  result := TushBookmarksInternal(Line, NumLines);
  if result then BookmarksMoved;
end;

function TTextFile.TushBookmarksInternal(Line, NumLines: integer): boolean;
var
  i: Integer;
begin
  result := false;
  for i := low(FBookmarks) to high(FBookmarks) do
    if FBookmarks[i].Y >= Line then
    begin
      result := true;
      inc(FBookmarks[i].Y, NumLines);
    end;
end;

function TTextFile.DeleteBookmarksOnLine(Line: integer): boolean;
var
  i: Integer;
begin
  result := False;
  for i := low(FBookmarks) to high(FBookmarks) do
    if FBookmarks[i].Y = Line then
    begin
      result := true;
      FBookmarks[i] := EMPTY_BOOKMARK;
    end;
end;

{ TCaretPos }

procedure TCaretPos.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

constructor TCaretPos.Create;
begin
  FCaretPos := Point(0, 0);
  FSelectionType := stLineBased;
end;

procedure TCaretPos.CreateSelection(const ASelStart, ASelEnd: TPoint;
  const ASelectionType: TSelectionType);
var
  CurFirstPoint, CurSecondPoint: TPoint;
  NewFirstPoint, NewSecondPoint: TPoint;
begin
  if (ASelectionType = FSelectionType) and (ASelectionType = stLineBased) then
  begin
    GetSelBdry(CurFirstPoint, CurSecondPoint);
    GetSelBdry(ASelStart, ASelEnd, NewFirstPoint, NewSecondPoint);

    SaveSelExtent;
    FSelectionType := ASelectionType;
    FCaretPos := ASelEnd;
    FSelStartPos := ASelStart;

    if SamePoint(CurFirstPoint, NewFirstPoint) then
      if CurSecondPoint.Y = NewSecondPoint.Y then
        SelChanged(ctBlock, CurFirstPoint.Y, CurFirstPoint.Y,
          min(CurSecondPoint.X, NewSecondPoint.X),
          max(CurSecondPoint.X, NewSecondPoint.X))
      else
        SelChanged(ctLineRange, min(CurSecondPoint.Y, NewSecondPoint.Y),
          max(CurSecondPoint.Y, NewSecondPoint.Y), 0, 0)
    else if SamePoint(CurSecondPoint, NewSecondPoint) then
      if CurFirstPoint.Y = NewFirstPoint.Y then
        SelChanged(ctBlock, CurFirstPoint.Y, CurFirstPoint.Y,
          min(CurFirstPoint.X, NewFirstPoint.X),
          max(CurFirstPoint.X, NewFirstPoint.X))
      else
        SelChanged(ctLineRange, min(CurFirstPoint.Y, NewFirstPoint.Y),
          max(CurFirstPoint.Y, NewFirstPoint.Y), 0, 0)
    else
    begin
      SelRemoved;
      with GetSelExtent(FCaretPos, FSelStartPos, FSelectionType) do
        SelChanged(ChangeType, Data1, Data2, Data3, Data4);
    end;

    Changed;
  end
  else
  begin
    SaveSelExtent;
    FSelectionType := ASelectionType;
    FCaretPos := ASelEnd;
    FSelStartPos := ASelStart;
    SelRemoved;
    with GetSelExtent(FCaretPos, FSelStartPos, FSelectionType) do
      SelChanged(ChangeType, Data1, Data2, Data3, Data4);
    Changed;
  end;
end;

procedure TCaretPos.SaveSelExtent;
begin
  FSavedSelExtent := GetSelExtent(FCaretPos, FSelStartPos, FSelectionType);
end;

procedure TCaretPos.SelChanged(ChangeType: TChangeType; Data1, Data2, Data3,
  Data4: integer);
begin
  if Assigned(FOnSelChange) then
    FOnSelChange(Self, ChangeType, Data1, Data2, Data3, Data4);
end;

procedure TCaretPos.SelRemoved;
begin
  if FSavedSelExtent.ChangeType = ctNone then Exit; // There was no selection.
  if Assigned(FOnSelChange) then
    FOnSelChange(Self, FSavedSelExtent.ChangeType,
      FSavedSelExtent.Data1, FSavedSelExtent.Data2, FSavedSelExtent.Data3,
      FSavedSelExtent.Data4);
end;

procedure TCaretPos.SetPoint(Point: TPoint; SelEnd: boolean);
begin
  SetPoint(Point.X, Point.Y, SelEnd);
end;

procedure TCaretPos.SetPoint(X, Y: integer; SelEnd: boolean);
var
  OldCaretPos: TPoint;
  OldExtent, NewExtent: TChangeRecord;
begin

  // Optimize?
  if FCaretPos.Y = Y then
    SetX(X, SelEnd)
  else if FCaretPos.X = X then
    SetY(Y, SelEnd)
  else
    if SelEnd then
    begin
      case FSelectionType of
        stLineBased:
          OldCaretPos := FCaretPos;
        stBlock:
          OldExtent := GetSelExtent(FCaretPos, FSelStartPos, stBlock);
      end;
      SetSelEndPos(Point(X,Y));
      case FSelectionType of
        stLineBased:
          SelChanged(ctLineRange, min(OldCaretPos.Y, Y), max(OldCaretPos.Y, Y), 0, 0);
        stBlock:
          begin
            NewExtent := GetSelExtent(FCaretPos, FSelStartPos, stBlock);

            if (NewExtent.Data1 = OldExtent.Data1) and (NewExtent.Data3 = OldExtent.Data3) then
            begin
              SelChanged(ctBlock, Min(NewExtent.Data2, OldExtent.Data2), Max(NewExtent.Data2, OldExtent.Data2), NewExtent.Data3, Max(NewExtent.Data4, OldExtent.Data4));
              SelChanged(ctBlock, NewExtent.Data1, Min(NewExtent.Data2, OldExtent.Data2), Min(NewExtent.Data4, OldExtent.Data4), Max(NewExtent.Data4, OldExtent.Data4));
            end
            else if (NewExtent.Data1 = OldExtent.Data1) and (NewExtent.Data4 = OldExtent.Data4) then
            begin
              SelChanged(ctBlock, Min(NewExtent.Data2, OldExtent.Data2), Max(NewExtent.Data2, OldExtent.Data2), Min(NewExtent.Data3, OldExtent.Data3), NewExtent.Data4);
              SelChanged(ctBlock, NewExtent.Data1, Min(NewExtent.Data2, OldExtent.Data2), Min(NewExtent.Data3, OldExtent.Data3), Max(NewExtent.Data3, OldExtent.Data3));
            end
            else if (NewExtent.Data2 = OldExtent.Data2) and (NewExtent.Data3 = OldExtent.Data3) then
            begin
              SelChanged(ctBlock, Min(NewExtent.Data1, OldExtent.Data1), Max(NewExtent.Data1, OldExtent.Data1), NewExtent.Data3, Max(NewExtent.Data4, OldExtent.Data4));
              SelChanged(ctBlock, Max(NewExtent.Data1, OldExtent.Data1), NewExtent.Data2, Min(NewExtent.Data4, OldExtent.Data4), Max(NewExtent.Data4, OldExtent.Data4));
            end
            else if (NewExtent.Data2 = OldExtent.Data2) and (NewExtent.Data4 = OldExtent.Data4) then
            begin
              SelChanged(ctBlock, Min(NewExtent.Data1, OldExtent.Data1), Max(NewExtent.Data1, OldExtent.Data1), Min(NewExtent.Data3, OldExtent.Data3), NewExtent.Data4);
              SelChanged(ctBlock, Max(NewExtent.Data1, OldExtent.Data1), NewExtent.Data2, Min(NewExtent.Data3, OldExtent.Data3), Max(NewExtent.Data3, OldExtent.Data3));
            end
            else
            begin // General case
              with OldExtent do                                      // TODO: this sucks, sym diff would be awesome
                SelChanged(ctBlock, Data1, Data2, Data3, Data4);
              with NewExtent do
                SelChanged(ctBlock, Data1, Data2, Data3, Data4);
            end;
          end;
      end;
    end
    else
      SetCaretPos(Point(X,Y));
end;

procedure TCaretPos.SetSelectionType(const Value: TSelectionType);
begin
  if FSelectionType <> Value then
  begin
    if FCaretPos.Y <> FSelStartPos.Y then RemoveSelection;
    FSelectionType := Value;
  end;
end;

procedure TCaretPos.SetCaretPos(const Value: TPoint);
begin
  SaveSelExtent;
  FCaretPos := Value;
  FSelStartPos := Value;
  SelRemoved;
  Changed;
  SelectionType := stLineBased;
end;

procedure TCaretPos.SetSelEndPos(const Value: TPoint);
begin
  if (FCaretPos.X <> Value.X) or (FCaretPos.Y <> Value.Y) then
  begin
    FCaretPos := Value;
    Changed;
  end;
end;

procedure TCaretPos.SetX(X: integer; SelEnd: boolean);
var
  OldCaretPos: TPoint;
begin
  if SelEnd then
  begin
    OldCaretPos := FCaretPos;
    SetSelEndPos(Point(X, FCaretPos.Y));
    case FSelectionType of
      stLineBased:
        SelChanged(ctBlock, FCaretPos.Y,
                            FCaretPos.Y,
                            min(OldCaretPos.X, X),
                            max(OldCaretPos.X, X));
      stBlock:
        SelChanged(ctBlock, min(OldCaretPos.Y, FSelStartPos.Y),
                            max(OldCaretPos.Y, FSelStartPos.Y),
                            min(OldCaretPos.X, X),
                            max(OldCaretPos.X, X));
    end;
  end
  else
    SetCaretPos(Point(X, FCaretPos.Y));
end;

procedure TCaretPos.SetY(Y: integer; SelEnd: boolean);
var
  OldCaretPos: TPoint;
begin
  if SelEnd then
  begin
    OldCaretPos := FCaretPos;
    SetSelEndPos(Point(FCaretPos.X, Y));
    case FSelectionType of
      stLineBased:
        SelChanged(ctLineRange, min(OldCaretPos.Y, Y), max(OldCaretPos.Y, Y), 0, 0);
      stBlock:
        SelChanged(ctBlock, min(OldCaretPos.Y, Y),
                            max(OldCaretPos.Y, Y),
                            min(FSelStartPos.X, FCaretPos.X),
                            max(FSelStartPos.X, FCaretPos.X));
    end;
  end
  else
    SetCaretPos(Point(FCaretPos.X, Y));
end;

function TCaretPos.GetFirstPoint: TPoint;
var
  dummy: TPoint;
begin
  GetSelBdry(result, dummy);
end;

function TCaretPos.GetLastPoint: TPoint;
var
  dummy: TPoint;
begin
  GetSelBdry(dummy, result);
end;

procedure TCaretPos.GetSelBdry(out FirstPoint, SecondPoint: TPoint);
begin
  GetSelBdry(FCaretPos, FSelStartPos, FirstPoint, SecondPoint);
end;

procedure TCaretPos.GetSelBdry(const PointA, PointB: TPoint; out FirstPoint,
  SecondPoint: TPoint);
begin
  case FSelectionType of
    stLineBased:
      begin
        if (PointA.Y < PointB.Y) or ((PointA.Y = PointB.Y) and (PointA.X <= PointB.X)) then
        begin
          FirstPoint := PointA;
          SecondPoint := PointB;
        end
        else
        begin
          FirstPoint := PointB;
          SecondPoint := PointA;
        end;
      end;
    stBlock:
      begin // FirstPoint: top-left corner; SecondPoint: bottom-right corner
        FirstPoint.Y := min(PointA.Y, PointB.Y);
        FirstPoint.X := min(PointA.X, PointB.X);
        SecondPoint.Y := max(PointA.Y, PointB.Y);
        SecondPoint.X := max(PointA.X, PointB.X);
      end;
  end;
end;

function TCaretPos.GetSelExtent(ACaretPos, ASelEndPos: TPoint;
  ASelectionType: TSelectionType): TChangeRecord;
var
  FirstPoint, SecondPoint: TPoint;
begin
  if SamePoint(ACaretPos, ASelEndPos) then
    Exit(NO_CHANGE_RECORD);
  GetSelBdry(FirstPoint, SecondPoint);
  case ASelectionType of
    stLineBased:
      begin
        if FirstPoint.Y = SecondPoint.Y then
        begin
          result.ChangeType := ctBlock;
          result.Data1 := FirstPoint.Y;
          result.Data2 := SecondPoint.Y;
          result.Data3 := FirstPoint.X;
          result.Data4 := SecondPoint.X;
        end
        else
        begin
          result.ChangeType := ctLineRange;
          result.Data1 := FirstPoint.Y;
          result.Data2 := SecondPoint.Y;
        end;
      end;
    stBlock:
      begin
        result.ChangeType := ctBlock;
        result.Data1 := FirstPoint.Y;
        result.Data2 := SecondPoint.Y;
        result.Data3 := FirstPoint.X;
        result.Data4 := SecondPoint.X;
      end;
  end;
end;

// Caution: Internal! No sel change notification
procedure TCaretPos.InternalPush(Size: integer; LastLine: boolean = true);
begin
  if LastLine or (FSelStartPos.Y < FCaretPos.Y) then
    inc(FSelStartPos.X, Size);
  if LastLine or (FCaretPos.Y < FSelStartPos.Y) then
    inc(FCaretPos.X, Size);

  if FSelStartPos.X < 0 then FSelStartPos.X := 0;
  if FCaretPos.X < 0 then FCaretPos.X := 0;
  Changed;
end;

procedure TCaretPos.RemoveSelection;
begin
  SaveSelExtent;
  FSelStartPos := FCaretPos;
  SelRemoved;
  Changed;
  SelectionType := stLineBased;
end;

procedure TCaretPos.Reset;
begin
  FCaretPos := Point(0, 0);
  FSelStartPos := Point(0, 0);
  FSelectionType := stLineBased;
  FillChar(FSavedSelExtent, sizeof(FSavedSelExtent), 0);
end;

function TTextFile.GetText: string;
var
  i, p: Integer;
begin
  SetLength(result, GetPhysicalTextLength);
  p := 1;
  for i := 0 to LineCount - 1 do
  begin
    if not FLines[i].IsEmpty then
      Move(FLines[i][1], result[p], PhysicalLineWidths[i] * SizeOf(Char));
    if i < LineCount - 1 then
    begin
      inc(p, PhysicalLineWidths[i] + 2);
      result[p-2] := #13;
      result[p-1] := #10;
    end;
  end;
end;

function TTextFile.GetUnicodeBlockStatistics: TIntegerArray;
var
  y, x, i: Integer;
begin
  SetLength(result, UCD.BlockCount);
  ZeroMemory(@result[0], Length(result) * sizeof(result[0]));
  for y := 0 to Length(FLines) - 1 do
  begin
    if IsControlLine(y) then Continue;
    for x := 1 to Length(FLines[y]) do
      for i := 0 to UCD.BlockCount - 1 do
        if InRange(ord(FLines[y][x]), UCD.Blocks[i].BlockBegin, UCD.Blocks[i].BlockEnd) then
        begin
          inc(result[i]);
          break;
        end;
  end;
end;

function TTextFile.GetURLAtCaret(out AURL: string): boolean;

  function IsURLChar(const C: char): boolean;
  begin
    result := C.IsLetterOrDigit or
      (C in ['!', '$', '&', '''', '(', ')', '*', '+', ',', '-', '.', '/', ':',
        ';', '=', '?', '@', '_', '~', '%', '#']);
  end;

var
  S, E: integer; {incl.}
  x: integer;

begin
  S := 0;
  E := PhysicalLineWidths[FCaretPos.Y] - 1;
  if FCaretPos.X > PhysicalLineWidths[FCaretPos.Y] then Exit(false);
  for x := FCaretPos.X - 1 downto 0 do
    if not IsURLChar(FLines[FCaretPos.Y][x+1]) then
    begin
      S := x + 1;
      break;
    end;
  for x := FCaretPos.X to E do
    if not IsURLChar(FLines[FCaretPos.Y][x+1]) then
    begin
      E := x - 1;
      break;
    end;
  AURL := Copy(FLines[FCaretPos.Y], S + 1, E - S + 1);
  result := StartsText('http://', AURL) or StartsText('https://', AURL) or
    StartsText('ftp://', AURL) or StartsText('file:', AURL) or
    StartsText('gopher://', AURL) or StartsText('ws://', AURL) or
    StartsText('wss://', AURL) or StartsText('mailto:', AURL) or StartsText('www.', AURL);
end;

function TTextFile.GetUsedBookmarkCount: integer;
var
  i: Integer;
begin
  result := 0;
  for i := 0{sic!} to high(FBookmarks) do
    if not SamePoint(FBookmarks[i], EMPTY_BOOKMARK) then
      inc(result);
end;

{ THistoryManager }

procedure THistoryManager.Add(const AText: string; const AClasses: string;
  const ACaretPos, ASelStartPos: TPoint; ASelType: TSelectionType;
  const ATime: TDateTime; const AComment: string;
  const ABookmarks: TBookmarkList; AUID: integer = 0);
var
  UDA: TUndoDataItem;
begin
  UDA.Text := AText;
  UDA.Classes := AClasses;
  UDA.CaretPos := ACaretPos;
  UDA.SelStartPos := ASelStartPos;
  UDA.SelType := ASelType;
  UDA.Time := ATime;
  UDA.Comment := AComment;
  UDA.UID := AUID;
  UDA.Bookmarks := ABookmarks;
  Add(UDA);
end;

procedure THistoryManager.Add(AUndoDataItem: TUndoDataItem);
begin

  if FHistoryIndex < FActualLength - 1 then
    Revert;

  if FActualLength = length(FUndoData) then
    SetLength(FUndoData, Length(FUndoData) + HISTORY_ALLOC_BY);
  FUndoData[FActualLength] := AUndoDataItem;
  inc(FSize, SizeOfItem(FActualLength));
  inc(FActualLength);
  inc(FHistoryIndex);
  TrimLeft;

end;

function THistoryManager.CanRedo: boolean;
begin
  result := FHistoryIndex < FActualLength - 1;
end;

function THistoryManager.CanUndo: boolean;
begin
  result := FHistoryIndex > FFirstItem;
end;

procedure THistoryManager.Clear;
begin
  SetLength(FUndoData, 0);
  FActualLength := 0;
  FSize := 0;
  FFirstItem := 0;
  FHistoryIndex := -1;
end;

procedure THistoryManager.ClearItem(ItemIndex: integer);
begin
  with FUndoData[ItemIndex] do
  begin
    dec(FSize, (Length(Text) + Length(Classes) + Length(Comment)) * sizeof(char));
    Text := '';
    Classes := '';
    CaretPos := Point(0, 0);
    SelStartPos := Point(0, 0);
    Time := 0;
    Comment := '';
  end;
end;

constructor THistoryManager.Create;
begin
  inherited;
  FMaxSize := DEFAULT_MAX_UNDO_SIZE;
  Clear;
end;

procedure THistoryManager.CreateDataStream(out Data: pointer; out Len: UInt64);
var
  MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  try
    SaveToStream(MS);
    Len := MS.Size;
    GetMem(Data, Len);
    try
      CopyMemory(Data, MS.Memory, Len);
    except
      FreeMem(Data);
      raise;
    end;
  finally
    MS.Free;
  end;
end;

destructor THistoryManager.Destroy;
begin
  inherited;
  Clear;
end;

function THistoryManager.GetLastItem: integer;
begin
  result := FActualLength - 1;
end;

function THistoryManager.GetLength: integer;
begin
  result := FActualLength - FFirstItem;
end;

function THistoryManager.GetUndoData(Index: integer): TUndoDataItem;
begin
  result := FUndoData[Index];
end;

function THistoryManager.GotoVersion(Index: integer;
  out UndoData: TUndoDataItem): boolean;
begin
  result := InRange(Index, FFirstItem, FActualLength - 1) and (Index <> FHistoryIndex);
  if result then
  begin
    UndoData := FUndoData[Index];
    FHistoryIndex := Index;
  end;
end;

procedure THistoryManager.LoadFromBuffer(const Data: pointer;
  const Len: UInt64);
var
  MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  try
    MS.WriteBuffer(Data^, Len);
    MS.Position := 0;
    LoadFromStream(MS);
  finally
    MS.Free;
  end;
end;

procedure THistoryManager.LoadFromStream(AStream: TStream);

  procedure Inv;
  begin
    raise Exception.Create('THistoryManager.LoadFromStream: Invalid stream.');
  end;

var
  data_dword: DWORD;
  data_char: char;
  len, size, idx, strlen: integer;
  i: Integer;
begin

  if AStream = nil then
    raise Exception.Create('THistoryManager.LoadFromStream: Stream is unassigned.');

  AStream.ReadData(data_dword);
  if data_dword <> UNDO_SIGNATURE then Inv;

  AStream.ReadData(len);
  if len < 0 then Inv;

  AStream.ReadData(size);
  if size < 0 then Inv;

  AStream.ReadData(idx);
  if (len > 0) and not InRange(idx, 0, len - 1) then Inv;

  Clear;
  try

    SetLength(FUndoData, len);
    for i := 0 to len - 1 do
    begin

      AStream.ReadData(data_dword);
      if data_dword <> UNDO_SIGNATURE_ITEM then Inv;

      AStream.ReadData(strlen);
      if strlen < 0 then Inv;
      SetLength(FUndoData[i].Text, strlen);
      if strlen > 0 then
      AStream.ReadBuffer(FUndoData[i].Text[1], strlen * sizeof(char));

      AStream.ReadData(strlen);
      if strlen < 0 then Inv;
      SetLength(FUndoData[i].Classes, strlen);
      if strlen > 0 then
      AStream.ReadBuffer(FUndoData[i].Classes[1], strlen * sizeof(char));

      AStream.ReadBuffer(FUndoData[i].CaretPos, sizeof(FUndoData[i].CaretPos));
      AStream.ReadBuffer(FUndoData[i].SelStartPos, sizeof(FUndoData[i].SelStartPos));
      AStream.ReadBuffer(FUndoData[i].SelType, sizeof(FUndoData[i].SelType));
      AStream.ReadBuffer(FUndoData[i].Time, sizeof(FUndoData[i].Time));

      AStream.ReadData(strlen);
      if strlen < 0 then Inv;
      SetLength(FUndoData[i].Comment, strlen);
      if strlen > 0 then
      AStream.ReadBuffer(FUndoData[i].Comment[1], strlen * sizeof(char));

      AStream.ReadBuffer(FUndoData[i].UID, sizeof(FUndoData[i].UID));
      AStream.ReadBuffer(FUndoData[i].Bookmarks, sizeof(FUndoData[i].Bookmarks));

    end;

    AStream.ReadData(data_dword);
    AStream.ReadData(data_char);
    if (data_dword <> UNDO_SIGNATURE) or (data_char <> #0) then Inv;

    FFirstItem := 0;
    FActualLength := Length(FUndoData);
    FHistoryIndex := idx;
    FSize := size;

  except
    Clear;
    raise;
  end;

end;

function THistoryManager.Redo(out UndoData: TUndoDataItem): boolean;
begin
  result := CanRedo;
  if result then
  begin
    UndoData := FUndoData[FHistoryIndex + 1];
    inc(FHistoryIndex);
  end;
end;

function THistoryManager.RemoveFirstItem;
begin
  result := false;
  if FFirstItem >= FActualLength then Exit;
  ClearItem(FFirstItem);
  inc(FFirstItem);
  result := true;
end;

procedure THistoryManager.Revert;
var
  OldHistoryIndex: integer;
begin
  OldHistoryIndex := FHistoryIndex;
  FHistoryIndex := FActualLength - 1;
  with FUndoData[OldHistoryIndex] do
    Add(Text, Classes, CaretPos, SelStartPos, SelType, Now,
      Format(SUndoReverted, [OldHistoryIndex + 1, DateTimeToStr(Time)]),
      Bookmarks);
end;

procedure THistoryManager.SaveToStream(AStream: TStream);
var
  i: Integer;
begin

  if AStream = nil then
    raise Exception.Create('THistoryManager.SaveToStream: Stream is unassigned.');

  AStream.WriteData(UNDO_SIGNATURE);
  AStream.WriteData(FActualLength - FFirstItem);
  AStream.WriteData(FSize);
  AStream.WriteData(FHistoryIndex - FFirstItem);

  for i := FFirstItem to FActualLength - 1 do
  begin
    AStream.WriteData(UNDO_SIGNATURE_ITEM);
    AStream.WriteData(Integer(FUndoData[i].Text.Length));
    if not FUndoData[i].Text.IsEmpty then
      AStream.WriteBuffer(FUndoData[i].Text[1], FUndoData[i].Text.Length * sizeof(char));
    AStream.WriteData(Integer(FUndoData[i].Classes.Length));
    if not FUndoData[i].Classes.IsEmpty then
      AStream.WriteBuffer(FUndoData[i].Classes[1], FUndoData[i].Classes.Length * sizeof(char));
    AStream.WriteBuffer(FUndoData[i].CaretPos, sizeof(FUndoData[i].CaretPos));
    AStream.WriteBuffer(FUndoData[i].SelStartPos, sizeof(FUndoData[i].SelStartPos));
    AStream.WriteBuffer(FUndoData[i].SelType, sizeof(FUndoData[i].SelType));
    AStream.WriteBuffer(FUndoData[i].Time, sizeof(FUndoData[i].Time));
    AStream.WriteData(Integer(FUndoData[i].Comment.Length));
    if not FUndoData[i].Comment.IsEmpty then
      AStream.WriteBuffer(FUndoData[i].Comment[1], FUndoData[i].Comment.Length * sizeof(char));
    AStream.WriteData(FUndoData[i].UID);
    AStream.WriteBuffer(FUndoData[i].Bookmarks, sizeof(FUndoData[i].Bookmarks));
  end;

  AStream.WriteData(UNDO_SIGNATURE);
  AStream.WriteData(#0);

end;

procedure THistoryManager.SetMaxSize(Value: integer);
begin
  if FMaxSize <> Value then
  begin
    FMaxSize := Value;
    TrimLeft;
  end;
end;

function THistoryManager.SizeOfItem(ItemIndex: integer): integer;
begin
  with FUndoData[ItemIndex] do
    result := Length(Text) * Sizeof(char) + Length(Classes) * Sizeof(char) +
      SizeOf(CaretPos) + SizeOf(SelStartPos) + SizeOf(Time) +
      Length(Comment) * Sizeof(char) + SizeOf(Bookmarks);
end;

procedure THistoryManager.TrimLeft;
begin
  while (FSize > FMaxSize) and RemoveFirstItem do;
  if FSize > FMaxSize then Clear;
end;

function THistoryManager.Undo(out UndoData: TUndoDataItem): boolean;
begin
  result := CanUndo;
  if result then
  begin
    UndoData := FUndoData[FHistoryIndex - 1];
    dec(FHistoryIndex);
  end;
end;

function MakeCSSDeclaration(const AProperty, AValue: string): TCSSDeclaration;
begin
  result.CSSProperty := AProperty;
  result.Value := AValue;
end;

function MakeCSSOptionalDeclaration(const AUse: boolean;
  const AProperty, AValue: string): TCSSDeclaration;
begin
  if AUse then
    result := MakeCSSDeclaration(AProperty, AValue)
  else
    result := MakeCSSDeclaration('', '');
end;

function MakeCSSRule(const ASelector: string;
  const ADeclarations: array of TCSSDeclaration): TCSSRule;
var
  i, n, j: integer;
begin
  result.Selector := ASelector;
  n := 0;
  for i := low(ADeclarations) to high(ADeclarations) do
    if ADeclarations[i].CSSProperty <> '' then
      inc(n);

  SetLength(result.Declarations, n);
  j  := 0;
  for i := low(ADeclarations) to high(ADeclarations) do
    if ADeclarations[i].CSSProperty <> '' then
      begin
        result.Declarations[j] := ADeclarations[i];
        inc(j);
      end;
end;

function CSSColor(const AColor: TColor): string;
begin
  result := '#' + IntToHex(GetRValue(AColor), 2) +
    IntToHex(GetGValue(AColor), 2) +
    IntToHex(GetBValue(AColor), 2);
end;

{ TFormattingProcessor }

procedure TFormattingProcessor.BeginUpdate;
begin
  inc(FUpdateLevel);
end;

procedure TFormattingProcessor.Changed;
begin
  if (FUpdateLevel = 0) and Assigned(FOnChange) then
    FOnChange(Self);
end;

procedure TFormattingProcessor.ClearCache;
begin

end;

constructor TFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FUpdateLevel := 0;
end;

procedure TFormattingProcessor.EndUpdate;
begin
  dec(FUpdateLevel);
  if FUpdateLevel < 0 then
    FUpdateLevel := 0;
  if FUpdateLevel = 0 then
    Changed;
end;

function TFormattingProcessor.FileChangeNotification(ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  FillChar(result, sizeof(result), 0);
end;


function TFormattingProcessor.GetCache(out ACache: PByte): integer;
begin
  ACache := nil;
  result := 0;
end;

function TFormattingProcessor.RestoreCache(ACache: PByte;
  ASize: integer): boolean;
begin
  result := false;
end;

function TFormattingProcessor.TextChar(ALineIndex, ACol: integer): char;
begin
  result := FOnGetChar(ALineIndex, ACol);
end;

function TFormattingProcessor.TextGetWord(const APoint: TPoint;
  APascalIdent: boolean): string;
begin
  result := FOnGetWord(APoint, APascalIdent);
end;

function TFormattingProcessor.TextGetWordBoundary(const APoint: TPoint; out SP,
  EP: integer): boolean;
begin
  result := FOnGetWordBoundary(APoint, SP, EP);
end;

function TFormattingProcessor.TextLineCount: integer;
begin
  result := FOnGetLineCount;
end;

function TFormattingProcessor.TextLineWidth(ALineIndex: integer): integer;
begin
  result := FOnGetLineWidth(ALineIndex);
end;

{ TVowelsAndConsonantsFormattingProcessor }

procedure TVowelsAndConsonantsFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FVowelColor := AColorScheme.Accent3;
  FConsonantColor := AColorScheme.Accent2;
  Changed;
end;

procedure TVowelsAndConsonantsFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TVowelsAndConsonantsFormattingProcessor then
  begin
    FVowelColor := TVowelsAndConsonantsFormattingProcessor(Source).VowelColor;
    FVowelsBold := TVowelsAndConsonantsFormattingProcessor(Source).VowelsBold;
    FConsonantColor := TVowelsAndConsonantsFormattingProcessor(Source).ConsonantColor;
    FConsonantsBold := TVowelsAndConsonantsFormattingProcessor(Source).ConsonantBold;
    Changed;
  end
  else
    inherited;
end;

constructor TVowelsAndConsonantsFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FVowelColor := DEFAULT_VOWEL_COLOR;
  FConsonantColor := DEFAULT_CONSONANT_COLOR;
  FVowelsBold := DEFAULT_VOWELS_BOLD;
  FConsonantsBold := DEFAULT_CONSONANTS_BOLD;
end;

function TVowelsAndConsonantsFormattingProcessor.GetCharCSSClass(ALineIndex,
  ACol: Integer; AChar: Char): integer;
begin
  if IsVowel(AChar) then
    result := CSS_CLASS_VOWEL
  else
    result := CSS_CLASS_CONSONANT;
end;

procedure TVowelsAndConsonantsFormattingProcessor.GetCharFormat(ALineIndex,
  ACol: Integer; AChar: Char; var AFontRecord: TFontRecord);
begin
  if IsVowel(AChar) then
  begin
    AFontRecord.Color := FVowelColor;
    if FVowelsBold then
      Include(AFontRecord.Style, fsBold)
  end
  else
  begin
    AFontRecord.Color := FConsonantColor;
    if FConsonantsBold then
      Include(AFontRecord.Style, fsBold)
  end;
end;

function TVowelsAndConsonantsFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_VOWEL] := MakeCSSRule('vowel',
    [MakeCSSDeclaration('color', CSSColor(FVowelColor)),
    MakeCSSOptionalDeclaration(FVowelsBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_CONSONANT] := MakeCSSRule('consonant',
    [MakeCSSDeclaration('color', CSSColor(FConsonantColor)),
    MakeCSSOptionalDeclaration(FConsonantsBold, 'font-weight', 'bold')]);
end;

function TVowelsAndConsonantsFormattingProcessor.IsVowel(
  const AChar: Char): boolean;
begin
  result := AChar in ['A', 'E', 'I', 'O', 'U', 'Y', 'Å', 'Ä', 'Ö',
                      'a', 'e', 'i', 'o', 'u', 'y', 'å', 'ä', 'ö'];
end;

procedure TVowelsAndConsonantsFormattingProcessor.SetConsonantColor(
  const Value: TColor);
begin
  if FConsonantColor <> Value then
  begin
    FConsonantColor := Value;
    Changed;
  end;
end;

procedure TVowelsAndConsonantsFormattingProcessor.SetConsonantsBold(
  const Value: boolean);
begin
  if FConsonantsBold <> Value then
  begin
    FConsonantsBold := Value;
    Changed;
  end;
end;

procedure TVowelsAndConsonantsFormattingProcessor.SetVowelColor(
  const Value: TColor);
begin
  if FVowelColor <> Value then
  begin
    FVowelColor := Value;
    Changed;
  end;
end;

procedure TVowelsAndConsonantsFormattingProcessor.SetVowelsBold(
  const Value: boolean);
begin
  if FVowelsBold <> Value then
  begin
    FVowelsBold := Value;
    Changed;
  end;
end;

{ TXMLFormattingProcessor }

procedure TXMLFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FTagColor := AColorScheme.Accent1;
  FTagNameColor := AColorScheme.Accent3;
  FParamColor := AColorScheme.Accent1;
  FValueColor := AColorScheme.Accent2;
  FCommentColor := AColorScheme.Soft;
  FCDATAMColor := AColorScheme.Soft;
  FCDATAColor := AColorScheme.Soft;
  Changed;
end;

procedure TXMLFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TXMLFormattingProcessor then
  begin
    FTagColor := TXMLFormattingProcessor(Source).TagColor;
    FTagNameColor := TXMLFormattingProcessor(Source).TagNameColor;
    FTagNameBold := TXMLFormattingProcessor(Source).TagNameBold;
    FParamColor := TXMLFormattingProcessor(Source).ParamColor;
    FValueColor := TXMLFormattingProcessor(Source).ValueColor;
    FCommentColor := TXMLFormattingProcessor(Source).CommentColor;
    FCDATAMColor := TXMLFormattingProcessor(Source).CDATAMarkerColor;
    FCDATAMBold := TXMLFormattingProcessor(Source).CDATAMarkerBold;
    FCDATAColor := TXMLFormattingProcessor(Source).CDATAColor;
    Changed;
  end
  else
    inherited;
end;

constructor TXMLFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FTagColor := DEFAULT_TAG_COLOR;
  FTagNameColor := DEFAULT_TAG_NAME_COLOR;
  FTagNameBold := DEFAULT_TAG_NAME_BOLD;
  FParamColor := DEFAULT_PARAM_COLOR;
  FValueColor := DEFAULT_VALUE_COLOR;
  FCommentColor := DEFAULT_COMMENT_COLOR;
  FCDATAMColor := DEFAULT_CDATAM_COLOR;
  FCDATAMBold := DEFAULT_CDATAM_BOLD;
  FCDATAColor := DEFAULT_CDATA_COLOR;
end;

function TXMLFormattingProcessor.FileChangeNotification(ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  inherited;
  case ChangeType of
    ctNone: ;
    ctFile:
      begin
        ParseText;
        result.ChangeType := ctFile;
      end;
    ctLineRange:
      begin
        if Data3 = 1 {change caused by VK_RETURN, can optimize} then
        begin
          PushTokensDownFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else if Data3 = 2 {single #13#10 removed} then
        begin
          PushTokensUpFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else
          ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctBlock:
      begin
        ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctLine:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctChar:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctTwoChars:
      begin
        ParseText(min(Data1, Data3));
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := TextLineCount - 1;
      end;
    ctPostFile: ;
  end;
end;

function TXMLFormattingProcessor.GetCharCSSClass(ALineIndex, ACol: Integer;
  AChar: Char): Integer;
begin
  case GetChrKind(ALineIndex, ACol) of
    ckXmlUndefined, ckXmlText:
      result := CSS_CLASS_TEXT;
    ckXmlTag:
      result := CSS_CLASS_TAG;
    ckXmlTagName:
      result := CSS_CLASS_TAG_NAME;
    ckXmlParam:
      result := CSS_CLASS_PARAM;
    ckXmlValue:
      result := CSS_CLASS_VALUE;
    ckXmlComment:
      result := CSS_CLASS_COMMENT;
    ckCDATAMarker:
      result := CSS_CLASS_CDATAMARKER;
    ckCDATA:
      result := CSS_CLASS_CDATA;
  else
    raise Exception.Create('TXMLFormattingProcessor.GetCharCSSClass: Invalid character kind.');
  end;
end;

procedure TXMLFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: Char; var AFontRecord: TFontRecord);
begin
  case GetChrKind(ALineIndex, ACol) of
    ckXmlTag:
      AFontRecord.Color := FTagColor;
    ckXmlTagName:
      begin
        AFontRecord.Color := FTagNameColor;
        if FTagNameBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckXmlParam:
      AFontRecord.Color := FParamColor;
    ckXmlValue:
      AFontRecord.Color := FValueColor;
    ckXmlComment:
      AFontRecord.Color := FCommentColor;
    ckCDATAMarker:
      begin
        AFontRecord.Color := FCDATAMColor;
        if FCDATAMBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckCDATA:
      AFontRecord.Color := FCDATAColor;
  end;
end;

function TXMLFormattingProcessor.GetChrKind(ALineIndex,
  ACol: Integer): TXMLChrKind;
var
  i: integer;
begin
  i := 0;
  result := ckXmlUndefined;
  if ALineIndex <= high(FTokens) then
    while (i <= high(FTokens[ALineIndex])) and (FTokens[ALineIndex][i].x <= ACol) do
    begin
      result := FTokens[ALineIndex][i].kind;
      inc(i);
    end;
end;

function TXMLFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_TEXT] := MakeCSSRule('text', []);
  result[CSS_CLASS_TAG] := MakeCSSRule('tag',
    [MakeCSSDeclaration('color', CSSColor(FTagColor))]);
  result[CSS_CLASS_TAG_NAME] := MakeCSSRule('tag-name',
    [MakeCSSDeclaration('color', CSSColor(FTagNameColor)),
     MakeCSSOptionalDeclaration(FTagNameBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_PARAM] := MakeCSSRule('param',
    [MakeCSSDeclaration('color', CSSColor(FParamColor))]);
  result[CSS_CLASS_VALUE] := MakeCSSRule('value',
    [MakeCSSDeclaration('color', CSSColor(FValueColor))]);
  result[CSS_CLASS_COMMENT] := MakeCSSRule('comment',
    [MakeCSSDeclaration('color', CSSColor(FCommentColor))]);
  result[CSS_CLASS_CDATAMARKER] := MakeCSSRule('cdata-marker',
    [MakeCSSDeclaration('color', CSSColor(FCDATAMColor)),
     MakeCSSOptionalDeclaration(FCDATAMBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_CDATA] := MakeCSSRule('cdata',
    [MakeCSSDeclaration('color', CSSColor(FCDATAColor))]);
end;

function TXMLFormattingProcessor.ParseText(AFromLine: integer = 0;
  SingleLinePossibility: boolean = false; ANumLines: integer = 1): integer;
const
  ALLOC_BY = 16;
var
  ToLine: integer;
  ActualLengths: array of integer;
  y, x: Integer;
  InTag,
  InAttrib,
  InComment,
  InCDATAMarker,
  InCDATA,
  EndingCDATA: boolean;
  InVal: char; {#0, '''', '"'}
  Chr: char;
  _counter: integer;

  function GetSignature: cardinal;
  begin
    result := Byte(InTag) or (Byte(InComment) shl 1) or (Byte(InAttrib) shl 2)
       or (Byte(InCDATAMarker) shl 3) or (Byte(InCDATA) shl 4) or (Byte(EndingCDATA) shl 5)
       or (Ord(InVal) shl 16) or (1 shl 15);
  end;

  // Must only be called within the inner loop (y, x)!
  procedure AddToken(AKind: TXMLChrKind; Signature: boolean = false);
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := AKind;
    if Signature then
      FTokens[y][ActualLengths[y]].signature := GetSignature
    else
      FTokens[y][ActualLengths[y]].signature := 0;
    inc(ActualLengths[y]);
  end;

  function GetLastKind: TXMLChrKind;
  var
    yp: Integer;
    xp: Integer;
  begin
    for yp := y downto 0 do
      for xp := ActualLengths[yp] - 1 downto 0 do
        Exit(FTokens[yp][xp].kind);
    result := ckXmlText; // SOF default
  end;

  procedure AddSignature;
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := GetLastKind;
    FTokens[y][ActualLengths[y]].signature := GetSignature;
    inc(ActualLengths[y]);
  end;

  function Peek: TXMLChrKind;
  var
    yp: integer;
  begin
    for yp := y downto 0 do
      if ActualLengths[yp] > 0 then
        Exit(FTokens[yp][ActualLengths[yp] - 1].kind);
    result := ckXmlUndefined;
  end;

  procedure ExtractSignature(ASignature: cardinal; out AInTag,
    AInComment, AInAttrib, AInCDATAMarker, AInCDATA, AEndingCDATA: boolean; out AInVal: char);
  begin
    AInTag := ASignature and 1 <> 0;
    AInComment := ASignature and 2 <> 0;
    AInAttrib := ASignature and 4 <> 0;
    AInCDATAMarker := ASignature and 8 <> 0;
    AInCDATA := ASignature and 16 <> 0;
    AEndingCDATA := ASignature and 32 <> 0;
    AInVal := Char(ASignature shr 16);
  end;

  function GetLastSignature: cardinal;
  var
    yp: integer;
  begin
    for yp := AFromLine - 1 downto 0 do
      if Length(FTokens[yp]) > 0 then
      begin
        Assert(FTokens[yp][high(FTokens[yp])].signature and (1 shl 15) <> 0);
        Exit(FTokens[yp][high(FTokens[yp])].signature);
      end;
    result := 0;
  end;

  function PeekSignatureForward: cardinal;
  var
    yp: integer;
  begin
    for yp := y + 1 to high(FTokens) do
      if Length(FTokens[yp]) > 0 then
        Exit(FTokens[yp][0].signature);
    result := 0;
  end;

  function PeekIsComment: boolean;
  begin
    result := (TextLineWidth(y) >= x + 4) and
      (TextChar(y, x + 1) = '!') and
      (TextChar(y, x + 2) = '-') and
      (TextChar(y, x + 3) = '-');
  end;

  function DoesEndComment: boolean;
  begin
    result := (x >= 2) and
      (TextChar(y, x - 1) = '-') and
      (TextChar(y, x - 2) = '-');
  end;

  function PeekIsCDATAMarker: boolean;
  begin
    result := (TextLineWidth(y) >= x + 9) and
      (TextChar(y, x + 1) = '!') and
      (TextChar(y, x + 2) = '[') and
      (TextChar(y, x + 3) = 'C') and
      (TextChar(y, x + 4) = 'D') and
      (TextChar(y, x + 5) = 'A') and
      (TextChar(y, x + 6) = 'T') and
      (TextChar(y, x + 7) = 'A') and
      (TextChar(y, x + 8) = '[');
  end;

  function PeekDoesEndCDATA: boolean;
  begin
    result := (TextLineWidth(y) >= x + 3) and
      (TextChar(y, x + 1) = ']') and
      (TextChar(y, x + 2) = '>');
  end;

begin

  _counter := 0; // stupid compiler

  if AFromLine = 0 then
  begin
    InTag := false;
    InComment := false;
    InAttrib := false;
    InCDATAMarker := false;
    InCDATA := false;
    EndingCDATA := false;
    InVal := #0;
  end
  else
  begin
    ExtractSignature(GetLastSignature, InTag, InComment, InAttrib,
      InCDATAMarker, InCDATA, EndingCDATA, InVal);
  end;

  SetLength(FTokens, TextLineCount);
  SetLength(ActualLengths, TextLineCount);
  ToLine := TextLineCount - 1;
  for y := 0 to AFromLine - 1 do
    ActualLengths[y] := length(FTokens[y]);
  for y := AFromLine to ToLine do
    ActualLengths[y] := 0;
  for y := AFromLine to ToLine do
  begin
    for x := 0 to TextLineWidth(y) - 1 do
    begin
      if x=0 then
        AddToken(Peek, true);
      Chr := TextChar(y, x);
      if InCDATA then
      begin
        if (Chr = ']') and PeekDoesEndCDATA then
        begin
          InCDATA := false;
          InCDATAMarker := true;
          _counter := 1;
          EndingCDATA := true;
          AddToken(ckCDATAMarker);
        end;
      end
      else if InCDATAMarker then
      begin
        inc(_counter);
        if EndingCDATA then
        begin
          if _counter = 4 - 1{sic!} then
          begin
            InCDATAMarker := false;
            InCDATA := false;
            EndingCDATA := false;
          end
        end
        else
        begin
          if _counter = 10 then
          begin
            InCDATAMarker := false;
            InCDATA := true;
            AddToken(ckCDATA);
          end;
        end;
      end
      else if InComment then
      begin
        if (Chr = '>') and DoesEndComment then
          InComment := false;
      end
      else if InTag then
      begin
        if InVal <> #0 then
        begin
          if Chr = InVal then
            InVal := #0;
        end
        else
        begin
          if (x=0) or (Chr = #32) and (Peek <> ckXmlParam) then
          begin
            InAttrib := true;
            AddToken(ckXmlParam);
          end
          else if (Chr = '''') or (Chr = '"') then
          begin
            InVal := Chr;
            AddToken(ckXmlValue);
          end
          else if Chr = '/' then
          begin
            if Peek <> ckXmlTag then
              AddToken(ckXmlTag);
          end
          else if Chr = '>' then
          begin
            InTag := false;
            AddToken(ckXmlTag);
          end
          else
          begin
            if InAttrib and (Peek <> ckXmlParam) then
              AddToken(ckXmlParam)
            else if (not InAttrib) and (Peek <> ckXmlTagName) then
              AddToken(ckXmlTagName);
          end;
        end;
      end
      else if (Chr = '<') then
      begin
        if PeekIsComment then
        begin
          InComment := true;
          AddToken(ckXmlComment);
        end
        else if PeekIsCDATAMarker then
        begin
          InCDATAMarker := true;
          EndingCDATA := false;
          _counter := 1;
          AddToken(ckCDATAMarker);
        end
        else
        begin
          InTag := true;
          InAttrib := false;
          AddToken(ckXmlTag);
        end;
      end
      else if Peek <> ckXmlText then
        AddToken(ckXmlText);
      if x = TextLineWidth(y) - 1 then
        AddSignature;
    end;
    if SingleLinePossibility and (y - AFromLine >= ANumLines - 1) and (GetSignature = PeekSignatureForward) then
    begin
      ToLine := y;
      break;
    end;
  end;

  for y := AFromLine to ToLine do
    SetLength(FTokens[y], ActualLengths[y]);

  result := ToLine;

end;

procedure TXMLFormattingProcessor.PushTokensDownFrom(ALineIndex: integer);
var
  i: Integer;
begin
  SetLength(FTokens, Length(FTokens) + 1);
  for i := high(FTokens) downto ALineIndex + 1 do
    FTokens[i] := Copy(FTokens[i - 1]);
end;

procedure TXMLFormattingProcessor.PushTokensUpFrom(ALineIndex: integer);
var
  i: Integer;
begin
  for i := ALineIndex + 1 to high(FTokens) - 1 do
    FTokens[i] := Copy(FTokens[i + 1]);
  SetLength(FTokens, Length(FTokens) - 1);
end;

procedure TXMLFormattingProcessor.SetCDATAColor(const Value: TColor);
begin
  if FCDATAColor <> Value then
  begin
    FCDATAColor := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetCDATAMBold(const Value: boolean);
begin
  if FCDATAMBold <> Value then
  begin
    FCDATAMBold := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetCDATAMColor(const Value: TColor);
begin
  if FCDATAMColor <> Value then
  begin
    FCDATAMColor := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetCommentColor(const Value: TColor);
begin
  if FCommentColor <> Value then
  begin
    FCommentColor := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetParamColor(const Value: TColor);
begin
  if FParamColor <> Value then
  begin
    FParamColor := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetTagColor(const Value: TColor);
begin
  if FTagColor <> Value then
  begin
    FTagColor := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetTagNameBold(const Value: boolean);
begin
  if FTagNameBold <> Value then
  begin
    FTagNameBold := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetTagNameColor(const Value: TColor);
begin
  if FTagNameColor <> Value then
  begin
    FTagNameColor := Value;
    Changed;
  end;
end;

procedure TXMLFormattingProcessor.SetValueColor(const Value: TColor);
begin
  if FValueColor <> Value then
  begin
    FValueColor := Value;
    Changed;
  end;
end;

{ TCSSFormattingProcessor }

procedure TCSSFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FSelectorColor := AColorScheme.Accent3;
  FPropertyColor := AColorScheme.Accent1;
  FValueColor := AColorScheme.Default;
  FCommentColor := AColorScheme.Soft;
  FBlockDelimColor := AColorScheme.Accent3;
  FImportantColor := AColorScheme.Intense;
  Changed;
end;

procedure TCSSFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TCSSFormattingProcessor then
  begin
    FSelectorColor := TCSSFormattingProcessor(Source).SelectorColor;
    FSelectorBold := TCSSFormattingProcessor(Source).SelectorBold;
    FPropertyColor := TCSSFormattingProcessor(Source).PropertyColor;
    FValueColor := TCSSFormattingProcessor(Source).ValueColor;
    FCommentColor := TCSSFormattingProcessor(Source).CommentColor;
    FBlockDelimColor := TCSSFormattingProcessor(Source).BlockDelimColor;
    FBlockDelimBold := TCSSFormattingProcessor(Source).BlockDelimBold;
    FImportantColor := TCSSFormattingProcessor(Source).ImportantColor;
    FImportantBold := TCSSFormattingProcessor(Source).ImportantBold;
    Changed;
  end
  else
    inherited;
end;

constructor TCSSFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FSelectorColor := DEFAULT_SELECTOR_COLOR;
  FSelectorBold := DEFAULT_SELECTOR_BOLD;
  FPropertyColor := DEFAULT_PROPERTY_COLOR;
  FValueColor := DEFAULT_VALUE_COLOR;
  FCommentColor := DEFAULT_COMMENT_COLOR;
  FBlockDelimColor := DEFAULT_BLOCK_DELIM_COLOR;
  FBlockDelimBold := DEFAULT_BLOCK_DELIM_BOLD;
  FImportantColor := DEFAULT_IMPORTANT_COLOR;
  FImportantBold := DEFAULT_IMPORTANT_BOLD;
end;

function TCSSFormattingProcessor.FileChangeNotification(ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  inherited;
  case ChangeType of
    ctNone: ;
    ctFile:
      begin
        ParseText;
        result.ChangeType := ctFile;
      end;
    ctLineRange:
      begin
        if Data3 = 1 {change caused by VK_RETURN, can optimize} then
        begin
          PushTokensDownFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else if Data3 = 2 {single #13#10 removed} then
        begin
          PushTokensUpFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else
          ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctBlock:
      begin
        ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctLine:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctChar:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctTwoChars:
      begin
        ParseText(min(Data1, Data3));
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := TextLineCount - 1;
      end;
    ctPostFile: ;
  end;
end;

function TCSSFormattingProcessor.GetCharCSSClass(ALineIndex, ACol: Integer;
  AChar: Char): Integer;
begin
  case GetChrKind(ALineIndex, ACol) of
    ckCssSelector:
      result := CSS_CLASS_SELECTOR;
    ckCssBlockDelim:
      result := CSS_CLASS_BLOCK_DELIM;
    ckCssProperty:
      result := CSS_CLASS_PROPERTY;
    ckCssValue:
      result := CSS_CLASS_VALUE;
    ckCssImportant:
      result := CSS_CLASS_IMPORTANT;
    ckCssComment:
      result := CSS_CLASS_COMMENT;
  else
    raise Exception.Create('TCSSFormattingProcessor.GetCharCSSClass: Invalid character kind.');
  end;
end;

procedure TCSSFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: Char; var AFontRecord: TFontRecord);
begin
  case GetChrKind(ALineIndex, ACol) of
    ckCssSelector:
      begin
        AFontRecord.Color := FSelectorColor;
        if FSelectorBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckCssBlockDelim:
      begin
        AFontRecord.Color := FBlockDelimColor;
        if FBlockDelimBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckCssProperty:
      AFontRecord.Color := FPropertyColor;
    ckCssValue:
      AFontRecord.Color := FValueColor;
    ckCssImportant:
      begin
        AFontRecord.Color := FImportantColor;
        if FImportantBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckCssComment:
      AFontRecord.Color := FCommentColor;
  end;
end;

function TCSSFormattingProcessor.GetChrKind(ALineIndex,
  ACol: Integer): TCSSChrKind;
var
  i: integer;
begin
  i := 0;
  result := ckCssSelector; // SOF default
  if ALineIndex <= high(FTokens) then
    while (i <= high(FTokens[ALineIndex])) and (FTokens[ALineIndex][i].x <= ACol) do
    begin
      result := FTokens[ALineIndex][i].kind;
      inc(i);
    end;
end;

function TCSSFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_SELECTOR] := MakeCSSRule('selector',
    [MakeCSSDeclaration('color', CSSColor(FSelectorColor)),
     MakeCSSOptionalDeclaration(FSelectorBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_PROPERTY] := MakeCSSRule('property',
    [MakeCSSDeclaration('color', CSSColor(FPropertyColor))]);
  result[CSS_CLASS_VALUE] := MakeCSSRule('value',
    [MakeCSSDeclaration('color', CSSColor(FValueColor))]);
  result[CSS_CLASS_COMMENT] := MakeCSSRule('comment',
    [MakeCSSDeclaration('color', CSSColor(FCommentColor))]);
  result[CSS_CLASS_BLOCK_DELIM] := MakeCSSRule('delim',
    [MakeCSSDeclaration('color', CSSColor(FBlockDelimColor)),
     MakeCSSOptionalDeclaration(FBlockDelimBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_IMPORTANT] := MakeCSSRule('important',
    [MakeCSSDeclaration('color', CSSColor(FImportantColor)),
     MakeCSSOptionalDeclaration(FImportantBold, 'font-weight', 'bold')]);
end;

function TCSSFormattingProcessor.ParseText(AFromLine: integer = 0;
  SingleLinePossibility: boolean = false; ANumLines: integer = 1): integer;
type
  TNibble = type byte; { only use the four least significant bits }
const
  ALLOC_BY = 8;
var
  ToLine: integer;
  ActualLengths: array of integer;
  InBlock: TNibble;
  InValue,
  InImportant,
  InComment: boolean;
  InStr: char;
  y, x: Integer;
  Chr: char;

  function GetSignature: cardinal;
  begin
    result := ((InBlock and $F) shl 4) or (Byte(InValue) shl 1) or (Byte(InImportant) shl 2) or
      (Byte(InComment) shl 3) or (Ord(InStr) shl 16) or (1 shl 15);
  end;

  // Must only be called within the inner loop (y, x)!
  procedure AddToken(AKind: TCSSChrKind; Signature: boolean = false);
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := AKind;
    if Signature then
      FTokens[y][ActualLengths[y]].signature := GetSignature
    else
      FTokens[y][ActualLengths[y]].signature := 0;
    inc(ActualLengths[y]);
  end;

  function GetLastKind: TCSSChrKind;
  var
    yp: Integer;
    xp: Integer;
  begin
    for yp := y downto 0 do
      for xp := ActualLengths[yp] - 1 downto 0 do
        Exit(FTokens[yp][xp].kind);
    result := ckCssUndefined;
  end;

  procedure AddSignature;
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := GetLastKind;
    FTokens[y][ActualLengths[y]].signature := GetSignature;
    inc(ActualLengths[y]);
  end;

  function Peek: TCSSChrKind;
  var
    yp: integer;
  begin
    for yp := y downto 0 do
      if ActualLengths[yp] > 0 then
        Exit(FTokens[yp][ActualLengths[yp] - 1].kind);
    result := ckCssSelector; // SOF default
  end;

  procedure ExtractSignature(ASignature: cardinal; out AInValue,
    AInImportant, AInComment: boolean; out AInStr: char; out AInBlock: TNibble);
  begin
    AInBlock := (ASignature shr 4) and $F;
    AInValue := ASignature and 2 <> 0;
    AInImportant := ASignature and 4 <> 0;
    AInComment := ASignature and 8 <> 0;
    AInStr := Char(ASignature shr 16);
  end;

  function GetLastSignature: cardinal;
  var
    yp: integer;
  begin
    for yp := AFromLine - 1 downto 0 do
      if Length(FTokens[yp]) > 0 then
      begin
        Assert(FTokens[yp][high(FTokens[yp])].signature and (1 shl 15) <> 0);
        Exit(FTokens[yp][high(FTokens[yp])].signature);
      end;
    result := 0;
  end;

  function PeekSignatureForward: cardinal;
  var
    yp: integer;
  begin
    for yp := y + 1 to high(FTokens) do
      if Length(FTokens[yp]) > 0 then
        Exit(FTokens[yp][0].signature);
    result := 0;
  end;

  function PeekImportant: boolean;
  begin
    result := (TextLineWidth(y) >= x + 10) and
      (TextChar(y, x + 1) = 'i') and
      (TextChar(y, x + 2) = 'm') and
      (TextChar(y, x + 3) = 'p') and
      (TextChar(y, x + 4) = 'o') and
      (TextChar(y, x + 5) = 'r') and
      (TextChar(y, x + 6) = 't') and
      (TextChar(y, x + 7) = 'a') and
      (TextChar(y, x + 8) = 'n') and
      (TextChar(y, x + 9) = 't');
  end;

  function PeekComment: boolean;
  begin
    result := (TextLineWidth(y) >= x + 2) and
      (TextChar(y, x + 1) = '*');
  end;

  function EndsComment: boolean;
  begin
    result := (x >= 1) and (TextChar(y, x - 1) = '*');
  end;

begin

  if AFromLine = 0 then
  begin
    InBlock := 0;
    InValue := false;
    InImportant := false;
    InComment := false;
    InStr := #0;
  end
  else
  begin
    ExtractSignature(GetLastSignature, InValue, InImportant, InComment,
      InStr, InBlock);
  end;

  SetLength(FTokens, TextLineCount);
  SetLength(ActualLengths, TextLineCount);
  ToLine := TextLineCount - 1;
  for y := 0 to AFromLine - 1 do
    ActualLengths[y] := length(FTokens[y]);
  for y := AFromLine to ToLine do
    ActualLengths[y] := 0;
  for y := AFromLine to ToLine do
  begin
    for x := 0 to TextLineWidth(y) - 1 do
    begin
      if x=0 then
        AddToken(Peek, true);
      Chr := TextChar(y, x);
      if InStr <> #0 then
      begin
        if Chr = InStr then
          InStr := #0
      end
      else if (not InComment) and ((Chr = '"') or (Chr = '''')) then
      begin
        InStr := Chr;
        if InValue and (Peek <> ckCssValue) then
          AddToken(ckCssValue);
      end
      else if InComment then
      begin
        if (Chr = '/') and EndsComment then
          InComment := false;
      end
      else if (Chr = '/') and PeekComment then
      begin
        AddToken(ckCssComment);
        InComment := true;
      end
      else if InImportant then
      begin
        if Chr = ';' then
        begin
          AddToken(ckCssValue);
          InImportant := false;
          InValue := false;
        end;
      end
      else if InValue then
      begin
        if (Chr = '!') and PeekImportant then
        begin
          AddToken(ckCssImportant);
          InImportant := true;
        end
        else
        begin
          if Peek <> ckCssValue then
            AddToken(ckCssValue);
          if Chr = ';' then
          begin
            InValue := false;
          end
          else if Chr = '}' then
          begin
            AddToken(ckCssBlockDelim);
            InValue := false;
            dec(InBlock);
          end
        end;
      end
      else if InBlock > 0 then
      begin
        if Chr = '{' then
        begin
          AddToken(ckCssBlockDelim);
          inc(InBlock);
        end
        else if Chr = '}' then
        begin
          AddToken(ckCssBlockDelim);
          dec(InBlock);
        end
        else if Peek <> ckCssProperty then
          AddToken(ckCssProperty);
        if Chr = ':' then
        begin
          InValue := true;
        end;
      end
      else if Chr = '{' then
      begin
        AddToken(ckCssBlockDelim);
        inc(InBlock);
      end
      else if Peek <> ckCssSelector then
        AddToken(ckCssSelector);
      if x = TextLineWidth(y) - 1 then
        AddSignature;
    end;
    if SingleLinePossibility and (y - AFromLine >= ANumLines - 1) and (GetSignature = PeekSignatureForward) then
    begin
      ToLine := y;
      break;
    end;
  end;
  for y := AFromLine to ToLine do
    SetLength(FTokens[y], ActualLengths[y]);
  result := ToLine;
end;

procedure TCSSFormattingProcessor.PushTokensDownFrom(ALineIndex: integer);
var
  i: Integer;
begin
  SetLength(FTokens, Length(FTokens) + 1);
  for i := high(FTokens) downto ALineIndex + 1 do
    FTokens[i] := Copy(FTokens[i - 1]);
end;

procedure TCSSFormattingProcessor.PushTokensUpFrom(ALineIndex: integer);
var
  i: Integer;
begin
  for i := ALineIndex + 1 to high(FTokens) - 1 do
    FTokens[i] := Copy(FTokens[i + 1]);
  SetLength(FTokens, Length(FTokens) - 1);
end;

procedure TCSSFormattingProcessor.SetBlockDelimBold(const Value: boolean);
begin
  if FBlockDelimBold <> Value then
  begin
    FBlockDelimBold := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetBlockDelimColor(const Value: TColor);
begin
  if FBlockDelimColor <> Value then
  begin
    FBlockDelimColor := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetCommentColor(const Value: TColor);
begin
  if FCommentColor <> Value then
  begin
    FCommentColor := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetImportantBold(const Value: boolean);
begin
  if FImportantBold <> Value then
  begin
    FImportantBold := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetImportantColor(const Value: TColor);
begin
  if FImportantColor <> Value then
  begin
    FImportantColor := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetPropertyColor(const Value: TColor);
begin
  if FPropertyColor <> Value then
  begin
    FPropertyColor := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetSelectorBold(const Value: boolean);
begin
  if FSelectorBold <> Value then
  begin
    FSelectorBold := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetSelectorColor(const Value: TColor);
begin
  if FSelectorColor <> Value then
  begin
    FSelectorColor := Value;
    Changed;
  end;
end;

procedure TCSSFormattingProcessor.SetValueColor(const Value: TColor);
begin
  if FValueColor <> Value then
  begin
    FValueColor := Value;
    Changed;
  end;
end;

{ TINIFormattingProcessor }

procedure TINIFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FSectionColor := AColorScheme.Accent3;
  FNameColor := AColorScheme.Accent1;
  FValueColor := AColorScheme.Default;
  FCommentColor := AColorScheme.Soft;
  Changed;
end;

procedure TINIFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TINIFormattingProcessor then
  begin
    FSectionColor := TINIFormattingProcessor(Source).SectionColor;
    FSectionBold := TINIFormattingProcessor(Source).SectionBold;
    FNameColor := TINIFormattingProcessor(Source).NameColor;
    FValueColor := TINIFormattingProcessor(Source).ValueColor;
    FCommentColor := TINIFormattingProcessor(Source).CommentColor;
    Changed;
  end
  else
    inherited;
end;

constructor TINIFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FSectionColor := DEFAULT_SECTION_COLOR;
  FSectionBold := DEFAULT_SECTION_BOLD;
  FNameColor := DEFAULT_NAME_COLOR;
  FValueColor := DEFAULT_VALUE_COLOR;
  FCommentColor := DEFAULT_COMMENT_COLOR;
end;

function TINIFormattingProcessor.FileChangeNotification(ChangeType: TChangeType;
  Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  inherited;
  case ChangeType of
    ctNone: ;
    ctFile:
      result.ChangeType := ctFile;
    ctLineRange:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctBlock:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctLine:
      begin
        result.ChangeType := ctLine;
        result.Data1 := Data1;
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLineFrom;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctChar:
      begin
        result.ChangeType := ctLineFrom;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctTwoChars:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := max(Data1, Data3);
      end;
    ctPostFile: ;
  end;
end;

function TINIFormattingProcessor.GetCharCSSClass(ALineIndex, ACol: Integer;
  AChar: Char): Integer;

  function AfterEqualsSign: boolean;
  var
    x: Integer;
  begin
    result := false;
    for x := 0 to ACol - 1 do
      if TextChar(ALineIndex, x) = '=' then
        Exit(true);
  end;

var
  FirstChar: char;
begin
  FirstChar := TextChar(ALineIndex, 0);
  if FirstChar = '[' then
    result := CSS_CLASS_SECTION
  else if FirstChar = ';' then
    result := CSS_CLASS_COMMENT
  else if AChar = '=' then
    result := CSS_CLASS_EQUALS
  else if AfterEqualsSign then
    result := CSS_CLASS_VALUE
  else
    Result := CSS_CLASS_NAME
end;

procedure TINIFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: char; var AFontRecord: TFontRecord);

  function AfterEqualsSign: boolean;
  var
    x: Integer;
  begin
    result := false;
    for x := 0 to ACol - 1 do
      if TextChar(ALineIndex, x) = '=' then
        Exit(true);
  end;

var
  FirstChar: char;
begin
  FirstChar := TextChar(ALineIndex, 0);
  if FirstChar = '[' then
  begin
    AFontRecord.Color := FSectionColor;
    if FSectionBold then
      Include(AFontRecord.Style, fsBold);
  end
  else if FirstChar = ';' then
    AFontRecord.Color := FCommentColor
  else if AChar = '=' then
    {Do nothing}
  else if AfterEqualsSign then
    AFontRecord.Color := FValueColor
  else
    AFontRecord.Color := FNameColor;
end;

function TINIFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_SECTION] := MakeCSSRule('section',
    [MakeCSSDeclaration('color', CSSColor(FSectionColor)),
     MakeCSSOptionalDeclaration(FSectionBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_NAME] := MakeCSSRule('name',
    [MakeCSSDeclaration('color', CSSColor(FNameColor))]);
  result[CSS_CLASS_VALUE] := MakeCSSRule('value',
    [MakeCSSDeclaration('color', CSSColor(FValueColor))]);
  result[CSS_CLASS_COMMENT] := MakeCSSRule('comment',
    [MakeCSSDeclaration('color', CSSColor(FCommentColor))]);
  result[CSS_CLASS_EQUALS] := MakeCSSRule('equals', []);
end;

procedure TINIFormattingProcessor.SetCommentColor(const Value: TColor);
begin
  if FCommentColor <> Value then
  begin
    FCommentColor := Value;
    Changed;
  end;
end;

procedure TINIFormattingProcessor.SetNameColor(const Value: TColor);
begin
  if FNameColor <> Value then
  begin
    FNameColor := Value;
    Changed;
  end;
end;

procedure TINIFormattingProcessor.SetSectionBold(const Value: boolean);
begin
  if FSectionBold <> Value then
  begin
    FSectionBold := Value;
    Changed;
  end;
end;

procedure TINIFormattingProcessor.SetSectionColor(const Value: TColor);
begin
  if FSectionColor <> Value then
  begin
    FSectionColor := Value;
    Changed;
  end;
end;

procedure TINIFormattingProcessor.SetValueColor(const Value: TColor);
begin
  if FValueColor <> Value then
  begin
    FValueColor := Value;
    Changed;
  end;
end;

{ TPascalFormattingProcessor }

procedure TPascalFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FKeywordColor := AColorScheme.Accent3;
  FStringColor := AColorScheme.Accent1;
  FNumberColor := AColorScheme.Accent1;
  FCommentColor := AColorScheme.Accent2;
  FCompilerDirectiveColor := AColorScheme.Accent3;
  Changed;
end;

procedure TPascalFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TPascalFormattingProcessor then
  begin
    FKeywordColor := TPascalFormattingProcessor(Source).KeywordColor;
    FKeywordBold := TPascalFormattingProcessor(Source).KeywordBold;
    FStringColor := TPascalFormattingProcessor(Source).StringColor;
    FNumberColor := TPascalFormattingProcessor(Source).NumberColor;
    FCommentColor := TPascalFormattingProcessor(Source).CommentColor;
    FCompilerDirectiveColor := TPascalFormattingProcessor(Source).CompilerDirectiveColor;
    Changed;
  end
  else
    inherited;
end;

procedure TPascalFormattingProcessor.ClearCache;
begin
  SetLength(FTokens, 0);
end;

constructor TPascalFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FKeywordColor := DEFAULT_KEYWORD_COLOR;
  FKeywordBold := DEFAULT_KEYWORD_BOLD;
  FStringColor := DEFAULT_STRING_COLOR;
  FNumberColor := DEFAULT_NUMBER_COLOR;
  FCommentColor := DEFAULT_COMMENT_COLOR;
  FCompilerDirectiveColor := DEFAULT_COMPILER_DIRECTIVE_COLOR;
end;

function TPascalFormattingProcessor.FileChangeNotification(
  ChangeType: TChangeType; Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  case ChangeType of
    ctNone: ;
    ctFile:
      begin
        ParseText;
        result.ChangeType := ctFile;
      end;
    ctLineRange:
      begin
        if Data3 = 1 {change caused by VK_RETURN, can optimize} then
        begin
          PushTokensDownFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else if Data3 = 2 {single #13#10 removed} then
        begin
          PushTokensUpFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else
          ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctBlock:
      begin
        ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctLine:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctChar:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctTwoChars:
      begin
        ParseText(min(Data1, Data3));
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := TextLineCount - 1;
      end;
    ctPostFile: ;
  end;
end;

function TPascalFormattingProcessor.GetCache(out ACache: PByte): Integer;
var
  i: Integer;
  p: PByte;
begin
  // Layout: N len1 data1 len2 data2 ... lenN dataN
  result := (1 + length(FTokens)) * sizeof(integer);
  for i := 0 to high(FTokens) do
    inc(result, length(FTokens[i]) * sizeof(TFmtBreak));
  try
    GetMem(ACache, result);
    try
      p := ACache;
      PInteger(p)^ := length(FTokens);
      inc(p, sizeof(integer));
      for i := 0 to high(FTokens) do
      begin
        PInteger(p)^ := length(FTokens[i]);
        inc(p, sizeof(integer));
        Move(FTokens[i][0], p^, length(FTokens[i]) * sizeof(TFmtBreak));
        inc(p, length(FTokens[i]) * sizeof(TFmtBreak));
      end;
    except
      FreeMem(ACache);
      raise;
    end;
  except
    ACache := nil;
    result := 0;
  end;
end;

function TPascalFormattingProcessor.GetCharCSSClass(ALineIndex, ACol: Integer;
  AChar: Char): Integer;
begin
  case GetChrKind(ALineIndex, ACol) of
    ckPasUndefined:
      result := CSS_CLASS_DEFAULT;
    ckPasKeyword:
      result := CSS_CLASS_KEYWORD;
    ckPasString:
      result := CSS_CLASS_STRING;
    ckPasNumber:
      result := CSS_CLASS_NUMBER;
    ckPasComment:
      result := CSS_CLASS_COMMENT;
    ckPasCompilerDirective:
      result := CSS_CLASS_COMPILER_DIRECTIVE;
  else
    raise Exception.Create('TPascalFormattingProcessor.GetCharCSSClass: Invalid character kind.');
  end;
end;

procedure TPascalFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: Char; var AFontRecord: TFontRecord);
begin
  case GetChrKind(ALineIndex, ACol) of
    ckPasUndefined:
      ;
    ckPasKeyword:
      begin
        AFontRecord.Color := FKeywordColor;
        if FKeywordBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckPasString:
      AFontRecord.Color := FStringColor;
    ckPasNumber:
      AFontRecord.Color := FNumberColor;
    ckPasComment:
      AFontRecord.Color := FCommentColor;
    ckPasCompilerDirective:
      AFontRecord.Color := FCompilerDirectiveColor;
  end;
end;

function TPascalFormattingProcessor.GetChrKind(ALineIndex,
  ACol: Integer): TPascalChrKind;
var
  i: integer;
begin
  result := ckPasUndefined;
  i := 0;
  if ALineIndex <= high(FTokens) then
    while (i <= high(FTokens[ALineIndex])) and (FTokens[ALineIndex][i].x <= ACol) do
    begin
      result := FTokens[ALineIndex][i].kind;
      inc(i);
    end;
end;

function TPascalFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_DEFAULT] := MakeCSSRule('default', []);
  result[CSS_CLASS_KEYWORD] := MakeCSSRule('keyword',
    [MakeCSSDeclaration('color', CSSColor(FKeywordColor)),
     MakeCSSOptionalDeclaration(FKeywordBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_STRING] := MakeCSSRule('string',
    [MakeCSSDeclaration('color', CSSColor(FStringColor))]);
  result[CSS_CLASS_NUMBER] := MakeCSSRule('number',
    [MakeCSSDeclaration('color', CSSColor(FNumberColor))]);
  result[CSS_CLASS_COMMENT] := MakeCSSRule('comment',
    [MakeCSSDeclaration('color', CSSColor(FCommentColor))]);
  result[CSS_CLASS_COMPILER_DIRECTIVE] := MakeCSSRule('compiler-directive',
    [MakeCSSDeclaration('color', CSSColor(FCompilerDirectiveColor))]);
end;

function TPascalFormattingProcessor.ParseText(AFromLine: integer;
  SingleLinePossibility: boolean; ANumLines: integer): integer;
const
  ALLOC_BY = 16;
var
  ToLine: integer;
  ActualLengths: array of integer;
  y, x: Integer;
  InComment: char; {#0, '/', '{', '('}
  InDirective: boolean;
  InStr: boolean;
  InNumber: boolean;
  InKeyword: boolean;
  Chr: char;
  lasttoken: TPascalChrKind;
  NumberEndsAt: integer;

  function GetSignature: cardinal;
  begin
    result := Byte(InKeyword) or (Byte(InStr) shl 1) or (Byte(InNumber) shl 2) or
      (Byte(InDirective) shl 3) or (Ord(InComment) shl 16) or (1 shl 15);
  end;

  // Must only be called within the inner loop (y, x)!
  procedure AddToken(AKind: TPascalChrKind; Signature: boolean = false);
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := AKind;
    if Signature then
      FTokens[y][ActualLengths[y]].signature := GetSignature
    else
      FTokens[y][ActualLengths[y]].signature := 0;
    inc(ActualLengths[y]);
  end;

  function GetLastKind: TPascalChrKind;
  var
    yp: Integer;
    xp: Integer;
  begin
    for yp := y downto 0 do
      for xp := ActualLengths[yp] - 1 downto 0 do
        Exit(FTokens[yp][xp].kind);
    result := ckPasUndefined; // SOF default
  end;

  procedure AddSignature;
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := GetLastKind;
    FTokens[y][ActualLengths[y]].signature := GetSignature;
    inc(ActualLengths[y]);
  end;

  function Peek: TPascalChrKind;
  var
    yp: integer;
  begin
    for yp := y downto 0 do
      if ActualLengths[yp] > 0 then
        Exit(FTokens[yp][ActualLengths[yp] - 1].kind);
    result := ckPasUndefined;
  end;

  procedure ExtractSignature(ASignature: cardinal; out AInKeyword,
    AInStr, AInNumber: boolean; out AInComment: char; out AInDirective: boolean);
  begin
    AInKeyword := ASignature and 1 <> 0;
    AInStr := ASignature and 2 <> 0;
    AInNumber := ASignature and 4 <> 0;
    AInComment := Char(ASignature shr 16);
    AInDirective := ASignature and 8 <> 0;
  end;

  function GetLastSignature: cardinal;
  var
    yp: integer;
  begin
    for yp := AFromLine - 1 downto 0 do
      if Length(FTokens[yp]) > 0 then
      begin
        Assert(FTokens[yp][high(FTokens[yp])].signature and (1 shl 15) <> 0);
        Exit(FTokens[yp][high(FTokens[yp])].signature);
      end;
    result := 0;
  end;

  function PeekSignatureForward: cardinal;
  var
    yp: integer;
  begin
    for yp := y + 1 to high(FTokens) do
      if Length(FTokens[yp]) > 0 then
        Exit(FTokens[yp][0].signature);
    result := 0;
  end;

  function PeekSolidusComment: boolean;
  begin
    result := (x < TextLineWidth(y) - 1) and
      (TextChar(y, x + 1) = '/');
  end;

  function PeekSpecialComment: boolean;
  begin
    result := (x < TextLineWidth(y) - 1) and
      (TextChar(y, x + 1) = '*');
  end;

  function PeekDirective: boolean;
  begin
    result := (x < TextLineWidth(y) - 1) and
      (TextChar(y, x + 1) = '$');
  end;

  function WasClosingSpecialComment: boolean;
  begin
    result := (x > 0) and
      (TextChar(y, x - 1) = '*');
  end;

  function IsInKeyword: boolean;
  var
    wrd: string;
    i: Integer;
  begin
    wrd := LowerCase(TextGetWord(Point(x, y), true));
    result := false;
    for i := low(PASCAL_IDENTS) to high(PASCAL_IDENTS) do
      if SameStr(wrd, PASCAL_IDENTS[i]) then
        Exit(true);
  end;

  function StartsNumber: boolean;
  var
    i: integer;
    c: char;
    PeriodUsed: boolean;
    EPos: integer;
  begin
    result := true;
    PeriodUsed := false;
    EPos := -1;
    NumberEndsAt := TextLineWidth(y) - 1;
    for i := x to TextLineWidth(y) - 1 do
    begin
      c := TextChar(y, i);
      if c in ['0'..'9'] then
        Continue
      else if (c = '.') and not PeriodUsed then
      begin
        PeriodUsed := true;
        Continue;
      end
      else if (c in ['E', 'e']) and (EPos = -1) and (i > x) then
      begin
        EPos := i;
        Continue;
      end
      else if (c in ['+', '-']) and (i = EPos + 1) then
        Continue
      else
      begin
        NumberEndsAt := i - 1;
        break;
      end;
    end;
  end;

  function StartsHexNumber: boolean;
  var
    i: integer;
    c: char;
  begin
    result := true;
    NumberEndsAt := TextLineWidth(y) - 1;
    for i := x to TextLineWidth(y) - 1 do
    begin
      c := TextChar(y, i);
      if ((c='$') and (i=x)) or (c in ['0'..'9', 'a'..'f', 'A'..'F']) then
        Continue
      else
      begin
        NumberEndsAt := i - 1;
        break;
      end;
    end;
  end;

  function IsValidIdent(const C: char): boolean;
  begin
    result := C.IsLetterOrDigit or (C = '_');
  end;

  function StartNumLittPossible: boolean;
  begin
    result := (x = 0) or
      ((x > 0) and not IsValidIdent(TextChar(y, x - 1)));
  end;

  function LastChrOfKeyword: boolean;
  begin
    result := (x = TextLineWidth(y) - 1) or
      not (TextChar(y, x + 1) in ['a'..'z', 'A'..'Z']);
  end;

begin

  if AFromLine = 0 then
  begin
    InKeyword := false;
    InStr := false;
    InNumber := false;
    InComment := #0;
    InDirective := false;
  end
  else
  begin
    ExtractSignature(GetLastSignature, InKeyword, InStr, InNumber, InComment,
      InDirective);
  end;

  SetLength(FTokens, TextLineCount);
  SetLength(ActualLengths, TextLineCount);
  ToLine := TextLineCount - 1;
  for y := 0 to AFromLine - 1 do
    ActualLengths[y] := length(FTokens[y]);
  for y := AFromLine to ToLine do
    ActualLengths[y] := 0;
  for y := AFromLine to ToLine do
  begin
    for x := 0 to TextLineWidth(y) - 1 do
    begin
      if x=0 then
      begin
        lasttoken := Peek;
        if InComment = '/' then
        begin
          InComment := #0;
          lasttoken := ckPasUndefined;
        end;
        if InKeyword then
        begin
          InKeyword := false;
          lasttoken := ckPasUndefined;
        end;
        if InStr then
        begin
          InStr := false;
          lasttoken := ckPasUndefined;
        end;
        AddToken(lasttoken, true);
      end;
      Chr := TextChar(y, x);
      if InComment = '/' then
        // No way to terminate
      else if (InComment = '{') or InDirective then
      begin
        if Chr = '}' then
        begin
         InComment := #0;
         InDirective := false;
        end;
      end
      else if (InComment = '(') then
      begin
        if (Chr = ')') and WasClosingSpecialComment then
          InComment := #0;
      end
      else if InStr then
      begin
        if Chr = '''' then
          InStr := false;
      end
      else if Chr = '''' then
      begin
        InStr := true;
        AddToken(ckPasString);
      end
      else if (Chr = '/') and PeekSolidusComment then
      begin
        InComment := '/';
        AddToken(ckPasComment);
      end
      else if (Chr = '{') and PeekDirective then
      begin
        InDirective := true;
        AddToken(ckPasCompilerDirective);
      end
      else if (Chr = '{') then
      begin
        InComment := '{';
        AddToken(ckPasComment);
      end
      else if (Chr = '(') and PeekSpecialComment then
      begin
        InComment := '(';
        AddToken(ckPasComment);
      end
      else if InKeyword then
      begin
        if LastChrOfKeyword then
          InKeyword := false
      end
      else if InNumber then
      begin
        if x = NumberEndsAt then
          InNumber := false
      end
      else if (Chr in ['a'..'z', 'A'..'Z']) and IsInKeyword then
      begin
        InKeyword := true;
        AddToken(ckPasKeyword);
      end
      else if (Chr in ['0'..'9']) and StartNumLittPossible and StartsNumber then
      begin
        InNumber := true;
        AddToken(ckPasNumber);
        if x = NumberEndsAt then
          InNumber := false
      end
      else if (Chr = '$') and StartsHexNumber then
      begin
        InNumber := true;
        AddToken(ckPasNumber);
        if x = NumberEndsAt then
          InNumber := false
      end
      else if (Chr = '#') then
      begin
        AddToken(ckPasString)
      end
      else
        if Peek <> ckPasUndefined then
          AddToken(ckPasUndefined);
      if x = TextLineWidth(y) - 1 then
        AddSignature;
    end;
    if SingleLinePossibility and (y - AFromLine >= ANumLines - 1) and (GetSignature = PeekSignatureForward) then
    begin
      ToLine := y;
      break;
    end;
  end;
  for y := AFromLine to ToLine do
    SetLength(FTokens[y], ActualLengths[y]);
  result := ToLine;

end;

procedure TPascalFormattingProcessor.PushTokensDownFrom(ALineIndex: integer);
var
  i: Integer;
begin
  SetLength(FTokens, Length(FTokens) + 1);
  for i := high(FTokens) downto ALineIndex + 1 do
    FTokens[i] := Copy(FTokens[i - 1]);
end;

procedure TPascalFormattingProcessor.PushTokensUpFrom(ALineIndex: integer);
var
  i: Integer;
begin
  for i := ALineIndex + 1 to high(FTokens) - 1 do
    FTokens[i] := Copy(FTokens[i + 1]);
  SetLength(FTokens, Length(FTokens) - 1);
end;

function TPascalFormattingProcessor.RestoreCache(ACache: PByte;
  ASize: Integer): Boolean;
var
  i: Integer;
begin
  result := false;
  if (ACache = nil) or (ASize = 0) then Exit;

  SetLength(FTokens, PInteger(ACache)^);
  inc(ACache, sizeof(integer));
  for i := 0 to high(FTokens) do
  begin
    SetLength(FTokens[i], PInteger(ACache)^);
    inc(ACache, sizeof(integer));
    Move(ACache^, FTokens[i][0], Length(FTokens[i]) * sizeof(TFmtBreak));
    inc(ACache, Length(FTokens[i]) * sizeof(TFmtBreak));
  end;

  result := true;
end;

procedure TPascalFormattingProcessor.SetCommentColor(const Value: TColor);
begin
  if FCommentColor <> Value then
  begin
    FCommentColor := Value;
    Changed;
  end;
end;

procedure TPascalFormattingProcessor.SetCompilerDirectiveColor(
  const Value: TColor);
begin
  if FCompilerDirectiveColor <> Value then
  begin
    FCompilerDirectiveColor := Value;
    Changed;
  end;
end;

procedure TPascalFormattingProcessor.SetKeywordBold(const Value: boolean);
begin
  if FKeywordBold <> Value then
  begin
    FKeywordBold := Value;
    Changed;
  end;
end;

procedure TPascalFormattingProcessor.SetKeywordColor(const Value: TColor);
begin
  if FKeywordColor <> Value then
  begin
    FKeywordColor := Value;
    Changed;
  end;
end;

procedure TPascalFormattingProcessor.SetNumberColor(const Value: TColor);
begin
  if FNumberColor <> Value then
  begin
    FNumberColor := Value;
    Changed;
  end;
end;

procedure TPascalFormattingProcessor.SetStringColor(const Value: TColor);
begin
  if FStringColor <> Value then
  begin
    FStringColor := Value;
    Changed;
  end;
end;

{ TAlgoSimFormattingProcessor }

procedure TAlgoSimFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FKeywordColor := AColorScheme.Accent3;
  FStringColor := AColorScheme.Accent1;
  FNumberColor := AColorScheme.Accent1;
  FCommentColor := AColorScheme.Accent2;
  Changed;
end;

procedure TAlgoSimFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TAlgoSimFormattingProcessor then
  begin
    FKeywordColor := TAlgoSimFormattingProcessor(Source).KeywordColor;
    FKeywordBold := TAlgoSimFormattingProcessor(Source).KeywordBold;
    FStringColor := TAlgoSimFormattingProcessor(Source).StringColor;
    FNumberColor := TAlgoSimFormattingProcessor(Source).NumberColor;
    FCommentColor := TAlgoSimFormattingProcessor(Source).CommentColor;
    Changed;
  end
  else
    inherited;
end;

constructor TAlgoSimFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FKeywordColor := DEFAULT_KEYWORD_COLOR;
  FKeywordBold := DEFAULT_KEYWORD_BOLD;
  FStringColor := DEFAULT_STRING_COLOR;
  FNumberColor := DEFAULT_NUMBER_COLOR;
  FCommentColor := DEFAULT_COMMENT_COLOR;
end;

function TAlgoSimFormattingProcessor.FileChangeNotification(
  ChangeType: TChangeType; Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  case ChangeType of
    ctNone: ;
    ctFile:
      begin
        result.ChangeType := ctFile;
      end;
    ctLineRange:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctBlock:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctLine:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data1;
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data1;
      end;
    ctChar:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data1;
      end;
    ctTwoChars:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := max(Data1, Data3);
      end;
    ctPostFile: ;
  end;
end;

function TAlgoSimFormattingProcessor.GetCharCSSClass(ALineIndex, ACol: Integer;
  AChar: Char): Integer;
  
  function BeforeSpace: boolean;
  var
    i: Integer;
    AfterSemicolon: boolean;
  begin
    result := true;
    AfterSemicolon := false;
    for i := 0 to ACol do
      case TextChar(ALineIndex, i) of
        ';': AfterSemicolon := true;
        ' ': if AfterSemicolon then Exit(false);             
      end;
  end;

  function IsNumber: boolean;
  var
    i: Integer;
    BaseN: boolean;
    SP, EP: integer;
  begin
    if (AChar = '#') or (AChar = '.') then
      Exit(true)
    else if not (AChar in ['0'..'9', 'A'..'Z', 'a'..'z']) then
      Exit(false);

    TextGetWordBoundary(Point(ACol, ALineIndex), SP, EP);
    dec(EP);
    BaseN := (EP < TextLineWidth(ALineIndex) - 3) and (TextChar(ALineIndex, EP + 1) = '#');
    result := true;
    if BaseN then
    begin
      for i := SP to EP do
        if not (TextChar(ALineIndex, i) in ['0'..'9', 'A'..'Z', 'a'..'z']) then
          Exit(false)
    end
    else
      for i := SP to EP do
        if not (TextChar(ALineIndex, i) in ['0'..'9']) then
          Exit(false);
  end;

var
  InStr: boolean;
  i: Integer;
  InIndent: boolean;
  SemicolonCount: integer;

begin

  InIndent := true;
  SemicolonCount := 0;
  for i := 0 to TextLineWidth(ALineIndex) - 1 do
    if (TextChar(ALineIndex, i) = ' ') and InIndent then
      Continue
    else
    begin
      InIndent := false;
      if TextChar(ALineIndex, i) = ';' then
      begin
        inc(SemicolonCount);
        if SemicolonCount = 2 then break;
      end  
      else
        break;
    end;

  result := CSS_CLASS_DEFAULT;

  if SemicolonCount = 2 then
    Exit(CSS_CLASS_COMMENT);

  if SemicolonCount = 1 then
    Exit(CSS_CLASS_KEYWORD);

  InStr := false;
  for i := 0 to ACol do
  begin
    if InStr then
    begin
      if TextChar(ALineIndex, i) = '"' then
        InStr := false
    end
    else
    begin
      if TextChar(ALineIndex, i) = '"' then
        InStr := true
    end;
  end;

  if InStr or (AChar = '"') then
    result := CSS_CLASS_STRING
  else if IsNumber then
    result := CSS_CLASS_NUMBER;
end;

procedure TAlgoSimFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: Char; var AFontRecord: TFontRecord);
begin

  case GetCharCSSClass(ALineIndex, ACol, AChar) of
    CSS_CLASS_KEYWORD:
      begin
        AFontRecord.Color := FKeywordColor;
        if FKeywordBold then
          Include(AFontRecord.Style, fsBold);
      end;  
    CSS_CLASS_STRING:
      AFontRecord.Color := FStringColor;
    CSS_CLASS_NUMBER:
      AFontRecord.Color := FNumberColor;
    CSS_CLASS_COMMENT:
      AFontRecord.Color := FCommentColor;
  end;

end;

function TAlgoSimFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_DEFAULT] := MakeCSSRule('default', []);
  result[CSS_CLASS_KEYWORD] := MakeCSSRule('keyword',
    [MakeCSSDeclaration('color', CSSColor(FKeywordColor)),
     MakeCSSOptionalDeclaration(FKeywordBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_STRING] := MakeCSSRule('string',
    [MakeCSSDeclaration('color', CSSColor(FStringColor))]);
  result[CSS_CLASS_NUMBER] := MakeCSSRule('number',
    [MakeCSSDeclaration('color', CSSColor(FNumberColor))]);
  result[CSS_CLASS_COMMENT] := MakeCSSRule('comment',
    [MakeCSSDeclaration('color', CSSColor(FCommentColor))]);
end;

procedure TAlgoSimFormattingProcessor.SetCommentColor(const Value: TColor);
begin
  if FCommentColor <> Value then
  begin
    FCommentColor := Value;
    Changed;
  end;
end;

procedure TAlgoSimFormattingProcessor.SetKeywordBold(const Value: boolean);
begin
  if FKeywordBold <> Value then
  begin
    FKeywordBold := Value;
    Changed;
  end;
end;

procedure TAlgoSimFormattingProcessor.SetKeywordColor(const Value: TColor);
begin
  if FKeywordColor <> Value then
  begin
    FKeywordColor := Value;
    Changed;
  end;
end;

procedure TAlgoSimFormattingProcessor.SetNumberColor(const Value: TColor);
begin
  if FNumberColor <> Value then
  begin
    FNumberColor := Value;
    Changed;
  end;
end;

procedure TAlgoSimFormattingProcessor.SetStringColor(const Value: TColor);
begin
  if FStringColor <> Value then
  begin
    FStringColor := Value;
    Changed;
  end;
end;

{ THTMLFormattingProcessor }

procedure THTMLFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FTagColor := AColorScheme.Accent1;
  FTagNameColor := AColorScheme.Accent3;
  FParamColor := AColorScheme.Accent1;
  FValueColor := AColorScheme.Accent2;
  FCommentColor := AColorScheme.Soft;
  FCssSelectorColor := AColorScheme.Accent3;
  FCssPropertyColor := AColorScheme.Accent1;
  FCssValueColor := AColorScheme.Accent2;
  FCssCommentColor := AColorScheme.Soft;
  FCssBlockDelimColor := AColorScheme.Accent3;
  FCssImportantColor := AColorScheme.Intense;
  FDoctypeColor := AColorScheme.Soft;
  Changed;
end;

procedure THTMLFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is THTMLFormattingProcessor then
  begin
    FTagColor := THTMLFormattingProcessor(Source).TagColor;
    FTagNameColor := THTMLFormattingProcessor(Source).TagNameColor;
    FTagNameBold := THTMLFormattingProcessor(Source).TagNameBold;
    FParamColor := THTMLFormattingProcessor(Source).ParamColor;
    FValueColor := THTMLFormattingProcessor(Source).ValueColor;
    FCommentColor := THTMLFormattingProcessor(Source).CommentColor;
    FCssSelectorColor := THTMLFormattingProcessor(Source).CssSelectorColor;
    FCssSelectorBold := THTMLFormattingProcessor(Source).CssSelectorBold;
    FCssPropertyColor := THTMLFormattingProcessor(Source).CssPropertyColor;
    FCssValueColor := THTMLFormattingProcessor(Source).CssValueColor;
    FCssCommentColor := THTMLFormattingProcessor(Source).CssCommentColor;
    FCssBlockDelimColor := THTMLFormattingProcessor(Source).CssBlockDelimColor;
    FCssBlockDelimBold := THTMLFormattingProcessor(Source).CssBlockDelimBold;
    FCssImportantColor := THTMLFormattingProcessor(Source).CssImportantColor;
    FCssImportantBold := THTMLFormattingProcessor(Source).CssImportantBold;
    FDoctypeColor := THTMLFormattingProcessor(Source).DoctypeColor;
    FDoctypeBold := THTMLFormattingProcessor(Source).DoctypeBold;
    FDoctypeItalics := THTMLFormattingProcessor(Source).DoctypeItalics;
    Changed;
  end
  else if Source is TXMLFormattingProcessor then
  begin
    FTagColor := TXMLFormattingProcessor(Source).TagColor;
    FTagNameColor := TXMLFormattingProcessor(Source).TagNameColor;
    FTagNameBold := TXMLFormattingProcessor(Source).TagNameBold;
    FParamColor := TXMLFormattingProcessor(Source).ParamColor;
    FValueColor := TXMLFormattingProcessor(Source).ValueColor;
    FCommentColor := TXMLFormattingProcessor(Source).CommentColor;
    Changed;
  end
  else if Source is TCSSFormattingProcessor then
  begin
    FCssSelectorColor := TCSSFormattingProcessor(Source).SelectorColor;
    FCssSelectorBold := TCSSFormattingProcessor(Source).SelectorBold;
    FCssPropertyColor := TCSSFormattingProcessor(Source).PropertyColor;
    FCssValueColor := TCSSFormattingProcessor(Source).ValueColor;
    FCssCommentColor := TCSSFormattingProcessor(Source).CommentColor;
    FCssBlockDelimColor := TCSSFormattingProcessor(Source).BlockDelimColor;
    FCssBlockDelimBold := TCSSFormattingProcessor(Source).BlockDelimBold;
    FCssImportantColor := TCSSFormattingProcessor(Source).ImportantColor;
    FCssImportantBold := TCSSFormattingProcessor(Source).ImportantBold;
    Changed;
  end
  else
    inherited;
end;

constructor THTMLFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FTagColor := DEFAULT_TAG_COLOR;
  FTagNameColor := DEFAULT_TAG_NAME_COLOR;
  FTagNameBold :=  DEFAULT_TAG_NAME_BOLD;
  FParamColor := DEFAULT_PARAM_COLOR;
  FValueColor := DEFAULT_VALUE_COLOR;
  FCommentColor := DEFAULT_COMMENT_COLOR;
  FCssSelectorColor := DEFAULT_CSS_SELECTOR_COLOR;
  FCssSelectorBold := DEFAULT_CSS_SELECTOR_BOLD;
  FCssPropertyColor := DEFAULT_CSS_PROPERTY_COLOR;
  FCssValueColor := DEFAULT_CSS_VALUE_COLOR;
  FCssCommentColor := DEFAULT_CSS_COMMENT_COLOR;
  FCssBlockDelimColor := DEFAULT_CSS_BLOCK_DELIM_COLOR;
  FCssBlockDelimBold := DEFAULT_CSS_BLOCK_DELIM_BOLD;
  FCssImportantColor := DEFAULT_CSS_IMPORTANT_COLOR;
  FCssImportantBold := DEFAULT_CSS_IMPORTANT_BOLD;
  FDoctypeColor := DEFAULT_DOCTYPE_COLOR;
  FDoctypeBold := DEFAULT_DOCTYPE_BOLD;
  FDoctypeItalics := DEFAULT_DOCTYPE_ITALICS;
end;

function THTMLFormattingProcessor.FileChangeNotification(
  ChangeType: TChangeType; Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  inherited;
  case ChangeType of
    ctNone: ;
    ctFile:
      begin
        ParseText;
        result.ChangeType := ctFile;
      end;
    ctLineRange:
      begin
        if Data3 = 1 {change caused by VK_RETURN, can optimize} then
        begin
          PushTokensDownFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else if Data3 = 2 {single #13#10 removed} then
        begin
          PushTokensUpFrom(Data1);
          ParseText(Data1, true, 2);
        end
        else
          ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctBlock:
      begin
        ParseText(Data1);
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := TextLineCount - 1;
      end;
    ctLine:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctChar:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := ParseText(Data1, true);
      end;
    ctTwoChars:
      begin
        ParseText(min(Data1, Data3));
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := TextLineCount - 1;
      end;
    ctPostFile: ;
  end;
end;

function THTMLFormattingProcessor.GetCharCSSClass(ALineIndex, ACol: Integer;
  AChar: Char): Integer;
begin
  case GetChrKind(ALineIndex, ACol) of
    ckHtmlUndefined, ckHtmlText:
      result := CSS_CLASS_TEXT;
    ckHtmlTag:
      result := CSS_CLASS_TAG;
    ckHtmlTagName:
      result := CSS_CLASS_TAG_NAME;
    ckHtmlParam:
      result := CSS_CLASS_PARAM;
    ckHtmlValue:
      result := CSS_CLASS_VALUE;
    ckHtmlComment:
      result := CSS_CLASS_COMMENT;
    ckHtmlCssSelector:
      result := CSS_CLASS_CSS_SELECTOR;
    ckHtmlCssBlockDelim:
      result := CSS_CLASS_CSS_BLOCK_DELIM;
    ckHtmlCssProperty:
      result := CSS_CLASS_CSS_PROPERTY;
    ckHtmlCssValue:
      result := CSS_CLASS_CSS_VALUE;
    ckHtmlCssImportant:
      result := CSS_CLASS_CSS_IMPORTANT;
    ckHtmlCssComment:
      result := CSS_CLASS_CSS_COMMENT;
    ckHtmlDoctype:
      result := CSS_CLASS_DOCTYPE;
    ckHtmlScript:
      result := CSS_CLASS_SCRIPT;
  else
    raise Exception.Create('THTMLFormattingProcessor.GetCharCSSClass: Invalid character kind.');
  end;
end;

procedure THTMLFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: Char; var AFontRecord: TFontRecord);
begin
  case GetChrKind(ALineIndex, ACol) of
    ckHtmlTag:
      AFontRecord.Color := FTagColor;
    ckHtmlTagName:
      begin
        AFontRecord.Color := FTagNameColor;
        if FTagNameBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckHtmlParam:
      AFontRecord.Color := FParamColor;
    ckHtmlValue:
      AFontRecord.Color := FValueColor;
    ckHtmlComment:
      AFontRecord.Color := FCommentColor;
    ckHtmlCssSelector:
      begin
        AFontRecord.Color := FCssSelectorColor;
        if FCssSelectorBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckHtmlCssBlockDelim:
      begin
        AFontRecord.Color := FCssBlockDelimColor;
        if FCssBlockDelimBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckHtmlCssProperty:
      AFontRecord.Color := FCssPropertyColor;
    ckHtmlCssValue:
      AFontRecord.Color := FCssValueColor;
    ckHtmlCssImportant:
      begin
        AFontRecord.Color := FCssImportantColor;
        if FCssImportantBold then
          Include(AFontRecord.Style, fsBold);
      end;
    ckHtmlCssComment:
      AFontRecord.Color := FCssCommentColor;
    ckHtmlDoctype:
      begin
        AFontRecord.Color := FDoctypeColor;
        if FDoctypeBold then
          Include(AFontRecord.Style, fsBold);
        if FDoctypeItalics then
          Include(AFontRecord.Style, fsItalic);
      end;
  end;
end;

function THTMLFormattingProcessor.GetChrKind(ALineIndex,
  ACol: Integer): THtmlChrKind;
var
  i: integer;
begin
  result := ckHtmlUndefined;
  i := 0;
  if ALineIndex <= high(FTokens) then
    while (i <= high(FTokens[ALineIndex])) and (FTokens[ALineIndex][i].x <= ACol) do
    begin
      result := FTokens[ALineIndex][i].kind;
      inc(i);
    end;
end;

function THTMLFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_TEXT] := MakeCSSRule('text', []);
  result[CSS_CLASS_TAG] := MakeCSSRule('tag',
    [MakeCSSDeclaration('color', CSSColor(FTagColor))]);
  result[CSS_CLASS_TAG_NAME] := MakeCSSRule('tag-name',
    [MakeCSSDeclaration('color', CSSColor(FTagNameColor)),
     MakeCSSOptionalDeclaration(FTagNameBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_PARAM] := MakeCSSRule('param',
    [MakeCSSDeclaration('color', CSSColor(FParamColor))]);
  result[CSS_CLASS_VALUE] := MakeCSSRule('value',
    [MakeCSSDeclaration('color', CSSColor(FValueColor))]);
  result[CSS_CLASS_COMMENT] := MakeCSSRule('comment',
    [MakeCSSDeclaration('color', CSSColor(FCommentColor))]);
  result[CSS_CLASS_CSS_SELECTOR] := MakeCSSRule('css-selector',
    [MakeCSSDeclaration('color', CSSColor(FCssSelectorColor)),
     MakeCSSOptionalDeclaration(FCssSelectorBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_CSS_PROPERTY] := MakeCSSRule('css-property',
    [MakeCSSDeclaration('color', CSSColor(FCssPropertyColor))]);
  result[CSS_CLASS_CSS_VALUE] := MakeCSSRule('css-value',
    [MakeCSSDeclaration('color', CSSColor(FCssValueColor))]);
  result[CSS_CLASS_CSS_COMMENT] := MakeCSSRule('css-comment',
    [MakeCSSDeclaration('color', CSSColor(FCssCommentColor))]);
  result[CSS_CLASS_CSS_BLOCK_DELIM] := MakeCSSRule('css-delim',
    [MakeCSSDeclaration('color', CSSColor(FCssBlockDelimColor)),
     MakeCSSOptionalDeclaration(FCssBlockDelimBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_CSS_IMPORTANT] := MakeCSSRule('css-important',
    [MakeCSSDeclaration('color', CSSColor(FCssImportantColor)),
     MakeCSSOptionalDeclaration(FCssImportantBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_DOCTYPE] := MakeCSSRule('doctype',
    [MakeCSSDeclaration('color', CSSColor(FDoctypeColor)),
     MakeCSSOptionalDeclaration(FDoctypeBold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FDoctypeItalics, 'text-style', 'italics')]);
  result[CSS_CLASS_SCRIPT] := MakeCSSRule('script', []);
end;

function THTMLFormattingProcessor.ParseText(AFromLine: integer;
  SingleLinePossibility: boolean; ANumLines: integer): integer;
type
  TNibble = type byte;
const
  ALLOC_BY = 16;
var
  ToLine: integer;
  ActualLengths: array of integer;
  y, x: Integer;
  InTag,
  InScript,
  InComment: boolean;
  InVal: char; {#0, '''', '"'}
  InCss: boolean;
  InCssBlock: TNibble;
  InCssValue,
  InCssImportant,
  InCssComment: boolean;
  InCssStr: char;
  InDoctype: boolean;
  Chr: char;
  TagStart: TPoint;
  TagName: string;
  InAttrib: boolean;

  function GetSignature: cardinal;
  begin
    result := Byte(InTag) or (Byte(InComment) shl 1) or (Ord(InVal) shl 16) or (1 shl 15)
      or (Byte(InCss) shl 2) or ((InCssBlock and $F) shl 9) or (Byte(InCssValue) shl 4)
      or (Byte(InCssImportant) shl 5) or (Byte(InCssComment) shl 6) or (Byte(InDoctype) shl 7)
      or (Byte(InAttrib) shl 8) or (Byte(InScript) shl 3);
  end;

  procedure ExtractSignature(ASignature: cardinal; out AInTag,
    AInComment, AInScript: boolean; out AInVal: char; out AInCss,
    AInCssValue, AInCssImportant, AInCssComment: boolean; out AInCSSStr: char;
    out AInDoctype, AInAttrib: boolean; out AInCssBlock: TNibble);
  begin
    AInTag := ASignature and 1 <> 0;
    AInComment := ASignature and 2 <> 0;
    AInScript := ASignature and 8 <> 0;
    AInVal := Char(ASignature shr 16);
    AInCss := ASignature and 4 <> 0;
    AInCssBlock := (ASignature shr 9) and $F;
    AInCssValue := ASignature and 16 <> 0;
    AInCssImportant := ASignature and 32 <> 0;
    AInCssComment := ASignature and 64 <> 0;
    AInCSSStr := Char(ASignature shr 16);
    AInDoctype := ASignature and 128 <> 0;
    AInAttrib := ASignature and 256 <> 0;
  end;

  // Must only be called within the inner loop (y, x)!
  procedure AddToken(AKind: THtmlChrKind; Signature: boolean = false);
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := AKind;
    if Signature then
      FTokens[y][ActualLengths[y]].signature := GetSignature
    else
      FTokens[y][ActualLengths[y]].signature := 0;
    inc(ActualLengths[y]);
  end;

  function GetLastKind: THtmlChrKind;
  var
    yp: Integer;
    xp: Integer;
  begin
    for yp := y downto 0 do
      for xp := ActualLengths[yp] - 1 downto 0 do
        Exit(FTokens[yp][xp].kind);
    result := ckHtmlText; // SOF default
  end;

  procedure AddSignature;
  begin
    if Length(FTokens[y]) = ActualLengths[y] then
      SetLength(FTokens[y], Length(FTokens[y]) + ALLOC_BY);
    FTokens[y][ActualLengths[y]].x := x;
    FTokens[y][ActualLengths[y]].kind := GetLastKind;
    FTokens[y][ActualLengths[y]].signature := GetSignature;
    inc(ActualLengths[y]);
  end;

  function Peek: THtmlChrKind;
  var
    yp: integer;
  begin
    for yp := y downto 0 do
      if ActualLengths[yp] > 0 then
        Exit(FTokens[yp][ActualLengths[yp] - 1].kind);
    result := ckHtmlUndefined;
  end;

  function GetLastSignature: cardinal;
  var
    yp: integer;
  begin
    for yp := AFromLine - 1 downto 0 do
      if Length(FTokens[yp]) > 0 then
      begin
        Assert(FTokens[yp][high(FTokens[yp])].signature and (1 shl 15) <> 0);
        Exit(FTokens[yp][high(FTokens[yp])].signature);
      end;
    result := 0;
  end;

  function PeekSignatureForward: cardinal;
  var
    yp: integer;
  begin
    for yp := y + 1 to high(FTokens) do
      if Length(FTokens[yp]) > 0 then
        Exit(FTokens[yp][0].signature);
    result := 0;
  end;

  function PeekIsComment: boolean;
  begin
    result := (TextLineWidth(y) >= x + 4) and
      (TextChar(y, x + 1) = '!') and
      (TextChar(y, x + 2) = '-') and
      (TextChar(y, x + 3) = '-');
  end;

  function DoesEndComment: boolean;
  begin
    result := (x >= 2) and
      (TextChar(y, x - 1) = '-') and
      (TextChar(y, x - 2) = '-');
  end;

  function PeekDoctype: boolean;
  begin
    result := (TextLineWidth(y) >= x + 9) and
      (TextChar(y, x + 1) = '!') and
      (LowerCase(TextChar(y, x + 2)) = 'd') and
      (LowerCase(TextChar(y, x + 3)) = 'o') and
      (LowerCase(TextChar(y, x + 4)) = 'c') and
      (LowerCase(TextChar(y, x + 5)) = 't') and
      (LowerCase(TextChar(y, x + 6)) = 'y') and
      (LowerCase(TextChar(y, x + 7)) = 'p') and
      (LowerCase(TextChar(y, x + 8)) = 'e');
  end;

  function CssPeekImportant: boolean;
  begin
    result := (TextLineWidth(y) >= x + 10) and
      (TextChar(y, x + 1) = 'i') and
      (TextChar(y, x + 2) = 'm') and
      (TextChar(y, x + 3) = 'p') and
      (TextChar(y, x + 4) = 'o') and
      (TextChar(y, x + 5) = 'r') and
      (TextChar(y, x + 6) = 't') and
      (TextChar(y, x + 7) = 'a') and
      (TextChar(y, x + 8) = 'n') and
      (TextChar(y, x + 9) = 't');
  end;

  function PeekStartsTag: boolean;
  begin
    result := (TextLineWidth(y) >= x + 2) and
      (TextChar(y, x + 1).IsLetter or (TextChar(y, x + 1) = '/'));
  end;

  function CssPeekComment: boolean;
  begin
    result := (TextLineWidth(y) >= x + 2) and
      (TextChar(y, x + 1) = '*');
  end;

  function CssEndsComment: boolean;
  begin
    result := (x >= 1) and (TextChar(y, x - 1) = '*');
  end;

  function PeekStyleEnd: boolean;
  begin
    result := (TextLineWidth(y) >= x + 8) and
      (TextChar(y, x + 1) = '/') and
      (LowerCase(TextChar(y, x + 2)) = 's') and
      (LowerCase(TextChar(y, x + 3)) = 't') and
      (LowerCase(TextChar(y, x + 4)) = 'y') and
      (LowerCase(TextChar(y, x + 5)) = 'l') and
      (LowerCase(TextChar(y, x + 6)) = 'e') and
      (TextChar(y, x + 7) = '>');
  end;

  function PeekScriptEnd: boolean;
  begin
    result := (TextLineWidth(y) >= x + 9) and
      (TextChar(y, x + 1) = '/') and
      (LowerCase(TextChar(y, x + 2)) = 's') and
      (LowerCase(TextChar(y, x + 3)) = 'c') and
      (LowerCase(TextChar(y, x + 4)) = 'r') and
      (LowerCase(TextChar(y, x + 5)) = 'i') and
      (LowerCase(TextChar(y, x + 6)) = 'p') and
      (LowerCase(TextChar(y, x + 7)) = 't') and
      (TextChar(y, x + 8) = '>');
  end;

  function GetTagName: string;
  var
    pnt: TPoint;
  begin
    pnt := TagStart;
    inc(pnt.X);
    result := TextGetWord(pnt);
  end;


begin

  if AFromLine = 0 then
  begin
    InTag := false;
    InScript := false;
    InComment := false;
    InVal := #0;
    InCss := false;
    InCssBlock := 0;
    InCssValue := false;
    InCssImportant := false;
    InCssComment := false;
    InCssStr := #0;
    InDoctype := false;
    InAttrib := false;
  end
  else
  begin
    ExtractSignature(GetLastSignature, InTag, InComment, InScript, InVal, InCss,
      InCssValue, InCssImportant, InCssComment, InCssStr{was InVal}, InDoctype,
      InAttrib, InCssBlock);
  end;

  SetLength(FTokens, TextLineCount);
  SetLength(ActualLengths, TextLineCount);
  ToLine := TextLineCount - 1;
  for y := 0 to AFromLine - 1 do
    ActualLengths[y] := length(FTokens[y]);
  for y := AFromLine to ToLine do
    ActualLengths[y] := 0;
  for y := AFromLine to ToLine do
  begin
    for x := 0 to TextLineWidth(y) - 1 do
    begin
      if x=0 then
        AddToken(Peek, true);
      Chr := TextChar(y, x);

      // <style>
      if InCss then
      begin

        if InCssStr <> #0 then
        begin
          if Chr = InCssStr then
            InCssStr := #0
        end
        else if (not InCssComment) and ((Chr = '"') or (Chr = '''')) then
        begin
          InCssStr := Chr;
          if InCssValue and (Peek <> ckHtmlCssValue) then
            AddToken(ckHtmlCssValue);
        end
        else if InCssComment then
        begin
          if (Chr = '/') and CssEndsComment then
            InCssComment := false;
        end
        else if (Chr = '/') and CssPeekComment then
        begin
          AddToken(ckHtmlCssComment);
          InCssComment := true;
        end
        else if InCssImportant then
        begin
          if Chr = ';' then
          begin
            AddToken(ckHtmlCssValue);
            InCssImportant := false;
            InCssValue := false;
          end;
        end
        else if InCssValue then
        begin
          if (Chr = '!') and CssPeekImportant then
          begin
            AddToken(ckHtmlCssImportant);
            InCssImportant := true;
          end
          else
          begin
            if Peek <> ckHtmlCssValue then
              AddToken(ckHtmlCssValue);
            if Chr = ';' then
            begin
              InCssValue := false;
            end
            else if Chr = '}' then
            begin
              AddToken(ckHtmlCssBlockDelim);
              InCssValue := false;
              dec(InCssBlock);
            end
          end;
        end
        else if InCssBlock > 0 then
        begin
          if Chr = '{' then
          begin
            AddToken(ckHtmlCssBlockDelim);
            inc(InCssBlock);
          end
          else if Chr = '}' then
          begin
            AddToken(ckHtmlCssBlockDelim);
            dec(InCssBlock);
          end
          else if Peek <> ckHtmlCssProperty then
            AddToken(ckHtmlCssProperty);
          if Chr = ':' then
          begin
            InCssValue := true;
          end;
        end
        else if Chr = '{' then
        begin
          AddToken(ckHtmlCssBlockDelim);
          inc(InCssBlock);
        end
        else if (Chr = '<') and PeekStyleEnd then
        begin
          InCSS := false;
          InTag := true;
          InAttrib := false;
          InVal := #0;
          InComment := false;
          InDoctype := false;
          AddToken(ckHtmlTag);
          TagStart := Point(x, y);
        end
        else if Peek <> ckHtmlCssSelector then
          AddToken(ckHtmlCssSelector);

      end
      // </style>

      // <script>
      else if InScript then
      begin
        if (Chr = '<') and PeekScriptEnd then
        begin
          InScript := false;
          InTag := true;
          InAttrib := false;
          InVal := #0;
          InComment := false;
          InDoctype := false;
          AddToken(ckHtmlTag);
          TagStart := Point(x, y);
        end else if Peek <> ckHtmlScript then
          AddToken(ckHtmlScript);
      end
      // </script>

      else if InComment then
      begin
        if (Chr = '>') and DoesEndComment then
          InComment := false;
      end
      else if InDoctype then
      begin
        if Chr = '>' then
          InDoctype := false;
      end
      else if InTag then
      begin
        if InVal <> #0 then
        begin
          if Chr = InVal then
            InVal := #0;
        end
        else
        begin
          if (x=0) or (Chr = #32) and (Peek <> ckHtmlParam) then
          begin
            InAttrib := true;
            AddToken(ckHtmlParam);
          end
          else if (Chr = '''') or (Chr = '"') then
          begin
            InVal := Chr;
            AddToken(ckHtmlValue);
          end
          else if Chr = '/' then
          begin
            if Peek <> ckHtmlTag then
              AddToken(ckHtmlTag);
          end
          else if Chr = '>' then
          begin
            TagName := GetTagName;
            InTag := false;
            AddToken(ckHtmlTag);
            if SameText(TagName, 'style') then
            begin
              InCss := true;
              InCssBlock := 0;
              InCssValue := false;
              InCssImportant := false;
              InCssComment := false;
              InCssStr := #0;
            end
            else if SameText(TagName, 'script') then
            begin
              InScript := true;
            end
          end
          else
          begin
            if InAttrib and (Peek <> ckHtmlParam) then
              AddToken(ckHtmlParam)
            else if (not InAttrib) and (Peek <> ckHtmlTagName) then
              AddToken(ckHtmlTagName);
          end;
        end;
      end
      else if (Chr = '<') then
      begin
        if PeekIsComment then
        begin
          InComment := true;
          AddToken(ckHtmlComment);
        end
        else if PeekDoctype then
        begin
          InDoctype := true;
          AddToken(ckHtmlDoctype);
        end
        else if PeekStartsTag then
        begin
          InTag := true;
          InAttrib := false;
          AddToken(ckHtmlTag);
          TagStart := Point(x, y);
        end
      end
      else if Peek <> ckHtmlText then
        AddToken(ckHtmlText);
      if x = TextLineWidth(y) - 1 then
        AddSignature;
    end;
    if SingleLinePossibility and (y - AFromLine >= ANumLines - 1) and (GetSignature = PeekSignatureForward) then
    begin
      ToLine := y;
      break;
    end;
  end;
  for y := AFromLine to ToLine do
    SetLength(FTokens[y], ActualLengths[y]);
  result := ToLine;
end;

procedure THTMLFormattingProcessor.PushTokensDownFrom(ALineIndex: integer);
var
  i: Integer;
begin
  SetLength(FTokens, Length(FTokens) + 1);
  for i := high(FTokens) downto ALineIndex + 1 do
    FTokens[i] := Copy(FTokens[i - 1]);
end;

procedure THTMLFormattingProcessor.PushTokensUpFrom(ALineIndex: integer);
var
  i: Integer;
begin
  for i := ALineIndex + 1 to high(FTokens) - 1 do
    FTokens[i] := Copy(FTokens[i + 1]);
  SetLength(FTokens, Length(FTokens) - 1);
end;

procedure THTMLFormattingProcessor.SetCommentColor(const Value: TColor);
begin
  if FCommentColor <> Value then
  begin
    CommentColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssBlockDelimBold(const Value: boolean);
begin
  if FCssBlockDelimBold <> Value then
  begin
    FCssBlockDelimBold := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssBlockDelimColor(const Value: TColor);
begin
  if FCssBlockDelimColor <> Value then
  begin
    FCssBlockDelimColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssCommentColor(const Value: TColor);
begin
  if FCssCommentColor <> Value then
  begin
    FCssCommentColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssImportantBold(const Value: boolean);
begin
  if FCssImportantBold <> Value then
  begin
    FCssImportantBold := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssImportantColor(const Value: TColor);
begin
  if FCssImportantColor <> Value then
  begin
    FCssImportantColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssPropertyColor(const Value: TColor);
begin
  if FCssPropertyColor <> Value then
  begin
    FCssPropertyColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssSelectorBold(const Value: boolean);
begin
  if FCssSelectorBold <> Value then
  begin
    FCssSelectorBold := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssSelectorColor(const Value: TColor);
begin
  if FCssSelectorColor <> Value then
  begin
    FCssSelectorColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetCssValueColor(const Value: TColor);
begin
  if FCssValueColor <> Value then
  begin
    FCssValueColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetDoctypeBold(const Value: boolean);
begin
  if FDoctypeBold <> Value then
  begin
    FDoctypeBold := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetDoctypeColor(const Value: TColor);
begin
  if FDoctypeColor <> Value then
  begin
    FDoctypeColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetDoctypeItalics(const Value: boolean);
begin
  if FDoctypeItalics <> Value then
  begin
    FDoctypeItalics := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetParamColor(const Value: TColor);
begin
  if FParamColor <> Value then
  begin
    FParamColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetTagColor(const Value: TColor);
begin
  if FTagColor <> Value then
  begin
    FTagColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetTagNameBold(const Value: boolean);
begin
  if FTagNameBold <> Value then
  begin
    FTagNameBold := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetTagNameColor(const Value: TColor);
begin
  if FTagNameColor <> Value then
  begin
    FTagNameColor := Value;
    Changed;
  end;
end;

procedure THTMLFormattingProcessor.SetValueColor(const Value: TColor);
begin
  if FValueColor <> Value then
  begin
    FValueColor := Value;
    Changed
  end;
end;

{ TMediaWikiFormattingProcessor }

procedure TMediaWikiFormattingProcessor.ApplyColorScheme(
  const AColorScheme: TColorScheme);
begin
  FHeading1Color := AColorScheme.Accent1;
  FHeading2Color := AColorScheme.Accent1;
  FHeading3Color := AColorScheme.Accent1;
  FHeading4Color := AColorScheme.Accent1;
  FHeading5Color := AColorScheme.Soft;
  FHeading6Color := AColorScheme.Soft;
  FWikilinkColor := AColorScheme.Accent3;
  FExtlinkColor := AColorScheme.Accent3;
  FTemplateColor := AColorScheme.Accent2;
  FIndentColor := AColorScheme.Soft;
  Changed;
end;

procedure TMediaWikiFormattingProcessor.Assign(Source: TPersistent);
begin
  if Source is TMediaWikiFormattingProcessor then
  begin
    FHeading1Color := TMediaWikiFormattingProcessor(Source).Heading1Color;
    FHeading1Bold := TMediaWikiFormattingProcessor(Source).Heading1Bold;
    FHeading1Italics := TMediaWikiFormattingProcessor(Source).Heading1Italics;
    FHeading2Color := TMediaWikiFormattingProcessor(Source).Heading2Color;
    FHeading2Bold := TMediaWikiFormattingProcessor(Source).Heading2Bold;
    FHeading2Italics := TMediaWikiFormattingProcessor(Source).Heading2Italics;
    FHeading3Color := TMediaWikiFormattingProcessor(Source).Heading3Color;
    FHeading3Bold := TMediaWikiFormattingProcessor(Source).Heading3Bold;
    FHeading3Italics := TMediaWikiFormattingProcessor(Source).Heading3Italics;
    FHeading4Color := TMediaWikiFormattingProcessor(Source).Heading4Color;
    FHeading4Bold := TMediaWikiFormattingProcessor(Source).Heading4Bold;
    FHeading4Italics := TMediaWikiFormattingProcessor(Source).Heading4Italics;
    FHeading5Color := TMediaWikiFormattingProcessor(Source).Heading5Color;
    FHeading5Bold := TMediaWikiFormattingProcessor(Source).Heading5Bold;
    FHeading5Italics := TMediaWikiFormattingProcessor(Source).Heading5Italics;
    FHeading6Color := TMediaWikiFormattingProcessor(Source).Heading6Color;
    FHeading6Bold := TMediaWikiFormattingProcessor(Source).Heading6Bold;
    FHeading6Italics := TMediaWikiFormattingProcessor(Source).Heading6Italics;
    FWikilinkColor := TMediaWikiFormattingProcessor(Source).WikilinkColor;
    FExtlinkColor := TMediaWikiFormattingProcessor(Source).ExtlinkColor;
    FTemplateColor := TMediaWikiFormattingProcessor(Source).TemplateColor;
    FTemplateNameBold := TMediaWikiFormattingProcessor(Source).TemplateNameBold;
    FBoldBold := TMediaWikiFormattingProcessor(Source).BoldBold;
    FItalicsItalics := TMediaWikiFormattingProcessor(Source).ItalicsItalics;
    FIndentColor := TMediaWikiFormattingProcessor(Source).IndentColor;
    Changed;
  end
  else
    inherited;
end;

constructor TMediaWikiFormattingProcessor.Create(AOwner: TComponent);
begin
  inherited;
  FHeading1Color := DEFAULT_HEADING1_COLOR;
  FHeading1Bold := DEFAULT_HEADING1_BOLD;
  FHeading1Italics := DEFAULT_HEADING1_ITALICS;
  FHeading2Color := DEFAULT_HEADING2_COLOR;
  FHeading2Bold := DEFAULT_HEADING2_BOLD;
  FHeading2Italics := DEFAULT_HEADING2_ITALICS;
  FHeading3Color := DEFAULT_HEADING3_COLOR;
  FHeading3Bold := DEFAULT_HEADING3_BOLD;
  FHeading3Italics := DEFAULT_HEADING3_ITALICS;
  FHeading4Color := DEFAULT_HEADING4_COLOR;
  FHeading4Bold := DEFAULT_HEADING4_BOLD;
  FHeading4Italics := DEFAULT_HEADING4_ITALICS;
  FHeading5Color := DEFAULT_HEADING5_COLOR;
  FHeading5Bold := DEFAULT_HEADING5_BOLD;
  FHeading5Italics := DEFAULT_HEADING5_ITALICS;
  FHeading6Color := DEFAULT_HEADING6_COLOR;
  FHeading6Bold := DEFAULT_HEADING6_BOLD;
  FHeading6Italics := DEFAULT_HEADING6_ITALICS;
  FWikilinkColor := DEFAULT_WIKILINK_COLOR;
  FExtlinkColor := DEFAULT_EXTLINK_COLOR;
  FTemplateColor := DEFAULT_TEMPLATE_COLOR;
  FTemplateNameBold := DEFAULT_TEMPLATE_NAME_BOLD;
  FBoldBold := DEFAULT_BOLD_BOLD;
  FItalicsItalics := DEFAULT_ITALICS_ITALICS;
  FIndentColor := DEFAULT_INDENT_COLOR;
end;

function TMediaWikiFormattingProcessor.FileChangeNotification(
  ChangeType: TChangeType; Data1, Data2, Data3, Data4: Integer): TChangeRecord;
begin
  inherited;
  case ChangeType of
    ctNone: ;
    ctFile:
      result.ChangeType := ctFile;
    ctLineRange:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctBlock:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := Data1;
        result.Data2 := Data2;
      end;
    ctLine:
      begin
        result.ChangeType := ctLine;
        result.Data1 := Data1;
      end;
    ctLineFrom:
      begin
        result.ChangeType := ctLine;
        result.Data1 := Data1;
      end;
    ctChar:
      begin
        result.ChangeType := ctLine;
        result.Data1 := Data1;
      end;
    ctTwoChars:
      begin
        result.ChangeType := ctLineRange;
        result.Data1 := min(Data1, Data3);
        result.Data2 := max(Data1, Data3);
      end;
    ctPostFile: ;
  end;
end;

function TMediaWikiFormattingProcessor.GetCharCSSClass(ALineIndex,
  ACol: Integer; AChar: Char): Integer;
var
  i: Integer;
  TLW: integer;
  InIndent: boolean;
  InTemplate,
  InWikilink: integer;
  InName,
  PastSep,
  InExtLink,
  InBold,
  InItalics: boolean;
  RunDecTemplate,
  RunDecWikilink: boolean;

  function PeekTemplateStart: boolean;
  begin
    result := (TextChar(ALineIndex, i) = '{') and (i < TLW - 1) and
      (TextChar(ALineIndex, i + 1) = '{');
  end;

  function PeekTemplateEnd: boolean;
  begin
    result := (TextChar(ALineIndex, i) = '}') and (i < TLW - 1) and
      (TextChar(ALineIndex, i + 1) = '}');
  end;

  function PeekWikilinkStart: boolean;
  begin
    result := (TextChar(ALineIndex, i) = '[') and (i < TLW - 1) and
      (TextChar(ALineIndex, i + 1) = '[');
  end;

  function PeekWikilinkEnd: boolean;
  begin
    result := (TextChar(ALineIndex, i) = ']') and (i < TLW - 1) and
      (TextChar(ALineIndex, i + 1) = ']');
  end;

  function ExtlinkEnded: boolean;
  begin
    result := (i >= 1) and (TextChar(ALineIndex, i - 1) = ']');
  end;

  function PeekBold: boolean;
  begin
    result := (TextChar(ALineIndex, i) = '''') and (i < TLW - 2) and
      (TextChar(ALineIndex, i + 1) = '''') and (TextChar(ALineIndex, i + 2) = '''');
  end;

  function PeekItalics: boolean;
  begin
    result := (TextChar(ALineIndex, i) = '''') and (i < TLW - 1) and
      (TextChar(ALineIndex, i + 1) = '''');
  end;

  function GetStyleHighBits: cardinal;
  begin
    if InBold and InItalics then
      result := CSS_CLASS_BOLDITALICS shl 16
    else if InBold then
      result := CSS_CLASS_BOLD shl 16
    else if InItalics then
      result := CSS_CLASS_ITALICS shl 16
    else
      result := 0;
  end;


begin

  TLW := TextLineWidth(ALineIndex);

  if (TLW >= 1) and (TextChar(ALineIndex, 0) = ';') then
    Exit(CSS_CLASS_BOLD);

  if (TLW >= 1) and (TextChar(ALineIndex, 0) = '=') then
    if (TLW >= 2) and (TextChar(ALineIndex, 1) = '=') then
      if (TLW >= 3) and (TextChar(ALineIndex, 2) = '=') then
        if (TLW >= 4) and (TextChar(ALineIndex, 3) = '=') then
          if (TLW >= 5) and (TextChar(ALineIndex, 4) = '=') then
            if (TLW >= 6) and (TextChar(ALineIndex, 5) = '=') then
              Exit(CSS_CLASS_HEADING6)
            else
              Exit(CSS_CLASS_HEADING5)
          else
            Exit(CSS_CLASS_HEADING4)
        else
          Exit(CSS_CLASS_HEADING3)
      else
        Exit(CSS_CLASS_HEADING2)
    else
      Exit(CSS_CLASS_HEADING1);

  if AChar = ':' then
  begin
    InIndent := true;
    for i := 0 to ACol - 1 do
      if TextChar(ALineIndex, i) <> ':' then
      begin
        InIndent := false;
        break;
      end;
    if InIndent then
      Exit(CSS_CLASS_INDENT);
  end;

  InTemplate := 0;
  InName := false;
  PastSep := false;
  InWikiLink := 0;
  InExtLink := false;
  InBold := false;
  InItalics := false;
  RunDecTemplate := false;
  RunDecWikilink := false;
  i := 0;
  while i <= ACol do
  begin

    if RunDecTemplate then
    begin
      dec(InTemplate);
      RunDecTemplate := false;
    end;

    if RunDecWikilink then
    begin
      dec(InWikilink);
      RunDecWikilink := false;
    end;

    if PeekTemplateStart then
    begin
      inc(InTemplate);
      inc(i);
      InName := false;
      PastSep := false;
    end
    else
    begin

      if (InTemplate > 0) and PeekTemplateEnd then
      begin
        RunDecTemplate := true;
        inc(i);
      end;

      if InTemplate > 0 then
      begin
        if TextChar(ALineIndex, i) = '|' then
        begin
          InName := false;
          PastSep := true;
        end
        else if (not PastSep) and (TextChar(ALineIndex, i) <> '{') then
          InName := true;
        if TextChar(ALineIndex, i) = '}' then
          InName := false;
      end
      else
      begin

        if PeekWikilinkStart then
        begin
          inc(InWikilink);
          inc(i);
        end

        else if (InWikilink > 0) and PeekWikilinkEnd then
        begin
          RunDecWikilink := true;
          inc(i);
        end

        else if InExtlink and ExtlinkEnded then
          InExtlink := false

        else if (TextChar(ALineIndex, i) = '[') then
          InExtlink := true

        else if PeekBold then
        begin
          InBold := not InBold;
          inc(i, 2);
        end

        else if PeekItalics then
        begin
          InItalics := not InItalics;
          inc(i);
        end;

      end;

    end;

    inc(i);
  end;

  if (InTemplate > 0) and InName then
    result := CSS_CLASS_TEMPLATE_NAME
  else if (InTemplate > 0) then
    result := CSS_CLASS_TEMPLATE
  else if (InWikiLink > 0) then
    result := CSS_CLASS_WIKILINK or GetStyleHighBits
  else if InExtLink then
    result := CSS_CLASS_EXTLINK
  else if InBold and InItalics then
    result := CSS_CLASS_BOLDITALICS
  else if InBold then
    result := CSS_CLASS_BOLD
  else if InItalics then
    result := CSS_CLASS_ITALICS
  else
    result := CSS_CLASS_TEXT;

end;

procedure TMediaWikiFormattingProcessor.GetCharFormat(ALineIndex, ACol: Integer;
  AChar: Char; var AFontRecord: TFontRecord);
begin
  case GetCharCSSClass(ALineIndex, ACol, AChar) of
    CSS_CLASS_TEXT: ;
    CSS_CLASS_HEADING1:
      begin
        AFontRecord.Color := FHeading1Color;
        if FHeading1Bold then
          Include(AFontRecord.Style, fsBold);
        if FHeading1Italics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_HEADING2:
      begin
        AFontRecord.Color := FHeading2Color;
        if FHeading2Bold then
          Include(AFontRecord.Style, fsBold);
        if FHeading2Italics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_HEADING3:
      begin
        AFontRecord.Color := FHeading3Color;
        if FHeading3Bold then
          Include(AFontRecord.Style, fsBold);
        if FHeading3Italics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_HEADING4:
      begin
        AFontRecord.Color := FHeading4Color;
        if FHeading4Bold then
          Include(AFontRecord.Style, fsBold);
        if FHeading4Italics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_HEADING5:
      begin
        AFontRecord.Color := FHeading5Color;
        if FHeading5Bold then
          Include(AFontRecord.Style, fsBold);
        if FHeading5Italics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_HEADING6:
      begin
        AFontRecord.Color := FHeading6Color;
        if FHeading6Bold then
          Include(AFontRecord.Style, fsBold);
        if FHeading6Italics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_WIKILINK:
      AFontRecord.Color := FWikilinkColor;
    CSS_CLASS_WIKILINK or (CSS_CLASS_BOLD shl 16):
      begin
        AFontRecord.Color := FWikilinkColor;
        if FBoldBold then
          Include(AFontRecord.Style, fsBold);
      end;
    CSS_CLASS_WIKILINK or (CSS_CLASS_ITALICS shl 16):
      begin
        AFontRecord.Color := FWikilinkColor;
        if FItalicsItalics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_WIKILINK or (CSS_CLASS_BOLDITALICS shl 16):
      begin
        AFontRecord.Color := FWikilinkColor;
        if FBoldBold then
          Include(AFontRecord.Style, fsBold);
        if FItalicsItalics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_EXTLINK:
      AFontRecord.Color := FExtlinkColor;
    CSS_CLASS_TEMPLATE_NAME:
      begin
        AFontRecord.Color := FTemplateColor;
        if FTemplateNameBold then
          Include(AFontRecord.Style, fsBold);
      end;
    CSS_CLASS_TEMPLATE:
      AFontRecord.Color := FTemplateColor;
    CSS_CLASS_BOLD:
      if FBoldBold then
        Include(AFontRecord.Style, fsBold);
    CSS_CLASS_ITALICS:
      if FItalicsItalics then
        Include(AFontRecord.Style, fsItalic);
    CSS_CLASS_BOLDITALICS:
      begin
        if FBoldBold then
          Include(AFontRecord.Style, fsBold);
        if FItalicsItalics then
          Include(AFontRecord.Style, fsItalic);
      end;
    CSS_CLASS_INDENT:
      AFontRecord.Color := FIndentColor;
  end;
end;

function TMediaWikiFormattingProcessor.GetCSSRules: TCSSRules;
begin
  SetLength(result, CSS_CLASS_LENGTH);
  result[CSS_CLASS_TEXT] := MakeCSSRule('text', []);
  result[CSS_CLASS_HEADING1] := MakeCSSRule('heading1',
    [MakeCSSDeclaration('color', CSSColor(FHeading1Color)),
     MakeCSSOptionalDeclaration(FHeading1Bold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FHeading1Italics, 'font-style', 'italic')]);
  result[CSS_CLASS_HEADING2] := MakeCSSRule('heading2',
    [MakeCSSDeclaration('color', CSSColor(FHeading2Color)),
     MakeCSSOptionalDeclaration(FHeading2Bold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FHeading2Italics, 'font-style', 'italic')]);
  result[CSS_CLASS_HEADING3] := MakeCSSRule('heading3',
    [MakeCSSDeclaration('color', CSSColor(FHeading3Color)),
     MakeCSSOptionalDeclaration(FHeading3Bold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FHeading3Italics, 'font-style', 'italic')]);
  result[CSS_CLASS_HEADING4] := MakeCSSRule('heading4',
    [MakeCSSDeclaration('color', CSSColor(FHeading4Color)),
     MakeCSSOptionalDeclaration(FHeading4Bold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FHeading4Italics, 'font-style', 'italic')]);
  result[CSS_CLASS_HEADING5] := MakeCSSRule('heading5',
    [MakeCSSDeclaration('color', CSSColor(FHeading5Color)),
     MakeCSSOptionalDeclaration(FHeading5Bold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FHeading5Italics, 'font-style', 'italic')]);
  result[CSS_CLASS_HEADING6] := MakeCSSRule('heading6',
    [MakeCSSDeclaration('color', CSSColor(FHeading6Color)),
     MakeCSSOptionalDeclaration(FHeading6Bold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FHeading6Italics, 'font-style', 'italic')]);
  result[CSS_CLASS_WIKILINK] := MakeCSSRule('wikilink',
    [MakeCSSDeclaration('color', CSSColor(FWikilinkColor))]);
  result[CSS_CLASS_EXTLINK] := MakeCSSRule('extlink',
    [MakeCSSDeclaration('color', CSSColor(FExtlinkColor))]);
  result[CSS_CLASS_TEMPLATE_NAME] := MakeCSSRule('template-name',
    [MakeCSSDeclaration('color', CSSColor(FTemplateColor)),
     MakeCSSOptionalDeclaration(FTemplateNameBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_TEMPLATE] := MakeCSSRule('template',
    [MakeCSSDeclaration('color', CSSColor(FTemplateColor))]);
  result[CSS_CLASS_BOLD] := MakeCSSRule('bold',
    [MakeCSSOptionalDeclaration(FBoldBold, 'font-weight', 'bold')]);
  result[CSS_CLASS_ITALICS] := MakeCSSRule('italics',
    [MakeCSSOptionalDeclaration(FItalicsItalics, 'font-style', 'italic')]);
  result[CSS_CLASS_BOLDITALICS] := MakeCSSRule('bold-italic',
    [MakeCSSOptionalDeclaration(FBoldBold, 'font-weight', 'bold'),
     MakeCSSOptionalDeclaration(FItalicsItalics, 'font-style', 'italic')]);
  result[CSS_CLASS_INDENT] := MakeCSSRule('indent',
    [MakeCSSDeclaration('color', CSSColor(FIndentColor))]);
end;

procedure TMediaWikiFormattingProcessor.SetBoldBold(const Value: boolean);
begin
  if FBoldBold <> Value then
  begin
    FBoldBold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetExtlinkColor(const Value: TColor);
begin
  if FExtlinkColor <> Value then
  begin
    FExtlinkColor := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading1Bold(const Value: boolean);
begin
  if FHeading1Bold <> Value then
  begin
    FHeading1Bold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading1Color(const Value: TColor);
begin
  if FHeading1Color <> Value then
  begin
    FHeading1Color := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading1Italics(
  const Value: boolean);
begin
  if FHeading1Italics <> Value then
  begin
    FHeading1Italics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading2Bold(const Value: boolean);
begin
  if FHeading2Bold <> Value then
  begin
    FHeading2Bold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading2Color(const Value: TColor);
begin
  if FHeading2Color <> Value then
  begin
    FHeading2Color := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading2Italics(
  const Value: boolean);
begin
  if FHeading2Italics <> Value then
  begin
    FHeading2Italics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading3Bold(const Value: boolean);
begin
  if FHeading3Bold <> Value then
  begin
    FHeading3Bold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading3Color(const Value: TColor);
begin
  if FHeading3Color <> Value then
  begin
    FHeading3Color := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading3Italics(
  const Value: boolean);
begin
  if FHeading3Italics <> Value then
  begin
    FHeading3Italics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading4Bold(const Value: boolean);
begin
  if FHeading4Bold <> Value then
  begin
    FHeading4Bold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading4Color(const Value: TColor);
begin
  if FHeading4Color <> Value then
  begin
    FHeading4Color := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading4Italics(
  const Value: boolean);
begin
  if FHeading4Italics <> Value then
  begin
    FHeading4Italics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading5Bold(const Value: boolean);
begin
  if FHeading5Bold <> Value then
  begin
    FHeading5Bold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading5Color(const Value: TColor);
begin
  if FHeading5Color <> Value then
  begin
    FHeading5Color := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading5Italics(
  const Value: boolean);
begin
  if FHeading5Italics <> Value then
  begin
    FHeading5Italics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading6Bold(const Value: boolean);
begin
  if FHeading6Bold <> Value then
  begin
    FHeading6Bold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading6Color(const Value: TColor);
begin
  if FHeading6Color <> Value then
  begin
    FHeading6Color := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetHeading6Italics(
  const Value: boolean);
begin
  if FHeading6Italics <> Value then
  begin
    FHeading6Italics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetIndentColor(const Value: TColor);
begin
  if FIndentColor <> Value then
  begin
    FIndentColor := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetItalicsItalics(const Value: boolean);
begin
  if FItalicsItalics <> Value then
  begin
    FItalicsItalics := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetTemplateColor(const Value: TColor);
begin
  if FTemplateColor <> Value then
  begin
    FTemplateColor := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetTemplateNameBold(
  const Value: boolean);
begin
  if FTemplateNameBold <> Value then
  begin
    FTemplateNameBold := Value;
    Changed;
  end;
end;

procedure TMediaWikiFormattingProcessor.SetWikilinkColor(const Value: TColor);
begin
  if FWikilinkColor <> Value then
  begin
    FWikilinkColor := Value;
    Changed;
  end;
end;

{ TPrintSettings }

procedure TPrintSettings.Assign(Source: TPersistent);
begin
  if Source is TPrintSettings then
  begin
    FVerticalMargin := TPrintSettings(Source).VerticalMargin;
    FHorizontalMargin := TPrintSettings(Source).HorizontalMargin;
    FWordWrap := TPrintSettings(Source).WordWrap;
    FNiceWordWrap := TPrintSettings(Source).NiceWordWrap;
    FWordWrapChar := TPrintSettings(Source).WordWrapIcon;
    FShowWordWrapIcon := TPrintSettings(Source).ShowWordWrapIcon;
    FWordWrapIconColor := TPrintSettings(Source).WordWrapIconColor;
  end
  else
    inherited;
end;

constructor TPrintSettings.Create;
begin
  FVerticalMargin := DEFAULT_VERTICAL_MARGIN;
  FHorizontalMargin := DEFAULT_HORIZONTAL_MARGIN;
  FWordWrap := DEFAULT_WORD_WRAP;
  FNiceWordWrap := DEFAULT_NICE_WORD_WRAP;
  FWordWrapChar := DEFAULT_WORD_WRAP_CHAR;
  FShowWordWrapIcon := DEFAULT_SHOW_WORD_WRAP_ICON;
  FWordWrapIconColor := DEFAULT_WORD_WRAP_ICON_COLOR;
end;

{ TEditorState }

constructor TEditorState.Create;
begin
  FRulerVisible := true;
  FZoomLevel := 100;
end;

destructor TEditorState.Destroy;
begin
  if Assigned(FFPCache) then
  begin
    FreeMem(FFPCache);
    FFPCache := nil;
  end;
  inherited;
end;

function EnumFontFamExProc(LF: PLogFont; TM: PTextMetric; FontType: DWORD;
  lParam: LPARAM): integer; stdcall;
begin
  if ((LF.lfPitchAndFamily and 3) = FIXED_PITCH) and (LF.lfFaceName[0] <> '@') then
    if FixedWidthFonts.IndexOf(LF.lfFaceName) = -1 then
      FixedWidthFonts.Add(LF.lfFaceName);

  result := 1;
end;

var
  LF: TLogFont;

{ TTextEditorDataObject }

class constructor TTextEditorDataObject.ClassCreate;
begin
  Formats := [FORMATETC_UNICODETEXT];
end;

constructor TTextEditorDataObject.Create(AEditor: TTextEditor);
begin
  FTextEditor := AEditor;
  FBuffer := FTextEditor.SelText;
end;

class function TTextEditorDataObject.CreateHGlobal(Data: pointer; Len: UInt64;
  uFlags: DWORD; out hGlobal: HGLOBAL): HRESULT;
var
  p: pointer;
begin
  hGlobal := GlobalAlloc(uFlags, Len);
  if hGlobal <> 0 then
  begin
    p := GlobalLock(hGlobal);
    if Assigned(p) then
    begin
      CopyMemory(p, Data, Len);
      GlobalUnlock(hGlobal);
    end
    else
    begin
      GlobalFree(hGlobal);
      hGlobal := 0;
    end;
  end;
  result := IfThen(hGlobal <> 0, S_OK, E_OUTOFMEMORY);
end;

function TTextEditorDataObject.DAdvise(const formatetc: tagFORMATETC;
  advf: Integer; const advSink: IAdviseSink;
  out dwConnection: Integer): HRESULT;
begin
  result := OLE_E_ADVISENOTSUPPORTED;
end;

function TTextEditorDataObject.DUnadvise(dwConnection: Integer): HRESULT;
begin
  result := OLE_E_ADVISENOTSUPPORTED;
end;

function TTextEditorDataObject.EnumDAdvise(
  out enumAdvise: IEnumSTATDATA): HRESULT;
begin
  result := OLE_E_ADVISENOTSUPPORTED;
end;

function TTextEditorDataObject.EnumFormatEtc(dwDirection: Integer;
  out enumFormatEtc: IEnumFORMATETC): HRESULT;
begin
  if dwDirection = DATADIR_GET then
  begin
    enumFormatEtc := TEnumFormatEtc.Create;
    result := S_OK;
  end
  else
  begin
    enumFormatEtc := nil;
    result := E_NOTIMPL;
  end;
end;

function TTextEditorDataObject.GetCanonicalFormatEtc(
  const formatetc: tagFORMATETC; out formatetcOut: tagFORMATETC): HRESULT;
begin
  formatetcOut := formatetc;
  formatetcOut.ptd := nil;
  result := DATA_S_SAMEFORMATETC;
end;

function TTextEditorDataObject.GetData(const formatetcIn: tagFORMATETC;
  out medium: tagSTGMEDIUM): HRESULT;
const
  nullchr: char = #0;
begin

  FillChar(medium, sizeof(medium), 0);

  case GetMatchingFormatIdx(formatetcIn) of
    FMT_UNICODETEXT:
      begin
        medium.tymed := TYMED_HGLOBAL;
        if FBuffer.IsEmpty then
          result := CreateHGlobal(@nullchr, sizeof(nullchr),
            GMEM_MOVEABLE, medium.hGlobal)
        else
          result := CreateHGlobal(PChar(FBuffer), (FBuffer.Length + 1) * sizeof(char),
            GMEM_MOVEABLE, medium.hGlobal);
      end;
  else
    result := DV_E_FORMATETC;
  end;

end;

function TTextEditorDataObject.GetDataHere(const formatetc: tagFORMATETC;
  out medium: tagSTGMEDIUM): HRESULT;
begin
  result := E_NOTIMPL;
end;

function TTextEditorDataObject.GetMatchingFormatIdx(
  const AFormatEtc: TFormatEtc): integer;
var
  i: integer;
begin

  for i := 0 to high(Formats) do
    if
      (Formats[i].cfFormat = AFormatEtc.cfFormat)
      and
      ((Formats[i].tymed and AFormatEtc.tymed) <> 0)
      and
      (Formats[i].dwAspect = AFormatEtc.dwAspect)
      and
      (Formats[i].lindex = AFormatEtc.lindex)
    then
      Exit(i);

  result := -1;

end;

function TTextEditorDataObject.QueryGetData(
  const formatetc: tagFORMATETC): HRESULT;
begin
  result := IfThen(GetMatchingFormatIdx(formatetc) <> -1, S_OK, S_FALSE);
end;

function TTextEditorDataObject.SetData(const formatetc: tagFORMATETC;
  var medium: tagSTGMEDIUM; fRelease: LongBool): HRESULT;
begin
  result := E_NOTIMPL;
end;

{ TTextFile.TFixedString }

class operator TTextFile.TFixedString.Implicit(const S: TFixedString): string;
begin
  result := string(S.Data);
end;

class operator TTextFile.TFixedString.Implicit(const S: string): TFixedString;
begin
  if S.Length > MAXLEN then
    raise Exception.Create('String too long for fixed string.');
  FillChar(result, sizeof(result), 0);
  if not S.IsEmpty then
    Move(S[1], result.Data[0], S.Length * sizeof(char));
end;

{ TTextEditorDataObject.TEnumFormatEtc }

function TTextEditorDataObject.TEnumFormatEtc.Clone(
  out Enum: IEnumFormatEtc): HResult;
begin
  try
    Enum := TEnumFormatEtc.Create;
    TEnumFormatEtc(Enum).FIndex := Self.FIndex;
    result := S_OK;
  except
    result := E_UNEXPECTED;
  end;
end;

function TTextEditorDataObject.TEnumFormatEtc.Next(celt: Longint; out elt;
  pceltFetched: PLongint): HResult;
var
  count: integer;
  p: PFormatEtc;
begin

  if (celt <= 0) or ((celt > 1) and (pceltFetched = nil)) then
    Exit(E_INVALIDARG);

  count := 0;
  p := @elt;
  while (FIndex <= high(Formats)) and (count < celt) do
  begin
    p^ := Formats[FIndex];
    inc(p);
    inc(count);
    inc(FIndex);
  end;

  if Assigned(pceltFetched) then
    pceltFetched^ := count;

  result := IfThen(count = celt, S_OK, S_FALSE);

end;

function TTextEditorDataObject.TEnumFormatEtc.Reset: HResult;
begin
  FIndex := 0;
  Result := S_OK;
end;

function TTextEditorDataObject.TEnumFormatEtc.Skip(celt: Longint): HResult;
begin
  if FIndex + celt <= high(Formats) then
  begin
    inc(FIndex, celt);
    result := S_OK;
  end
  else
    result := S_FALSE;
end;

{ TFileStatistics }

procedure TFileStatistics.Clear;
begin
  Flags := [];
  NumLines := 0;
  NumChars := 0;
  NumLetters := 0;
  NumDigits := 0;
  NumWhitespace := 0;
  NumPunctuation := 0;
  MaxLineLength := 0;
  AvgLineLength := 0;
  LineLengthDistr := nil;
  NumWords := 0;
  MaxWordLength := 0;
  AvgWordLength := 0;
  WordLengthDistr := nil;
end;

{ TWordFreqItem }

constructor TWordFreqItem.Create(AInNaturalCase: string; AIsLower: Boolean;
  ACount: Int64);
begin
  Self.InNaturalCase := AInNaturalCase;
  Self.Count := ACount;
  Self.IsLower := AIsLower;
end;

initialization
  FixedWidthFonts := TStringList.Create;
  FixedWidthFonts.BeginUpdate;
  LF.lfCharSet := DEFAULT_CHARSET;
  LF.lfFaceName := '';
  LF.lfPitchAndFamily := 0;
  with TBitmap.Create do
    try
      EnumFontFamiliesEx(Canvas.Handle, LF, @EnumFontFamExProc, 0, 0);
    finally
      Free;
    end;
  FixedWidthFonts.EndUpdate;

finalization
  FixedWidthFonts.Free;

end.