[anjuta-extras] Update to scintilla 3.7.5



commit 949ce76f4b6464abf4b170a34006f20e7d2e171b
Author: Sébastien Granjoux <seb sfo free fr>
Date:   Sun Jun 4 21:37:24 2017 +0200

    Update to scintilla 3.7.5

 plugins/scintilla/aneditor-priv.h                  |    1 +
 plugins/scintilla/print.c                          |    1 +
 plugins/scintilla/properties/styles.properties     | 1854 +++++-
 plugins/scintilla/scintilla/Makefile.am            |    7 +
 plugins/scintilla/scintilla/gtk/Converter.h        |   44 +-
 plugins/scintilla/scintilla/gtk/PlatGTK.cxx        | 1025 ++--
 plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx   | 1462 +++--
 plugins/scintilla/scintilla/gtk/ScintillaGTK.h     |  289 +
 .../scintilla/gtk/ScintillaGTKAccessible.cxx       | 1263 ++++
 .../scintilla/gtk/ScintillaGTKAccessible.h         |  196 +
 .../scintilla/scintilla/gtk/scintilla-marshal.list |    3 +-
 plugins/scintilla/scintilla/include/ILexer.h       |   50 +-
 plugins/scintilla/scintilla/include/Platform.h     |   79 +-
 plugins/scintilla/scintilla/include/SciLexer.h     |  231 +-
 plugins/scintilla/scintilla/include/Sci_Position.h |   21 +
 plugins/scintilla/scintilla/include/Scintilla.h    |  236 +-
 .../scintilla/scintilla/include/Scintilla.iface    |  914 +++-
 .../scintilla/scintilla/include/ScintillaWidget.h  |   35 +-
 plugins/scintilla/scintilla/lexers.make            |   34 +-
 plugins/scintilla/scintilla/lexers/LexA68k.cxx     |  180 +-
 plugins/scintilla/scintilla/lexers/LexAPDL.cxx     |   10 +-
 plugins/scintilla/scintilla/lexers/LexASY.cxx      |   20 +-
 plugins/scintilla/scintilla/lexers/LexAU3.cxx      |   36 +-
 plugins/scintilla/scintilla/lexers/LexAVE.cxx      |   18 +-
 plugins/scintilla/scintilla/lexers/LexAVS.cxx      |   18 +-
 plugins/scintilla/scintilla/lexers/LexAbaqus.cxx   |   77 +-
 plugins/scintilla/scintilla/lexers/LexAda.cxx      |   12 +-
 plugins/scintilla/scintilla/lexers/LexAsm.cxx      |   55 +-
 plugins/scintilla/scintilla/lexers/LexAsn1.cxx     |    4 +-
 plugins/scintilla/scintilla/lexers/LexBaan.cxx     |  932 +++-
 plugins/scintilla/scintilla/lexers/LexBash.cxx     |  167 +-
 plugins/scintilla/scintilla/lexers/LexBasic.cxx    |  130 +-
 plugins/scintilla/scintilla/lexers/LexBatch.cxx    |  500 ++
 plugins/scintilla/scintilla/lexers/LexBibTeX.cxx   |  310 +
 plugins/scintilla/scintilla/lexers/LexBullant.cxx  |   14 +-
 plugins/scintilla/scintilla/lexers/LexCLW.cxx      |   26 +-
 plugins/scintilla/scintilla/lexers/LexCOBOL.cxx    |   38 +-
 plugins/scintilla/scintilla/lexers/LexCPP.cxx      |  721 ++-
 plugins/scintilla/scintilla/lexers/LexCSS.cxx      |   24 +-
 plugins/scintilla/scintilla/lexers/LexCaml.cxx     |   27 +-
 plugins/scintilla/scintilla/lexers/LexCmake.cxx    |   48 +-
 .../scintilla/scintilla/lexers/LexCoffeeScript.cxx |  381 +-
 plugins/scintilla/scintilla/lexers/LexConf.cxx     |   22 +-
 plugins/scintilla/scintilla/lexers/LexCrontab.cxx  |   18 +-
 plugins/scintilla/scintilla/lexers/LexCsound.cxx   |   12 +-
 plugins/scintilla/scintilla/lexers/LexD.cxx        |   48 +-
 plugins/scintilla/scintilla/lexers/LexDMAP.cxx     |  228 +
 plugins/scintilla/scintilla/lexers/LexDMIS.cxx     |  355 ++
 plugins/scintilla/scintilla/lexers/LexDiff.cxx     |  155 +
 plugins/scintilla/scintilla/lexers/LexECL.cxx      |   34 +-
 plugins/scintilla/scintilla/lexers/LexEDIFACT.cxx  |  319 +
 plugins/scintilla/scintilla/lexers/LexEScript.cxx  |   16 +-
 plugins/scintilla/scintilla/lexers/LexEiffel.cxx   |   24 +-
 plugins/scintilla/scintilla/lexers/LexErlang.cxx   |   14 +-
 .../scintilla/scintilla/lexers/LexErrorList.cxx    |  395 ++
 plugins/scintilla/scintilla/lexers/LexFlagship.cxx |   14 +-
 plugins/scintilla/scintilla/lexers/LexForth.cxx    |   29 +-
 plugins/scintilla/scintilla/lexers/LexFortran.cxx  |  497 ++-
 plugins/scintilla/scintilla/lexers/LexGAP.cxx      |   18 +-
 plugins/scintilla/scintilla/lexers/LexGui4Cli.cxx  |   25 +-
 plugins/scintilla/scintilla/lexers/LexHTML.cxx     |  176 +-
 plugins/scintilla/scintilla/lexers/LexHaskell.cxx  |   66 +-
 plugins/scintilla/scintilla/lexers/LexHex.cxx      | 1045 ++++
 plugins/scintilla/scintilla/lexers/LexIndent.cxx   |   73 +
 plugins/scintilla/scintilla/lexers/LexInno.cxx     |   30 +-
 plugins/scintilla/scintilla/lexers/LexJSON.cxx     |  499 ++
 plugins/scintilla/scintilla/lexers/LexKVIrc.cxx    |  473 ++
 plugins/scintilla/scintilla/lexers/LexKix.cxx      |    9 +-
 plugins/scintilla/scintilla/lexers/LexLaTeX.cxx    |   91 +-
 plugins/scintilla/scintilla/lexers/LexLisp.cxx     |   24 +-
 plugins/scintilla/scintilla/lexers/LexLout.cxx     |   14 +-
 plugins/scintilla/scintilla/lexers/LexLua.cxx      |   60 +-
 plugins/scintilla/scintilla/lexers/LexMMIXAL.cxx   |    4 +-
 plugins/scintilla/scintilla/lexers/LexMPT.cxx      |   14 +-
 plugins/scintilla/scintilla/lexers/LexMSSQL.cxx    |   41 +-
 plugins/scintilla/scintilla/lexers/LexMagik.cxx    |   14 +-
 plugins/scintilla/scintilla/lexers/LexMake.cxx     |  144 +
 plugins/scintilla/scintilla/lexers/LexMarkdown.cxx |   36 +-
 plugins/scintilla/scintilla/lexers/LexMatlab.cxx   |  182 +-
 plugins/scintilla/scintilla/lexers/LexMetapost.cxx |   24 +-
 plugins/scintilla/scintilla/lexers/LexModula.cxx   |   32 +-
 plugins/scintilla/scintilla/lexers/LexMySQL.cxx    |   46 +-
 plugins/scintilla/scintilla/lexers/LexNimrod.cxx   |   42 +-
 plugins/scintilla/scintilla/lexers/LexNsis.cxx     |   42 +-
 plugins/scintilla/scintilla/lexers/LexNull.cxx     |   40 +
 plugins/scintilla/scintilla/lexers/LexOScript.cxx  |   40 +-
 plugins/scintilla/scintilla/lexers/LexOpal.cxx     |   38 +-
 plugins/scintilla/scintilla/lexers/LexOthers.cxx   | 1141 ----
 plugins/scintilla/scintilla/lexers/LexPB.cxx       |   16 +-
 plugins/scintilla/scintilla/lexers/LexPLM.cxx      |   30 +-
 plugins/scintilla/scintilla/lexers/LexPO.cxx       |   52 +-
 plugins/scintilla/scintilla/lexers/LexPOV.cxx      |   18 +-
 plugins/scintilla/scintilla/lexers/LexPS.cxx       |   45 +-
 plugins/scintilla/scintilla/lexers/LexPascal.cxx   |   75 +-
 plugins/scintilla/scintilla/lexers/LexPerl.cxx     |  276 +-
 plugins/scintilla/scintilla/lexers/LexPowerPro.cxx |   34 +-
 .../scintilla/scintilla/lexers/LexPowerShell.cxx   |   30 +-
 plugins/scintilla/scintilla/lexers/LexProgress.cxx |  759 ++-
 plugins/scintilla/scintilla/lexers/LexProps.cxx    |  189 +
 plugins/scintilla/scintilla/lexers/LexPython.cxx   |  678 ++-
 plugins/scintilla/scintilla/lexers/LexR.cxx        |   12 +-
 plugins/scintilla/scintilla/lexers/LexRebol.cxx    |   12 +-
 plugins/scintilla/scintilla/lexers/LexRegistry.cxx |  416 ++
 plugins/scintilla/scintilla/lexers/LexRuby.cxx     |  970 ++--
 plugins/scintilla/scintilla/lexers/LexRust.cxx     |  838 +++
 plugins/scintilla/scintilla/lexers/LexSML.cxx      |   17 +-
 plugins/scintilla/scintilla/lexers/LexSQL.cxx      |  253 +-
 plugins/scintilla/scintilla/lexers/LexSTTXT.cxx    |   51 +-
 plugins/scintilla/scintilla/lexers/LexScriptol.cxx |   62 +-
 .../scintilla/scintilla/lexers/LexSmalltalk.cxx    |    2 +-
 plugins/scintilla/scintilla/lexers/LexSorcus.cxx   |    2 +-
 plugins/scintilla/scintilla/lexers/LexSpecman.cxx  |   16 +-
 plugins/scintilla/scintilla/lexers/LexSpice.cxx    |   35 +-
 plugins/scintilla/scintilla/lexers/LexTACL.cxx     |   34 +-
 plugins/scintilla/scintilla/lexers/LexTADS3.cxx    |   22 +-
 plugins/scintilla/scintilla/lexers/LexTAL.cxx      |   34 +-
 plugins/scintilla/scintilla/lexers/LexTCL.cxx      |  369 +-
 plugins/scintilla/scintilla/lexers/LexTCMD.cxx     |   45 +-
 plugins/scintilla/scintilla/lexers/LexTeX.cxx      |   34 +-
 plugins/scintilla/scintilla/lexers/LexTxt2tags.cxx |   30 +-
 plugins/scintilla/scintilla/lexers/LexVB.cxx       |   16 +-
 plugins/scintilla/scintilla/lexers/LexVHDL.cxx     |  192 +-
 plugins/scintilla/scintilla/lexers/LexVerilog.cxx  | 1093 +++-
 .../scintilla/scintilla/lexers/LexVisualProlog.cxx |  269 +-
 plugins/scintilla/scintilla/lexers/LexYAML.cxx     |  120 +-
 plugins/scintilla/scintilla/lexlib/Accessor.cxx    |   22 +-
 plugins/scintilla/scintilla/lexlib/Accessor.h      |    6 +-
 .../scintilla/lexlib/CharacterCategory.cxx         |  776 ++-
 .../scintilla/scintilla/lexlib/CharacterCategory.h |    6 +
 .../scintilla/scintilla/lexlib/CharacterSet.cxx    |   15 +-
 plugins/scintilla/scintilla/lexlib/CharacterSet.h  |   20 +-
 plugins/scintilla/scintilla/lexlib/LexAccessor.h   |   84 +-
 plugins/scintilla/scintilla/lexlib/LexerBase.cxx   |   13 +-
 plugins/scintilla/scintilla/lexlib/LexerBase.h     |    8 +-
 plugins/scintilla/scintilla/lexlib/LexerModule.cxx |   30 +-
 plugins/scintilla/scintilla/lexlib/LexerModule.h   |   22 +-
 .../scintilla/lexlib/LexerNoExceptions.cxx         |   20 +-
 .../scintilla/scintilla/lexlib/LexerNoExceptions.h |   16 +-
 plugins/scintilla/scintilla/lexlib/LexerSimple.cxx |   12 +-
 plugins/scintilla/scintilla/lexlib/LexerSimple.h   |    6 +-
 .../scintilla/scintilla/lexlib/PropSetSimple.cxx   |   14 +-
 plugins/scintilla/scintilla/lexlib/SparseState.h   |    2 +-
 plugins/scintilla/scintilla/lexlib/StringCopy.h    |   36 +
 .../scintilla/scintilla/lexlib/StyleContext.cxx    |   45 +-
 plugins/scintilla/scintilla/lexlib/StyleContext.h  |   94 +-
 plugins/scintilla/scintilla/lexlib/SubStyles.h     |   28 +-
 plugins/scintilla/scintilla/lexlib/WordList.cxx    |  141 +-
 plugins/scintilla/scintilla/lexlib/WordList.h      |    3 +-
 plugins/scintilla/scintilla/src/AutoComplete.cxx   |   50 +-
 plugins/scintilla/scintilla/src/AutoComplete.h     |   14 +-
 plugins/scintilla/scintilla/src/CallTip.cxx        |  106 +-
 plugins/scintilla/scintilla/src/CallTip.h          |   12 +-
 plugins/scintilla/scintilla/src/CaseConvert.cxx    |  500 ++-
 plugins/scintilla/scintilla/src/CaseConvert.h      |    3 +
 plugins/scintilla/scintilla/src/CaseFolder.cxx     |    3 +-
 plugins/scintilla/scintilla/src/CaseFolder.h       |    4 +-
 plugins/scintilla/scintilla/src/Catalogue.cxx      |   46 +-
 plugins/scintilla/scintilla/src/CellBuffer.cxx     |  254 +-
 plugins/scintilla/scintilla/src/CellBuffer.h       |  124 +-
 plugins/scintilla/scintilla/src/CharClassify.cxx   |   13 +-
 plugins/scintilla/scintilla/src/CharClassify.h     |    2 +-
 .../scintilla/scintilla/src/ContractionState.cxx   |  134 +-
 plugins/scintilla/scintilla/src/ContractionState.h |   54 +-
 plugins/scintilla/scintilla/src/Decoration.cxx     |  146 +-
 plugins/scintilla/scintilla/src/Decoration.h       |   29 +-
 plugins/scintilla/scintilla/src/Document.cxx       | 1912 +++++--
 plugins/scintilla/scintilla/src/Document.h         |  365 +-
 plugins/scintilla/scintilla/src/EditModel.cxx      |   79 +
 plugins/scintilla/scintilla/src/EditModel.h        |   70 +
 plugins/scintilla/scintilla/src/EditView.cxx       | 2371 ++++++++
 plugins/scintilla/scintilla/src/EditView.h         |  184 +
 plugins/scintilla/scintilla/src/Editor.cxx         | 6340 ++++++++------------
 plugins/scintilla/scintilla/src/Editor.h           |  440 +-
 plugins/scintilla/scintilla/src/ExternalLexer.cxx  |  110 +-
 plugins/scintilla/scintilla/src/ExternalLexer.h    |   36 +-
 plugins/scintilla/scintilla/src/FontQuality.h      |   16 +
 plugins/scintilla/scintilla/src/Indicator.cxx      |  163 +-
 plugins/scintilla/scintilla/src/Indicator.h        |   35 +-
 plugins/scintilla/scintilla/src/KeyMap.cxx         |   24 +-
 plugins/scintilla/scintilla/src/KeyMap.h           |   23 +-
 plugins/scintilla/scintilla/src/LineMarker.cxx     |  323 +-
 plugins/scintilla/scintilla/src/LineMarker.h       |   33 +-
 plugins/scintilla/scintilla/src/MarginView.cxx     |  470 ++
 plugins/scintilla/scintilla/src/MarginView.h       |   50 +
 plugins/scintilla/scintilla/src/Partitioning.h     |   36 +-
 plugins/scintilla/scintilla/src/PerLine.cxx        |  315 +-
 plugins/scintilla/scintilla/src/PerLine.h          |  117 +-
 plugins/scintilla/scintilla/src/Position.h         |   30 +
 plugins/scintilla/scintilla/src/PositionCache.cxx  |  385 +-
 plugins/scintilla/scintilla/src/PositionCache.h    |  142 +-
 plugins/scintilla/scintilla/src/RESearch.cxx       |  107 +-
 plugins/scintilla/scintilla/src/RESearch.h         |   24 +-
 plugins/scintilla/scintilla/src/RunStyles.cxx      |   39 +-
 plugins/scintilla/scintilla/src/RunStyles.h        |    9 +-
 plugins/scintilla/scintilla/src/ScintillaBase.cxx  |  274 +-
 plugins/scintilla/scintilla/src/ScintillaBase.h    |   37 +-
 plugins/scintilla/scintilla/src/Selection.cxx      |  130 +-
 plugins/scintilla/scintilla/src/Selection.h        |   54 +-
 plugins/scintilla/scintilla/src/SparseVector.h     |  158 +
 plugins/scintilla/scintilla/src/SplitVector.h      |  168 +-
 plugins/scintilla/scintilla/src/Style.cxx          |   10 +-
 plugins/scintilla/scintilla/src/Style.h            |    9 +-
 plugins/scintilla/scintilla/src/UniConversion.cxx  |  130 +-
 plugins/scintilla/scintilla/src/UniConversion.h    |   40 +-
 plugins/scintilla/scintilla/src/UnicodeFromUTF8.h  |   13 +
 plugins/scintilla/scintilla/src/UniqueString.h     |   34 +
 plugins/scintilla/scintilla/src/ViewStyle.cxx      |  449 +-
 plugins/scintilla/scintilla/src/ViewStyle.h        |  133 +-
 plugins/scintilla/scintilla/src/XPM.cxx            |   61 +-
 plugins/scintilla/scintilla/src/XPM.h              |   21 +-
 plugins/scintilla/text-editor-iterable.c           |    1 +
 plugins/scintilla/text_editor.c                    |    1 +
 plugins/scintilla/text_editor_cbs.c                |    1 +
 plugins/scintilla/text_editor_prefs.c              |    1 +
 214 files changed, 30504 insertions(+), 13684 deletions(-)
---
diff --git a/plugins/scintilla/aneditor-priv.h b/plugins/scintilla/aneditor-priv.h
index c22536e..4637943 100644
--- a/plugins/scintilla/aneditor-priv.h
+++ b/plugins/scintilla/aneditor-priv.h
@@ -38,6 +38,7 @@
 #include <gtk/gtk.h>
 
 #define GTK
+#define INCLUDE_DEPRECATED_FEATURES
 #include "Platform.h"
 #include "PropSet.h"
 #include "Scintilla.h"
diff --git a/plugins/scintilla/print.c b/plugins/scintilla/print.c
index ba4c260..93a845a 100644
--- a/plugins/scintilla/print.c
+++ b/plugins/scintilla/print.c
@@ -39,6 +39,7 @@
 #undef PLAT_GTK
 #define PLAT_GTK 1
 
+#define INCLUDE_DEPRECATED_FEATURES
 #include "Scintilla.h"
 #include "ScintillaWidget.h"
 #include "print.h"
diff --git a/plugins/scintilla/properties/styles.properties b/plugins/scintilla/properties/styles.properties
index 3e5331f..c9a656f 100644
--- a/plugins/scintilla/properties/styles.properties
+++ b/plugins/scintilla/properties/styles.properties
@@ -19,6 +19,8 @@
 file.patterns.abaqus=*.inp;*.dat;*.msg
 filter.abaqus=ABAQUS input (inp)|$(file.patterns.abaqus)|
 
+*filter.abaqus=$(filter.abaqus)
+
 #lexer.$(file.patterns.abaqus)=abaqus
 lexer.$(file.patterns.abaqus)=abaqus
 
@@ -74,10 +76,16 @@ calltip.abaqus.ignorecase=1
 
 filter.ada=Ada (ads adb)|*.ads;*.adb|
 
+*filter.ada=$(filter.ada)
+
 file.patterns.ada=*.ads;*.adb
 
+*source.patterns.ada=$(file.patterns.ada);
+
 lexer.$(file.patterns.ada)=ada
 
+*language.ada=Ada|ads||
+
 #indent.size.$(file.patterns.ada)=3
 #use.tabs.$(file.patterns.ada)=0
 
@@ -101,7 +109,7 @@ comment.block.ada=--~
 
 braces.ada.style=4
 
-statement.indent.$(file.patterns.ada)=5 begin declare else elsif exception for if is loop while
+statement.indent.$(file.patterns.ada)=1 begin declare else elsif exception for if is loop while
 statement.lookback.$(file.patterns.ada)=20
 block.start.$(file.patterns.ada)=10 then is
 block.end.$(file.patterns.ada)=10 end
@@ -129,10 +137,19 @@ command.go.*.adb=$(FileName)
 
 # Nasm files
 file.patterns.asm=*.asm
-filter.asm=Assembler x86/x64(asm)|$(file.patterns.asm)|
+#file.patterns.as=*.s
+
+*source.patterns.asm=$(file.patterns.asm);
+
+filter.asm=Assembler x86/x64 (asm)|$(file.patterns.asm)|
+filter.as=Assembler x86/x64 (as)|$(file.patterns.as)|
+
+*filter.asm=$(filter.asm)
 
 lexer.$(file.patterns.asm)=asm
+lexer.$(file.patterns.as)=as
 
+*language.assembler=Assembler|asm||
 
 bcd_instruction=aaa aad aam aas daa das
 flow_instruction=ja jae jb jbe jc jcxz je jg jge jl jle jmp jna \
@@ -520,7 +537,15 @@ keywords4.$(file.patterns.asm)=$(directive_nasm)
 keywords5.$(file.patterns.asm)=$(directive_operand_nasm)
 keywords6.$(file.patterns.asm)=$(mmx_instruction) $(mmx2_instruction) $(emmx_instruction) $(k3d_instruction) 
$(k3d2_instruction) $(k3dgeode_instruction) $(k3dprefetch_instruction) $(sse_instruction) $(sse2_instruction) 
$(sse3_instruction) $(ssse3_instruction) $(sse4a_instruction) $(sse41_instruction) $(sse42_instruction) 
$(aes_instruction) $(padlock_instruction) $(avx_instruction) $(avx2_instruction) $(xop_instruction) 
$(cvt16_instruction) $(fma4_instruction) $(fma3_instruction)
 
+keywords.$(file.patterns.as)=$(bcd_instruction) $(flow_instruction) $(alu_instruction) $(mem_instruction) 
$(stack_instruction) $(pred_instruction) $(flag_instruction) $(cmov_instruction) $(prefix_instruction) 
$(string_instruction) $(info_instruction) $(lwp_instruction) $(ext_instruction) $(bmi1_instruction) 
$(bmi2_instruction)
+keywords2.$(file.patterns.as)=$(fpu_instruction)
+keywords3.$(file.patterns.as)=$(register) $(register_64)
+keywords4.$(file.patterns.as)=$(directive_nasm)
+keywords5.$(file.patterns.as)=$(directive_operand_nasm)
+keywords6.$(file.patterns.as)=$(mmx_instruction) $(mmx2_instruction) $(emmx_instruction) $(k3d_instruction) 
$(k3d2_instruction) $(k3dgeode_instruction) $(k3dprefetch_instruction) $(sse_instruction) $(sse2_instruction) 
$(sse3_instruction) $(ssse3_instruction) $(sse4a_instruction) $(sse41_instruction) $(sse42_instruction) 
$(aes_instruction) $(padlock_instruction) $(avx_instruction) $(avx2_instruction) $(xop_instruction) 
$(cvt16_instruction) $(fma4_instruction) $(fma3_instruction)
+
 comment.block.asm=;
+comment.block.as=#
 
 
 # Assembler Styles
@@ -535,6 +560,7 @@ command.0.*.asm=link $(FileName)
 
 
 statement.indent.$(file.patterns.asm)=9 .if
+statement.indent.$(file.patterns.as)=9 .if
 
 
 
@@ -544,10 +570,14 @@ statement.indent.$(file.patterns.asm)=9 .if
 
 filter.asn1=ASN.1 (asn1)|*.mib|
 
+*filter.asn1=$(filter.asn1)
+
 file.patterns.asn1=*.mib
 
 lexer.$(file.patterns.asn1)=asn1
 
+*language.asn=ASN.1|mib||
+
 # ASN.1 styles
 
 # Keywords
@@ -618,135 +648,192 @@ UInteger32 UNITS Unsigned32
 
 ###############################################################################
 # From au3.properties
-# SciTE settings for AutoIt v3
+# Define SciTE settings for AutoIt files.
 #
-# May, 17  2004 - jos van der Zande  (jvdzande yahoo com)
-# Contains keywords/functions/macros for build 101 & beta 102
-#
-# *** Specify here your AutoIt program directory  ***
-autoit3dir=C:\program files\autoit3
+# SciTE settings for AutoIt 3.3.14.2
 
+# File filters, patterns, language, lexer and source
 file.patterns.au3=*.au3
-filter.au3=AutoIt (au3)|*.au3|
+filter.au3=AutoIt (au3)|$(file.patterns.au3)|
 lexer.$(file.patterns.au3)=au3
 
-# Commands to compile / run your script
-command.compile.*.au3=$(autoit3dir)\aut2exe\aut2exe.exe /in "$(FilePath)"
-command.build.*.au3=$(autoit3dir)\aut2exe\aut2exe.exe /in "$(FilePath)"
-command.go.*.au3=$(autoit3dir)\autoit3.exe "$(FilePath)"
-# Tidy is a formatting program for Autoit 3 and can be downloaded from
-#      http://www.hiddensoft.com/fileman/users/jdeb/install_tidy.exe
-command.9.*.au3=tidy\tidy.exe "$(FilePath)"
-command.name.9.*.au3=Tidy AutoIt Source
-command.save.before.9.*.au3=1
-command.shortcut.9.*=Ctrl+9
-# Standard LUA Functions
-extension.*.au3=$(SciteDefaultHome)\AutoIt3.lua
-command.name.11.*.au3=MsgBox(4096,'debug',...)
-command.subsystem.11.*.au3=3
-command.11.*.au3=Debug_MsgBox
-command.shortcut.11.*.au3=Ctrl+Shift+D
-command.save.before.11.*.au3=2
-
-command.name.12.*.au3=Insert Bookmarked Line(s)
-command.subsystem.12.*.au3=3
-command.12.*.au3=Copy_BookMarks
-command.shortcut.12.*.au3=Ctrl+Shift+B
-command.save.before.12.*.au3=2
-
-# Commands to for Help F1
-command.help.*.au3=$(CurrentWord)!$(autoit3dir)\autoit.chm
-command.help.subsystem.*.au3=4
-# Autocomplete and call tip settings
-api.*.au3=$(SciteDefaultHome)\api\au3.api
-calltip.au3.word.characters=$(chars.alpha)$(chars.numeric)
-calltip.au3.ignorecase=1
+*filter.au3=$(filter.au3)
+*language.au3=AutoIt|au3||
+*source.patterns.au3=$(file.patterns.au3);
+
+# Autocomplete and CallTip
 autocomplete.au3.ignorecase=1
-autocomplete.au3.start.characters=$(chars.alpha)$(chars.numeric)$@
-word.characters.*.au3=$(chars.alpha)$(chars.numeric)@$_
-# auto indent stuff
-indent.size.*.au3=3
-statement.indent.*.au3=
-statement.lookback.*.au3=
-block.start.*.au3=5 case if do for func else elseif while select \
-                    Case If Do For Func Else ElseIf While Select \
-                    CASE IF DO FOR FUNC ELSE ELSEIF WHILE SELECT
-block.end.*.au3=5 case else endif elseif endfunc endselect next until wend \
-                  Case Else EndIf ElseIf EndFunc EndSelect Next Until Wend \
-                  CASE ELSE ENDIF ELSEIF ENDFUNC ENDSELECT NEXT UNTIL WEND
-#Comments functions definition
+autocomplete.au3.start.characters=$(chars.alpha)$(chars.numeric)_@#$
+calltip.au3.end.definition=)
+calltip.au3.ignorecase=1
+calltip.au3.use.escapes=1
+calltip.au3.word.characters=$(chars.alpha)$(chars.numeric)_.
+word.characters.$(file.patterns.au3)=$(chars.alpha)$(chars.numeric)$(chars.accented)_@#$.
+
+# Indentation
+indent.size.$(file.patterns.au3)=4
+tab.size.$(file.patterns.au3)=4
+use.tabs.$(file.patterns.au3)=1
+
+block.start.$(file.patterns.au3)=5\
+ case if do for func else elseif while select switch with\
+ Case If Do For Func Else ElseIf While Select Switch With\
+ CASE IF DO FOR FUNC ELSE ELSEIF WHILE SELECT SWITCH WITH
+
+block.end.$(file.patterns.au3)=5\
+ case else endif elseif endfunc endselect endswitch next until wend endwith\
+ Case Else EndIf ElseIf EndFunc EndSelect EndSwitch Next Until WEnd EndWith Wend\
+ CASE ELSE ENDIF ELSEIF ENDFUNC ENDSELECT ENDSWITCH NEXT UNTIL WEND ENDWITH
+
+# Comment Block, Box and Stream
 comment.block.au3=;~
 comment.block.at.line.start.au3=1
-comment.stream.start.au3=#CS
-comment.stream.end.au3=#CE
-comment.box.start.au3=#CS
-comment.box.middle.au3=
-comment.box.end.au3= #CE
-
-#autoit keywords
-keywordclass.au3= \
- and byref case continueloop dim do else elseif endfunc endif endselect exit exitloop for func \
-  global if local next not or return select step then to until wend while exit
-
-keywords.$(file.patterns.au3)=$(keywordclass.au3)
-
-#autoit functions
-keywords2.$(file.patterns.au3)= \
- abs acos adlibdisable adlibenable asc asin atan autoitsetoption autoitwingettitle autoitwinsettitle \
-  bitand bitnot bitor bitshift bitxor blockinput break call cdtray chr clipget clipput controlclick \
-  controlcommand controldisable controlenable controlfocus controlgetfocus controlgetpos controlgettext \
-  controlhide controlmove controlsend controlsettext controlshow cos dec dircopy dircreate dirmove \
-  dirremove drivegetdrive drivegetfilesystem drivegetlabel drivegetserial drivegettype drivesetlabel \
-  drivespacefree drivespacetotal drivestatus envget envset envupdate eval exp filechangedir fileclose \
-  filecopy filecreateshortcut filedelete fileexists filefindfirstfile filefindnextfile filegetattrib \
-  filegetlongname filegetshortname filegetsize filegettime filegetversion fileinstall filemove \
-  fileopen fileopendialog fileread filereadline filerecycle filerecycleempty filesavedialog fileselectfolder 
\
-  filesetattrib filesettime filewrite filewriteline guicreate guicreateex guidefaultfont guidelete \
-  guigetcontrolstate guihide guimsg guiread guirecvmsg guisendmsg guisetcontrol guisetcontroldata \
-  guisetcontrolex guisetcontrolfont guisetcontrolnotify guisetcoord guisetcursor guishow guiwaitclose \
-  guiwrite hex hotkeyset inidelete iniread iniwrite inputbox int isadmin isarray isdeclared isfloat \
-  isint isnumber isstring log memgetstats mod mouseclick mouseclickdrag mousedown mousegetcursor \
-  mousegetpos mousemove mouseup mousewheel msgbox number pixelchecksum pixelgetcolor pixelsearch \
-  processclose processexists processsetpriority processwait processwaitclose progressoff progresson \
-  progressset random regdelete regenumkey regenumval regread regwrite round run runasset runwait \
-  send seterror shutdown sin sleep soundplay soundsetwavevolume splashimageon splashoff splashtexton \
-  sqrt statusbargettext string stringaddcr stringformat stringinstr stringisalnum stringisalpha \
-  stringisascii stringisdigit stringisfloat stringisint stringislower stringisspace stringisupper \
-  stringisxdigit stringleft stringlen stringlower stringmid stringreplace stringright stringsplit \
-  stringstripcr stringstripws stringtrimleft stringtrimright stringupper tan timerstart timerstop \
-  tooltip traytip ubound urldownloadtofile winactivate winactive winclose winexists wingetcaretpos \
-  wingetclasslist wingetclientsize wingethandle wingetpos wingetstate wingettext wingettitle \
-  winkill winmenuselectitem winminimizeall winminimizeallundo winmove winsetontop winsetstate \
-  winsettitle winwait winwaitactive winwaitclose winwaitnotactive
-
-#autoit macros
-keywords3.$(file.patterns.au3)= \
- @appdatacommondir @appdatadir @autoitversion @commonfilesdir @compiled @computername @comspec \
-  @cr @crlf @desktopcommondir @desktopdir @desktopheight @desktopwidth @documentscommondir @error \
-  @favoritescommondir @favoritesdir @homedrive @homepath @homeshare @hour @ipaddress1 @ipaddress2 \
-  @ipaddress3 @ipaddress4 @lf @logondnsdomain @logondomain @logonserver @mday @min @mon @mydocumentsdir \
-  @osbuild @oslang @osservicepack @ostype @osversion @programfilesdir @programscommondir @programsdir \
-  @scriptdir @scriptfullpath @scriptname @sec @startmenucommondir @startmenudir @startupcommondir \
-  @startupdir @sw_hide @sw_maximize @sw_minimize @sw_restore @sw_show @systemdir @tab @tempdir \
-  @userprofiledir @username @wday @windowsdir @workingdir @yday @year
-
-#autoit Sent Keys
-keywords4.$(file.patterns.au3)= {!} {#} {^} {{} {}} {+} {alt} {altdown} {altup} {appskey} {asc} {backspace} 
{browser_back} \
-{browser_favorites} {browser_forward} {browser_home} {browser_refresh} {browser_search} {browser_stop} {bs} 
{capslock} {ctrlbreak} \
-{ctrldown} {ctrlup} {del} {delete} {down} {end} {enter} {esc} {escape} {f1} {f10} {f11} {f12} {f2} {f3} {f4} 
{f5} {f6} {f7} {f8} {f9} \
-{home} {ins} {insert} {lalt} {launch_app1} {launch_app2} {launch_mail} {launch_media} {lctrl} {left} 
{lshift} {lwin} \
-{lwindown} {media_next} {media_play_pause} {media_prev} {media_stop} {numlock} \
-{numpad0} {numpad1} {numpad2} {numpad3} {numpad4} {numpad5} {numpad6} {numpad7} {numpad8} {numpad9} \
-{numpadadd} {numpaddiv} {numpaddot} {numpadenter} {numpadmult} {numpadsub} {pause} {pgdn} {pgup} \
-{printscreen} {ralt} {rctrl} {right} {rshift} {rwin} {rwindown} {scrolllock} {shiftdown} {shiftup} {sleep} 
{space} {tab} {up} \
-{volume_down} {volume_mute} {volume_up}
-
-#Pre-Processor
-keywords5.$(file.patterns.au3)= #include #include-once
-
-#Special
-keywords6.$(file.patterns.au3)= #region #endregion
+comment.box.start.au3=#cs
+comment.box.middle.au3=;
+comment.box.end.au3=#ce
+comment.stream.start.au3=#cs
+comment.stream.end.au3=#ce
+
+# Au3 keywords
+# Imported Scite4AutoIt3 files may resolve i.e. $(au3.variables.used) as keyword values
+
+# Keyword
+keywords.$(file.patterns.au3)=and byref case const continuecase continueloop default dim\
+ do else elseif endfunc endif endselect endswitch endwith enum exit exitloop false\
+ for func global if in local next not null or redim return select static step switch\
+ then to true until volatile wend while with
+
+# Function
+keywords2.$(file.patterns.au3)=abs acos adlibregister adlibunregister asc ascw asin assign\
+ atan autoitsetoption autoitwingettitle autoitwinsettitle beep binary binarylen binarymid\
+ binarytostring bitand bitnot bitor bitrotate bitshift bitxor blockinput break call\
+ cdtray ceiling chr chrw clipget clipput consoleread consolewrite consolewriteerror\
+ controlclick controlcommand controldisable controlenable controlfocus controlgetfocus\
+ controlgethandle controlgetpos controlgettext controlhide controllistview controlmove\
+ controlsend controlsettext controlshow controltreeview cos dec dircopy dircreate\
+ dirgetsize dirmove dirremove dllcall dllcalladdress dllcallbackfree dllcallbackgetptr\
+ dllcallbackregister dllclose dllopen dllstructcreate dllstructgetdata dllstructgetptr\
+ dllstructgetsize dllstructsetdata drivegetdrive drivegetfilesystem drivegetlabel\
+ drivegetserial drivegettype drivemapadd drivemapdel drivemapget drivesetlabel drivespacefree\
+ drivespacetotal drivestatus envget envset envupdate eval execute exp filechangedir\
+ fileclose filecopy filecreatentfslink filecreateshortcut filedelete fileexists filefindfirstfile\
+ filefindnextfile fileflush filegetattrib filegetencoding filegetlongname filegetpos\
+ filegetshortcut filegetshortname filegetsize filegettime filegetversion fileinstall\
+ filemove fileopen fileopendialog fileread filereadline filereadtoarray filerecycle\
+ filerecycleempty filesavedialog fileselectfolder filesetattrib filesetend filesetpos\
+ filesettime filewrite filewriteline floor ftpsetproxy funcname guicreate guictrlcreateavi\
+ guictrlcreatebutton guictrlcreatecheckbox guictrlcreatecombo guictrlcreatecontextmenu\
+ guictrlcreatedate guictrlcreatedummy guictrlcreateedit guictrlcreategraphic guictrlcreategroup\
+ guictrlcreateicon guictrlcreateinput guictrlcreatelabel guictrlcreatelist guictrlcreatelistview\
+ guictrlcreatelistviewitem guictrlcreatemenu guictrlcreatemenuitem guictrlcreatemonthcal\
+ guictrlcreateobj guictrlcreatepic guictrlcreateprogress guictrlcreateradio guictrlcreateslider\
+ guictrlcreatetab guictrlcreatetabitem guictrlcreatetreeview guictrlcreatetreeviewitem\
+ guictrlcreateupdown guictrldelete guictrlgethandle guictrlgetstate guictrlread guictrlrecvmsg\
+ guictrlregisterlistviewsort guictrlsendmsg guictrlsendtodummy guictrlsetbkcolor guictrlsetcolor\
+ guictrlsetcursor guictrlsetdata guictrlsetdefbkcolor guictrlsetdefcolor guictrlsetfont\
+ guictrlsetgraphic guictrlsetimage guictrlsetlimit guictrlsetonevent guictrlsetpos\
+ guictrlsetresizing guictrlsetstate guictrlsetstyle guictrlsettip guidelete guigetcursorinfo\
+ guigetmsg guigetstyle guiregistermsg guisetaccelerators guisetbkcolor guisetcoord\
+ guisetcursor guisetfont guisethelp guiseticon guisetonevent guisetstate guisetstyle\
+ guistartgroup guiswitch hex hotkeyset httpsetproxy httpsetuseragent hwnd inetclose\
+ inetget inetgetinfo inetgetsize inetread inidelete iniread inireadsection inireadsectionnames\
+ inirenamesection iniwrite iniwritesection inputbox int isadmin isarray isbinary isbool\
+ isdeclared isdllstruct isfloat isfunc ishwnd isint iskeyword isnumber isobj isptr\
+ isstring log memgetstats mod mouseclick mouseclickdrag mousedown mousegetcursor mousegetpos\
+ mousemove mouseup mousewheel msgbox number objcreate objcreateinterface objevent\
+ objevent objget objname onautoitexitregister onautoitexitunregister opt ping pixelchecksum\
+ pixelgetcolor pixelsearch processclose processexists processgetstats processlist\
+ processsetpriority processwait processwaitclose progressoff progresson progressset\
+ ptr random regdelete regenumkey regenumval regread regwrite round run runas runaswait\
+ runwait send sendkeepactive seterror setextended shellexecute shellexecutewait shutdown\
+ sin sleep soundplay soundsetwavevolume splashimageon splashoff splashtexton sqrt\
+ srandom statusbargettext stderrread stdinwrite stdioclose stdoutread string stringaddcr\
+ stringcompare stringformat stringfromasciiarray stringinstr stringisalnum stringisalpha\
+ stringisascii stringisdigit stringisfloat stringisint stringislower stringisspace\
+ stringisupper stringisxdigit stringleft stringlen stringlower stringmid stringregexp\
+ stringregexpreplace stringreplace stringreverse stringright stringsplit stringstripcr\
+ stringstripws stringtoasciiarray stringtobinary stringtrimleft stringtrimright stringupper\
+ tan tcpaccept tcpclosesocket tcpconnect tcplisten tcpnametoip tcprecv tcpsend tcpshutdown\
+ tcpstartup timerdiff timerinit tooltip traycreateitem traycreatemenu traygetmsg trayitemdelete\
+ trayitemgethandle trayitemgetstate trayitemgettext trayitemsetonevent trayitemsetstate\
+ trayitemsettext traysetclick trayseticon traysetonevent traysetpauseicon traysetstate\
+ traysettooltip traytip ubound udpbind udpclosesocket udpopen udprecv udpsend udpshutdown\
+ udpstartup vargettype winactivate winactive winclose winexists winflash wingetcaretpos\
+ wingetclasslist wingetclientsize wingethandle wingetpos wingetprocess wingetstate\
+ wingettext wingettitle winkill winlist winmenuselectitem winminimizeall winminimizeallundo\
+ winmove winsetontop winsetstate winsettitle winsettrans winwait winwaitactive winwaitclose\
+ winwaitnotactive
+
+# Macro
+keywords3.$(file.patterns.au3)=@appdatacommondir @appdatadir @autoitexe @autoitpid @autoitversion\
+ @autoitx64 @com_eventobj @commonfilesdir @compiled @computername @comspec @cpuarch\
+ @cr @crlf @desktopcommondir @desktopdepth @desktopdir @desktopheight @desktoprefresh\
+ @desktopwidth @documentscommondir @error @exitcode @exitmethod @extended @favoritescommondir\
+ @favoritesdir @gui_ctrlhandle @gui_ctrlid @gui_dragfile @gui_dragid @gui_dropid @gui_winhandle\
+ @homedrive @homepath @homeshare @hotkeypressed @hour @ipaddress1 @ipaddress2 @ipaddress3\
+ @ipaddress4 @kblayout @lf @localappdatadir @logondnsdomain @logondomain @logonserver\
+ @mday @min @mon @msec @muilang @mydocumentsdir @numparams @osarch @osbuild @oslang\
+ @osservicepack @ostype @osversion @programfilesdir @programscommondir @programsdir\
+ @scriptdir @scriptfullpath @scriptlinenumber @scriptname @sec @startmenucommondir\
+ @startmenudir @startupcommondir @startupdir @sw_disable @sw_enable @sw_hide @sw_lock\
+ @sw_maximize @sw_minimize @sw_restore @sw_show @sw_showdefault @sw_showmaximized\
+ @sw_showminimized @sw_showminnoactive @sw_showna @sw_shownoactivate @sw_shownormal\
+ @sw_unlock @systemdir @tab @tempdir @tray_id @trayiconflashing @trayiconvisible @username\
+ @userprofiledir @wday @windowsdir @workingdir @yday @year
+
+# Send key
+keywords4.$(file.patterns.au3)={!} {#} {^} {{} {}} {+} {alt} {altdown} {altup} {appskey}\
+ {asc} {backspace} {break} {browser_back} {browser_favorites} {browser_forward} {browser_home}\
+ {browser_refresh} {browser_search} {browser_stop} {bs} {capslock} {ctrldown} {ctrlup}\
+ {del} {delete} {down} {end} {enter} {esc} {escape} {f1} {f10} {f11} {f12} {f2} {f3}\
+ {f4} {f5} {f6} {f7} {f8} {f9} {home} {ins} {insert} {lalt} {launch_app1} {launch_app2}\
+ {launch_mail} {launch_media} {lctrl} {left} {lshift} {lwin} {lwindown} {lwinup} {media_next}\
+ {media_play_pause} {media_prev} {media_stop} {numlock} {numpad0} {numpad1} {numpad2}\
+ {numpad3} {numpad4} {numpad5} {numpad6} {numpad7} {numpad8} {numpad9} {numpadadd}\
+ {numpaddiv} {numpaddot} {numpadenter} {numpadmult} {numpadsub} {oem_102} {pause}\
+ {pgdn} {pgup} {printscreen} {ralt} {rctrl} {right} {rshift} {rwin} {rwindown} {rwinup}\
+ {scrolllock} {shiftdown} {shiftup} {sleep} {space} {tab} {up} {volume_down} {volume_mute}\
+ {volume_up}
+
+# Pre-Processor
+keywords5.$(file.patterns.au3)=#ce #comments-end #comments-start #cs #include #include-once\
+#notrayicon #onautoitstartregister #requireadmin
+
+# Special
+keywords6.$(file.patterns.au3)=#endregion #forcedef #forceref #ignorefunc #pragma #region\
+ $(autoit3wrapper.keywords.special)
 
+# Abbrev-Expand
+keywords7.$(file.patterns.au3)=$(au3.keywords.abbrev) $(au3.keywords.userabbrev)
+
+# Standard UDF
+keywords8.$(file.patterns.au3)=$(au3.keywords.udfs)
+
+# Au3 styles
+
+
+# Properties using paths
+
+# Directory containing AutoIt program files
+autoit3dir=$(SciteDefaultHome)\..
+
+# API path
+api.$(file.patterns.au3)=$(SciteDefaultHome)\api\au3.api;$(SciteDefaultHome)\api\au3.autoit3wrapper.api;$(SciteUserHome)\au3.user.calltips.api
+
+# Commands for F1 Help
+command.help.$(file.patterns.au3)=$(CurrentWord)!$(autoit3dir)\AutoIt.chm
+command.help.subsystem.$(file.patterns.au3)=4
+
+# Commands to Compile, Build and Go
+command.compile.$(file.patterns.au3)="$(autoit3dir)\Aut2Exe\Aut2exe.exe" /in "$(FilePath)"
+command.build.$(file.patterns.au3)="$(autoit3dir)\Aut2Exe\Aut2exe.exe" /in "$(FilePath)" /x64
+command.go.$(file.patterns.au3)="$(autoit3dir)\AutoIt3.exe" /ErrorStdOut "$(FilePath)" $(1) $(2) $(3) $(4)
+
+# Au3Check
+command.0.$(file.patterns.au3)="$(autoit3dir)\Au3Check.exe" -q "$(FilePath)"
+command.name.0.$(file.patterns.au3)=Syntax Check
+command.shortcut.0.$(file.patterns.au3)=Ctrl+F5
+command.save.before.0.$(file.patterns.au3)=1
 
 
 
@@ -756,12 +843,15 @@ keywords6.$(file.patterns.au3)= #region #endregion
 
 filter.ave=AVE (ave)|*.ave|
 
+*filter.ave=$(filter.ave)
 
 file.patterns.ave=*.ave
 
 lexer.*.ave=ave
 lexer.$(file.patterns.ave)=ave
 
+*language.avenue=Avenue|ave||
+
 ####################################################
 # import classes and requests
 # files ave.classes &  ave.funcs is to large
@@ -936,60 +1026,165 @@ braces.avs.style=5
 ###############################################################################
 # From baan.properties
 # Define SciTE settings for Baan files.
+#set Below as per Preference.
+font.baan.monospace=font:Consolas,size:10
+
+fold.baan.keywords.based=1
+fold.baan.syntax.based=0
+fold.baan.sections=1
+fold.baan.inner.level=0
+lexer.baan.styling.within.preprocessor=1
+
+#uncomment below, set the full path of API files. If more than one, seperate it with ';'.
+#api.$(file.patterns.baan)=
+
+#Uncomment below two properties, set the full path of CHM files.
+#command.help.$(file.patterns.baan)=$(CurrentWord)!D:\
+#command.help.subsystem.$(file.patterns.baan)=4
 
+#Not much to change.  Check Baan Styles for preference.
 file.patterns.baan=*.bc;*.cln
 
 filter.baan=Baan (baan)|$(file.patterns.baan)|
 
+*filter.baan=$(filter.baan)
+
 lexer.$(file.patterns.baan)=baan
 
+*language.baan=Baan|bc||
+
 word.characters.$(file.patterns.baan)=$(chars.alpha)$(chars.numeric)_#.$
-calltip.baan.word.characters="._0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$"
+calltip.baan.word.characters=$(chars.alpha)$(chars.numeric)_#.$
 autocomplete.baan.ignorecase=1
 calltip.baan.ignorecase=1
+autocomplete.baan.start.characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_."
 
-#styling.within.preprocessor=1
 preprocessor.symbol.$(file.patterns.baan)=#
 preprocessor.start.$(file.patterns.baan)=if ifdef ifndef
 preprocessor.middle.$(file.patterns.baan)=else elif
 preprocessor.end.$(file.patterns.baan)=endif
 
-keywordclass.baan=
-keywords.$(file.patterns.baan)=$(keywordclass.baan)
-
 # Comment blocks for Baan
 comment.block.baan=|
-comment.box.start.baan=|
-comment.box.middle.baan=|
-comment.box.end.baan=|
-# Doesnot work too good for Baan use block or box commands
-comment.stream.start.baan=DllUsage
-comment.stream.end.baan=EndDllUsage
+comment.block.at.line.start.baan=1
+
+block.start.$(file.patterns.baan)=4 case  else for  if repeat selectdo selectempty selecteos selecterror
+block.end.$(file.patterns.baan)=4 else endcase  endfor  endif endselect endwhile selectempty selecteos 
selecterror
+statement.lookback.$(file.patterns.baan)=0
+
+# Baan styles. Change colours based on preference.
+# Gray
+colour.baan.whitespace=fore:#808080
+#Olive
+colour.baan.preproc=fore:#808000
+#Magenta
+colour.baan.string=fore:#FF00FF
+#Teal
+colour.baan.comment.doc=fore:#008080
+#green
+colour.baan.comment.line=fore:#008000
+#Red
+colour.baan.numbers=fore:#FF0000
+#Maroon
+colour.baan.keyword=fore:#800000
+#Blue
+colour.baan.keyword2=fore:#0000FF
+colour.baan.keyword3=fore:#0000FF
+#Orange Red
+colour.baan.keyword4=fore:#FF4500 
+#Purple
+colour.baan.keyword5=fore:#800080
+colour.baan.keyword6=fore:#FF00FF,back:#4EE2EC
+colour.baan.keyword7=fore:#FF0000,back:#90EE90
+colour.baan.keyword8=fore:#CC00CC,back:#FFFF99
+colour.baan.keyword9=fore:#00FFFF
+#DarkOrchid
+colour.baan.tabledef=fore:#9932CC 
+#BlueViolet
+colour.baan.tablesql=fore:#8A2BE2
+#Navy
+colour.baan.functions=fore:#000080
+#DarkGoldenrod
+colour.baan.domaindef=fore:#B8860B
+# FireBrick
+colour.baan.funcdefs=fore:#B22222
+# OrangeRed
+colour.baan.objdefs=fore:#FF4500
+#Dark Olive Green
+colour.baan.definedefs=fore:#556B2F
+
+colour.baan.braces.highlight=fore:#0000FF
+colour.baan.braces.incomplete=fore:#FF0000
+colour.baan.eol.string.not.closed=fore:#000000,back:#E0C0E0
+colour.baan.operator=fore:#007F00      
 
 
-# Baan styles
-
-colour.baan.operator=fore:#B06000
-
 # Braces are only matched in operator style
-braces.baan.style=10
+braces.baan.style=7
 
 #Indent properties
-statement.indent.$(file.patterns.baan)=5 after.choice  after.commit.transaction  after.delete  \
-after.display  after.field  \
-after.form  after.input  after.program  after.read  after.rewrite  \
-after.group  after.skip.delete  after.skip.rewrite  after.skip.write  \
-after.update.db.commit  after.write  after.zoom  \
-before.checks  before.choice  before.delete  before.display  \
-before.display.object  before.field  before.form  before.input  before.layout  \
-before.group before.program  before.read  before.rewrite  before.write  before.zoom  \
-case check.input  declaration  default  dllusage  \
-else  elseif  functions  if  on.input  on.entry  on.exit \
-read.view  ref.input  ref.display selectdo  selectempty  selecteos \
-when.field.changes  while
+statement.indent.$(file.patterns.baan)=12 after.choice: after.delete: after.display: after.field: 
after.form.read: after.form: \
+after.group: after.input: after.layout: after.program: after.receive.data: after.rewrite: after.skip.delete: 
after.skip.rewrite: \
+after.skip.write: after.update.db.commit: after.write: after.zoom: before.checks: before.choice: 
before.delete: before.display.object: \
+before.display: before.field: before.form: before.group: before.input: before.layout: before.new.object: 
before.print: before.program: \
+before.read: before.rewrite: before.write: before.zoom: check.input: declaration: domain.error: init.field: 
init.form: init.group: on.choice: \
+on.display.total.line: on.entry: on.error: on.exit: on.input: read.view: ref.display: ref.input: 
selection.filter: when.field.changes:
+
+#keywords Reserved Keywords (Do not Change)
+keywords.$(file.patterns.baan)=alike all and array as asc at avg base based between boolean both break bset 
buffer by call case cast chart clear \
+clearunref common const continue count cross current_date current_timestamp date date.num date.to.num debug 
default delete deleteempty \
+deleteerror desc dim distinct dll dllusage domain double else empty end endcase enddelete enddllusage endfor 
endfunctionusage endif endselect \
+endupdate endwhile enum_description eq escape exists extern false fatal fetching field first fixed for from 
full function functionusage ge global goto \
+group gt having hint hints if in include index inner input inrange integer is join label last le leading 
left like long lt max mb menu message min multibyte \
+ne no nodebug not notransactions nowarnings null on or order ordered outer path pi prepared print prompt 
question raw real ref reference refers repeat \
+retry return right row rows select selectbind selectdo selectempty selecteos selecterror session set 
setunref size skip static step sticky stop strict_boolean \
+string subhint sum table text_content then timestamp to trailing trim true union unref until update 
updateempty updateerror use used void warning warnings \
+when where wherebind whereused while with
+
+#Keywords2 Functions (Set your Functions based on Baan version & TIV level.)
+keywords2.$(file.patterns.baan)=abort abort.io  \
+db.after.delete db.after.insert db.after.update \
+xmlSetData \
+zoom.to$
+
+#Keywords3 Functions InListAbridged (Set Functions, based on Baan Version & TIV Level.) ~.is.mandatory will 
work for <any.field>.is.mandatory() DAL function.
+keywords3.$(file.patterns.baan)=~.is.mandatory 
+
+#Keywords4 Sub Sections (Sub Sections should always come before main sections, because after.~: in main 
section would overtake after.choice: and so on). (Do Not Change)
+keywords4.$(file.patterns.baan)=after.choice: after.delete: after.display: after.field: after.form: 
after.group: after.input: after.layout: after.read: after.rewrite: \
+after.skip.delete: after.skip.rewrite: after.skip.write: after.write: after.zoom: before.checks:  
before.choice: before.delete: before.display: before.field: before.form: \
+before.group: before.input: before.layout: before.print: before.read: before.rewrite: before.write: 
before.zoom: check.input: domain.error: init.field: init.form: \
+init.group: on.choice: on.entry: on.exit: on.input: read.view: ref.display: ref.input: selection.filter: 
when.field.changes:
+
+#Keyword5 Main Sections InListAbridged (Do Not Change)
+keywords5.$(file.patterns.baan)=after.~: before.~: choice.abort.program: choice.abort.work: choice.add.set: 
choice.ask.helpinfo: choice.attachments: \
+choice.bms: choice.calculator: choice.calender: choice.cancel.work: choice.change.frm: choice.change.order: 
choice.cmd.about.baan: choice.cmd.copy: \
+choice.cmd.cut: choice.cmd.options: choice.cmd.paste: choice.cont.process: choice.create.job: 
choice.current.work: choice.cust.grid: choice.def.find: \
+choice.display.set: choice.dupl.occur: choice.end.program: choice.field.browse: choice.field.help: 
choice.find.data: choice.first.frm: choice.first.set: \
+choice.first.view: choice.freeze.columns: choice.get.defaults: choice.global.copy: choice.global.delete: 
choice.glossary: choice.help.index: choice.hide.fields: \
+choice.interrupt: choice.last.frm: choice.last.set: choice.last.view: choice.mark.delete: choice.mark.occur: 
choice.modify.set: choice.next.frm: choice.next.set: \
+choice.next.view: choice.next.work: choice.prev.frm: choice.prev.set: choice.prev.view: choice.print.data: 
choice.processes: choice.recover.set: choice.reference: \
+choice.resize.frm: choice.rotate.curr: choice.run.job: choice.save.defaults: choice.select.all: 
choice.send.data: choice.sendto.desktop: choice.sendto.editor: \
+choice.sendto.mail: choice.sendto.tasklst: choice.start.chart: choice.start.query: choice.start.set: 
choice.suspend.work: choice.switch.windows: choice.synchronize: \
+choice.text.manager: choice.to.clipboard: choice.unfreeze.colum: choice.update.db: choice.user.0: 
choice.user.1: choice.user.2: choice.user.3: choice.user.4: choice.user.5: \
+choice.user.6: choice.user.7: choice.user.8: choice.user.9: choice.using.help: choice.zoom:  declaration: 
detail.~: field.~: footer.~: form.~: functions: group.~: \
+header.~:  main.table.io: on.display.total.line: on.error: zoom.from.~:
+
+#Keyword6 PreDefined Variables (Set these predefined variables based on your Baan Version).
+keywords6.$(file.patterns.baan)=actual.occ \
+zoomreturn$
+
+#keywords7 Attributes PreDefined ( Below list needs to be typed in UPPER case in scripts, but keep it in 
lower here). (Set these predefined Attributes based on your Baan Version).
+keywords7.$(file.patterns.baan)=__file__ \
+z.session
+
+#keywords8 Enumerate domains. Enter domain domain names starting with '^' and ending with '.'. All the 
enumerates would be listed. (Based on your Baan Version).
+keywords8.$(file.patterns.baan)=^tcyesno. ^tdsls.corg.
+
+#Keywords9 MACROS from standard based on your Baan Version. Write in CAPS inside the scripts, but in lower 
here.
+keywords9.$(file.patterns.baan)=dalnew dalupdate
+
 
-#Unindent properties
-statement.lookback.$(file.patterns.baan)=1 endif endwhile endfor endselect return
 
 
 ###############################################################################
@@ -1000,6 +1195,8 @@ file.patterns.blitzbasic=*.bb
 
 filter.blitzbasic=BlitzBasic (bb)|$(file.patterns.blitzbasic)|
 
+*filter.blitzbasic=$(filter.blitzbasic)
+
 lexer.$(file.patterns.blitzbasic)=blitzbasic
 
 # keywords must be all lowercase
@@ -1068,10 +1265,14 @@ keywords.$(file.patterns.blitzbasic)=$(keywordclass.blitzbasic)
 
 filter.bullant=Bullant (.ant)|*.ant|
 
+*filter.bullant=$(filter.bullant)
+
 file.patterns.bullant=*.ant
 
 lexer.$(file.patterns.bullant)=bullant
 
+*language.bullant=Bullant|ant||
+
 keywordclass.bullant=abstract all ancestor and application \
 assert attributes author \
 begin \
@@ -1151,6 +1352,8 @@ command.build.subsystem.*.ant=
 file.patterns.caml=*.ml;*.mli
 file.patterns.sml=*.sml
 
+*filter.objectivecaml=$(filter.caml)
+
 filter.caml=Objective Caml (ml mli)|$(file.patterns.caml)|
 filter.sml=Standard ML 97 (sml ml)|$(file.patterns.sml)|
 
@@ -1158,6 +1361,8 @@ lexer.*.caml=caml
 lexer.$(file.patterns.caml)=caml
 lexer.$(file.patterns.sml)=caml
 
+#*language.objectivecaml=Objective Caml|ml||
+
 # the line below is ONLY used as part of "external" lexer support
 #lexerpath.$(file.patterns.caml)=LexCaml.dll
 #lexerpath.$(file.patterns.sml)=LexCaml.dll
@@ -1245,9 +1450,11 @@ command.compile.$(file.patterns.caml)=ocamlc -c $(FileNameExt)
 # Define SciTE settings for CMake.
 # contributed by Cristian Adam <cristian dot adam at gmx dot net>
 
-filter.cmake=CMake (CMakeLists.txt, *.cmake, *.ctest)|CMakeLists.txt;*.cmake;*.cmake.in;*.ctest;*.ctest.in|
+filter.cmake=CMake (CMakeLists.txt cmake ctest)|CMakeLists.txt;*.cmake;*.cmake.in;*.ctest;*.ctest.in|
+*filter.cmake=$(filter.cmake)
 file.patterns.cmake=CMakeLists.txt;*.cmake;*.cmake.in;*.ctest;*.ctest.in
 lexer.$(file.patterns.cmake)=cmake
+*language.cmake=CMake|cmake||
 
 # Commands:
 keywords.$(file.patterns.cmake)= add_custom_command \
@@ -1477,12 +1684,15 @@ calltip.cmake.parameters.end=)
 # From cobol.properties
 # Define SciTE settings for COBOL files.
 
-file.patterns.COBOL=*.cob
-filter.cobol=COBOL (cob)|$(file.patterns.COBOL)|
+file.patterns.COBOL=*.cob;*.cbl;*.cpy
+filter.cobol=COBOL (cob cbl cpy)|$(file.patterns.COBOL)|
+*filter.cobol=$(filter.cobol)
 
 lexer.$(file.patterns.COBOL)=COBOL
 
-word.characters.$(file.patterns.cobol)=$(chars.alpha)$(chars.numeric)$(chars.accented)_-
+*language.cobol=COBOL|cob||
+
+word.characters.$(file.patterns.COBOL)=$(chars.alpha)$(chars.numeric)$(chars.accented)_-
 
 # These keywords are case insensitive
 keywords.$(file.patterns.COBOL)=configuration data declaratives division environment environment-division 
file file-control function i-o i-o-control identification input input-output linkage local-storage output 
procedure program program-id receive-control section special-names working-storage
@@ -1501,13 +1711,29 @@ keywords3.$(file.patterns.COBOL)=access acquire actual address advancing after a
 
 
 ###############################################################################
+# From coffeescript.properties
+# Define SciTE settings for CoffeeScript files.
+
+filter.coffeescript=CoffeeScript (coffee)|*.coffee|
+
+file.patterns.coffeescript=*.coffee
+
+lexer.$(file.patterns.coffeescript)=coffeescript
+
+
+
+
+###############################################################################
 # From conf.properties
 # Define SciTE settings for Apache Configuration files.
 # contributed by Ahmad Zawawi <zeus_go64 hotmail com>
 
 file.patterns.conf=*.conf;.htaccess
+*source.patterns.conf=$(file.patterns.conf);
 filter.conf=Apache Conf (conf)|$(file.patterns.conf)|
+*filter.apacheconfig=$(filter.conf)
 lexer.$(file.patterns.conf)=conf
+#*language.apacheconfig=Apache Confi&g|conf||
 # for future implemention...
 #api.$(file.patterns.conf)=conf.api
 
@@ -1653,11 +1879,10 @@ file.patterns.cpp=*.c;*.cc;*.cpp;*.cxx;*.h;*.hh;*.hpp;*.hxx;*.ipp;*.m;*.mm;*.sma
 file.patterns.cplusplus=*.cc;*.cpp;*.cxx
 # jad = decompiled class files; pde = Processing.org sketch files
 file.patterns.java=*.java;*.jad;*.pde
-file.patterns.javafx=*.fx
 # pln, inc and t are SilkTest (4Test) files.
 file.patterns.test=*.pln;*.inc;*.t
 # es = JS dialect of Abobe for SVG
-file.patterns.js=*.js;*.es
+file.patterns.js=*.js;*.es;*.ts
 file.patterns.cs=*.cs
 file.patterns.rc=*.rc;*.rc2;*.dlg
 file.patterns.idl=*.idl;*.odl
@@ -1666,24 +1891,33 @@ file.patterns.ch=*.ch;*.chf;*.chs
 file.patterns.vala=*.vala
 file.patterns.go=*.go
 file.patterns.pike=*.pike
+file.patterns.swift=*.swift
 
file.patterns.c.like=$(file.patterns.cpp);$(file.patterns.cs);$(file.patterns.idl);$(file.patterns.java);$(file.patterns.js);$(file.patterns.flash);$(file.patterns.ch);$(file.patterns.vala);$(file.patterns.pike)
 
+*source.patterns.cpp=$(file.patterns.c.like);
+*source.patterns.resource=$(file.patterns.rc);*.def;
+
 shbang.tcc=cpp
 shbang.tinycc=cpp
 
 filter.cpp=C/C++ (c cc cpp cxx cs vala h hh hxx hpp ipp dlg rc rc2 mak)|\
 $(file.patterns.cpp);$(file.patterns.cs);$(file.patterns.rc);$(file.patterns.vala);*.mak;make*|
 filter.java=Java (java)|*.java|
-filter.js=JavaScript (js es)|$(file.patterns.js)|
+filter.js=JavaScript (js es ts)|$(file.patterns.js)|
 filter.idl=IDL (idl odl)|$(file.patterns.idl)|
 filter.test=SilkTest (pln inc t)|$(file.patterns.test)|
 filter.flash=Flash (as asc jsfl)|$(file.patterns.flash)|
 filter.ch=Ch (ch chf chs)|$(file.patterns.ch)|
 filter.go=Go (go)|$(file.patterns.go)|
 filter.pike=Pike (pike)|$(file.patterns.pike)|
+filter.swift=Swift (swift)|$(file.patterns.swift)|
+
+*filter.cpp=$(filter.cpp)
+*filter.java=$(filter.java)
+*filter.javascript=$(filter.js)
+*filter.idl=$(filter.idl)
 
 lexer.$(file.patterns.java)=cpp
-lexer.$(file.patterns.javafx)=cpp
 lexer.$(file.patterns.cpp)=cpp
 lexer.$(file.patterns.rc)=cpp
 lexer.$(file.patterns.idl)=cpp
@@ -1695,16 +1929,35 @@ lexer.$(file.patterns.ch)=cpp
 lexer.$(file.patterns.vala)=cpp
 lexer.$(file.patterns.go)=cpp
 lexer.$(file.patterns.pike)=cpp
-
-keywordclass.cpp=and and_eq asm auto bitand bitor bool break \
-case catch char class compl const const_cast continue \
-default delete do double dynamic_cast else enum explicit export extern false float for \
-friend goto if inline int long mutable namespace new not not_eq \
-operator or or_eq private protected public \
-register reinterpret_cast return short signed sizeof static static_cast struct switch \
-template this throw true try typedef typeid typename union unsigned using \
+lexer.$(file.patterns.swift)=cpp
+
+*language.c=&C / C++|c||
+*language.csharp=C&#|cs||
+*language.java=&Java|java||
+*language.javascript=Java&Script|js||
+#*language.resource=Reso&urce|rc||
+
+keywordclass.cpp=alignas alignof and and_eq asm auto bitand bitor bool break \
+case catch char char16_t char32_t class compl const constexpr const_cast continue \
+decltype default delete do double dynamic_cast else enum explicit export extern false final float for \
+friend goto if inline int long mutable namespace new noexcept not not_eq nullptr \
+operator or or_eq override private protected public \
+register reinterpret_cast return short signed sizeof static static_assert static_cast struct switch \
+template this thread_local throw true try typedef typeid typename union unsigned using \
 virtual void volatile wchar_t while xor xor_eq
-keywords.$(file.patterns.cpp)=$(keywordclass.cpp)
+
+directives.objective.c=\
+@class @defs @protocol @required @optional @end \
+@interface @public @package @protected @private @property \
+@implementation @synthesize @dynamic \
+@throw @try @catch @finally \
+@synchronized @autoreleasepool \
+@selector @encode \
+@compatibility_alias
+
+# Since Objective C and C++ share the .h extension, allow Objective C directives as keywords
+# For stricter display of pure C++, specify keywords.$(file.patterns.cpp)=$(keywordclass.cpp)
+keywords.$(file.patterns.cpp)=$(keywordclass.cpp) $(directives.objective.c)
 
 # keywords2 is for highlighting user defined keywords or function calls or similar
 #keywords2.$(file.patterns.cpp)=file
@@ -1743,6 +1996,7 @@ comment.box.end.cpp= */
 
 # Folding
 #fold.cpp.syntax.based=0
+#fold.comment=0
 #fold.cpp.comment.multiline=0
 #fold.cpp.comment.explicit=0
 #defaults for fold.cpp.explicit.start=//{ and fold.cpp.explicit.end=//}
@@ -1752,10 +2006,10 @@ comment.box.end.cpp= */
 #if fold strings are set to something like /*{{{ and /*}}} (Origami/WinF style fold strings), enable
 #  fold.cpp.explicit.anywhere, allowing explicit fold points being anywhere, not just in line comments
 #fold.cpp.explicit.anywhere=1
+#fold.preprocessor=1
+#fold.compact=1
 #fold.at.else=1
 
-word.characters.$(file.patterns.javafx)=$(word.chars.cxx)$-
-
 
file.patterns.c.except.cpp=$(file.patterns.cs);$(file.patterns.idl);*.java;$(file.patterns.flash);$(file.patterns.ch)
 statement.indent.$(file.patterns.c.except.cpp)=5 case default do else for if while
 statement.indent.$(file.patterns.cpp)=5 case default do else for if private protected public while
@@ -1874,21 +2128,6 @@ return short static strictfp super switch synchronized this throw throws \
 transient try var void volatile while
 keywords.$(file.patterns.java)=$(keywordclass.java)
 
-keywordclass.javafx=abstract after and as assert at attribute before bind bound break \
-catch class continue def delete else exclusive extends false finally for from function \
-if import indexof insert instanceof lazy mod new not null \
-or override package private protected public-init public public-read \
-return reverse sizeof static super then this throw true try typeof \
-var while
-keywords.$(file.patterns.javafx)=$(keywordclass.javafx)
-# Base types and global functions (defined in javafx.lang.Builtins and javafx.lang.FX)
-# And now language words deprecated from their keyword status...
-keywords2.$(file.patterns.javafx)=Boolean Duration Integer Number Object String Void \
-Character Byte Short Long Float Double \
-isInitialized isSameObject print println \
-first in init into inverse last on postinit replace step trigger tween where with
-# I don't know what first and last nor trigger do. Neither lazy or typeof...
-
 keywordclass.javascript=abstract boolean break byte case catch char class \
 const continue debugger default delete do double else enum export extends \
 final finally float for function goto if implements import in instanceof \
@@ -1936,9 +2175,48 @@ return typeof catch class lambda import inherit static void int string float mix
 function program array mapping multiset
 keywords.$(file.patterns.pike)=$(keywordclass.pike)
 
+keywordclass.swift.declarations=class deinit enum extension func import init \
+internal let operator private protocol public static struct subscript typealias var
+keywordclass.swift.statements=break case continue default do else fallthrough \
+for if in return switch where while
+keywordclass.swift.expressions=as dynamicType false is nil self Self super \
+true __COLUMN__ __FILE__ __FUNCTION__ __LINE__
+# The contextual keywords are only keywords in particular contexts
+keywordclass.swift.contextual=associativity convenience dynamic didSet final get \
+infix inout lazy left mutating none nonmutating optional override postfix \
+precedence prefix Protocol required right set Type unowned weak willSet
+
+keywords.$(file.patterns.swift)=$(keywordclass.swift.declarations) \
+$(keywordclass.swift.statements) $(keywordclass.swift.expressions) \
+$(keywordclass.swift.contextual)
+
+# Substyles can be used for extra lists of highlighted identifiers and doc comment keywords
+# Identifiers
+#substyles.cpp.11=2
+#substylewords.11.1.$(file.patterns.cpp)=std map string vector
+#style.cpp.11.1=fore:#EE00AA
+#style.cpp.75.1=$(style.cpp.75),fore:#BB6666
+# Doc comment keywords
+#substyles.cpp.17=1
+#style.cpp.17.1=$(style.cpp.17),fore:#00AAEE
+#style.cpp.81.1=$(style.cpp.81),fore:#6699AA
+#substylewords.17.1.$(file.patterns.cpp)=check
+
+# Markers
+# keywords6.$(file.patterns.c.like)=FIXME TODO XXX HACK UnresolvedMergeConflict UNDONE
+
+#styling.within.preprocessor=1
+#lexer.cpp.allow.dollars=1
 #lexer.cpp.track.preprocessor=1
 #lexer.cpp.update.preprocessor=1
+# For C# leave lexer.cpp.verbatim.strings.allow.escapes as 0 but change to 1 for Objective C
+#lexer.cpp.verbatim.strings.allow.escapes=1
+#lexer.cpp.triplequoted.strings=1
 #lexer.cpp.hashquoted.strings=1
+#lexer.cpp.backquoted.strings=1
+#lexer.cpp.escape.sequence=1
+
+#lexer.cpp.escape.sequence=1
 
 # C++ styles
 
@@ -1957,17 +2235,20 @@ make.command=make
 command.compile.*.c=$(ccc) -std=c99
 command.build.*.c=$(make.command)
 command.build.*.h=$(make.command)
+command.clean.*.c=$(make.command) clean
+command.clean.*.h=$(make.command) clean
 command.go.*.c=./$(FileName)
 # To make the Go command both compile (if needed) and execute, use this setting:
 #command.go.needs.*.c=gcc $(ccopts) -std=c99 $(FileNameExt) -o $(FileName)
 
 command.compile.$(file.patterns.cplusplus)=$(cc)
 command.build.$(file.patterns.cplusplus)=$(make.command)
+command.clean.$(file.patterns.cplusplus)=$(make.command) clean
 command.go.$(file.patterns.cplusplus)=./$(FileName)
 command.go.needs.$(file.patterns.cplusplus)=g++ $(ccopts) $(FileNameExt) -o $(FileName)
 
 command.name.0.$(file.patterns.cpp)=Indent
-command.0.$(file.patterns.cpp)=astyle -taOHUKk3 -M8 $(FileNameExt)
+command.0.$(file.patterns.cpp)=astyle --style=attach --indent=force-tab=8 --keep-one-line-blocks 
--pad-header --unpad-paren --pad-comma --indent-cases --align-pointer=name $(FileNameExt)
 command.is.filter.0.$(file.patterns.cpp)=1
 
 command.name.1.$(file.patterns.cplusplus)=Lint
@@ -2000,10 +2281,6 @@ command.compile.*.java=javac $(FileNameExt)
 command.build.*.java=javac *.java
 command.go.*.java=java -cp . $(FileName)
 
-command.compile.*.fx=javafxc -d bin $(FileNameExt)
-command.build.*.fx=javafxc -d bin *.fx
-command.go.*.fx=javafx -cp bin $(FileName)
-
 if PLAT_WIN
        command.help.*.java=http://java.sun.com/javase/6/docs/api/java/util/$(CurrentWord).html
        command.help.subsystem.*.java=2
@@ -2015,10 +2292,6 @@ command.go.*.ch=ch -u $(FileNameExt)
 command.compile.*.as=mtasc -strict $(FileNameExt)
 command.build.*.as=mtasc -strict *.as
 
-command.compile.*.fx=javafxc -d . $(FileNameExt)
-command.build.*.fx=javafxc -d . *.fx
-command.go.*.fx=javafx -cp . $(FileName)
-
 command.build.$(file.patterns.vala)=valac $(FileNameExt)
 command.go.*.vala=./$(FileName)
 
@@ -2027,6 +2300,8 @@ command.compile.*.go=8g $(FileNameExt)
 command.build.*.go=$(make.command)
 command.go.*.go=./$(FileName)
 
+command.compile.*.ts=tsc $(FileNameExt)
+
 
 
 ###############################################################################
@@ -2038,9 +2313,12 @@ command.go.*.go=./$(FileName)
 # Csound files
 file.patterns.csound=*.orc;*.sco;*.csd
 filter.csound=Csound (orc sco csd)|$(file.patterns.csound)|
+*filter.csound=$(filter.csound)
 
 lexer.$(file.patterns.csound)=csound
 
+*language.csound=Csound|orc||
+
 # Csound opcodes
 
 # This list was extracted from Csound_opcodes.vim which can be found here:
@@ -2155,11 +2433,13 @@ comment.block.csound=;
 ###############################################################################
 # From css.properties
 # Define SciTE settings for CSS files
-# Jakub Vrána - jakub vrana cz
+# Jakub Vr�na - jakub vrana cz
 # Updated Andy Holder - Jan 2011
 
 filter.css=CSS (css)|*.css|
+*filter.css=$(filter.css)
 lexer.*.css=css
+*language.css=CSS|css||
 
 indent.size.*.css=4
 tab.size.*.css=4
@@ -2235,7 +2515,7 @@ ThreeDFace ThreeDHighlight ThreeDLightShadow ThreeDShadow Window WindowFrame Win
 silent x-soft soft medium loud x-loud spell-out mix \
 left-side far-left center-left center-right far-right right-side behind leftwards rightwards \
 below level above higher lower x-slow slow medium fast x-fast faster slower \
-male female child x-low low high x-high code digits continous
+male female child x-low low high x-high code digits continuous
 
 # properties and pseudos starting with -moz- etc.
 keywordclass.vendor.prefixes=^-moz- ^-webkit- ^-o- ^-ms-
@@ -2314,7 +2594,9 @@ block.end.*.css=5 }
 
 file.patterns.d=*.d
 filter.d=D (d)|$(file.patterns.d)|
+*filter.d=$(filter.d)
 lexer.$(file.patterns.d)=d
+*language.d=D|d||
 
 word.chars.d=$(chars.alpha)$(chars.numeric)_#
 word.characters.$(file.patterns.d)=$(word.chars.d)
@@ -2388,6 +2670,8 @@ var verbatim verbinclude version warning weakgroup $ @ \ & < > # { }
 # 12 - char
 # 13 - operator
 # 14 - identifier
+# 15, 16, 17 - Doc comments: line doc /// or //!, doc keyword, doc keyword err
+# 18, 19 stringb, stringr
 # breaces must be operator style to allow matching
 braces.d.style=13
 
@@ -2402,7 +2686,8 @@ command.go.*.d=$(FileName)
 ###############################################################################
 # From ecl.properties
 file.patterns.ecl=*.ecl;*.eclattr;*.hql
-filter.ecl=ECL (ecl, eclattr, hql)|$(file.patterns.ecl)|
+filter.ecl=ECL (ecl eclattr hql)|$(file.patterns.ecl)|
+*filter.ecl=$(filter.ecl)
 lexer.$(file.patterns.ecl)=ecl
 
 word.chars.ecl=$(chars.alpha)$(chars.numeric)_#
@@ -2442,13 +2727,19 @@ keywords6.$(file.patterns.ecl)=#append #break #declare #demangle #end #for #getd
 
 filter.eiffel=Eiffel (e)|*.e|
 
+*filter.eiffel=$(filter.eiffel)
+
 file.patterns.eiffel=*.e
 
+*source.patterns.eiffel=$(file.patterns.eiffel);
+
 # Main Eiffel lexer dows indentation based folding
 lexer.$(file.patterns.eiffel)=eiffel
 # Alternative key word based folding has trouble with redefine and rename clauses
 #lexer.$(file.patterns.eiffel)=eiffelkw
 
+*language.eiffel=&Eiffel|e||
+
 # These keywords are case insensitive although Eiffel has conventions for
 # keywords, predefined names and predefined classes: alias, Current, BOOLEAN
 # Could differentiate between these
@@ -2472,7 +2763,7 @@ keywords.$(file.patterns.eiffel)=$(keywordclass.eiffel)
 braces.eiffel.style=6
 braces.eiffelkw.style=$(braces.eiffel.style)
 
-statement.indent.$(file.patterns.eiffel)=5 do else elsif rescue if is loop
+statement.indent.$(file.patterns.eiffel)=3 do else elsif rescue if is loop
 statement.end.$(file.patterns.eiffel)=10 ;
 statement.lookback.$(file.patterns.eiffel)=20
 block.start.$(file.patterns.eiffel)=10 check debug deferred do from if inspect once
@@ -2491,8 +2782,12 @@ file.patterns.erlang=*.erl;*.hrl
 # M: Erlang M-Files
 filter.erlang=Erlang (erl hrl)|$(file.patterns.erlang)|
 
+*filter.erlang=$(filter.erlang)
+
 lexer.$(file.patterns.erlang)=erlang
 
+#*language.erlang=Erlang|erl||
+
 # Reserved Erlang words
 keywords.$(file.patterns.erlang)=after and andalso band begin bnot bor bsl bsr bxor case catch cond div end 
fun if let not of or orelse query receive rem try when xor
 # Erlang built-in functions (BIFs)
@@ -2534,6 +2829,8 @@ ECOMPILEHOME=C:\Daten\Code\CVS Workspace\etheria-pol095\scripts
 #
 filter.escript=E-Script (src em)|$(file.patterns.escript)|
 #filter.escript=E-Script (src inc cfg em)|$(file.patterns.escript)|
+*filter.escript=$(filter.escript)
+
 file.patterns.escript=*.src;*.em
 #file.patterns.escript=*.src;*.inc;*.cfg;*.em
 
@@ -2857,6 +3154,8 @@ file.patterns.flagship=*.prg
 
 lexer.$(file.patterns.flagship)=flagship
 
+*language.flagship=FlagShip|prg||
+
 # FlagShip 6 Commands
 keywordclass.fs6commands=\
 ? @ accept access all alternate announce ansi any append as assign autolock average \
@@ -3016,8 +3315,12 @@ file.patterns.forth=*.forth
 
 lexer.$(file.patterns.forth)=forth
 
+*language.forth=Forth|forth||
+
 filter.forth=Forth files (f spf)|$(file.patterns.forth)|
 
+*filter.forth=$(filter.forth)
+
 word.characters.$(file.patterns.forth)=$(chars.alpha)$(chars.numeric)%-
 
 comment.block.forth=\
@@ -3089,6 +3392,8 @@ S" ABORT" Z" " ." C"
 
 filter.fortran=Fortran (f for f90 f95 f2k)|*.f;*.for;*.f90;*.f95;*.f2k|
 
+*filter.fortran=$(filter.fortran)
+
 file.patterns.f95=*.f90;*.f95;*.f2k
 file.patterns.f77=*.f;*.for
 file.patterns.fortran=$(file.patterns.f95);$(file.patterns.f77)
@@ -3096,6 +3401,8 @@ file.patterns.fortran=$(file.patterns.f95);$(file.patterns.f77)
 lexer.$(file.patterns.f95)=fortran
 lexer.$(file.patterns.f77)=f77
 
+*language.fortran=&Fortran|f90||
+
 # keywords and input/output specifiers
 keywordclass.fortran=access action advance allocatable allocate \
 apostrophe assign assignment associate asynchronous backspace \
@@ -3108,7 +3415,7 @@ endselect endsubroutine endtype endwhere entry eor equivalence \
 err errmsg exist exit external file flush fmt forall form format \
 formatted function go goto id if implicit in include inout \
 integer inquire intent interface intrinsic iomsg iolength \
-iostat kind len logical module name named namelist nextrec nml \
+iostat is kind len logical module name named namelist nextrec nml \
 none nullify number only open opened operator optional out pad \
 parameter pass pause pending pointer pos position precision \
 print private procedure program protected public quote read readwrite \
@@ -3212,8 +3519,12 @@ file.patterns.freebasic=*.bas;*.bi
 
 filter.freebasic=FreeBasic (bb bi)|$(file.patterns.freebasic)|
 
+*filter.freebasic=$(filter.freebasic)
+
 lexer.$(file.patterns.freebasic)=freebasic
 
+*language.freebasic=FreeBasic|bas||
+
 # keywords must be all lowercase
 
 keywordclass.freebasic=\
@@ -3269,8 +3580,12 @@ file.patterns.gap=*.g;*.gd;*.gi
 # GAP files
 filter.gap=Gap (g gi gd)|$(file.patterns.gap)|
 
+*filter.gap=$(filter.gap)
+
 lexer.$(file.patterns.gap)=gap
 
+*language.gap=Gap|g||
+
 keywords.$(file.patterns.gap)=and break continue do elif else end fi for function \
 if in local mod not od or quit rec repeat return then until while QUIT
 
@@ -3294,6 +3609,12 @@ braces.gap.style=8
 lexer.*.hs=haskell
 filter.hs=Haskell (hs)|*.hs|
 
+*filter.hs=$(filter.hs)
+
+*language.haskell=Haskell|hs||
+
+
+# Available in literatehaskell lexer:
 
 # keywords for Haskell 98
 keywordclass.haskell98=case class data default deriving do else hiding if \
@@ -3311,13 +3632,44 @@ keywords2.*.hs=$(keywordclass.ffi)
 
 
 ###############################################################################
+# From hex.properties
+# Define SciTE settings for Motorola S-Record and Intel HEX files.
+
+file.patterns.srec=*.mot;*.srec
+file.patterns.ihex=*.hex
+file.patterns.tehex=*.tek
+
+filter.srec=S-Record (mot)|$(file.patterns.srec)|
+filter.ihex=Intel HEX (hex)|$(file.patterns.ihex)|
+filter.tehex=Tektronix extended HEX (tek)|$(file.patterns.tehex)|
+
+*filter.srec=$(filter.srec)
+*filter.ihex=$(filter.ihex)
+*filter.tehex=$(filter.tehex)
+
+lexer.$(file.patterns.srec)=srec
+lexer.$(file.patterns.ihex)=ihex
+lexer.$(file.patterns.tehex)=tehex
+
+*language.srecord=S-Record|mot||
+*language.intelhex=Intel HEX|hex||
+*language.tektronixhex=Tektronix extended HEX|tek||
+
+# .11 N/A
+
+# .8 N/A
+
+# .14 N/A
+
+
+
+###############################################################################
 # From html.properties
 # Define SciTE settings for HTML files.
 
 # vxml added by lseredi
 
-# tpl is X and Mail specific
-file.patterns.web=*.html;*.htm;*.asp;*.shtml;*.htd;*.jsp
+file.patterns.web=*.html;*.htm;*.asp;*.shtml;*.htd;*.jsp;*.xhtml
 file.patterns.php=*.php3;*.phtml;*.php
 file.patterns.html=$(file.patterns.web);$(file.patterns.php);*.htt;*.cfm;*.tpl;*.dtd;*.hta
 file.patterns.vxml=*.vxml
@@ -3325,6 +3677,10 @@ file.patterns.xml=*.xml;*.xsl;*.svg;*.xul;*.xsd;*.dtd;*.xslt;*.axl;*.xrc;*.rdf
 file.patterns.docbook=*.docbook
 file.patterns.mako=*.mak;*.mako
 
+*source.patterns.cgi=*.cgi;
+*source.patterns.html=$(file.patterns.web);
+*source.patterns.xml=$(file.patterns.xml);
+
 lexer.$(file.patterns.html)=hypertext
 lexer.$(file.patterns.vxml)=hypertext
 lexer.$(file.patterns.xml)=xml
@@ -3334,6 +3690,13 @@ lexer.$(file.patterns.mako)=hypertext
 filter.web=Web (html htm asp shtml css xml docbook jsp)|$(file.patterns.web);*.css;*.xml;*.docbook|
 filter.php=PHP (php php3 phtml)|$(file.patterns.php)|
 
+*filter.web=$(filter.web)
+*filter.php=$(filter.php)
+
+*language.html=H&ypertext|html|$(keyHTML)|
+*language.php=P&HP|php||
+*language.xml=&XML|xml|$(keyXML)|
+
 fold.html=1
 #fold.html.preprocessor=0
 #fold.hypertext.comment=1
@@ -3549,10 +3912,14 @@ keywords.$(file.patterns.docbook)=$(keywordclass.docbook)
 keywords6.$(file.patterns.docbook)=ELEMENT DOCTYPE ATTLIST ENTITY NOTATION
 # END DocBook
 
-word.characters.$(file.patterns.html)=$(chars.alpha)$(chars.numeric)_-
+word.characters.$(file.patterns.html)=$(chars.alpha)$(chars.numeric)$(chars.accented)_-$
 comment.stream.start.hypertext=<!--
 comment.stream.end.hypertext=-->
 comment.block.hypertext=//~
+comment.block.at.line.start.hypertext=1
+
+comment.box.start.xml=
+comment.stream.start.xml=
 
 # No keyword for xml, as it accepts any keyword
 keywords.$(file.patterns.xml)=
@@ -3568,6 +3935,15 @@ keywords2.$(file.patterns.vxml)=$(keywordclass.javascript)
 
 word.characters.$(file.patterns.vxml)=$(chars.alpha)$(chars.numeric)_-
 
+# Define the background colours for SGML and each scripting language
+colour.hypertext.sgml.back=back:#EFEFFF
+colour.hypertext.server.javascript.back=back:#DFDF7F
+colour.hypertext.client.vbs.back=back:#EFEFFF
+colour.hypertext.server.vbs.back=back:#CFCFEF
+colour.hypertext.client.python.back=back:#EFFFEF
+colour.hypertext.server.python.back=back:#CFEFCF
+colour.hypertext.server.php.back=back:#FFF8F8
+
 # HTML and XML share lexing code so use the same style numbers
 # Hypertext Markup Language
 
@@ -3616,8 +3992,12 @@ file.patterns.inno=*.iss;*.isl
 
 filter.inno=Inno Setup (iss isl)|$(file.patterns.inno)|
 
+*filter.inno=$(filter.inno)
+
 lexer.$(file.patterns.inno)=inno
 
+*language.innosetup=&InnoSetup|iss||
+
 comment.block.inno=;~
 
 # Sections
@@ -3697,6 +4077,33 @@ keywords6.$(file.patterns.inno)=
 
 
 ###############################################################################
+# From json.properties
+# Define SciTE settings for JSON files.
+
+file.patterns.json=*.json;*.eslintrc;*.jshintrc;*.jsonld
+*source.patterns.json=$(file.patterns.json);
+
+filter.json=JSON (json eshintrc jshintrc)|$(file.patterns.json)|
+*filter.json=$(filter.json)
+
+lexer.$(file.patterns.json)=json
+
+*language.json=JSON|json||
+
+lexer.json.allow.comments=1
+lexer.json.escape.sequence=1
+
+# JSON keywords
+keywords.$(file.patterns.json)=false true null
+
+# JSON-LD keywords
+keywords2.$(file.patterns.json)=@id @context @type @value @language @container \
+@list @set @reverse @index @base @vocab @graph
+
+
+
+
+###############################################################################
 # From kix.properties
 # Define SciTE settings for Assembler files
 # Black Horus blackhorus gmx net
@@ -3705,9 +4112,13 @@ keywords6.$(file.patterns.inno)=
 file.patterns.kix=*.kix
 filter.kix=Kix-Script (kix)|$(file.patterns.kix)|
 
+*filter.kix=$(filter.kix)
+
 #lexer.$(file.patterns.kix)=asm
 lexer.$(file.patterns.kix)=kix
 
+*language.kix=&Kix|kix||
+
 # These keywords are commands
 keywords.$(file.patterns.kix)=? and beep big break call cd cls color cookie1 copy \
        debug del dim display do until exit flushkb for each next function endfunction \
@@ -3731,7 +4142,7 @@ keywords2.$(file.patterns.kix)=abs addkey addprinterconnection addprogramgroup \
        trim ubound ucase unloadhive val vartype vartypename writeline \
        writeprofilestring writevalue
 
-# This keywords are macros if preceeded by @
+# This keywords are macros if preceded by @
 keywords3.$(file.patterns.kix)=address build color comment cpu crlf csd curdir \
        date day domain dos error fullname homedir homedrive homeshr hostname \
        inwin ipaddress0 ipaddress1 ipaddress2 ipaddress3 kix lanroot ldomain \
@@ -3766,6 +4177,8 @@ file.patterns.latex=*.tex;*.sty
 
 filter.latex=LaTeX (tex sty)|$(file.patterns.latex)|
 
+*filter.latex=$(filter.latex)
+
 lexer.$(file.patterns.latex)=latex
 
 # LaTeX styles
@@ -3792,9 +4205,14 @@ filter.lisp=LISP (lsp lisp)|$(file.patterns.lisp)|
 file.patterns.scheme=*.scm;*.smd;*.ss
 filter.scheme=Scheme (scm smd)|$(file.patterns.scheme)|
 
+#*filter.lisp=$(filter.lisp)
+#*filter.scheme=$(filter.scheme)
+
 lexer.$(file.patterns.lisp)=lisp
 lexer.$(file.patterns.scheme)=lisp
 
+*language.lisp=Lisp|lisp||
+
 # lisp build in functions, xlisp dialect
 keywords.$(file.patterns.lisp)= not defun + - * / = < > <= >= princ \
 eval apply funcall quote identity function complement backquote lambda set setq setf \
@@ -3887,8 +4305,12 @@ file.patterns.lot=*.lot
 
 filter.lot=Lot (lot)|$(file.patterns.lot)|
 
+*filter.lot=$(filter.lot)
+
 lexer.$(file.patterns.lot)=lot
 
+*language.lot=Lot|lot||
+
 word.characters.$(file.patterns.lot)=$(chars.alpha)$(chars.numeric)
 
 # LOT FileStyles
@@ -3905,8 +4327,12 @@ file.patterns.lout=*.lt
 
 filter.lout=Lout (lt)|*.lt|
 
+*filter.lout=$(filter.lout)
+
 lexer.$(file.patterns.lout)=lout
 
+*language.lout=Lout|lt||
+
 # @-prefixed keywords
 keywords.$(file.patterns.lout)= \
 @OptGall @FontDef @Family @Face @Name @Metrics @ExtraMetrics \
@@ -3969,12 +4395,18 @@ if PLAT_GTK
 
 file.patterns.lua=*.lua
 
+*source.patterns.lua=$(file.patterns.lua);
+
 shbang.lua=lua
 
 filter.lua=Lua (lua)|$(file.patterns.lua)|
 
+*filter.lua=$(filter.lua)
+
 lexer.$(file.patterns.lua)=lua
 
+*language.lua=Lu&a|lua||
+
 word.chars.lua=$(chars.alpha)$(chars.numeric)$(chars.accented)_%
 word.characters.$(file.patterns.lua)=$(word.chars.lua)
 
@@ -4129,30 +4561,73 @@ keywordclass5.lua52=$(keywordclass5.lua50) \
 debug.getmetatable debug.getregistry debug.setmetatable \
 debug.getuservalue debug.setuservalue debug.upvalueid debug.upvaluejoin
 
+#### Lua 5.3.0
+
+# Keywords
+keywordclass.lua53=$(keywordclass.lua50) goto
+
+# Basic Functions
+keywordclass2.lua53=$(keywordclass2.lua5) \
+load rawlen select package utf8 _ENV
+
+# String, UTF8, Table , Mathematical
+keywordclass3.utf8=\
+utf8.char utf8.charpattern utf8.codes \
+utf8.codepoint utf8.len utf8.offset
+
+keywordclass3.lua53=\
+string.byte string.char string.dump string.find string.format \
+string.gmatch string.gsub string.len string.lower string.match \
+string.pack string.packsize string.rep \
+string.reverse string.sub string.unpack string.upper \
+table.concat table.insert table.move table.pack \
+table.remove table.sort table.unpack \
+math.abs math.acos math.asin math.atan \
+math.ceil math.cos math.deg math.exp \
+math.floor math.fmod math.huge \
+math.log math.max math.maxinteger math.min math.mininteger \
+math.modf math.pi math.rad \
+math.random math.randomseed math.sin \
+math.sqrt math.tan \
+math.tointeger math.type math.ult \
+$(keywordclass3.utf8)
+
+# Coroutine, Input/Output, System, Package
+keywordclass4.lua53=$(keywordclass4.lua50) \
+coroutine.isyieldable coroutine.running io.popen \
+package.config package.searchers package.searchpath \
+$(keywordclass4.package)
+
+# Debug (not enabled by default)
+keywordclass5.lua53=$(keywordclass5.lua52)
+
 #### Lua 5.x
 
 # Keywords
-keywordclass.lua5x=$(keywordclass.lua52)
+keywordclass.lua5x=$(keywordclass.lua53)
 
 # Basic Functions
 keywordclass2.lua5x=$(keywordclass2.lua5) \
 getfenv gcinfo load loadlib loadstring \
 require select setfenv unpack \
 _LOADED LUA_PATH _REQUIREDNAME \
-package rawlen package bit32 _ENV
+package rawlen package bit32 utf8 _ENV
 
 # String, Table , Mathematical, Bitwise
 keywordclass3.lua5x=$(keywordclass3.lua5) \
 string.gfind string.gmatch string.match string.reverse \
+string.pack string.packsize string.unpack \
 table.foreach table.foreachi table.getn table.setn \
-table.maxn table.pack table.unpack \
+table.maxn table.pack table.unpack table.move \
 math.cosh math.fmod math.huge math.log10 math.modf \
-math.mod math.sinh math.tanh \
-$(keywordclass3.bit32)
+math.mod math.sinh math.tanh math.maxinteger math.mininteger \
+math.tointeger math.type math.ult \
+$(keywordclass3.bit32) \
+$(keywordclass3.utf8)
 
 # Coroutine, Input/Output, System, Package
 keywordclass4.lua5x=$(keywordclass4.lua50) \
-coroutine.running io.popen \
+coroutine.isyieldable coroutine.running io.popen \
 module package.loaders package.seeall \
 package.config package.searchers package.searchpath \
 $(keywordclass4.package)
@@ -4163,7 +4638,7 @@ debug.getfenv debug.getmetatable debug.getregistry debug.setfenv debug.setmetata
 debug.getuservalue debug.setuservalue debug.upvalueid debug.upvaluejoin
 
 # Keyword highlighting selection
-# Options: lua4, lua50, lua51, lua52, lua5x (default)
+# Options: lua4, lua50, lua51, lua52, lua53, lua5x (default)
 # or enable everything like this: $(keywordclass.lua4)$(keywordclass.lua5x)
 keywords.$(file.patterns.lua)=$(keywordclass.lua5x)
 keywords2.$(file.patterns.lua)=$(keywordclass2.lua5x)
@@ -4220,27 +4695,47 @@ filter.octave=Octave (m)|$(file.patterns.octave)|
 
 lexer.$(file.patterns.octave)=octave
 
+#*language.octave=Octave|m.octave||
+
 keywordclass.octave=\
+__FILE__ \
+__LINE__ \
 break \
 case \
 catch \
+classdef \
 continue \
 do \
 else \
 elseif \
 end \
+end_try_catch \
 end_unwind_protect \
+endclassdef \
+endenumeration \
+endevents \
 endfor \
 endif \
+endmethods \
+endparfor \
+endproperties \
 endswitch \
 endwhile \
+enumeration \
+events \
 for \
 function endfunction \
+get \
 global \
 if \
+methods \
 otherwise \
+parfor \
 persistent \
+properties \
 return \
+set \
+static \
 switch \
 try \
 until \
@@ -4265,8 +4760,12 @@ file.patterns.matlab=*.m.matlab
 # M: Matlab M-Files
 filter.matlab=Matlab (m)|$(file.patterns.matlab)|
 
+*filter.matlab=$(filter.matlab)
+
 lexer.$(file.patterns.matlab)=matlab
 
+*language.matlab=Matlab|m.matlab||
+
 keywordclass.matlab=break case catch continue else elseif end for function \
 global if otherwise persistent return switch try while
 
@@ -4290,12 +4789,16 @@ comment.block.matlab=%~
 file.patterns.metapost=*.mp;*.mpx
 file.patterns.metafun=*.mp;*.mpx;*.mpy
 
-filter.metapost=MetaPost|$(file.patterns.metapost)|
-filter.metafun=MetaFun|$(file.patterns.metafun)|
+filter.metapost=MetaPost (mp mpx)|$(file.patterns.metapost)|
+filter.metafun=MetaFun (mp mpx mpy)|$(file.patterns.metafun)|
+
+*filter.metapost=$(filter.metapost)
 
 lexer.$(file.patterns.metapost)=metapost
 lexer.$(file.patterns.metafun)=metapost
 
+*language.metapost=MetaPost|mp||
+
 # Metapost: commands (check process view)
 
 command.compile.$(file.patterns.metapost)=
@@ -4460,9 +4963,12 @@ import metafun-scite.properties
 
 file.patterns.mmixal=*.mms
 filter.mmixal=MMIXAL (mms)|$(file.patterns.mmixal)|
+*filter.mmixal=$(filter.mmixal)
 
 lexer.$(file.patterns.mmixal)=mmixal
 
+*language.mmixal=MMIXAL|mms||
+
 opcodes=2ADDU 4ADDU 8ADDU 16ADDU ADD ADDU AND ANDNH ANDNL ANDNMH ANDNML \
        BDIF BEV BN BNN BNP BNZ BOD BP BSPEC BYTE BZ CMP CMPU CSEV CSN CSNN CSNP CSNZ CSOD CSP CSWAP CSZ \
        DIV DIVU ESPEC EXPR FADD FCMP FCMPE FDIV FEQL FEQLE FIX FIXU FLOT FLOTU FMUL FREM FSQRT FSUB FUN FUNE 
\
@@ -4513,7 +5019,9 @@ command.2.$(file.patterns.mmixal)=mmotype $(FileName).mmo $(FileName).out
 file.patterns.m3=*.m3;*.mg;*.i3;*.ig
 
 filter.modula3=Modula-3 (m3 i3 mg ig)|$(file.patterns.m3)|
+*filter.modula3=$(filter.modula3)
 lexer.$(file.patterns.m3)=modula
+*language.modula3=Modula-3|m3||
 
 #      Keywords
 #
@@ -4634,6 +5142,8 @@ shbang.nimrod=nim
 
 filter.nimrod=Nimrod (nim)|$(file.patterns.nimrod)|
 
+*filter.nimrod=$(filter.nimrod)
+
 lexer.$(file.patterns.nimrod)=nimrod
 
 keywordclass.nimrod=addr and as asm \
@@ -4684,7 +5194,7 @@ if PLAT_GTK
        command.go.*.nim=nimrod c -r "$(FileNameExt)"
 
 command.name.1.*.nim=Syntax Check
-command.1.*.nim=nimrod check $(FilePath)
+command.1.*.nim=nimrod check "$(FilePath)"
 
 # compile
 command.compile.*.nim=nimrod c "$(FilePath)"
@@ -4704,13 +5214,17 @@ command.build.subsystem.*.nim=1
 # (http://nemtsev.eserv.ru/)
 
 file.patterns.nncron=*.tab;*.spf
-# add '*.tab;*.spf;' to 'source.files' variable in 'SciTEGlobal.properties' 
+# add '*.tab;*.spf;' to 'source.files' variable in 'SciTEGlobal.properties'
 # if you want to include these file patterns into default source file list
 
 lexer.$(file.patterns.nncron)=nncrontab
 
+*language.nnCron=&nnCron crontab|tab||
+
 filter.nncrontab=nnCron files (tab spf)|$(file.patterns.nncron)|
 
+*filter.nncrontab=$(filter.nncrontab)
+
 word.characters.$(file.patterns.nncron)=$(chars.alpha)$(chars.numeric)%-
 
 comment.block.nncrontab=\ 
@@ -4722,7 +5236,7 @@ keywords.$(file.patterns.nncron)=\
 AGAIN ALLOT AND Action BEGIN CASE COMPARE CONSTANT CREATE DO Days ELSE \
 ENDCASE ENDOF EVAL-SUBST EVALUATE FALSE Hours I IF LEAVE LOOP Minutes \
 Months NOT OF OFF ON OR PAD REPEAT Rule SET THEN TRUE Time UNTIL VALUE \
-VARIABLE WHILE WeekDays Years 
+VARIABLE WHILE WeekDays Years
 
 # Keywords for nnCrontab
 keywords2.$(file.patterns.nncron)=\
@@ -4750,7 +5264,7 @@ WIN-MINIMIZE WIN-MOVE WIN-MOVER WIN-RESTORE WIN-SEND-KEYS WIN-SHOW \
 WIN-TERMINATE WIN-TOPMOST WIN-VER WIN-WAIT WINAPI WRITE-DATE WatchClipboard \
 WatchConnect WatchDir WatchDisconnect WatchDriveInsert WatchDriveRemove \
 WatchFile WatchProc WatchProcStop WatchWinActivate WatchWinCreate \
-WatchWinDestroy WatchWindow WinNT Year@ Yes 
+WatchWinDestroy WatchWindow WinNT Year@ Yes
 
 # Modifiers for nnCrontab
 keywords3.$(file.patterns.nncron)=\
@@ -4760,8 +5274,7 @@ NormalPriority OnceADay OnceAHour OnceAMonth OnceAWeek RECURSIVE \
 RealtimePriority RunOnce SWHide ShowMaximized ShowMinimized ShowNoActivate \
 ShowNormal StartIn StartPos StartSize TODEPTH WATCH-CHANGE-ATTRIBUTES \
 WATCH-CHANGE-DIR-NAME WATCH-CHANGE-FILE-NAME WATCH-CHANGE-LAST-WRITE \
-WATCH-CHANGE-SECURITY WATCH-CHANGE-SIZE WaitFor WatchSubtree WithoutProfile 
-
+WATCH-CHANGE-SECURITY WATCH-CHANGE-SIZE WaitFor WatchSubtree WithoutProfile
 
 
 
@@ -4775,8 +5288,10 @@ WATCH-CHANGE-SECURITY WATCH-CHANGE-SIZE WaitFor WatchSubtree WithoutProfile
 # Updated for NSIS v.2.05 and latest lexer / 2005-3-10 by Angelo Mandato <angelo at spaceblue dot com>
 
 filter.nsis=NSIS (nsi nsh)|*.nsi;*.nsh|
+*filter.nsis=$(filter.nsis)
 file.patterns.nsis=*.nsi;*.nsh
 lexer.$(file.patterns.nsis)=nsis
+*language.nsis=NSIS|nsis||
 
 # Advanced settings
 nsis.uservars=1
@@ -4879,8 +5394,11 @@ comment.box.end.nsis=*/
 
 filter.opal=OPAL (impl sign)|*.impl;*.sign|
 
+*filter.opal=$(filter.opal)
+
 file.patterns.opal=*.impl;*.sign
 lexer.$(file.patterns.opal)=opal
+*language.opal=Opal|impl||
 
 keywordclass.opal_keywords=ALL AND ANDIF ANY AS ASSERT AXM COMPLETELY DATA DEF DERIVE \
 DFD DISCRIMINATORS ELSE EX EXTERNAL FI FIX FUN IF IMPLEMENTATION IMPLIES IMPORT \
@@ -4905,7 +5423,7 @@ scrollWindow searchOpt second seekMode selector semaphor seq seqEntry set \
 setEntry short sigaction sighandler sigmask signal size sizeRequest some \
 sreal state stateId stateRequest string subrel tag textEditor time to tree \
 triple union user userid version view void wconfig wconfigCom wday widget \
-window wrapStyle 
+window wrapStyle
 
 keywords.$(file.patterns.opal)=$(keywordclass.opal_keywords)
 keywords2.$(file.patterns.opal)=$(keywordclass.opal_sorts)
@@ -4927,6 +5445,7 @@ keywords2.$(file.patterns.opal)=$(keywordclass.opal_sorts)
 
 file.patterns.oscript=*.osx
 filter.oscript=OScript (osx)|$(file.patterns.oscript)|
+*filter.oscript=$(filter.oscript)
 lexer.$(file.patterns.oscript)=oscript
 
 ##############################################################################
@@ -5084,23 +5603,41 @@ if PLAT_WIN
 # From others.properties
 # Define SciTE settings for other simple files.
 
-file.patterns.props=*.properties;*.session;*.ini;*.inf;*.reg;*.url;*.cfg;*.cnf;*.aut
+file.patterns.props=*.properties;*.session;*.ini;*.inf;*.url;*.cfg;*.cnf;*.aut
 file.patterns.text=*.txt;*.log;*.lst;*.doc;*.diz;*.nfo
 file.patterns.batch=*.bat;*.cmd;*.nt
 file.patterns.diff=*.diff;*.patch
 file.patterns.make=makefile;Makefile;*.mak;configure
+file.patterns.indent=*.indent
+
+*source.patterns.props=$(file.patterns.props);
+*source.patterns.batch=$(file.patterns.batch);
+*source.patterns.diff=$(file.patterns.diff);
+*source.patterns.make=$(file.patterns.make);*.iface;
 
 filter.properties=Properties (ini inf reg url cfg cnf)|$(file.patterns.props)|
 filter.text=Text (txt log lst doc diz nfo)|$(file.patterns.text);make*|
 filter.batch=Batch (bat cmd nt)|$(file.patterns.batch)|
 filter.diff=Difference (diff patch)|$(file.patterns.diff)|
 
+*filter.properties=$(filter.properties)
+*filter.text=$(filter.text)
+
 lexer.$(file.patterns.props)=props
 lexer.$(file.patterns.batch)=batch
 lexer.*.err=errorlist
 lexer.$(file.patterns.make)=makefile
 lexer.*.iface=makefile
 lexer.$(file.patterns.diff)=diff
+lexer.$(file.patterns.indent)=indent
+
+*language.batch=&Batch|bat||
+*language.difference=&Difference|diff||
+*language.errorlist=&Errorlist|err||
+*language.properties=&Properties|properties||
+*language.makefile=&Makefile|mak|$(keyMake)|
+*language._text=Text|txt|$(keyText)|
+*language.indent=Indent|indent|$(keyIndent)|
 
 word.characters.$(file.patterns.text)=$(chars.alpha)$(chars.numeric)$(chars.accented)-'
 
@@ -5116,16 +5653,19 @@ preprocessor.end.$(file.patterns.make)=ENDIF
 
 # Batch styles
 
-# List from http://www.easydos.com/dosindex.html
+# List from http://www.easydos.com/dosindex.html and https://sourceforge.net/p/scintilla/bugs/1686/
 # I limit here the commands to those built in command.com, ie. I don't list external Dos commands
 # if [no] (test) (command) -- test is EXIST (filename) | (string1)==(string2) | ERRORLEVEL (number)
 # for %%(variable) IN (set) DO (command) -- variable is [a-zA-Z] -- eg for %%X in (*.txt) do type %%X
-keywordclass.batch=rem set if exist errorlevel for in do \
-break call chcp cd chdir choice cls country ctty date del erase dir echo \
-exit goto loadfix loadhigh mkdir md move path pause prompt rename ren \
-rmdir rd shift time type ver verify vol \
-com con lpt nul \
-color copy defined else not start
+# Also includes device names.
+keywordclass.batch=\
+assoc aux break call cd chcp chdir choice cls cmdextversion \
+color com1 com2 com3 com4 con copy ctty date defined \
+del dir do dpath echo else endlocal erase errorlevel exist \
+exit for ftype goto if in lpt1 lpt2 lpt3 lpt4 md mkdir move \
+not nul path pause popd prompt prn pushd rd rem ren \
+rename rmdir set setlocal shift start time title type ver \
+verify vol
 keywords.$(file.patterns.batch)=$(keywordclass.batch)
 
 # Optional list of external commands to highlight in style 5.
@@ -5141,7 +5681,10 @@ comment.block.batch=REM ~
 comment.block.makefile=#~
 
 
+error.background=back:#FFF7E7,eolfilled
+
 lexer.errorlist.value.separate=1
+#lexer.errorlist.escape.sequences=1
 
 # Difference styles
 
@@ -5166,24 +5709,28 @@ if PLAT_WIN
 # Define SciTE settings for Pascal files.
 # Changed by Fernando Lozano <fsl centroin com br> for Free Pascal
 # Changed by Mathias Rauen <scite madshi net> for Delphi
-# Changed by Marko Njezic <sf maxempire com> to match new LexPascal lexer and updated for Delphi 2009
+# Changed by Marko Njezic <sf maxempire com> to match new LexPascal lexer and updated for Delphi XE4
 
 filter.pascal=Pascal (dpr dpk pas dfm inc pp)|*.dpr;*.dpk;*.pas;*.dfm;*.inc;*.pp|
 
+*filter.pascal=$(filter.pascal)
+
 file.patterns.pascal=*.dpr;*.pas;*.dfm;*.inc;*.pp
 file.patterns.pascal.package=*.dpk
 file.patterns.pascal.all=$(file.patterns.pascal);$(file.patterns.pascal.package)
 lexer.$(file.patterns.pascal.all)=pascal
+*language.pascal=Pascal|pas||
 
 keywordclass.pascal=absolute abstract and array as asm assembler automated begin case \
-cdecl class const constructor deprecated destructor dispid dispinterface div do downto \
-dynamic else end except export exports external far file final finalization finally for \
-forward function goto if implementation in inherited initialization inline interface is \
-label library message mod near nil not object of on or out overload override packed \
-pascal platform private procedure program property protected public published raise \
-record register reintroduce repeat resourcestring safecall sealed set shl shr static \
-stdcall strict string then threadvar to try type unit unsafe until uses var varargs \
-virtual while with xor
+cdecl class const constructor 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 in inherited initialization inline interface is label library \
+message mod near nil not object of on operator or out overload override packed \
+pascal platform private procedure program property protected public published \
+raise record reference register reintroduce repeat resourcestring safecall \
+sealed set shl shr static stdcall strict string then threadvar to try type unit \
+unsafe until uses var varargs virtual while winapi with xor
 
 keywordclass.pascal.smart=add default implements index name nodefault read readonly \
 remove stored write writeonly
@@ -5203,8 +5750,6 @@ lexer.pascal.smart.highlighting=1
 # Braces are only matched in operator style
 braces.pascal.style=13
 
-
-
 comment.block.pascal=//~
 comment.stream.start.pascal={
 comment.stream.end.pascal=}
@@ -5257,11 +5802,13 @@ if PLAT_GTK
 # From perl.properties
 # Define SciTE settings for Perl, Bash, and AWK files.
 
-
 file.patterns.perl=*.pl;*.pm;*.pod
 file.patterns.bash=*.sh;*.bsh;configure;*.ksh
 file.patterns.awk=*.awk
 
+*source.patterns.perl=$(file.patterns.perl);
+*source.patterns.bash=$(file.patterns.bash);
+
 shbang.perl=pl
 shbang.sh=sh
 shbang.bash=sh
@@ -5274,6 +5821,12 @@ filter.perl=Perl (pl pm)|$(file.patterns.perl)|
 filter.bash=Bash (sh bsh)|$(file.patterns.bash)|
 filter.awk=GAWK  (awk)|$(file.patterns.awk)|
 
+*filter.perl=$(filter.perl)
+*filter.bash=$(filter.bash)
+
+*language.perl=Pe&rl|pl||
+*language.shell=Shell|sh||
+
 lexer.$(file.patterns.perl)=perl
 lexer.$(file.patterns.bash)=bash
 lexer.$(file.patterns.awk)=perl
@@ -5418,6 +5971,8 @@ file.patterns.pov=*.pov;*.inc
 
 filter.pov=POV-Ray SDL (pov)|$(file.patterns.pov)|
 
+*filter.pov=$(filter.pov)
+
 indent.size.*.pov=2
 tab.size.*.pov=2
 use.tabs.*.pov=0
@@ -5427,6 +5982,8 @@ use.tabs.*.inc=0
 
 lexer.$(file.patterns.pov)=pov
 
+*language.povray=P&OV-Ray SDL|pov||
+
 word.chars.pov=$(chars.alpha)$(chars.numeric)_#
 word.characters.$(file.patterns.pov)=$(word.chars.pov)
 
@@ -5573,7 +6130,9 @@ if PLAT_WIN
 file.patterns.powerpro=*.powerpro
 
 filter.powerpro=PowerPro (powerpro)|$(file.patterns.powerpro)|
+*filter.powerpro=$(filter.powerpro)
 lexer.$(file.patterns.powerpro)=powerpro
+*language.powerpro=PowerPro|powerpro||
 
 keywordclass.control=\
 break do else elseif endfor endif for function global gt if ifelse \
@@ -5591,7 +6150,7 @@ bar case clip env exec fill flag floattostring format formattime ftos \
 index input inputcancel inputdefault inputdialog join length messagebox mouse \
 not note readline remove replace replacechars replaceg revindex select \
 stof validpath visiblewindow wait wait.activity wait.for wait.forinterval wait.message \
-wait.quit wait.ready wait.sleep wait.until wallpaper window window word 
+wait.quit wait.ready wait.sleep wait.until wallpaper window window word
 
 keywords2.$(file.patterns.powerpro)=$(keywordclass.plugins)|$(keywordclass.functions)
 
@@ -5627,8 +6186,12 @@ file.patterns.powershell=*.ps1
 
 filter.powershell=PowerShell (ps1)|$(file.patterns.powershell)|
 
+*filter.powershell=$(filter.powershell)
+
 lexer.$(file.patterns.powershell)=powershell
 
+*language.powershell=PowerShell|ps1||
+
 word.characters.$(file.patterns.powershell)=$(chars.alpha)$(chars.numeric)_-$
 
 # Keywords
@@ -5722,10 +6285,14 @@ comment.block.at.line.start.powershell=1
 
 file.patterns.ps=*.ps
 
-filter.ps=PS (PostScript)|$(file.patterns.ps)|
+filter.ps=PostScript (ps)|$(file.patterns.ps)|
+
+*filter.ps=$(filter.ps)
 
 lexer.$(file.patterns.ps)=ps
 
+*language.postscript=P&ostScript|ps||
+
 ps.tokenize=0
 ps.level=3
 
@@ -5832,6 +6399,8 @@ file.patterns.purebasic=*.pb
 
 filter.purebasic=PureBasic (pb)|$(file.patterns.purebasic)|
 
+*filter.purebasic=$(filter.purebasic)
+
 lexer.$(file.patterns.purebasic)=purebasic
 
 # keywords must be all lowercase
@@ -5863,16 +6432,22 @@ compilerelse compilerendif compilerendselect compilerif compilerselect
 # From python.properties
 # Define SciTE settings for Python files.
 
-file.patterns.py=*.py;*.pyw
+file.patterns.py=*.py;*.pyw;*.pyx;*.pxd;*.pxi
 file.patterns.scons=SConstruct;SConscript
 
+*source.patterns.python=$(file.patterns.py);
+
 shbang.python=py
 
 filter.python=Python (py pyw)|$(file.patterns.py)|
 
+*filter.python=$(filter.python)
+
 lexer.$(file.patterns.py)=python
 lexer.$(file.patterns.scons)=python
 
+*language.python=Pytho&n|py||
+
 keywordclass.python2=and as assert break class continue def del elif \
 else except exec finally for from global if import in is lambda not \
 or pass print raise return try while with yield
@@ -5897,6 +6472,49 @@ keywords.$(file.patterns.scons)=$(keywordclass.python)
 #keywords2.$(file.patterns.py)=$(keywordclass2.python)
 #keywords2.$(file.patterns.scons)=$(keywordclass2.python)
 
+# Use 2 sets of substyles to highlight standard library modules and
+# imports from the future.
+# Additional identifier sets can be added by incrementing the  next
+# line's value and adding extra definitions similar to below.
+substyles.python.11=2
+
+substylewords.11.1.$(file.patterns.py)=\
+__main__ _dummy_thread _thread abc aifc argparse \
+array ast asynchat asyncio asyncore atexit audioop \
+base64 bdb binascii binhex bisect builtins bz2 \
+calendar cgi cgitb chunk cmath cmd code codecs \
+codeop collections colorsys compileall concurrent \
+configparser contextlib copy copyreg crypt csv \
+ctypes curses datetime dbm decimal difflib dis \
+distutils dummy_threading email ensurepip enum \
+errno faulthandler fcntl filecmp fileinput fnmatch \
+formatter fpectl fractions ftplib functools gc getopt \
+getpass gettext glob grp gzip hashlib heapq hmac \
+html http http imaplib imghdr importlib inspect io \
+ipaddress itertools json keyword linecache locale \
+logging lzma macpath mailbox mailcap marshal math \
+mimetypes mmap modulefinder msilib msvcrt \
+multiprocessing netrc nis nntplib numbers operator \
+os os ossaudiodev parser pathlib pdb pickle \
+pickletools pipes pkgutil platform plistlib poplib posix \
+pprint pty pwd py_compile pyclbr queue quopri \
+random re readline reprlib resource rlcompleter runpy \
+sched select selectors shelve shlex shutil signal site \
+smtpd smtplib sndhdr socket socketserver spwd \
+sqlite3 ssl stat statistics string stringprep struct \
+subprocess sunau symbol symtable sys sysconfig \
+syslog tabnanny tarfile telnetlib tempfile termios \
+textwrap threading time timeit tkinter token \
+tokenize trace traceback tracemalloc tty turtle \
+types unicodedata unittest urllib uu uuid venv warnings \
+wave weakref webbrowser winreg winsound wsgiref \
+xdrlib xml xmlrpc zipfile zipimport zlib
+style.python.11.1=fore:#DD9900
+
+substylewords.11.2.$(file.patterns.py)=__future__ \
+with_statement unicode_literals print_function
+style.python.11.2=fore:#EE00AA,italics
+
 #~ statement.indent.$(file.patterns.py)=10 :
 statement.indent.$(file.patterns.py)=5 class def elif else except finally \
 for if try while with
@@ -5937,8 +6555,8 @@ if PLAT_MAC
        command.build.SConscript=scons --up .
        command.build.SConstruct=scons .
 
-command.name.1.*.py=Syntax Check
-command.1.*.py=python -c "import py_compile; py_compile.compile(r'$(FilePath)')"
+command.name.1.$(file.patterns.py)=Syntax Check
+command.1.$(file.patterns.py)=python -c "import py_compile; py_compile.compile(r'$(FilePath)')"
 
 
 
@@ -5951,8 +6569,12 @@ file.patterns.r.like=$(file.patterns.r)
 
 filter.r=R and S+ (R S rsouce)|$(file.patterns.r)|
 
+*filter.r=$(filter.r)
+
 lexer.$(file.patterns.r)=r
 
+*language.r=R|R||
+
 keywordclass.r=if else repeat while function for in next break TRUE FALSE NULL NA Inf NaN
 
 keywords.$(file.patterns.r)=$(keywordclass.r)
@@ -5988,6 +6610,8 @@ file.patterns.rebol=*.r;*.reb
 
 filter.rebol=REBOL (r)|$(file.patterns.rebol)|
 
+*filter.rebol=$(filter.rebol)
+
 lexer.$(file.patterns.rebol)=rebol
 
 # keywords. Found at http://www.rebol.com/docs/dictionary.html
@@ -6081,7 +6705,7 @@ keywords3.$(file.patterns.rebol)=action! any-block! any-function! any-string! an
  port! refinement! routine! series! set-path! set-word! string! struct! symbol! tag! \
  time! tuple! unset! url! word!
 
-word.chars.rebol=$(chars.alpha)$(chars.numeric)?!.\92+-*&|=_~
+word.chars.rebol=$(chars.alpha)$(chars.numeric)?!.�+-*&|=_~
 word.characters.$(file.patterns.rebol)=$(word.chars.rebol)
 
 comment.block.rebol=;
@@ -6102,17 +6726,38 @@ command.go.$(file.patterns.rebol)=E:\tools\lang\rebol\core\rebol.exe $(FilePath)
 
 
 ###############################################################################
+# From registry.properties
+# Define SciTE settings for registry files.
+
+file.patterns.registry=*.reg
+filter.registry=Registration files (reg)|$(file.patterns.registry)|
+lexer.$(file.patterns.registry)=registry
+
+comment.block.registry=;;
+
+[Styles]
+
+
+
+
+###############################################################################
 # From ruby.properties
 # Define SciTE settings for Ruby files.
 
 file.patterns.rb=*.rb;*.rbw;*.rake;*.rjs;Rakefile
 
+*source.patterns.ruby=$(file.patterns.rb);
+
 shbang.ruby=rb
 
 filter.ruby=Ruby (rb rbw)|$(file.patterns.rb)|
 
+*filter.ruby=$(filter.ruby)
+
 lexer.$(file.patterns.rb)=ruby
 
+*language.ruby=Ruby|rb||
+
 keywordclass.ruby=__FILE__ and def end in or self unless __LINE__ begin \
 defined? ensure module redo super until BEGIN break do false next rescue \
 then when END case else for nil retry true while alias class elsif if \
@@ -6161,11 +6806,59 @@ if PLAT_MAC
 
 
 ###############################################################################
+# From rust.properties
+# Define SciTE settings for Rust
+
+file.patterns.rust=*.rs
+filter.rust=Rust (rs)|$(file.patterns.rust)|
+*filter.rust=$(filter.rust)
+lexer.$(file.patterns.rust)=rust
+*language.rust=Rust|rs||
+
+word.chars.rust=$(chars.alpha)$(chars.numeric)_#
+word.characters.$(file.patterns.rust)=$(word.chars.rust)
+calltip.rust.word.characters=$(chars.alpha)$(chars.numeric)_
+
+comment.block.at.line.start.rust=1
+comment.block.rust=//~
+comment.stream.start.rust=/*
+comment.stream.end.rust=*/
+comment.box.start.rust=/*
+comment.box.middle.rust= *
+comment.box.end.rust= */
+
+statement.indent.$(file.patterns.rust)=6
+statement.end.$(file.patterns.rust)=16 ;
+statement.lookback.$(file.patterns.rust)=20
+block.start.$(file.patterns.rust)=16 {
+block.end.$(file.patterns.rust)=16 }
+braces.rust.style=16
+
+# Rust keywords
+keywords.$(file.patterns.rust)=alignof as be box break const continue crate do else enum extern false fn for 
if impl in let loop match mod mut offsetof once priv proc pub pure ref return self sizeof static struct super 
trait true type typeof unsafe unsized use virtual while yield
+
+# Built-in types
+keywords2.$(file.patterns.rust)=bool char f32 f64 i16 i32 i64 i8 int str u16 u32 u64 u8 uint
+
+# The Self parameter
+keywords3.$(file.patterns.rust)=Self
+
+
+command.compile.*.rs=rustc $(FileNameExt)
+command.build.*.rs=$(make.command)
+command.go.*.rs=./$(FileName)
+
+
+
+
+###############################################################################
 # From scriptol.properties
 # Define SciTE settings for scriptol files.
 
 filter.scriptol=Scriptol (sol)|*.sol|
 
+*filter.scriptol=$(filter.scriptol)
+
 lexer.*.sol=scriptol
 
 file.patterns.sol=*.sol
@@ -6192,8 +6885,6 @@ block.start.*.sol=10
 comment.block.scriptol=`~
 
 # scriptol styles
-# Triple quotes
-# Preprocessor
 
 
 if PLAT_WIN
@@ -6237,7 +6928,9 @@ command.is.filter.4.*.sol=1
 
 file.patterns.smalltalk=*.st
 
-filter.smalltalk=Smalltalk (.st)|$(file.patterns.smalltalk)|
+filter.smalltalk=Smalltalk (st)|$(file.patterns.smalltalk)|
+
+*filter.smalltalk=$(filter.smalltalk)
 
 lexer.$(file.patterns.smalltalk)=smalltalk
 
@@ -6256,7 +6949,9 @@ keywords.$(file.patterns.smalltalk)=\
 
 # SORCUS Installation files end with .ins
 file.patterns.sorcins=*.ins
-filter.sorcins=SORCUS Installation File|$(file.patterns.sorcins)|
+filter.sorcins=SORCUS Installation File (ins)|$(file.patterns.sorcins)|
+
+*filter.sorcins=$(filter.sorcins)
 
 lexer.$(file.patterns.sorcins)=sorcins
 
@@ -6273,7 +6968,7 @@ parameter=board slot layer osx file no usage task tasktype level irq flags \
 
 constants=MAX_NI_TASK MAX_TI_TASK MAX_II_TASK MAX_DI_TASK
 
-keywords.$(file.patterns.sorcins)=$(commands) 
+keywords.$(file.patterns.sorcins)=$(commands)
 keywords2.$(file.patterns.sorcins)=$(parameter)
 keywords3.$(file.patterns.sorcins)=$(constants)
 
@@ -6292,8 +6987,12 @@ file.patterns.specman=*.e
 filter.specman=Specman (e)|\
 $(file.patterns.specman)|
 
+*filter.specman=$(filter.specman)
+
 lexer.$(file.patterns.specman)=specman
 
+*language.specman=Specman|e||
+
 keywords.$(file.patterns.specman)= \
 struct unit \
 integer real bool int long uint nibble byte bits bytes bit time string \
@@ -6417,6 +7116,7 @@ braces.specman.style=10
 
 file.patterns.spice=*.scp;*.out
 filter.spice=Spice (out scp)|$(file.patterns.spice)|
+*filter.spice=$(filter.spice)
 lexer.$(file.patterns.spice)=spice
 
 #indent.size.$(file.patterns.spice)=3
@@ -6480,13 +7180,20 @@ calltip.spice.word.characters=._$(chars.alpha)
 
 filter.sql=SQL (sql)|*.sql|
 
+*filter.sql=$(filter.sql)
+
 file.patterns.sql=*.sql
 file.patterns.plsql=*.spec;*.body;*.sps;*.spb;*.sf;*.sp
 
 lexer.$(file.patterns.sql)=sql
 lexer.$(file.patterns.plsql)=sql
 
+*language.sql=S&QL|sql||
+
+#*language.plsql=P&LSQL|spec||
+
 # SQL styles
+# Not used
 # not used
 # style.sql.14=
 
@@ -6502,6 +7209,8 @@ braces.sql.style=10
 # (recommended for Oracle PL/SQL objects)
 #lexer.sql.allow.dotted.word=1
 
+#lexer.sql.backticks.identifier=1
+
 keywords.$(file.patterns.sql)=\
 absolute action add admin after aggregate \
 alias all allocate alter and any are array as asc \
@@ -6617,10 +7326,11 @@ dbms_output.put_line \
 
 file.patterns.TACL=*.tacl
 filter.tacl=TACL (TACL)|$(file.patterns.TACL)|
+*filter.tacl=$(filter.tacl)
 
 lexer.$(file.patterns.TACL)=TACL
 
-# These keywords are case insensitive 
+# These keywords are case insensitive
 keywords.$(file.patterns.TACL)=activate add adddsttransition adduser alter altpri assign attachseg backupcpu 
break builtins buscmd clear columnize comment compute copy dump copyvar create createseg debug debugnow 
default delete deluser detachseg env exit fileinfo filenames files filetovar help history home info initterm 
inlecho inleof inlout inlprefix inlto join keep keys lights load loaded files logoff logon o obey outvar 
param password pause pmsearch pmsg pop ppd purge push rcvdump receivedump reload remotepassword rename reset 
rpasswrd run rund seginfo set setprompt settime show sink status stop suspend switch system systimes time 
timestamp_to_text useusers variables varinfo vartofile vchange vcopy vdelete vfind vinsert vlist vmove volume 
vtree wakeup who xbusdown xbusup ybusdown ybusup _comparev _contime_to_text _contime_to_text_date 
_contime_to_text_time _debugger _execute _longest _month3
 
 comment.block.TACL===
@@ -6638,10 +7348,11 @@ comment.block.TACL===
 # Define SciTE settings for TAL files.
 file.patterns.TAL=*.TAL
 filter.tal=TAL (TAL)|$(file.patterns.TAL)|
+*filter.tal=$(filter.tal)
 
 lexer.$(file.patterns.TAL)=TAL
 
-# These keywords are case insensitive 
+# These keywords are case insensitive
 keywords.$(file.patterns.TAL)=and assert baddr begin by call callable case cbaddr code cwaddr define do 
downto drop else end entry external fixed for forward goto if int interrupt label land literal lor main not 
of or otherwise priv proc procaddr real resident return rscan scan sgbaddr sgwaddr sgxbaddr sgxwaddr stack 
store string struct subproc then to unsigned until use variable waddr while xor
 keywords2.$(file.patterns.TAL)=at below bit_filler block bytes c cobol elements ext extensible filler 
fortran language name pascal private unspecified words
 
@@ -6667,9 +7378,13 @@ file.patterns.tcl.like=$(file.patterns.tcl);$(file.patterns.itcl);
 filter.tcl=Tcl (tcl)|$(file.patterns.tcl)|
 filter.itcl=itcl (itcl)|$(file.patterns.itcl)|
 
+*filter.tcl=$(filter.tcl)
+
 lexer.$(file.patterns.tcl)=tcl
 lexer.$(file.patterns.itcl)=tcl
 
+*language.tcl=&TCL|tcl||
+
 keywordclass.tcl=after append array auto_execok \
 auto_import auto_load auto_load_index auto_qualify \
 beep bgerror binary break case catch cd clock \
@@ -6745,10 +7460,10 @@ tkTextPrevPara tkTextPrevPos tkTextPrevWord tkTextResetAnchor tkTextScrollPages
 tkTextSelectTo tkTextSetCursor tkTextTranspose tkTextUpDownLine tkTraverseToMenu \
 tkTraverseWithinMenu
 
-keywords.$(file.patterns.tcl.like)=$(keywordclass.tcl) 
+keywords.$(file.patterns.tcl.like)=$(keywordclass.tcl)
 keywords2.$(file.patterns.tcl.like)=$(keywordclass.tk)
 keywords3.$(file.patterns.tcl.like)= $(keywordclass.TkCommands)
-keywords4.$(file.patterns.itcl)=$(keywordclass.itcl) 
+keywords4.$(file.patterns.itcl)=$(keywordclass.itcl)
 keywords5.$(file.patterns.tcl.like)=expand
 
 comment.block.tcl=#~
@@ -6787,14 +7502,16 @@ file.patterns.context=*.tex;*.tui;*.tuo;*.sty
 
 # filter to be checked/tested:
 
-filter.context=TeX|$(file.patterns.tex)|
-filter.context=LaTeX|$(file.patterns.latex)|
-filter.context=ConTeXt|$(file.patterns.context)|
+filter.tex=TeX (tex sty)|$(file.patterns.tex)|
+filter.latex=LaTeX (tex sty aux toc idx)|$(file.patterns.latex)|
+filter.context=ConTeXt (tex tui tuo sty)|$(file.patterns.context)|
 
 lexer.$(file.patterns.tex)=tex
 lexer.$(file.patterns.latex)=tex
 lexer.$(file.patterns.context)=tex
 
+*language.tex=TeX|tex||
+
 # TeX: commands (check process view)
 
 command.compile.$(file.patterns.tex)=
@@ -6853,6 +7570,7 @@ command.2.$(file.patterns.context)=bibtex $(FileName)
 # TeX: highlighting
 
 
+
 # TeX: comments
 
 comment.block.tex=%
@@ -7227,8 +7945,12 @@ shbang.txt2tags=txt2tags
 
 filter.txt2tags=Txt2tags (t2t)|$(file.patterns.txt2tags)|
 
+*filter.txt2tags=$(filter.txt2tags)
+
 lexer.$(file.patterns.txt2tags)=txt2tags
 
+*language.txt2tags=&txt2tags|t2t||
+
 
 
 
@@ -7270,12 +7992,19 @@ file.patterns.vb=*.vb;*.bas;*.frm;*.cls;*.ctl;*.pag;*.dsr;*.dob
 # VBS: VBScript, DSM: Visual[ex. Dev] Studio macro
 file.patterns.wscript=*.vbs;*.dsm
 
+*source.patterns.vb=$(file.patterns.vb);$(file.patterns.wscript);
+
 # VBP: VB Project, VBG: VB Project Group (ActiveX), MAK: old (VB3) project file, VBW: VB Workspace
 filter.vb=VB (vb vbp vbs bas frm cls ctl pag dsr 
dob)|$(file.patterns.vb);$(file.patterns.wscript);*.vbp;*.vbg;*.mak;*.vbw|
 
+*filter.vb=$(filter.vb)
+
 lexer.$(file.patterns.vb)=vb
 lexer.$(file.patterns.wscript)=vbscript
 
+*language.vb=&VB|vb||
+#*language.vbscript=VBScr&ipt|vbs||
+
 # Keywords, operators, statements, data types and some words in .frm files
 keywordclass.vb6=\
 addressof alias and as attribute base begin binary boolean byref byte byval call case cdbl \
@@ -7343,8 +8072,12 @@ command.help.subsystem.$(file.patterns.vb)=4
 file.patterns.verilog=*.v;*.vh
 filter.verilog=Verilog (verilog)|$(file.patterns.verilog)|
 
+*filter.verilog=$(filter.verilog)
+
 lexer.$(file.patterns.verilog)=verilog
 
+*language.verilog=Verilog|v||
+
 word.chars.verilog=$(chars.alpha)$(chars.numeric)_`$#
 word.characters.$(file.patterns.verilog)=$(word.chars.verilog)
 
@@ -7399,6 +8132,8 @@ xnor xor
 
 keywords.$(file.patterns.verilog)=$(keywordclass.verilog)
 
+# Secondary keywords and identifiers
+keywords2.$(file.patterns.verilog)=
 keywords3.$(file.patterns.verilog)= \
 $async$and$array $async$and$plane $async$nand$array $async$nand$plane $async$nor$array $async$nor$plane 
$async$or$array $async$or$plane \
 $bitstoreal \
@@ -7422,6 +8157,10 @@ $test$plusargs $time $timeformat $timeskew \
 $ungetc $unsigned \
 $value$plusargs \
 $width $writeb $writeh $write $writeo
+# User defined tasks and identifiers
+keywords4.$(file.patterns.verilog)=
+# comment keyword
+keywords5.$(file.patterns.verilog)= synopsys parallel_case infer_mux TODO
 
 
 # Define SciTE settings for SystemVerilog files.
@@ -7474,7 +8213,7 @@ virtual void wait wait_order wand weak0 weak1 while wildcard wire with within \
 wor xnor xor
 
 # Secondary keywords and identifiers
-#keywords2.$(file.patterns.systemverilog)=
+keywords2.$(file.patterns.systemverilog)=
 
 # System Tasks
 keywords3.$(file.patterns.systemverilog)=\
@@ -7514,12 +8253,26 @@ $urandom $urandom_range $value$plusargs $warning $width $write $writeb $writeh \
 $writememb $writememh $writeo
 
 # User defined tasks and identifiers
-#keywords4.$(file.patterns.systemverilog)=
+keywords4.$(file.patterns.systemverilog)=
+# comment keyword
+keywords5.$(file.patterns.systemverilog)= synopsys parallel_case infer_mux TODO
 
 
 # Verilog styles
 
-# Operators
+
+# Turn on port styling features
+lexer.verilog.portstyling=1
+# Turn on treatment of all uppercase identifiers as user-defined keywords
+lexer.verilog.allupperkeywords=1
+
+# Support for colorizing inactive code due to preprocessor directives
+lexer.verilog.track.preprocessor=1
+lexer.verilog.update.preprocessor=1
+
+# Inactive states are 64 greater than their active counterparts
+
+
 # Braces are only matched in operator style
 braces.verilog.style=10
 
@@ -7534,8 +8287,12 @@ braces.verilog.style=10
 file.patterns.vhdl=*.vhd;*.vhdl
 filter.vhdl=VHDL (vhd vhdl)|$(file.patterns.vhdl)|
 
+*filter.vhdl=$(filter.vhdl)
+
 lexer.$(file.patterns.vhdl)=vhdl
 
+*language.vhdl=VHDL|vhd||
+
 word.chars.vhdl=$(chars.alpha)$(chars.numeric)_
 word.characters.$(file.patterns.vhdl)=$(word.chars.vhdl)
 
@@ -7593,7 +8350,6 @@ keywords6.$(file.patterns.vhdl)=
 
 # vhdl styles
 
-# Operators
 # Braces are only matched in operator style
 braces.vhdl.style=5
 
@@ -7606,7 +8362,9 @@ braces.vhdl.style=5
 # associate YAML file patter with the YAML lexer
 file.patterns.yaml=*.yaml;*.yml
 filter.yaml=YAML (yaml)|$(file.patterns.yaml)|
+*filter.yaml=$(filter.yaml)
 lexer.$(file.patterns.yaml)=yaml
+*language.yaml=YAML|yaml||
 
 # YAML requires spaces for tabs
 tabsize.$(file.patterns.yaml)=2
@@ -7778,8 +8536,46 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 
 ###############################################################################
+# Style for as from file asm.properties
+
+#
+       style.as.1=$(style.asm.1)
+#
+       style.as.2=$(style.asm.2)
+#
+       style.as.3=$(style.asm.3)
+#
+       style.as.4=$(style.asm.4)
+#
+       style.as.5=$(style.asm.5)
+#
+       style.as.6=$(style.asm.6)
+#
+       style.as.7=$(style.asm.7)
+#
+       style.as.8=$(style.asm.8)
+#
+       style.as.9=$(style.asm.9)
+#
+       style.as.10=$(style.asm.10)
+#
+       style.as.11=$(style.asm.11)
+#
+       style.as.12=$(style.asm.12)
+#
+       style.as.13=$(style.asm.13)
+#
+       style.as.14=$(style.asm.14)
+#
+       style.as.15=$(style.asm.15)
+
+
+
+###############################################################################
 # Style for asm from file asm.properties
 
+#
+       style.asm.0=$(style.asm.0)
 # Comment
        style.asm.1=$(style.anjuta.comment)
 # Number
@@ -7806,6 +8602,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.asm.13=$(style.anjuta.unclosed)
 # Extended instructions
        style.asm.14=$(style.anjuta.syskeyword)
+# Comment directive
+       style.asm.15=fore:#66AA00
 
 
 
@@ -7842,9 +8640,9 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 # White space
        style.au3.0=$(style.anjuta.whitespace)
-# Comment line
-       style.au3.1=$(style.anjuta.comment)
 # Comment block
+       style.au3.1=$(style.anjuta.comment)
+# Comment stream
        style.au3.2=$(style.anjuta.comment)
 # Number
        style.au3.3=$(style.anjuta.number)
@@ -7860,16 +8658,18 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.au3.8=$(style.anjuta.operator)
 # Variable
        style.au3.9=$(style.anjuta.identifier)
-# Sent keys in string
+# Send key
        style.au3.10=$(style.anjuta.char)
 # Pre-Processor
        style.au3.11=$(style.anjuta.preprocessor)
 # Special
        style.au3.12=$(style.anjuta.attribute)
-# Expand abbreviations
+# Abbrev-Expand
        style.au3.13=$(style.anjuta.regex)
-# ComObjects
+# COM Object
        style.au3.14=$(style.anjuta.attribute)
+# Standard UDF
+       style.au3.15=fore:#0080FF
 
 
 
@@ -7894,6 +8694,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.ave.9=$(style.anjuta.identifier)
 # Operators
        style.ave.10=$(style.anjuta.operator)
+# SCE_AVE_WORD1 allocated but unused
+       style.ave.11=back:#FF0000
 # Other keywords (bozo test colors :-)
        style.ave.12=$(style.anjuta.localkeyword)
 #
@@ -7952,7 +8754,7 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.baan.2=$(style.anjuta.comment)
 # Number
        style.baan.3=$(style.anjuta.number)
-# Keyword
+# Keyword ~ Reserved Words
        style.baan.4=$(style.anjuta.keyword)
 # Double quoted string
        style.baan.5=$(style.anjuta.string)
@@ -7964,8 +8766,36 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.baan.8=$(style.anjuta.identifier)
 # End of line where string is not closed
        style.baan.9=$(style.anjuta.unclosed)
-# Keywords2
+# Keywords2 ~ Functions
        style.baan.10=$(style.anjuta.localkeyword)
+# Keywords3 ~ Functions Abridged
+       style.baan.11=$(colour.baan.keyword3),$(font.baan.monospace),bold
+# Keywords4 ~ Sections
+       style.baan.12=$(colour.baan.keyword4),$(font.baan.monospace),bold
+# Keywords5 ~ Predefined Variables
+       style.baan.13=$(colour.baan.keyword5),$(font.baan.monospace),bold
+# Keywords6 ~ Attributes Predefined
+       style.baan.14=$(colour.baan.keyword6),$(font.baan.monospace),bold
+# Keywords7
+       style.baan.15=$(colour.baan.keyword7),$(font.baan.monospace),bold
+# Keywords8
+       style.baan.16=$(colour.baan.keyword8),$(font.baan.monospace),bold
+# Keywords9
+       style.baan.17=$(colour.baan.keyword9),$(font.baan.monospace),bold
+# TableDef
+       style.baan.18=$(colour.baan.tabledef),$(font.baan.monospace),bold
+# TableSQL
+       style.baan.19=$(colour.baan.tablesql),$(font.baan.monospace),bold
+# Functions
+       style.baan.20=$(colour.baan.functions),$(font.baan.monospace),bold
+# DomainDef
+       style.baan.21=$(colour.baan.domaindef),$(font.baan.monospace),bold
+# FunctionDef
+       style.baan.22=$(colour.baan.funcdefs),$(font.baan.monospace),bold
+# ObjectDef used in #include and #pragma used dll
+       style.baan.23=$(colour.baan.objdefs),$(font.baan.monospace),bold
+# DefineDef used in #define 
+       style.baan.24=$(colour.baan.definedefs),$(font.baan.monospace),bold
 
 
 
@@ -8158,6 +8988,62 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 
 ###############################################################################
+# Style for coffeescript from file coffeescript.properties
+
+# White space
+       style.coffeescript.0=fore:#808080
+# SCE_COFFEESCRIPT_COMMENT allocated but unused
+       style.coffeescript.1=$(colour.code.comment.box),$(font.code.comment.box)
+# Line Comment
+       style.coffeescript.2=$(colour.code.comment.line),$(font.code.comment.line)
+# SCE_COFFEESCRIPT_COMMENTDOC allocated but unused
+       style.coffeescript.3=$(colour.code.comment.doc),$(font.code.comment.doc)
+# Number
+       style.coffeescript.4=$(colour.number)
+# Keyword
+       style.coffeescript.5=$(colour.keyword),bold
+# Double quoted string
+       style.coffeescript.6=$(colour.string)
+# Single quoted string
+       style.coffeescript.7=$(colour.char)
+# SCE_COFFEESCRIPT_UUID allocated but unused
+       style.coffeescript.8=fore:#804080
+# SCE_COFFEESCRIPT_PREPROCESSOR allocated but unused
+       style.coffeescript.9=$(colour.preproc)
+# Operators
+       style.coffeescript.10=$(colour.operator),bold
+# SCE_COFFEESCRIPT_STRINGEOL allocated but unused
+       style.coffeescript.12=fore:#000000,$(font.monospace),back:#E0C0E0,eolfilled
+# SCE_COFFEESCRIPT_VERBATIM allocated but unused
+       style.coffeescript.13=fore:#007F00,$(font.monospace),back:#E0FFE0,eolfilled
+# Regular expressions
+       style.coffeescript.14=fore:#3F7F3F,$(font.monospace),back:#E0F0FF,eolfilled
+# SCE_COFFEESCRIPT_COMMENTLINEDOC allocated but unused
+       style.coffeescript.15=$(colour.code.comment.doc),$(font.code.comment.doc)
+# Keywords2
+       style.coffeescript.16=fore:#B00040
+# SCE_COFFEESCRIPT_COMMENTDOCKEYWORD allocated but unused
+       style.coffeescript.17=fore:#3060A0,$(font.code.comment.doc)
+# SCE_COFFEESCRIPT_COMMENTDOCKEYWORDERROR allocated but unused
+       style.coffeescript.18=fore:#804020,$(font.code.comment.doc)
+# Global class
+       style.coffeescript.19=fore:#DD9900
+# SCE_COFFEESCRIPT_STRINGRAW allocated but unused
+       style.coffeescript.20=$(colour.string),back:#FFF3FF,eolfilled
+# SCE_COFFEESCRIPT_TRIPLEVERBATIM allocated but unused
+       style.coffeescript.21=$(font.monospace),fore:#007F00,back:#E0FFE0,eolfilled
+# Comment block ###
+       style.coffeescript.22=$(font.monospace),fore:#007F00,back:#E7FFD7,eolfilled
+# Verbose REGEX
+       style.coffeescript.23=fore:#659900
+# Verbose REGEX comment
+       style.coffeescript.24=$(colour.code.comment.doc)
+# Iinstance property
+       style.coffeescript.25=fore:#C06000
+
+
+
+###############################################################################
 # Style for conf from file conf.properties
 
 # whitespace (SCE_CONF_DEFAULT)
@@ -8222,7 +9108,7 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.cpp.17=$(style.anjuta.comment)
 # Comment keyword error
        style.cpp.18=$(style.anjuta.comment)
-# Libraries symbols (needed to highlight library functions by example GTK+)
+# Global class
        style.cpp.19=$(style.anjuta.syskeyword)
 # Raw strings for C++0x
        style.cpp.20=$(style.anjuta.string)
@@ -8234,6 +9120,12 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.cpp.23=$(style.anjuta.preprocessor)
 # Preprocessor stream doc comment
        style.cpp.24=$(style.anjuta.preprocessor)
+# User defined literals
+       style.cpp.25=fore:#C06000
+# Task Marker
+       style.cpp.26=fore:#BE07FF,$(font.code.comment.line)
+# Escape sequence
+       style.cpp.27=$(colour.string)
 # White space
        style.cpp.64=$(style.anjuta.whitespace)
 # Comment: /* */.
@@ -8282,6 +9174,10 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.cpp.87=$(style.anjuta.preprocessor)
 # Preprocessor stream doc comment
        style.cpp.88=$(style.anjuta.preprocessor)
+# User defined literals
+       style.cpp.89=fore:#D7A090
+# Task Marker
+       style.cpp.90=fore:#C3A1CF,$(font.code.comment.line)
 
 
 
@@ -8316,12 +9212,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.csound.13=$(style.anjuta.identifier)
 # Global variable
        style.csound.14=$(style.anjuta.identifier)
-# F-statement
-       style.csound.15=$(style.anjuta.identifier)
-# I-statement
-       style.csound.16=$(style.anjuta.identifier)
 # End of line where string is not closed
-       style.csound.17=$(style.anjuta.unclosed)
+       style.csound.15=$(style.anjuta.identifier)
 
 
 
@@ -8372,13 +9264,15 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.css.21=$(style.anjuta.localkeyword)
 # "@media"
        style.css.22=$(style.anjuta.identifier)
+# Variable in SCSS, LESS, or HSS
+       style.css.23=fore:#DD9900
 
 
 
 ###############################################################################
 # Style for d from file d.properties
 
-# 15, 16, 17 - Doc comments: line doc /// or //!, doc keyword, doc keyword err
+# 20, 21, 22 keywords 5, 6, and 7
        style.d.0=$(style.anjuta.whitespace)
 #
        style.d.1=$(style.anjuta.comment)
@@ -8412,6 +9306,16 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.d.16=$(style.anjuta.comment)
 #
        style.d.17=$(style.anjuta.comment)
+#
+       style.d.18=fore:#DD9900
+#
+       style.d.19=fore:#DD9900
+#
+       style.d.20=fore:#DD9900
+#
+       style.d.21=fore:#DD9900
+#
+       style.d.22=fore:#DD9900
 
 
 
@@ -8598,6 +9502,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.erlang.23=$(style.anjuta.definition)
 # Module attributes
        style.erlang.24=$(style.anjuta.definition)
+# Unknown: error
+       style.erlang.31=back:#FF0000
 
 
 
@@ -8650,6 +9556,42 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.errorlist.21=$(style.anjuta.normal)
 # GCC showing include path to following error
        style.errorlist.22=$(style.anjuta.error)
+# Escape sequence
+       style.errorlist.23=fore:#000000,notvisible,back:#FFFFFF,$(error.background)
+# Escape sequence unknown
+       style.errorlist.24=back:#FFE0A0
+# Basic colours
+       style.errorlist.40=fore:#000000,$(error.background)
+#
+       style.errorlist.41=fore:#800000,$(error.background)
+#
+       style.errorlist.42=fore:#008000,$(error.background)
+#
+       style.errorlist.43=fore:#808000,$(error.background)
+#
+       style.errorlist.44=fore:#000080,$(error.background)
+#
+       style.errorlist.45=fore:#800080,$(error.background)
+#
+       style.errorlist.46=fore:#008080,$(error.background)
+#
+       style.errorlist.47=fore:#A0A0A0,$(error.background)
+# Intense colours
+       style.errorlist.48=fore:#000000,bold,$(error.background)
+#
+       style.errorlist.49=fore:#800000,bold,$(error.background)
+#
+       style.errorlist.50=fore:#008000,bold,$(error.background)
+#
+       style.errorlist.51=fore:#808000,bold,$(error.background)
+#
+       style.errorlist.52=fore:#000080,bold,$(error.background)
+#
+       style.errorlist.53=fore:#800080,bold,$(error.background)
+#
+       style.errorlist.54=fore:#008080,bold,$(error.background)
+#
+       style.errorlist.55=fore:#A0A0A0,bold,$(error.background)
 
 
 
@@ -8916,8 +9858,16 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.haskell.4=$(style.anjuta.string)
 # character
        style.haskell.5=$(style.anjuta.char)
+# class: error not implemented
+       style.haskell.6=back:#FF0000
+# data: error not implemented
+       style.haskell.9=back:#FF0000
+# import: error not implemented
+       style.haskell.10=back:#FF0000
 # operator
        style.haskell.11=$(style.anjuta.operator)
+# instance: error not implemented
+       style.haskell.12=back:#FF0000
 # line comment
        style.haskell.13=$(style.anjuta.comment)
 # block comment
@@ -8932,6 +9882,12 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.haskell.18=$(style.anjuta.preprocessor)
 # End of line where string is not closed
        style.haskell.19=$(style.anjuta.error)
+# Reserved operator
+       style.haskell.20=back:#FF8080
+# Literate comment
+       style.haskell.21=fore:#DD9900,$(font.code.comment.line),italics
+# Literate delimiter
+       style.haskell.22=fore:#EE00AA
 
 
 
@@ -8998,6 +9954,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.hypertext.28=$(style.anjuta.attribute)
 # SGML comment
        style.hypertext.29=$(style.anjuta.comment)
+# SGML first parameter - lexer internal. It is an error if any text is in this style.
+       style.hypertext.30=fore:#808000,back:#FF0000
 # SGML block
        style.hypertext.31=$(style.anjuta.preprocessor)
 # JS Start - allows eol filled background to not start on same line as SCRIPT tag
@@ -9158,6 +10116,48 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 
 ###############################################################################
+# Style for ihex from file hex.properties
+
+# Same color scheme as above, comments when differing
+       style.ihex.0=$(style.srec.0)
+# Record start ':'
+       style.ihex.1=$(style.srec.1)
+#
+       style.ihex.2=$(style.srec.2)
+#
+       style.ihex.3=$(style.srec.3)
+#
+       style.ihex.4=$(style.srec.4)
+#
+       style.ihex.5=$(style.srec.5)
+#
+       style.ihex.6=$(style.srec.6)
+#
+       style.ihex.7=$(style.srec.7)
+# Data field: Start address
+       style.ihex.9=$(style.srec.9)
+# Address field: Type unknown (4 digits as usual)
+       style.ihex.10=$(style.srec.10)
+# Data field: Extended address
+       style.ihex.11=$(style.ihex.9)
+#
+       style.ihex.12=$(style.srec.12)
+#
+       style.ihex.13=$(style.srec.13)
+# Data field: Type unknown
+       style.ihex.14=$(style.srec.14)
+#
+       style.ihex.15=$(style.srec.15)
+#
+       style.ihex.16=$(style.srec.16)
+#
+       style.ihex.17=$(style.srec.17)
+#
+       style.ihex.18=$(style.srec.18)
+
+
+
+###############################################################################
 # Style for inno from file inno.properties
 
 # Comment
@@ -9182,6 +10182,42 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.inno.10=$(style.anjuta.string)
 # Single quoted string
        style.inno.11=$(style.anjuta.char)
+# Identifier - lexer internal. It is an error if any text is in this style.
+       style.inno.12=back:#FF0000
+
+
+
+###############################################################################
+# Style for json from file json.properties
+
+# Default
+       style.json.0=fore:FFFFFF
+# Number
+       style.json.1=fore:#007F7F
+# String
+       style.json.2=fore:#7F0000
+# Unclosed string
+       style.json.3=fore:#FFFFFF,back:#FF0000,eolfilled
+# Property name
+       style.json.4=fore:#880AE8
+# Escape sequence
+       style.json.5=fore:#0B982E
+# Line comment
+       style.json.6=fore:#05BBAE,italics
+# Block comment
+       style.json.7=$(style.json.6)
+# Operator
+       style.json.8=fore:#18644A
+# URL/IRI
+       style.json.9=fore:#0000FF
+# JSON-LD compact IRI
+       style.json.10=fore:#D137C1
+# JSON keyword
+       style.json.11=fore:#0BCEA7,bold
+# JSON-LD keyword
+       style.json.12=fore:#EC2806
+# Parsing error
+       style.json.13=fore:#FFFFFF,back:#FF0000
 
 
 
@@ -9208,6 +10244,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.kix.8=$(style.anjuta.function)
 # Operator
        style.kix.9=$(style.anjuta.operator)
+# Stream comment
+       style.kix.10=$(colour.code.comment.box),$(font.code.comment.box)
 
 
 
@@ -9254,12 +10292,20 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.lisp.2=$(style.anjuta.number)
 # Keyword
        style.lisp.3=$(style.anjuta.keyword)
+# Keyword 2
+       style.lisp.4=fore:#EE00AA
+# Symbol
+       style.lisp.5=fore:#DD9900
 # String
        style.lisp.6=$(style.anjuta.string)
 # End of line where string is not closed
        style.lisp.8=$(style.anjuta.unclosed)
 # Operators
        style.lisp.10=$(style.anjuta.operator)
+# Special
+       style.lisp.11=fore:#60AA00
+# Multi-line comment
+       style.lisp.12=$(colour.code.comment.box),$(font.code.comment.box)
 
 
 
@@ -9548,6 +10594,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.nncrontab.8=$(style.anjuta.string)
 # Environment variable (SCE_NNCRONTAB_ENVIRONMENT)
        style.nncrontab.9=$(style.anjuta.identifier)
+# Identifier (SCE_NNCRONTAB_IDENTIFIER) - lexer internal. It is an error if any text is in this style.
+       style.nncrontab.10=back:#FF0000
 
 
 
@@ -9746,6 +10794,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.perl.14=$(style.anjuta.identifier)
 # Symbol table: *var
        style.perl.15=$(style.anjuta.identifier)
+# SCE_PL_VARIABLE_INDEXER allocated but unused
+       style.perl.16=back:#FF0000
 # Regex: /re/ or m{re}
        style.perl.17=$(style.anjuta.regex)
 # Substitution: s/re/ore/
@@ -9839,7 +10889,7 @@ keywords.$(file.patterns.yaml)=true false yes no
 # Keyword 7
        style.pov.15=$(style.anjuta.syskeyword)
 # Keyword 8
-       style.pov.17=$(style.anjuta.extrakeyword)
+       style.pov.16=$(colour.keyword),back:#E0E0E0
 
 
 
@@ -9910,8 +10960,14 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.powershell.10=$(style.anjuta.attribute)
 # Function
        style.powershell.11=$(style.anjuta.function)
-# Commment (multi-line)
+# Comment (multi-line)
        style.powershell.13=$(style.anjuta.comment)
+# Here-string
+       style.powershell.14=fore:#7F007F,back:#DDD0DD,eolfilled,bold
+# Here-string single quote
+       style.powershell.15=fore:#7F007F,back:#DDD0DD,eolfilled,notbold
+# Comment keyword
+       style.powershell.16=fore:#3060A0
 
 
 
@@ -10036,6 +11092,14 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.python.14=$(style.anjuta.identifier)
 # Decorators
        style.python.15=$(style.anjuta.attribute)
+# F-String
+       style.python.16=fore:#7F007F,$(font.monospace)
+# Single quoted f-string
+       style.python.17=fore:#7F007F,$(font.monospace)
+# Triple quoted f-string
+       style.python.18=fore:#7F0000
+# Triple double quoted f-string
+       style.python.19=fore:#7F0000
 
 
 
@@ -10118,6 +11182,48 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.rebol.22=$(style.anjuta.localkeyword)
 # Keyword (datatypes)
        style.rebol.23=$(style.anjuta.syskeyword)
+# Keyword 4
+       style.rebol.24=fore:#DD9900
+# Keyword 5
+       style.rebol.25=fore:#DD9900
+# Keyword 6
+       style.rebol.26=fore:#DD9900
+# Keyword 7
+       style.rebol.27=fore:#DD9900
+# Keyword 8
+       style.rebol.28=fore:#DD9900
+
+
+
+###############################################################################
+# Style for registry from file registry.properties
+
+# Default
+       style.registry.0=fore:#000000
+# Comment: ;;
+       style.registry.1=$(colour.code.comment.line)
+# Value name: "Icon"="cmd.exe,-1"
+       style.registry.2=fore:#0000FF
+# String
+       style.registry.3=$(colour.string)
+# Hex digit
+       style.registry.4=fore:#7F0B0C
+# Value type: dword, hex(2), hex(7)
+       style.registry.5=fore:#00007F,bold
+# Added key, [HKLM\*\shell\notepad]
+       style.registry.6=fore:#530155
+# Removed key, [-HKLM\*\shell\notepad]
+       style.registry.7=fore:#FF0000
+# Escaped characters in strings
+       style.registry.8=fore:#7D8187,bold
+# GUID in key path, [HKCU\{C4ACBD3E-6114-4618-904C-B206ABA9DEB0}]
+       style.registry.9=fore:#7B5F15
+# GUID in string, @="{C4ACBD3E-6114-4618-904C-B206ABA9DEB0}"
+       style.registry.10=$(style.registry.9)
+# Parameter: "notepad.exe %1 %*"
+       style.registry.11=fore:#0B6561
+# Operators
+       style.registry.12=bold
 
 
 
@@ -10188,6 +11294,60 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.ruby.31=$(style.anjuta.definition)
 # STDERR
        style.ruby.40=$(style.anjuta.definition)
+# SCE_RB_UPPER_BOUND allocated but unused
+       style.ruby.41=back:#FF0000
+
+
+
+###############################################################################
+# Style for rust from file rust.properties
+
+# Whitespace
+       style.rust.0=fore:#808080
+# Block comment
+       style.rust.1=$(colour.code.comment.box),$(font.code.comment.box)
+# Line comment
+       style.rust.2=$(colour.code.comment.line),$(font.code.comment.line)
+# Block doc comment
+       style.rust.3=$(colour.code.comment.doc),$(font.code.comment.doc)
+# Line doc comment
+       style.rust.4=$(colour.code.comment.doc),$(font.code.comment.doc)
+# Number
+       style.rust.5=$(colour.number)
+# Keywords 1-7
+       style.rust.6=$(colour.keyword),bold
+#
+       style.rust.7=$(colour.keyword),bold
+#
+       style.rust.8=$(colour.keyword)
+#
+       style.rust.9=$(colour.keyword),bold
+#
+       style.rust.10=$(colour.keyword),bold
+#
+       style.rust.11=$(colour.keyword),bold
+#
+       style.rust.12=$(colour.keyword),bold
+# Regular string
+       style.rust.13=$(colour.string)
+# Raw string
+       style.rust.14=fore:#B090B0
+# Character
+       style.rust.15=$(colour.char)
+# Operator
+       style.rust.16=$(colour.operator),bold
+# Lifetime
+       style.rust.18=fore:#007F7F
+# Macro
+       style.rust.19=$(colour.preproc)
+# Lexical error
+       style.rust.20=fore:#000000,$(font.monospace),back:#E0C0E0
+# Byte string
+       style.rust.21=$(colour.string)
+# Raw byte string
+       style.rust.22=fore:#B090B0
+# Byte character
+       style.rust.23=$(colour.char)
 
 
 
@@ -10311,7 +11471,7 @@ keywords.$(file.patterns.yaml)=true false yes no
 # HDL Signal
        style.specman.14=$(style.anjuta.attribute)
 # User defined
-       style.specman.15=$(style.anjuta.extrakeyword)
+       style.specman.19=back:#E0F0FF
 
 
 
@@ -10362,8 +11522,6 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.sql.9=$(style.anjuta.preprocessor)
 # Operators
        style.sql.10=$(style.anjuta.operator)
-# End of line where string is not closed / not used
-       style.sql.12=$(style.anjuta.unclosed)
 # SQL*Plus Comment
        style.sql.13=$(style.anjuta.comment)
 # Hash Line Comment
@@ -10382,6 +11540,46 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.sql.21=$(style.anjuta.syskeyword)
 # Keywords8: User Keywords 4
        style.sql.22=$(style.anjuta.extrakeyword)
+# Quoted identifier
+       style.sql.23=fore:#DD9900
+# Q operator
+       style.sql.24=fore:#EE00AA
+
+
+
+###############################################################################
+# Style for srec from file hex.properties
+
+# Record start 'S'
+       style.srec.1=$(style.srec.2)
+# Record type
+       style.srec.2=fore:#7F0000
+# Record type unknown
+       style.srec.3=$(style.srec.2),$(style.srec.10)
+# Byte count field: Correct byte count
+       style.srec.4=fore:#7F7F00
+# Byte count field: Wrong byte count
+       style.srec.5=$(colour.error)
+# Address field: No address
+       style.srec.6=fore:#7F00FF
+# Address field: Data address
+       style.srec.7=fore:#007FFF
+# Address field: Record count
+       style.srec.8=$(style.srec.6)
+# Address field: Start address
+       style.srec.9=$(style.srec.7)
+# Address field: Type unknown (this state does not contain any characters)
+       style.srec.10=italics
+# Data odd
+       style.srec.12=bold
+# Data field: Position unknown
+       style.srec.14=$(style.srec.10)
+# Checksum field: Correct checksum
+       style.srec.16=fore:#00BF00
+# Checksum field: Wrong checksum
+       style.srec.17=$(colour.error)
+# Garbage data after the record
+       style.srec.18=$(style.srec.10)
 
 
 
@@ -10436,6 +11634,40 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 
 ###############################################################################
+# Style for tehex from file hex.properties
+
+# Same color scheme as above, comments when differing
+       style.tehex.0=$(style.srec.0)
+# Record start '%'
+       style.tehex.1=$(style.srec.1)
+#
+       style.tehex.2=$(style.srec.2)
+#
+       style.tehex.3=$(style.srec.3)
+#
+       style.tehex.4=$(style.srec.4)
+#
+       style.tehex.5=$(style.srec.5)
+# .6 N/A
+       style.tehex.7=$(style.srec.7)
+# .8 N/A
+       style.tehex.9=$(style.srec.9)
+# Address field: Type unknown (9 digits as usual)
+       style.tehex.10=$(style.srec.10)
+# .11 N/A
+       style.tehex.12=$(style.srec.12)
+#
+       style.tehex.13=$(style.srec.13)
+# .15 N/A
+       style.tehex.16=$(style.srec.16)
+#
+       style.tehex.17=$(style.srec.17)
+#
+       style.tehex.18=$(style.srec.18)
+
+
+
+###############################################################################
 # Style for tex from file tex.properties
 
 # Default
@@ -10586,18 +11818,66 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.verilog.5=$(style.anjuta.keyword)
 # Double quoted string
        style.verilog.6=$(style.anjuta.string)
-# Keyword2
+# Keyword2, Secondary keywords and identifiers
        style.verilog.7=$(style.anjuta.localkeyword)
-# System tasks
+# keywords3, System tasks
        style.verilog.8=$(style.anjuta.syskeyword)
 # Preprocessor
        style.verilog.9=$(style.anjuta.preprocessor)
-#~ style.verilog.10=$(colour.operator),bold
+# Operators
        style.verilog.10=$(style.anjuta.operator)
 # End of line where string is not closed
        style.verilog.12=$(style.anjuta.error)
-# User defined identifiers and tasks
+# keywords4, User defined identifiers and tasks
        style.verilog.19=$(style.anjuta.extrakeyword)
+# comment keyword
+       style.verilog.20=fore:#2A00FF
+# port declare (input output ioput)
+       style.verilog.21=fore:#7F0000
+#
+       style.verilog.22=fore:#00007F
+#
+       style.verilog.23=fore:#0000FF
+# port connection
+       style.verilog.24=fore:#005032,bold
+# White space
+       style.verilog.64=back:#E0E0E0,eolfilled
+#
+       style.verilog.65=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.66=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.67=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.68=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.69=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.70=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.71=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.72=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.73=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.74=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.75=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.76=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.83=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.84=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.85=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.86=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.87=back:#E0E0E0,eolfilled,fore:#808080,italics
+#
+       style.verilog.88=back:#E0E0E0,eolfilled,fore:#808080,italics
 
 
 
@@ -10630,6 +11910,8 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.vhdl.13=$(style.anjuta.syskeyword)
 # User defined identifiers and tasks
        style.vhdl.14=$(style.anjuta.extrakeyword)
+# Block comment
+       style.vhdl.15=$(colour.code.comment.box),$(font.code.comment.box)
 
 
 
@@ -10714,5 +11996,7 @@ keywords.$(file.patterns.yaml)=true false yes no
        style.yaml.7=$(style.anjuta.syskeyword)
 # syntax error marker
        style.yaml.8=$(style.anjuta.error)
+# operator
+       style.yaml.9=$(colour.operator)
 
 
diff --git a/plugins/scintilla/scintilla/Makefile.am b/plugins/scintilla/scintilla/Makefile.am
index 6011653..b0e7d76 100644
--- a/plugins/scintilla/scintilla/Makefile.am
+++ b/plugins/scintilla/scintilla/Makefile.am
@@ -39,8 +39,12 @@ libanjuta_scintilla_la_SOURCES =\
        src/Decoration.h \
        src/Document.cxx \
        src/Document.h \
+       src/EditModel.cxx \
+       src/EditModel.h \
        src/Editor.cxx \
        src/Editor.h \
+       src/EditView.cxx \
+       src/EditView.h \
        src/ExternalLexer.cxx \
        src/ExternalLexer.h \
        src/Indicator.cxx \
@@ -49,6 +53,8 @@ libanjuta_scintilla_la_SOURCES =\
        src/KeyMap.h \
        src/LineMarker.cxx \
        src/LineMarker.h \
+       src/MarginView.cxx \
+       src/MarginView.h \
        src/Partitioning.h \
        src/PerLine.h \
        src/PerLine.cxx \
@@ -99,6 +105,7 @@ libanjuta_scintilla_la_SOURCES =\
        gtk/Converter.h \
        gtk/PlatGTK.cxx \
        gtk/ScintillaGTK.cxx \
+       gtk/ScintillaGTKAccessible.cxx \
        $(LEXER_SRCS) \
        $(BUILT_SOURCES)
 
diff --git a/plugins/scintilla/scintilla/gtk/Converter.h b/plugins/scintilla/scintilla/gtk/Converter.h
index 8e7e3e9..f17949d 100644
--- a/plugins/scintilla/scintilla/gtk/Converter.h
+++ b/plugins/scintilla/scintilla/gtk/Converter.h
@@ -3,21 +3,20 @@
 // Copyright 2004 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-typedef GIConv ConverterHandle;
-const ConverterHandle iconvhBad = (ConverterHandle)(-1);
-// Since various versions of iconv can not agree on whether the src argument
-// is char ** or const char ** provide a templatised adaptor.
-template<typename T>
-size_t iconv_adaptor(size_t(*f_iconv)(ConverterHandle, T, size_t *, char **, size_t *),
-               ConverterHandle cd, char** src, size_t *srcleft,
-               char **dst, size_t *dstleft) {
-       return f_iconv(cd, (T)src, srcleft, dst, dstleft);
-}
+#ifndef CONVERTER_H
+#define CONVERTER_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+const GIConv iconvhBad = (GIConv)(-1);
+const gsize sizeFailure = static_cast<gsize>(-1);
 /**
- * Encapsulate iconv safely and avoid iconv_adaptor complexity in client code.
+ * Encapsulate g_iconv safely.
  */
 class Converter {
-       ConverterHandle iconvh;
+       GIConv iconvh;
        void OpenHandle(const char *fullDestination, const char *charSetSource) {
                iconvh = g_iconv_open(fullDestination, charSetSource);
        }
@@ -38,15 +37,14 @@ public:
        operator bool() const {
                return Succeeded();
        }
-       void Open(const char *charSetDestination, const char *charSetSource, bool transliterations=true) {
+       void Open(const char *charSetDestination, const char *charSetSource, bool transliterations) {
                Close();
                if (*charSetSource) {
                        // Try allowing approximate transliterations
                        if (transliterations) {
-                               char fullDest[200];
-                               strcpy(fullDest, charSetDestination);
-                               strcat(fullDest, "//TRANSLIT");
-                               OpenHandle(fullDest, charSetSource);
+                               std::string fullDest(charSetDestination);
+                               fullDest.append("//TRANSLIT");
+                               OpenHandle(fullDest.c_str(), charSetSource);
                        }
                        if (!Succeeded()) {
                                // Transliterations failed so try basic name
@@ -60,11 +58,17 @@ public:
                        iconvh = iconvhBad;
                }
        }
-       size_t Convert(char** src, size_t *srcleft, char **dst, size_t *dstleft) const {
+       gsize Convert(char** src, gsize *srcleft, char **dst, gsize *dstleft) const {
                if (!Succeeded()) {
-                       return (size_t)(-1);
+                       return sizeFailure;
                } else {
-                       return iconv_adaptor(g_iconv, iconvh, src, srcleft, dst, dstleft);
+                       return g_iconv(iconvh, src, srcleft, dst, dstleft);
                }
        }
 };
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/gtk/PlatGTK.cxx b/plugins/scintilla/scintilla/gtk/PlatGTK.cxx
index a6ae84e..ee001cd 100644
--- a/plugins/scintilla/scintilla/gtk/PlatGTK.cxx
+++ b/plugins/scintilla/scintilla/gtk/PlatGTK.cxx
@@ -3,15 +3,17 @@
 // Copyright 1998-2004 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <math.h>
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <cstdio>
+#include <cmath>
 
 #include <string>
 #include <vector>
 #include <map>
+#include <memory>
+#include <sstream>
 
 #include <glib.h>
 #include <gmodule.h>
@@ -23,30 +25,15 @@
 
 #include "Scintilla.h"
 #include "ScintillaWidget.h"
-#include "UniConversion.h"
+#include "StringCopy.h"
 #include "XPM.h"
-
-#if defined(__clang__)
-// Clang 3.0 incorrectly displays  sentinel warnings. Fixed by clang 3.1.
-#pragma GCC diagnostic ignored "-Wsentinel"
-#endif
-
-/* GLIB must be compiled with thread support, otherwise we
-   will bail on trying to use locks, and that could lead to
-   problems for someone.  `glib-config --libs gthread` needs
-   to be used to get the glib libraries for linking, otherwise
-   g_thread_init will fail */
-#define USE_LOCK defined(G_THREADS_ENABLED) && !defined(G_THREADS_IMPL_NONE)
+#include "UniConversion.h"
 
 #include "Converter.h"
 
-#if GTK_CHECK_VERSION(2,20,0)
-#define IS_WIDGET_FOCUSSED(w) (gtk_widget_has_focus(GTK_WIDGET(w)))
-#else
-#define IS_WIDGET_FOCUSSED(w) (GTK_WIDGET_HAS_FOCUS(w))
-#endif
+static const double kPi = 3.14159265358979323846;
 
-// The Pango version guard for pango_units_from_double and pango_units_to_double 
+// The Pango version guard for pango_units_from_double and pango_units_to_double
 // is more complex than simply implementing these here.
 
 static int pangoUnitsFromDouble(double d) {
@@ -76,11 +63,7 @@ static cairo_surface_t *CreateSimilarSurface(GdkWindow *window, cairo_content_t
 }
 
 static GdkWindow *WindowFromWidget(GtkWidget *w) {
-#if GTK_CHECK_VERSION(3,0,0)
        return gtk_widget_get_window(w);
-#else
-       return w->window;
-#endif
 }
 
 #ifdef _MSC_VER
@@ -94,127 +77,48 @@ using namespace Scintilla;
 
 enum encodingType { singleByte, UTF8, dbcs};
 
-struct LOGFONT {
-       int size;
-       int weight;
-       bool italic;
-       int characterSet;
-       char faceName[300];
-};
-
-#if USE_LOCK
-static GMutex *fontMutex = NULL;
-
-static void InitializeGLIBThreads() {
-#if !GLIB_CHECK_VERSION(2,31,0)
-       if (!g_thread_supported()) {
-               g_thread_init(NULL);
-       }
-#endif
-}
-#endif
-
-static void FontMutexAllocate() {
-#if USE_LOCK
-       if (!fontMutex) {
-               InitializeGLIBThreads();
-#if GLIB_CHECK_VERSION(2,31,0)
-               fontMutex = g_new(GMutex, 1);
-               g_mutex_init(fontMutex);
-#else
-               fontMutex = g_mutex_new();
-#endif
-       }
-#endif
-}
-
-static void FontMutexFree() {
-#if USE_LOCK
-       if (fontMutex) {
-#if GLIB_CHECK_VERSION(2,31,0)
-               g_mutex_clear(fontMutex);
-               g_free(fontMutex);
-#else
-               g_mutex_free(fontMutex);
-#endif
-               fontMutex = NULL;
-       }
-#endif
-}
-
-static void FontMutexLock() {
-#if USE_LOCK
-       g_mutex_lock(fontMutex);
-#endif
-}
-
-static void FontMutexUnlock() {
-#if USE_LOCK
-       if (fontMutex) {
-               g_mutex_unlock(fontMutex);
-       }
-#endif
-}
-
 // Holds a PangoFontDescription*.
 class FontHandle {
-       XYPOSITION width[128];
-       encodingType et;
 public:
-       int ascent;
        PangoFontDescription *pfd;
        int characterSet;
-       FontHandle() : et(singleByte), ascent(0), pfd(0), characterSet(-1) {
-               ResetWidths(et);
+       FontHandle() : pfd(0), characterSet(-1) {
        }
        FontHandle(PangoFontDescription *pfd_, int characterSet_) {
-               et = singleByte;
-               ascent = 0;
                pfd = pfd_;
                characterSet = characterSet_;
-               ResetWidths(et);
        }
        ~FontHandle() {
                if (pfd)
                        pango_font_description_free(pfd);
                pfd = 0;
        }
-       void ResetWidths(encodingType et_) {
-               et = et_;
-               for (int i=0; i<=127; i++) {
-                       width[i] = 0;
-               }
-       }
-       XYPOSITION CharWidth(unsigned char ch, encodingType et_) const {
-               XYPOSITION w = 0;
-               FontMutexLock();
-               if ((ch <= 127) && (et == et_)) {
-                       w = width[ch];
-               }
-               FontMutexUnlock();
-               return w;
-       }
-       void SetCharWidth(unsigned char ch, XYPOSITION w, encodingType et_) {
-               if (ch <= 127) {
-                       FontMutexLock();
-                       if (et != et_) {
-                               ResetWidths(et_);
-                       }
-                       width[ch] = w;
-                       FontMutexUnlock();
-               }
-       }
+       static FontHandle *CreateNewFont(const FontParameters &fp);
 };
 
+FontHandle *FontHandle::CreateNewFont(const FontParameters &fp) {
+       PangoFontDescription *pfd = pango_font_description_new();
+       if (pfd) {
+               pango_font_description_set_family(pfd,
+                       (fp.faceName[0] == '!') ? fp.faceName+1 : fp.faceName);
+               pango_font_description_set_size(pfd, pangoUnitsFromDouble(fp.size));
+               pango_font_description_set_weight(pfd, static_cast<PangoWeight>(fp.weight));
+               pango_font_description_set_style(pfd, fp.italic ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL);
+               return new FontHandle(pfd,fp.characterSet);
+       }
+
+       return NULL;
+}
+
 // X has a 16 bit coordinate space, so stop drawing here to avoid wrapping
 static const int maxCoordinate = 32000;
 
 static FontHandle *PFont(Font &f) {
-       return reinterpret_cast<FontHandle *>(f.GetID());
+       return static_cast<FontHandle *>(f.GetID());
 }
 
 static GtkWidget *PWidget(WindowID wid) {
-       return reinterpret_cast<GtkWidget *>(wid);
+       return static_cast<GtkWidget *>(wid);
 }
 
 Point Point::FromLong(long lpoint) {
@@ -223,143 +127,18 @@ Point Point::FromLong(long lpoint) {
                   Platform::HighShortFromLong(lpoint));
 }
 
-static void SetLogFont(LOGFONT &lf, const char *faceName, int characterSet, float size, int weight, bool 
italic) {
-       memset(&lf, 0, sizeof(lf));
-       lf.size = size;
-       lf.weight = weight;
-       lf.italic = italic;
-       lf.characterSet = characterSet;
-       strncpy(lf.faceName, faceName, sizeof(lf.faceName) - 1);
-}
-
-/**
- * Create a hash from the parameters for a font to allow easy checking for identity.
- * If one font is the same as another, its hash will be the same, but if the hash is the
- * same then they may still be different.
- */
-static int HashFont(const FontParameters &fp) {
-       return
-           static_cast<int>(fp.size+0.5) ^
-           (fp.characterSet << 10) ^
-           ((fp.weight / 100) << 12) ^
-           (fp.italic ? 0x20000000 : 0) ^
-           fp.faceName[0];
-}
-
-class FontCached : Font {
-       FontCached *next;
-       int usage;
-       LOGFONT lf;
-       int hash;
-       FontCached(const FontParameters &fp);
-       ~FontCached() {}
-       bool SameAs(const FontParameters &fp);
-       virtual void Release();
-       static FontID CreateNewFont(const FontParameters &fp);
-       static FontCached *first;
-public:
-       static FontID FindOrCreate(const FontParameters &fp);
-       static void ReleaseId(FontID fid_);
-       static void ReleaseAll();
-};
-
-FontCached *FontCached::first = 0;
-
-FontCached::FontCached(const FontParameters &fp) :
-next(0), usage(0), hash(0) {
-       ::SetLogFont(lf, fp.faceName, fp.characterSet, fp.size, fp.weight, fp.italic);
-       hash = HashFont(fp);
-       fid = CreateNewFont(fp);
-       usage = 1;
-}
-
-bool FontCached::SameAs(const FontParameters &fp) {
-       return
-           lf.size == fp.size &&
-           lf.weight == fp.weight &&
-           lf.italic == fp.italic &&
-           lf.characterSet == fp.characterSet &&
-           0 == strcmp(lf.faceName, fp.faceName);
-}
-
-void FontCached::Release() {
-       if (fid)
-               delete PFont(*this);
-       fid = 0;
-}
-
-FontID FontCached::FindOrCreate(const FontParameters &fp) {
-       FontID ret = 0;
-       FontMutexLock();
-       int hashFind = HashFont(fp);
-       for (FontCached *cur = first; cur; cur = cur->next) {
-               if ((cur->hash == hashFind) &&
-                       cur->SameAs(fp)) {
-                       cur->usage++;
-                       ret = cur->fid;
-               }
-       }
-       if (ret == 0) {
-               FontCached *fc = new FontCached(fp);
-               fc->next = first;
-               first = fc;
-               ret = fc->fid;
-       }
-       FontMutexUnlock();
-       return ret;
-}
-
-void FontCached::ReleaseId(FontID fid_) {
-       FontMutexLock();
-       FontCached **pcur = &first;
-       for (FontCached *cur = first; cur; cur = cur->next) {
-               if (cur->fid == fid_) {
-                       cur->usage--;
-                       if (cur->usage == 0) {
-                               *pcur = cur->next;
-                               cur->Release();
-                               cur->next = 0;
-                               delete cur;
-                       }
-                       break;
-               }
-               pcur = &cur->next;
-       }
-       FontMutexUnlock();
-}
-
-void FontCached::ReleaseAll() {
-       while (first) {
-               ReleaseId(first->GetID());
-       }
-}
-
-FontID FontCached::CreateNewFont(const FontParameters &fp) {
-       PangoFontDescription *pfd = pango_font_description_new();
-       if (pfd) {
-               pango_font_description_set_family(pfd, 
-                       (fp.faceName[0] == '!') ? fp.faceName+1 : fp.faceName);
-               pango_font_description_set_size(pfd, pangoUnitsFromDouble(fp.size));
-               pango_font_description_set_weight(pfd, static_cast<PangoWeight>(fp.weight));
-               pango_font_description_set_style(pfd, fp.italic ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL);
-               return new FontHandle(pfd, fp.characterSet);
-       }
-
-       return new FontHandle();
-}
-
 Font::Font() : fid(0) {}
 
 Font::~Font() {}
 
 void Font::Create(const FontParameters &fp) {
        Release();
-       fid = FontCached::FindOrCreate(fp);
+       fid = FontHandle::CreateNewFont(fp);
 }
 
 void Font::Release() {
        if (fid)
-               FontCached::ReleaseId(fid);
+               delete static_cast<FontHandle *>(fid);
        fid = 0;
 }
 
@@ -384,49 +163,50 @@ class SurfaceImpl : public Surface {
        void SetConverter(int characterSet_);
 public:
        SurfaceImpl();
-       virtual ~SurfaceImpl();
-
-       void Init(WindowID wid);
-       void Init(SurfaceID sid, WindowID wid);
-       void InitPixMap(int width, int height, Surface *surface_, WindowID wid);
-
-       void Release();
-       bool Initialised();
-       void PenColour(ColourDesired fore);
-       int LogPixelsY();
-       int DeviceHeightFont(int points);
-       void MoveTo(int x_, int y_);
-       void LineTo(int x_, int y_);
-       void Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back);
-       void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back);
-       void FillRectangle(PRectangle rc, ColourDesired back);
-       void FillRectangle(PRectangle rc, Surface &surfacePattern);
-       void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back);
+       ~SurfaceImpl() override;
+
+       void Init(WindowID wid) override;
+       void Init(SurfaceID sid, WindowID wid) override;
+       void InitPixMap(int width, int height, Surface *surface_, WindowID wid) override;
+
+       void Clear();
+       void Release() override;
+       bool Initialised() override;
+       void PenColour(ColourDesired fore) override;
+       int LogPixelsY() override;
+       int DeviceHeightFont(int points) override;
+       void MoveTo(int x_, int y_) override;
+       void LineTo(int x_, int y_) override;
+       void Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back) override;
+       void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back) override;
+       void FillRectangle(PRectangle rc, ColourDesired back) override;
+       void FillRectangle(PRectangle rc, Surface &surfacePattern) override;
+       void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back) override;
        void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
-               ColourDesired outline, int alphaOutline, int flags);
-       void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage);
-       void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back);
-       void Copy(PRectangle rc, Point from, Surface &surfaceSource);
+               ColourDesired outline, int alphaOutline, int flags) override;
+       void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) override;
+       void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back) override;
+       void Copy(PRectangle rc, Point from, Surface &surfaceSource) override;
 
        void DrawTextBase(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired 
fore);
-       void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, 
ColourDesired fore, ColourDesired back);
-       void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, 
ColourDesired fore, ColourDesired back);
-       void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, 
ColourDesired fore);
-       void MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions);
-       XYPOSITION WidthText(Font &font_, const char *s, int len);
-       XYPOSITION WidthChar(Font &font_, char ch);
-       XYPOSITION Ascent(Font &font_);
-       XYPOSITION Descent(Font &font_);
-       XYPOSITION InternalLeading(Font &font_);
-       XYPOSITION ExternalLeading(Font &font_);
-       XYPOSITION Height(Font &font_);
-       XYPOSITION AverageCharWidth(Font &font_);
-
-       void SetClip(PRectangle rc);
-       void FlushCachedState();
-
-       void SetUnicodeMode(bool unicodeMode_);
-       void SetDBCSMode(int codePage);
+       void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, 
ColourDesired fore, ColourDesired back) override;
+       void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, 
ColourDesired fore, ColourDesired back) override;
+       void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, 
ColourDesired fore) override;
+       void MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions) override;
+       XYPOSITION WidthText(Font &font_, const char *s, int len) override;
+       XYPOSITION WidthChar(Font &font_, char ch) override;
+       XYPOSITION Ascent(Font &font_) override;
+       XYPOSITION Descent(Font &font_) override;
+       XYPOSITION InternalLeading(Font &font_) override;
+       XYPOSITION ExternalLeading(Font &font_) override;
+       XYPOSITION Height(Font &font_) override;
+       XYPOSITION AverageCharWidth(Font &font_) override;
+
+       void SetClip(PRectangle rc) override;
+       void FlushCachedState() override;
+
+       void SetUnicodeMode(bool unicodeMode_) override;
+       void SetDBCSMode(int codePage) override;
 };
 #ifdef SCI_NAMESPACE
 }
@@ -456,6 +236,8 @@ const char *CharacterSetID(int characterSet) {
                return "ASCII";
        case SC_CHARSET_RUSSIAN:
                return "KOI8-R";
+       case SC_CHARSET_OEM866:
+               return "CP866";
        case SC_CHARSET_CYRILLIC:
                return "CP1251";
        case SC_CHARSET_SHIFTJIS:
@@ -496,10 +278,10 @@ x(0), y(0), inited(false), createdGC(false)
 }
 
 SurfaceImpl::~SurfaceImpl() {
-       Release();
+       Clear();
 }
 
-void SurfaceImpl::Release() {
+void SurfaceImpl::Clear() {
        et = singleByte;
        if (createdGC) {
                createdGC = false;
@@ -523,28 +305,39 @@ void SurfaceImpl::Release() {
        createdGC = false;
 }
 
+void SurfaceImpl::Release() {
+       Clear();
+}
+
 bool SurfaceImpl::Initialised() {
+#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 8, 0)
+       if (inited && context) {
+               if (cairo_status(context) == CAIRO_STATUS_SUCCESS) {
+                       // Even when status is success, the target surface may have been
+                       // finished whch may cause an assertion to fail crashing the application.
+                       // The cairo_surface_has_show_text_glyphs call checks the finished flag
+                       // and when set, sets the status to CAIRO_STATUS_SURFACE_FINISHED
+                       // which leads to warning messages instead of crashes.
+                       // Performing the check in this method as it is called rarely and has no
+                       // other side effects.
+                       cairo_surface_t *psurfContext = cairo_get_target(context);
+                       if (psurfContext) {
+                               cairo_surface_has_show_text_glyphs(psurfContext);
+                       }
+               }
+               return cairo_status(context) == CAIRO_STATUS_SUCCESS;
+       }
+#endif
        return inited;
 }
 
 void SurfaceImpl::Init(WindowID wid) {
        Release();
        PLATFORM_ASSERT(wid);
-#if GTK_CHECK_VERSION(3,0,0)
-       GdkWindow *drawable_ = gtk_widget_get_window(PWidget(wid));
-#else
-       GdkDrawable *drawable_ = GDK_DRAWABLE(PWidget(wid)->window);
-#endif
-       if (drawable_) {
-               context = gdk_cairo_create(drawable_);
-               PLATFORM_ASSERT(context);
-       } else {
-               // Shouldn't happen with valid window but may when calls made before
-               // window completely allocated and mapped.
-               psurf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 1, 1);
-               context = cairo_create(psurf);
-       }
-       createdGC = true;
+       // if we are only created from a window ID, we can't perform drawing
+       psurf = 0;
+       context = 0;
+       createdGC = false;
        pcontext = gtk_widget_create_pango_context(PWidget(wid));
        PLATFORM_ASSERT(pcontext);
        layout = pango_layout_new(pcontext);
@@ -556,7 +349,7 @@ void SurfaceImpl::Init(SurfaceID sid, WindowID wid) {
        PLATFORM_ASSERT(sid);
        Release();
        PLATFORM_ASSERT(wid);
-       context = cairo_reference(reinterpret_cast<cairo_t *>(sid));
+       context = cairo_reference(static_cast<cairo_t *>(sid));
        pcontext = gtk_widget_create_pango_context(PWidget(wid));
        // update the Pango context in case sid isn't the widget's surface
        pango_cairo_update_context(context, pcontext);
@@ -592,6 +385,7 @@ void SurfaceImpl::InitPixMap(int width, int height, Surface *surface_, WindowID
        cairo_set_line_width(context, 1);
        createdGC = true;
        inited = true;
+       et = surfImpl->et;
 }
 
 void SurfaceImpl::PenColour(ColourDesired fore) {
@@ -662,9 +456,10 @@ void SurfaceImpl::LineTo(int x_, int y_) {
 
 void SurfaceImpl::Polygon(Point *pts, int npts, ColourDesired fore,
                           ColourDesired back) {
+       PLATFORM_ASSERT(context);
        PenColour(back);
        cairo_move_to(context, pts[0].x + 0.5, pts[0].y + 0.5);
-       for (int i = 1;i < npts;i++) {
+       for (int i = 1; i < npts; i++) {
                cairo_line_to(context, pts[i].x + 0.5, pts[i].y + 0.5);
        }
        cairo_close_path(context);
@@ -697,8 +492,9 @@ void SurfaceImpl::FillRectangle(PRectangle rc, ColourDesired back) {
 
 void SurfaceImpl::FillRectangle(PRectangle rc, Surface &surfacePattern) {
        SurfaceImpl &surfi = static_cast<SurfaceImpl &>(surfacePattern);
-       bool canDraw = surfi.psurf;
+       bool canDraw = surfi.psurf != NULL;
        if (canDraw) {
+               PLATFORM_ASSERT(context);
                // Tile pattern over rectangle
                // Currently assumes 8x8 pattern
                int widthPat = 8;
@@ -732,14 +528,14 @@ void SurfaceImpl::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesi
                                  Point(rc.left, rc.bottom - 2),
                                  Point(rc.left, rc.top + 2),
                              };
-               Polygon(pts, sizeof(pts) / sizeof(pts[0]), fore, back);
+               Polygon(pts, ELEMENTS(pts), fore, back);
        } else {
                RectangleDraw(rc, fore, back);
        }
 }
 
 static void PathRoundRectangle(cairo_t *context, double left, double top, double width, double height, int 
radius) {
-       double degrees = M_PI / 180.0;
+       double degrees = kPi / 180.0;
 
 #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 2, 0)
        cairo_new_sub_path(context);
@@ -755,7 +551,7 @@ static void PathRoundRectangle(cairo_t *context, double left, double top, double
 }
 
 void SurfaceImpl::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
-               ColourDesired outline, int alphaOutline, int flags) {
+               ColourDesired outline, int alphaOutline, int /*flags*/) {
        if (context && rc.Width() > 0) {
                ColourDesired cdFill(fill.AsLong());
                cairo_set_source_rgba(context,
@@ -784,6 +580,7 @@ void SurfaceImpl::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fi
 }
 
 void SurfaceImpl::DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) {
+       PLATFORM_ASSERT(context);
        if (rc.Width() > width)
                rc.left += (rc.Width() - width) / 2;
        rc.right = rc.left + width;
@@ -798,9 +595,9 @@ void SurfaceImpl::DrawRGBAImage(PRectangle rc, int width, int height, const unsi
 #endif
        int ucs = stride * height;
        std::vector<unsigned char> image(ucs);
-       for (int y=0; y<height; y++) {
-               for (int x=0; x<width; x++) {
-                       unsigned char *pixel = &image[0] + y*stride + x * 4;
+       for (int iy=0; iy<height; iy++) {
+               for (int ix=0; ix<width; ix++) {
+                       unsigned char *pixel = &image[0] + iy*stride + ix * 4;
                        unsigned char alpha = pixelsImage[3];
                        pixel[2] = (*pixelsImage++) * alpha / 255;
                        pixel[1] = (*pixelsImage++) * alpha / 255;
@@ -809,18 +606,19 @@ void SurfaceImpl::DrawRGBAImage(PRectangle rc, int width, int height, const unsi
                }
        }
 
-       cairo_surface_t *psurf = cairo_image_surface_create_for_data(&image[0], CAIRO_FORMAT_ARGB32, width, 
height, stride);
-       cairo_set_source_surface(context, psurf, rc.left, rc.top);
+       cairo_surface_t *psurfImage = cairo_image_surface_create_for_data(&image[0], CAIRO_FORMAT_ARGB32, 
width, height, stride);
+       cairo_set_source_surface(context, psurfImage, rc.left, rc.top);
        cairo_rectangle(context, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top);
        cairo_fill(context);
 
-       cairo_surface_destroy(psurf);
+       cairo_surface_destroy(psurfImage);
 }
 
 void SurfaceImpl::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back) {
+       PLATFORM_ASSERT(context);
        PenColour(back);
-       cairo_arc(context, (rc.left + rc.right) / 2 + 0.5, (rc.top + rc.bottom) / 2 + 0.5,
-               Platform::Minimum(rc.Width(), rc.Height()) / 2, 0, 2*M_PI);
+       cairo_arc(context, (rc.left + rc.right) / 2, (rc.top + rc.bottom) / 2,
+               Platform::Minimum(rc.Width(), rc.Height()) / 2, 0, 2*kPi);
        cairo_fill_preserve(context);
        PenColour(fore);
        cairo_stroke(context);
@@ -828,8 +626,9 @@ void SurfaceImpl::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back)
 
 void SurfaceImpl::Copy(PRectangle rc, Point from, Surface &surfaceSource) {
        SurfaceImpl &surfi = static_cast<SurfaceImpl &>(surfaceSource);
-       bool canDraw = surfi.psurf;
+       bool canDraw = surfi.psurf != NULL;
        if (canDraw) {
+               PLATFORM_ASSERT(context);
                cairo_set_source_surface(context, surfi.psurf,
                        rc.left - from.x, rc.top - from.y);
                cairo_rectangle(context, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top);
@@ -840,7 +639,7 @@ void SurfaceImpl::Copy(PRectangle rc, Point from, Surface &surfaceSource) {
 std::string UTF8FromLatin1(const char *s, int len) {
        std::string utfForm(len*2 + 1, '\0');
        size_t lenU = 0;
-       for (int i=0;i<len;i++) {
+       for (int i=0; i<len; i++) {
                unsigned int uch = static_cast<unsigned char>(s[i]);
                if (uch < 0x80) {
                        utfForm[lenU++] = uch;
@@ -857,12 +656,12 @@ static std::string UTF8FromIconv(const Converter &conv, const char *s, int len)
        if (conv) {
                std::string utfForm(len*3+1, '\0');
                char *pin = const_cast<char *>(s);
-               size_t inLeft = len;
+               gsize inLeft = len;
                char *putf = &utfForm[0];
                char *pout = putf;
-               size_t outLeft = len*3+1;
-               size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
-               if (conversions != ((size_t)(-1))) {
+               gsize outLeft = len*3+1;
+               gsize conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
+               if (conversions != sizeFailure) {
                        *pout = '\0';
                        utfForm.resize(pout - putf);
                        return utfForm;
@@ -877,29 +676,17 @@ static size_t MultiByteLenFromIconv(const Converter &conv, const char *s, size_t
        for (size_t lenMB=1; (lenMB<4) && (lenMB <= len); lenMB++) {
                char wcForm[2];
                char *pin = const_cast<char *>(s);
-               size_t inLeft = lenMB;
+               gsize inLeft = lenMB;
                char *pout = wcForm;
-               size_t outLeft = 2;
-               size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
-               if (conversions != ((size_t)(-1))) {
+               gsize outLeft = 2;
+               gsize conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
+               if (conversions != sizeFailure) {
                        return lenMB;
                }
        }
        return 1;
 }
 
-static size_t UTF8CharLength(const char *s) {
-       const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
-       unsigned char ch = *us;
-       if (ch < 0x80) {
-               return 1;
-       } else if (ch < 0x80 + 0x40 + 0x20) {
-               return 2;
-       } else {
-               return 3;
-       }
-}
-
 void SurfaceImpl::DrawTextBase(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
                                  ColourDesired fore) {
        PenColour(fore);
@@ -946,7 +733,7 @@ void SurfaceImpl::DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase,
 void SurfaceImpl::DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
                                   ColourDesired fore) {
        // Avoid drawing spaces in transparent mode
-       for (int i=0;i<len;i++) {
+       for (int i=0; i<len; i++) {
                if (s[i] != ' ') {
                        DrawTextBase(rc, font_, ybase, s, len, fore);
                        return;
@@ -992,13 +779,6 @@ void SurfaceImpl::MeasureWidths(Font &font_, const char *s, int len, XYPOSITION
        if (font_.GetID()) {
                const int lenPositions = len;
                if (PFont(font_)->pfd) {
-                       if (len == 1) {
-                               int width = PFont(font_)->CharWidth(*s, et);
-                               if (width) {
-                                       positions[0] = width;
-                                       return;
-                               }
-                       }
                        pango_layout_set_font_description(layout, PFont(font_)->pfd);
                        if (et == UTF8) {
                                // Simple and direct as UTF-8 is native Pango encoding
@@ -1043,7 +823,7 @@ void SurfaceImpl::MeasureWidths(Font &font_, const char *s, int len, XYPOSITION
                                                                        positions[i++] = iti.position - 
(places - place) * iti.distance / places;
                                                                        positionsCalculated++;
                                                                }
-                                                               clusterStart += 
UTF8CharLength(utfForm.c_str()+clusterStart);
+                                                               clusterStart += 
UTF8CharLength(static_cast<unsigned char>(utfForm.c_str()[clusterStart]));
                                                                place++;
                                                        }
                                                }
@@ -1051,8 +831,10 @@ void SurfaceImpl::MeasureWidths(Font &font_, const char *s, int len, XYPOSITION
                                        }
                                }
                                if (positionsCalculated < 1 ) {
-                                       // Either Latin1 or DBCS conversion failed so treat as Latin1.
+                                       // Either 8-bit or DBCS conversion failed so treat as 8-bit.
                                        SetConverter(PFont(font_)->characterSet);
+                                       const bool rtlCheck = PFont(font_)->characterSet == SC_CHARSET_HEBREW 
||
+                                               PFont(font_)->characterSet == SC_CHARSET_ARABIC;
                                        std::string utfForm = UTF8FromIconv(conv, s, len);
                                        if (utfForm.empty()) {
                                                utfForm = UTF8FromLatin1(s, len);
@@ -1060,26 +842,36 @@ void SurfaceImpl::MeasureWidths(Font &font_, const char *s, int len, XYPOSITION
                                        pango_layout_set_text(layout, utfForm.c_str(), utfForm.length());
                                        int i = 0;
                                        int clusterStart = 0;
-                                       // Each Latin1 input character may take 1 or 2 bytes in UTF-8
+                                       // Each 8-bit input character may take 1 or 2 bytes in UTF-8
                                        // and groups of up to 3 may be represented as ligatures.
                                        ClusterIterator iti(layout, utfForm.length());
                                        while (!iti.finished) {
                                                iti.Next();
                                                int clusterEnd = iti.curIndex;
                                                int ligatureLength = g_utf8_strlen(utfForm.c_str() + 
clusterStart, clusterEnd - clusterStart);
+                                               if (rtlCheck && ((clusterEnd <= clusterStart) || 
(ligatureLength == 0) || (ligatureLength > 3))) {
+                                                       // Something has gone wrong: exit quickly but pretend 
all the characters are equally spaced:
+                                                       int widthLayout = 0;
+                                                       pango_layout_get_size(layout, &widthLayout, NULL);
+                                                       XYPOSITION widthTotal = 
doubleFromPangoUnits(widthLayout);
+                                                       for (int bytePos=0; bytePos<lenPositions; bytePos++) {
+                                                               positions[bytePos] = widthTotal / 
lenPositions * (bytePos + 1);
+                                                       }
+                                                       return;
+                                               }
                                                PLATFORM_ASSERT(ligatureLength > 0 && ligatureLength <= 3);
                                                for (int charInLig=0; charInLig<ligatureLength; charInLig++) {
                                                        positions[i++] = iti.position - (ligatureLength - 1 - 
charInLig) * iti.distance / ligatureLength;
                                                }
                                                clusterStart = clusterEnd;
                                        }
+                                       while (i < lenPositions) {
+                                               // If something failed, fill in rest of the positions
+                                               positions[i++] = clusterStart;
+                                       }
                                        PLATFORM_ASSERT(i == lenPositions);
                                }
                        }
-                       if (len == 1) {
-                               PFont(font_)->SetCharWidth(*s, positions[0], et);
-                       }
-                       return;
                }
        } else {
                // No font so return an ascending range of values
@@ -1135,20 +927,17 @@ XYPOSITION SurfaceImpl::WidthChar(Font &font_, char ch) {
 XYPOSITION SurfaceImpl::Ascent(Font &font_) {
        if (!(font_.GetID()))
                return 1;
-       FontMutexLock();
-       int ascent = PFont(font_)->ascent;
-       if ((ascent == 0) && (PFont(font_)->pfd)) {
+       int ascent = 0;
+       if (PFont(font_)->pfd) {
                PangoFontMetrics *metrics = pango_context_get_metrics(pcontext,
                        PFont(font_)->pfd, pango_context_get_language(pcontext));
-               PFont(font_)->ascent =
+               ascent =
                        doubleFromPangoUnits(pango_font_metrics_get_ascent(metrics));
                pango_font_metrics_unref(metrics);
-               ascent = PFont(font_)->ascent;
        }
        if (ascent == 0) {
                ascent = 1;
        }
-       FontMutexUnlock();
        return ascent;
 }
 
@@ -1182,6 +971,7 @@ XYPOSITION SurfaceImpl::AverageCharWidth(Font &font_) {
 }
 
 void SurfaceImpl::SetClip(PRectangle rc) {
+       PLATFORM_ASSERT(context);
        cairo_rectangle(context, rc.left, rc.top, rc.right, rc.bottom);
        cairo_clip(context);
 }
@@ -1205,13 +995,24 @@ Surface *Surface::Allocate(int) {
 Window::~Window() {}
 
 void Window::Destroy() {
-       if (wid)
-               gtk_widget_destroy(GTK_WIDGET(wid));
-       wid = 0;
+       if (wid) {
+               ListBox *listbox = dynamic_cast<ListBox*>(this);
+               if (listbox) {
+                       gtk_widget_hide(GTK_WIDGET(wid));
+                       // clear up window content
+                       listbox->Clear();
+                       // resize the window to the smallest possible size for it to adapt
+                       // to future content
+                       gtk_window_resize(GTK_WINDOW(wid), 1, 1);
+               } else {
+                       gtk_widget_destroy(GTK_WIDGET(wid));
+               }
+               wid = 0;
+       }
 }
 
 bool Window::HasFocus() {
-       return IS_WIDGET_FOCUSSED(wid);
+       return gtk_widget_has_focus(GTK_WIDGET(wid));
 }
 
 PRectangle Window::GetPosition() {
@@ -1219,11 +1020,7 @@ PRectangle Window::GetPosition() {
        PRectangle rc(0, 0, 1000, 1000);
        if (wid) {
                GtkAllocation allocation;
-#if GTK_CHECK_VERSION(3,0,0)
                gtk_widget_get_allocation(PWidget(wid), &allocation);
-#else
-               allocation = PWidget(wid)->allocation;
-#endif
                rc.left = allocation.x;
                rc.top = allocation.y;
                if (allocation.width > 20) {
@@ -1243,32 +1040,50 @@ void Window::SetPosition(PRectangle rc) {
        gtk_widget_size_allocate(PWidget(wid), &alloc);
 }
 
+namespace {
+
+GdkRectangle MonitorRectangleForWidget(GtkWidget *wid) {
+       GdkWindow *wnd = WindowFromWidget(wid);
+       GdkRectangle rcScreen = GdkRectangle();
+#if GTK_CHECK_VERSION(3,22,0)
+       GdkDisplay *pdisplay = gtk_widget_get_display(wid);
+       GdkMonitor *monitor = gdk_display_get_monitor_at_window(pdisplay, wnd);
+       gdk_monitor_get_geometry(monitor, &rcScreen);
+#else
+       GdkScreen* screen = gtk_widget_get_screen(wid);
+       gint monitor_num = gdk_screen_get_monitor_at_window(screen, wnd);
+       gdk_screen_get_monitor_geometry(screen, monitor_num, &rcScreen);
+#endif
+       return rcScreen;
+}
+
+}
+
 void Window::SetPositionRelative(PRectangle rc, Window relativeTo) {
        int ox = 0;
        int oy = 0;
-       gdk_window_get_origin(WindowFromWidget(PWidget(relativeTo.wid)), &ox, &oy);
+       GdkWindow *wndRelativeTo = WindowFromWidget(PWidget(relativeTo.wid));
+       gdk_window_get_origin(wndRelativeTo, &ox, &oy);
        ox += rc.left;
-       if (ox < 0)
-               ox = 0;
        oy += rc.top;
-       if (oy < 0)
-               oy = 0;
+
+       GdkRectangle rcMonitor = MonitorRectangleForWidget(PWidget(relativeTo.wid));
 
        /* do some corrections to fit into screen */
        int sizex = rc.right - rc.left;
        int sizey = rc.bottom - rc.top;
-       int screenWidth = gdk_screen_width();
-       int screenHeight = gdk_screen_height();
-       if (sizex > screenWidth)
-               ox = 0; /* the best we can do */
-       else if (ox + sizex > screenWidth)
-               ox = screenWidth - sizex;
-       if (oy + sizey > screenHeight)
-               oy = screenHeight - sizey;
+       if (sizex > rcMonitor.width || ox < rcMonitor.x)
+               ox = rcMonitor.x; /* the best we can do */
+       else if (ox + sizex > rcMonitor.x + rcMonitor.width)
+               ox = rcMonitor.x + rcMonitor.width - sizex;
+       if (sizey > rcMonitor.height || oy < rcMonitor.y)
+               oy = rcMonitor.y;
+       else if (oy + sizey > rcMonitor.y + rcMonitor.height)
+               oy = rcMonitor.y + rcMonitor.height - sizey;
 
        gtk_window_move(GTK_WINDOW(PWidget(wid)), ox, oy);
 
-       gtk_widget_set_size_request(PWidget(wid), sizex, sizey);
+       gtk_window_resize(GTK_WINDOW(wid), sizex, sizey);
 }
 
 PRectangle Window::GetClientPosition() {
@@ -1306,28 +1121,30 @@ void Window::SetCursor(Cursor curs) {
                return;
 
        cursorLast = curs;
+       GdkDisplay *pdisplay = gtk_widget_get_display(PWidget(wid));
+
        GdkCursor *gdkCurs;
        switch (curs) {
        case cursorText:
-               gdkCurs = gdk_cursor_new(GDK_XTERM);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
                break;
        case cursorArrow:
-               gdkCurs = gdk_cursor_new(GDK_LEFT_PTR);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
                break;
        case cursorUp:
-               gdkCurs = gdk_cursor_new(GDK_CENTER_PTR);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_CENTER_PTR);
                break;
        case cursorWait:
-               gdkCurs = gdk_cursor_new(GDK_WATCH);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_WATCH);
                break;
        case cursorHand:
-               gdkCurs = gdk_cursor_new(GDK_HAND2);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_HAND2);
                break;
        case cursorReverseArrow:
-               gdkCurs = gdk_cursor_new(GDK_RIGHT_PTR);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_RIGHT_PTR);
                break;
        default:
-               gdkCurs = gdk_cursor_new(GDK_LEFT_PTR);
+               gdkCurs = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
                cursorLast = cursorArrow;
                break;
        }
@@ -1352,13 +1169,19 @@ PRectangle Window::GetMonitorRect(Point pt) {
 
        gdk_window_get_origin(WindowFromWidget(PWidget(wid)), &x_offset, &y_offset);
 
-       GdkScreen* screen;
-       gint monitor_num;
        GdkRectangle rect;
 
-       screen = gtk_widget_get_screen(PWidget(wid));
-       monitor_num = gdk_screen_get_monitor_at_point(screen, pt.x + x_offset, pt.y + y_offset);
+#if GTK_CHECK_VERSION(3,22,0)
+       GdkDisplay *pdisplay = gtk_widget_get_display(PWidget(wid));
+       GdkMonitor *monitor = gdk_display_get_monitor_at_point(pdisplay,
+               pt.x + x_offset, pt.y + y_offset);
+       gdk_monitor_get_geometry(monitor, &rect);
+#else
+       GdkScreen* screen = gtk_widget_get_screen(PWidget(wid));
+       gint monitor_num = gdk_screen_get_monitor_at_point(screen,
+               pt.x + x_offset, pt.y + y_offset);
        gdk_screen_get_monitor_geometry(screen, monitor_num, &rect);
+#endif
        rect.x -= x_offset;
        rect.y -= y_offset;
        return PRectangle(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
@@ -1391,51 +1214,73 @@ enum {
 };
 
 class ListBoxX : public ListBox {
+       WindowID widCached;
+       WindowID frame;
        WindowID list;
        WindowID scroller;
        void *pixhash;
        GtkCellRenderer* pixbuf_renderer;
+       GtkCellRenderer* renderer;
        RGBAImageSet images;
        int desiredVisibleRows;
        unsigned int maxItemCharacters;
        unsigned int aveCharWidth;
+#if GTK_CHECK_VERSION(3,0,0)
+       GtkCssProvider *cssProvider;
+#endif
 public:
        CallBackAction doubleClickAction;
        void *doubleClickActionData;
 
-       ListBoxX() : list(0), scroller(0), pixhash(NULL), pixbuf_renderer(0),
+       ListBoxX() : widCached(0), frame(0), list(0), scroller(0), pixhash(NULL), pixbuf_renderer(0),
+               renderer(0),
                desiredVisibleRows(5), maxItemCharacters(0),
-               aveCharWidth(1), doubleClickAction(NULL), doubleClickActionData(NULL) {
+               aveCharWidth(1),
+#if GTK_CHECK_VERSION(3,0,0)
+               cssProvider(NULL),
+#endif
+               doubleClickAction(NULL), doubleClickActionData(NULL) {
        }
-       virtual ~ListBoxX() {
+       ~ListBoxX() override {
                if (pixhash) {
                        g_hash_table_foreach((GHashTable *) pixhash, list_image_free, NULL);
                        g_hash_table_destroy((GHashTable *) pixhash);
                }
+               if (widCached) {
+                       gtk_widget_destroy(GTK_WIDGET(widCached));
+                       wid = widCached = 0;
+               }
+#if GTK_CHECK_VERSION(3,0,0)
+               if (cssProvider) {
+                       g_object_unref(cssProvider);
+                       cssProvider = NULL;
+               }
+#endif
        }
-       virtual void SetFont(Font &font);
-       virtual void Create(Window &parent, int ctrlID, Point location_, int lineHeight_, bool unicodeMode_, 
int technology_);
-       virtual void SetAverageCharWidth(int width);
-       virtual void SetVisibleRows(int rows);
-       virtual int GetVisibleRows() const;
-       virtual PRectangle GetDesiredRect();
-       virtual int CaretFromEdge();
-       virtual void Clear();
-       virtual void Append(char *s, int type = -1);
-       virtual int Length();
-       virtual void Select(int n);
-       virtual int GetSelection();
-       virtual int Find(const char *prefix);
-       virtual void GetValue(int n, char *value, int len);
+       void SetFont(Font &font) override;
+       void Create(Window &parent, int ctrlID, Point location_, int lineHeight_, bool unicodeMode_, int 
technology_) override;
+       void SetAverageCharWidth(int width) override;
+       void SetVisibleRows(int rows) override;
+       int GetVisibleRows() const override;
+       int GetRowHeight();
+       PRectangle GetDesiredRect() override;
+       int CaretFromEdge() override;
+       void Clear() override;
+       void Append(char *s, int type = -1) override;
+       int Length() override;
+       void Select(int n) override;
+       int GetSelection() override;
+       int Find(const char *prefix) override;
+       void GetValue(int n, char *value, int len) override;
        void RegisterRGBA(int type, RGBAImage *image);
-       virtual void RegisterImage(int type, const char *xpm_data);
-       virtual void RegisterRGBAImage(int type, int width, int height, const unsigned char *pixelsImage);
-       virtual void ClearRegisteredImages();
-       virtual void SetDoubleClickAction(CallBackAction action, void *data) {
+       void RegisterImage(int type, const char *xpm_data) override;
+       void RegisterRGBAImage(int type, int width, int height, const unsigned char *pixelsImage) override;
+       void ClearRegisteredImages() override;
+       void SetDoubleClickAction(CallBackAction action, void *data) override {
                doubleClickAction = action;
                doubleClickActionData = data;
        }
-       virtual void SetList(const char *listText, char separator, char typesep);
+       void SetList(const char *listText, char separator, char typesep) override;
 };
 
 ListBox *ListBox::Allocate() {
@@ -1443,9 +1288,88 @@ ListBox *ListBox::Allocate() {
        return lb;
 }
 
+static int treeViewGetRowHeight(GtkTreeView *view) {
+#if GTK_CHECK_VERSION(3,0,0)
+       // This version sometimes reports erroneous results on GTK2, but the GTK2
+       // version is inaccurate for GTK 3.14.
+       GdkRectangle rect;
+       GtkTreePath *path = gtk_tree_path_new_first();
+       gtk_tree_view_get_background_area(view, path, NULL, &rect);
+       gtk_tree_path_free(path);
+       return rect.height;
+#else
+       int row_height=0;
+       int vertical_separator=0;
+       int expander_size=0;
+       GtkTreeViewColumn *column = gtk_tree_view_get_column(view, 0);
+       gtk_tree_view_column_cell_get_size(column, NULL, NULL, NULL, NULL, &row_height);
+       gtk_widget_style_get(GTK_WIDGET(view),
+               "vertical-separator", &vertical_separator,
+               "expander-size", &expander_size, NULL);
+       row_height += vertical_separator;
+       row_height = Platform::Maximum(row_height, expander_size);
+       return row_height;
+#endif
+}
+
+// SmallScroller, a GtkScrolledWindow that can shrink very small, as
+// gtk_widget_set_size_request() cannot shrink widgets on GTK3
+typedef struct {
+       GtkScrolledWindow parent;
+       /* Workaround ABI issue with Windows GTK2 bundle and GCC > 3.
+          See http://lists.geany.org/pipermail/devel/2015-April/thread.html#9379
+
+          GtkScrolledWindow contains a bitfield, and GCC 3.4 and 4.8 don't agree
+          on the size of the structure (regardless of -mms-bitfields):
+          - GCC 3.4 has sizeof(GtkScrolledWindow)=88
+          - GCC 4.8 has sizeof(GtkScrolledWindow)=84
+          As Windows GTK2 bundle is built with GCC 3, it requires types derived
+          from GtkScrolledWindow to be at least 88 bytes, which means we need to
+          add some fake padding to fill in the extra 4 bytes.
+          There is however no other issue with the layout difference as we never
+          access any GtkScrolledWindow fields ourselves. */
+       int padding;
+} SmallScroller;
+typedef GtkScrolledWindowClass SmallScrollerClass;
+
+G_DEFINE_TYPE(SmallScroller, small_scroller, GTK_TYPE_SCROLLED_WINDOW)
+
+#if GTK_CHECK_VERSION(3,0,0)
+static void small_scroller_get_preferred_height(GtkWidget *widget, gint *min, gint *nat) {
+       GtkWidget *child = gtk_bin_get_child(GTK_BIN(widget));
+       if (GTK_IS_TREE_VIEW(child)) {
+               GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(child));
+               int n_rows = gtk_tree_model_iter_n_children(model, NULL);
+               int row_height = treeViewGetRowHeight(GTK_TREE_VIEW(child));
+
+               *min = MAX(1, row_height);
+               *nat = MAX(*min, n_rows * row_height);
+       } else {
+               GTK_WIDGET_CLASS(small_scroller_parent_class)->get_preferred_height(widget, min, nat);
+               if (*min > 1)
+                       *min = 1;
+       }
+}
+#else
+static void small_scroller_size_request(GtkWidget *widget, GtkRequisition *req) {
+       GTK_WIDGET_CLASS(small_scroller_parent_class)->size_request(widget, req);
+       req->height = 1;
+}
+#endif
+
+static void small_scroller_class_init(SmallScrollerClass *klass) {
+#if GTK_CHECK_VERSION(3,0,0)
+       GTK_WIDGET_CLASS(klass)->get_preferred_height = small_scroller_get_preferred_height;
+#else
+       GTK_WIDGET_CLASS(klass)->size_request = small_scroller_size_request;
+#endif
+}
+
+static void small_scroller_init(SmallScroller *){}
+
 static gboolean ButtonPress(GtkWidget *, GdkEventButton* ev, gpointer p) {
        try {
-               ListBoxX* lb = reinterpret_cast<ListBoxX*>(p);
+               ListBoxX* lb = static_cast<ListBoxX*>(p);
                if (ev->type == GDK_2BUTTON_PRESS && lb->doubleClickAction != NULL) {
                        lb->doubleClickAction(lb->doubleClickActionData);
                        return TRUE;
@@ -1467,7 +1391,11 @@ static void StyleSet(GtkWidget *w, GtkStyle*, void*) {
        recursive calls to this function after the value is updated and w->style to
        be set to a new object */
 
-#if GTK_CHECK_VERSION(3,0,0)
+#if GTK_CHECK_VERSION(3,16,0)
+       // On recent releases of GTK+, it does not appear necessary to set the list box colours.
+       // This may be because of common themes and may be needed with other themes.
+       // The *override* calls are deprecated now, so only call them for older versions of GTK+.
+#elif GTK_CHECK_VERSION(3,0,0)
        GtkStyleContext *styleContext = gtk_widget_get_style_context(w);
        if (styleContext == NULL)
                return;
@@ -1503,16 +1431,27 @@ static void StyleSet(GtkWidget *w, GtkStyle*, void*) {
 #endif
 }
 
-void ListBoxX::Create(Window &, int, Point, int, bool, int) {
-       wid = gtk_window_new(GTK_WINDOW_POPUP);
+void ListBoxX::Create(Window &parent, int, Point, int, bool, int) {
+       if (widCached != 0) {
+               wid = widCached;
+               return;
+       }
+
+#if GTK_CHECK_VERSION(3,0,0)
+       if (!cssProvider) {
+               cssProvider = gtk_css_provider_new();
+       }
+#endif
+
+       wid = widCached = gtk_window_new(GTK_WINDOW_POPUP);
 
-       GtkWidget *frame = gtk_frame_new(NULL);
-       gtk_widget_show(frame);
-       gtk_container_add(GTK_CONTAINER(GetID()), frame);
+       frame = gtk_frame_new(NULL);
+       gtk_widget_show(PWidget(frame));
+       gtk_container_add(GTK_CONTAINER(GetID()), PWidget(frame));
        gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
        gtk_container_set_border_width(GTK_CONTAINER(frame), 0);
 
-       scroller = gtk_scrolled_window_new(NULL, NULL);
+       scroller = g_object_new(small_scroller_get_type(), NULL);
        gtk_container_set_border_width(GTK_CONTAINER(scroller), 0);
        gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroller),
                                       GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
@@ -1526,6 +1465,14 @@ void ListBoxX::Create(Window &, int, Point, int, bool, int) {
        list = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store));
        g_signal_connect(G_OBJECT(list), "style-set", G_CALLBACK(StyleSet), NULL);
 
+#if GTK_CHECK_VERSION(3,0,0)
+       GtkStyleContext *styleContext = gtk_widget_get_style_context(GTK_WIDGET(list));
+       if (styleContext) {
+               gtk_style_context_add_provider(styleContext, GTK_STYLE_PROVIDER(cssProvider),
+                       GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
+       }
+#endif
+
        GtkTreeSelection *selection =
                gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
        gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
@@ -1543,7 +1490,7 @@ void ListBoxX::Create(Window &, int, Point, int, bool, int) {
        gtk_tree_view_column_add_attribute(column, pixbuf_renderer,
                                                                                "pixbuf", PIXBUF_COLUMN);
 
-       GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
+       renderer = gtk_cell_renderer_text_new();
        gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(renderer), 1);
        gtk_tree_view_column_pack_start(column, renderer, TRUE);
        gtk_tree_view_column_add_attribute(column, renderer,
@@ -1553,23 +1500,48 @@ void ListBoxX::Create(Window &, int, Point, int, bool, int) {
        if (g_object_class_find_property(G_OBJECT_GET_CLASS(list), "fixed-height-mode"))
                g_object_set(G_OBJECT(list), "fixed-height-mode", TRUE, NULL);
 
-       GtkWidget *wid = PWidget(list); // No code inside the G_OBJECT macro
-       gtk_container_add(GTK_CONTAINER(PWidget(scroller)), wid);
-       gtk_widget_show(wid);
-       g_signal_connect(G_OBJECT(wid), "button_press_event",
+       GtkWidget *widget = PWidget(list);      // No code inside the G_OBJECT macro
+       gtk_container_add(GTK_CONTAINER(PWidget(scroller)), widget);
+       gtk_widget_show(widget);
+       g_signal_connect(G_OBJECT(widget), "button_press_event",
                           G_CALLBACK(ButtonPress), this);
-       gtk_widget_realize(PWidget(wid));
+
+       GtkWidget *top = gtk_widget_get_toplevel(static_cast<GtkWidget *>(parent.GetID()));
+       gtk_window_set_transient_for(GTK_WINDOW(static_cast<GtkWidget *>(wid)),
+               GTK_WINDOW(top));
 }
 
-void ListBoxX::SetFont(Font &scint_font) {
+void ListBoxX::SetFont(Font &font) {
        // Only do for Pango font as there have been crashes for GDK fonts
-       if (Created() && PFont(scint_font)->pfd) {
+       if (Created() && PFont(font)->pfd) {
                // Current font is Pango font
 #if GTK_CHECK_VERSION(3,0,0)
-               gtk_widget_override_font(PWidget(list), PFont(scint_font)->pfd);
+               if (cssProvider) {
+                       PangoFontDescription *pfd = PFont(font)->pfd;
+                       std::ostringstream ssFontSetting;
+                       ssFontSetting << "GtkTreeView, treeview { ";
+                       ssFontSetting << "font-family: " << pango_font_description_get_family(pfd) <<  "; ";
+                       ssFontSetting << "font-size:";
+                       ssFontSetting << static_cast<double>(pango_font_description_get_size(pfd)) / 
PANGO_SCALE;
+                       // On GTK < 3.21.0 the units are incorrectly parsed, so a font size in points
+                       // need to use the "px" unit.  Normally we only get fonts in points here, so
+                       // don't bother to handle the case the font is actually in pixels on < 3.21.0.
+                       if (gtk_check_version(3, 21, 0) != NULL || // on < 3.21.0
+                           pango_font_description_get_size_is_absolute(pfd)) {
+                               ssFontSetting << "px; ";
+                       } else {
+                               ssFontSetting << "pt; ";
+                       }
+                       ssFontSetting << "font-weight:"<< pango_font_description_get_weight(pfd) << "; ";
+                       ssFontSetting << "}";
+                       gtk_css_provider_load_from_data(GTK_CSS_PROVIDER(cssProvider),
+                               ssFontSetting.str().c_str(), -1, NULL);
+               }
 #else
-               gtk_widget_modify_font(PWidget(list), PFont(scint_font)->pfd);
+               gtk_widget_modify_font(PWidget(list), PFont(font)->pfd);
 #endif
+               gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(renderer), -1);
+               gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(renderer), 1);
        }
 }
 
@@ -1585,6 +1557,10 @@ int ListBoxX::GetVisibleRows() const {
        return desiredVisibleRows;
 }
 
+int ListBoxX::GetRowHeight() {
+       return treeViewGetRowHeight(GTK_TREE_VIEW(list));
+}
+
 PRectangle ListBoxX::GetDesiredRect() {
        // Before any size allocated pretend its 100 wide so not scrolled
        PRectangle rc(0, 0, 100, 100);
@@ -1594,53 +1570,87 @@ PRectangle ListBoxX::GetDesiredRect() {
                        rows = desiredVisibleRows;
 
                GtkRequisition req;
-#if GTK_CHECK_VERSION(3,0,0)
                // This, apparently unnecessary call, ensures gtk_tree_view_column_cell_get_size
-               // returns reasonable values. 
-               gtk_widget_get_preferred_size(GTK_WIDGET(scroller), NULL, &req);
+               // returns reasonable values.
+#if GTK_CHECK_VERSION(3,0,0)
+               gtk_widget_get_preferred_size(GTK_WIDGET(frame), NULL, &req);
+#else
+               gtk_widget_size_request(GTK_WIDGET(frame), &req);
 #endif
                int height;
 
                // First calculate height of the clist for our desired visible
                // row count otherwise it tries to expand to the total # of rows
                // Get cell height
-               int row_width=0;
-               int row_height=0;
-               GtkTreeViewColumn * column =
-                       gtk_tree_view_get_column(GTK_TREE_VIEW(list), 0);
-               gtk_tree_view_column_cell_get_size(column, NULL,
-                       NULL, NULL, &row_width, &row_height);
+               int row_height = GetRowHeight();
 #if GTK_CHECK_VERSION(3,0,0)
-               GtkStyleContext *styleContextList = gtk_widget_get_style_context(PWidget(list));
-               GtkBorder padding;
-               gtk_style_context_get_padding(styleContextList, GTK_STATE_FLAG_NORMAL, &padding);
+               GtkStyleContext *styleContextFrame = gtk_widget_get_style_context(PWidget(frame));
+               GtkStateFlags stateFlagsFrame = gtk_style_context_get_state(styleContextFrame);
+               GtkBorder padding, border, border_border = { 0, 0, 0, 0 };
+               gtk_style_context_get_padding(styleContextFrame, stateFlagsFrame, &padding);
+               gtk_style_context_get_border(styleContextFrame, stateFlagsFrame, &border);
+
+#      if GTK_CHECK_VERSION(3,20,0)
+               // on GTK 3.20 the frame border is in a sub-node "border".
+               // Unfortunately we need to be built against 3.20 to be able to support this, as it requires
+               // new API.
+               GtkStyleContext *styleContextFrameBorder = gtk_style_context_new();
+               GtkWidgetPath *widget_path = 
gtk_widget_path_copy(gtk_style_context_get_path(styleContextFrame));
+               gtk_widget_path_append_type(widget_path, GTK_TYPE_BORDER); // dummy type
+               gtk_widget_path_iter_set_object_name(widget_path, -1, "border");
+               gtk_style_context_set_path(styleContextFrameBorder, widget_path);
+               gtk_widget_path_free(widget_path);
+               gtk_style_context_get_border(styleContextFrameBorder, stateFlagsFrame, &border_border);
+               g_object_unref(styleContextFrameBorder);
+#      else // < 3.20
+               if (gtk_check_version(3, 20, 0) == NULL) {
+                       // default to 1px all around as it's likely what it is, and so we don't miss 2px 
height
+                       // on GTK 3.20 when built against an earlier version.
+                       border_border.top = border_border.bottom = border_border.left = border_border.right = 
1;
+               }
+#      endif
+
                height = (rows * row_height
                          + padding.top + padding.bottom
-                         + 2 * (gtk_container_get_border_width(GTK_CONTAINER(PWidget(list))) + 1));
+                         + border.top + border.bottom
+                         + border_border.top + border_border.bottom
+                         + 2 * gtk_container_get_border_width(GTK_CONTAINER(PWidget(list))));
 #else
-               int ythickness = PWidget(list)->style->ythickness;
                height = (rows * row_height
-                         + 2 * (ythickness
-                                + GTK_CONTAINER(PWidget(list))->border_width + 1));
+                         + 2 * (PWidget(frame)->style->ythickness
+                                + GTK_CONTAINER(PWidget(list))->border_width));
 #endif
-               gtk_widget_set_size_request(GTK_WIDGET(PWidget(list)), -1, height);
+               rc.bottom = height;
 
-               // Get the size of the scroller because we set usize on the window
-#if GTK_CHECK_VERSION(3,0,0)
-               gtk_widget_get_preferred_size(GTK_WIDGET(scroller), NULL, &req);
-#else
-               gtk_widget_size_request(GTK_WIDGET(scroller), &req);
-#endif
-               rc.right = req.width;
-               rc.bottom = Platform::Maximum(height, req.height);
-
-               gtk_widget_set_size_request(GTK_WIDGET(list), -1, -1);
                int width = maxItemCharacters;
                if (width < 12)
                        width = 12;
                rc.right = width * (aveCharWidth + aveCharWidth / 3);
-               if (Length() > rows)
-                       rc.right = rc.right + 16;
+               // Add horizontal padding and borders
+               int horizontal_separator=0;
+               gtk_widget_style_get(PWidget(list),
+                       "horizontal-separator", &horizontal_separator, NULL);
+               rc.right += horizontal_separator;
+#if GTK_CHECK_VERSION(3,0,0)
+               rc.right += (padding.left + padding.right
+                            + border.left + border.right
+                            + border_border.left + border_border.right
+                            + 2 * gtk_container_get_border_width(GTK_CONTAINER(PWidget(list))));
+#else
+               rc.right += 2 * (PWidget(frame)->style->xthickness
+                                + GTK_CONTAINER(PWidget(list))->border_width);
+#endif
+               if (Length() > rows) {
+                       // Add the width of the scrollbar
+                       GtkWidget *vscrollbar =
+                               gtk_scrolled_window_get_vscrollbar(GTK_SCROLLED_WINDOW(scroller));
+#if GTK_CHECK_VERSION(3,0,0)
+                       gtk_widget_get_preferred_size(vscrollbar, NULL, &req);
+#else
+                       gtk_widget_size_request(vscrollbar, &req);
+#endif
+                       rc.right += req.width;
+               }
        }
        return rc;
 }
@@ -1743,21 +1753,14 @@ void ListBoxX::Select(int n) {
 #if GTK_CHECK_VERSION(3,0,0)
                GtkAdjustment *adj =
                        gtk_scrollable_get_vadjustment(GTK_SCROLLABLE(list));
-               gfloat value = ((gfloat)n / total) * (gtk_adjustment_get_upper(adj) - 
gtk_adjustment_get_lower(adj))
-                                                       + gtk_adjustment_get_lower(adj) - 
gtk_adjustment_get_page_size(adj) / 2;
 #else
                GtkAdjustment *adj =
                        gtk_tree_view_get_vadjustment(GTK_TREE_VIEW(list));
-               gfloat value = ((gfloat)n / total) * (adj->upper - adj->lower)
-                                                       + adj->lower - adj->page_size / 2;
 #endif
+               gfloat value = ((gfloat)n / total) * (gtk_adjustment_get_upper(adj) - 
gtk_adjustment_get_lower(adj))
+                                                       + gtk_adjustment_get_lower(adj) - 
gtk_adjustment_get_page_size(adj) / 2;
                // Get cell height
-               int row_width;
-               int row_height;
-               GtkTreeViewColumn * column =
-                       gtk_tree_view_get_column(GTK_TREE_VIEW(list), 0);
-               gtk_tree_view_column_cell_get_size(column, NULL, NULL,
-                                                                                       NULL, &row_width, 
&row_height);
+               int row_height = GetRowHeight();
 
                int rows = Length();
                if ((rows == 0) || (rows > desiredVisibleRows))
@@ -1769,13 +1772,8 @@ void ListBoxX::Select(int n) {
                }
                // Clamp it.
                value = (value < 0)? 0 : value;
-#if GTK_CHECK_VERSION(3,0,0)
                value = (value > (gtk_adjustment_get_upper(adj) - gtk_adjustment_get_page_size(adj)))?
                                        (gtk_adjustment_get_upper(adj) - gtk_adjustment_get_page_size(adj)) : 
value;
-#else
-               value = (value > (adj->upper - adj->page_size))?
-                                       (adj->upper - adj->page_size) : value;
-#endif
 
                // Set it.
                gtk_adjustment_set_value(adj, value);
@@ -1785,6 +1783,7 @@ void ListBoxX::Select(int n) {
 }
 
 int ListBoxX::GetSelection() {
+       int index = -1;
        GtkTreeIter iter;
        GtkTreeModel *model;
        GtkTreeSelection *selection;
@@ -1794,9 +1793,10 @@ int ListBoxX::GetSelection() {
                int *indices = gtk_tree_path_get_indices(path);
                // Don't free indices.
                if (indices)
-                       return indices[0];
+                       index = indices[0];
+               gtk_tree_path_free(path);
        }
-       return -1;
+       return index;
 }
 
 int ListBoxX::Find(const char *prefix) {
@@ -1828,8 +1828,7 @@ void ListBoxX::GetValue(int n, char *value, int len) {
                gtk_tree_model_get(model, &iter, TEXT_COLUMN, &text, -1);
        }
        if (text && len > 0) {
-               strncpy(value, text, len);
-               value[len - 1] = '\0';
+               g_strlcpy(value, text, len);
        } else {
                value[0] = '\0';
        }
@@ -1908,12 +1907,7 @@ Menu::Menu() : mid(0) {}
 void Menu::CreatePopUp() {
        Destroy();
        mid = gtk_menu_new();
-#if GLIB_CHECK_VERSION(2,10,0)
-        g_object_ref_sink(G_OBJECT(mid));
-#else
-       g_object_ref(G_OBJECT(mid));
-       gtk_object_sink(GTK_OBJECT(G_OBJECT(mid)));
-#endif
+       g_object_ref_sink(G_OBJECT(mid));
 }
 
 void Menu::Destroy() {
@@ -1922,32 +1916,38 @@ void Menu::Destroy() {
        mid = 0;
 }
 
-static void  MenuPositionFunc(GtkMenu *, gint *x, gint *y, gboolean *, gpointer userData) {
-       sptr_t intFromPointer = reinterpret_cast<sptr_t>(userData);
+#if !GTK_CHECK_VERSION(3,22,0)
+static void MenuPositionFunc(GtkMenu *, gint *x, gint *y, gboolean *, gpointer userData) {
+       sptr_t intFromPointer = GPOINTER_TO_INT(userData);
        *x = intFromPointer & 0xffff;
        *y = intFromPointer >> 16;
 }
+#endif
 
-void Menu::Show(Point pt, Window &) {
-       int screenHeight = gdk_screen_height();
-       int screenWidth = gdk_screen_width();
-       GtkMenu *widget = reinterpret_cast<GtkMenu *>(mid);
+void Menu::Show(Point pt, Window &w) {
+       GtkMenu *widget = static_cast<GtkMenu *>(mid);
        gtk_widget_show_all(GTK_WIDGET(widget));
+#if GTK_CHECK_VERSION(3,22,0)
+       // Rely on GTK+ to do the right thing with positioning
+       gtk_menu_popup_at_pointer(widget, NULL);
+#else
+       GdkRectangle rcMonitor = MonitorRectangleForWidget(PWidget(w.GetID()));
        GtkRequisition requisition;
 #if GTK_CHECK_VERSION(3,0,0)
        gtk_widget_get_preferred_size(GTK_WIDGET(widget), NULL, &requisition);
 #else
        gtk_widget_size_request(GTK_WIDGET(widget), &requisition);
 #endif
-       if ((pt.x + requisition.width) > screenWidth) {
-               pt.x = screenWidth - requisition.width;
+       if ((pt.x + requisition.width) > rcMonitor.x + rcMonitor.width) {
+               pt.x = rcMonitor.x + rcMonitor.width - requisition.width;
        }
-       if ((pt.y + requisition.height) > screenHeight) {
-               pt.y = screenHeight - requisition.height;
+       if ((pt.y + requisition.height) > rcMonitor.y + rcMonitor.height) {
+               pt.y = rcMonitor.y + rcMonitor.height - requisition.height;
        }
        gtk_menu_popup(widget, NULL, NULL, MenuPositionFunc,
-               reinterpret_cast<void *>((static_cast<int>(pt.y) << 16) | static_cast<int>(pt.x)), 0,
+               GINT_TO_POINTER((static_cast<int>(pt.y) << 16) | static_cast<int>(pt.x)), 0,
                gtk_get_current_event_time());
+#endif
 }
 
 ElapsedTime::ElapsedTime() {
@@ -1961,17 +1961,17 @@ class DynamicLibraryImpl : public DynamicLibrary {
 protected:
        GModule* m;
 public:
-       DynamicLibraryImpl(const char *modulePath) {
+       explicit DynamicLibraryImpl(const char *modulePath) {
                m = g_module_open(modulePath, G_MODULE_BIND_LAZY);
        }
 
-       virtual ~DynamicLibraryImpl() {
+       ~DynamicLibraryImpl() override {
                if (m != NULL)
                        g_module_close(m);
        }
 
        // Use g_module_symbol to get a pointer to the relevant function.
-       virtual Function FindFunction(const char *name) {
+       Function FindFunction(const char *name) override {
                if (m != NULL) {
                        gpointer fn_address = NULL;
                        gboolean status = g_module_symbol(m, name, &fn_address);
@@ -1979,11 +1979,12 @@ public:
                                return static_cast<Function>(fn_address);
                        else
                                return NULL;
-               } else
+               } else {
                        return NULL;
+               }
        }
 
-       virtual bool IsValid() {
+       bool IsValid() override {
                return m != NULL;
        }
 };
@@ -2139,8 +2140,7 @@ bool Platform::ShowAssertionPopUps(bool assertionPopUps_) {
 
 void Platform::Assert(const char *c, const char *file, int line) {
        char buffer[2000];
-       sprintf(buffer, "Assertion [%s] failed at %s %d", c, file, line);
-       strcat(buffer, "\r\n");
+       g_snprintf(buffer, sizeof(buffer), "Assertion [%s] failed at %s %d\r\n", c, file, line);
        Platform::DebugDisplay(buffer);
        abort();
 }
@@ -2154,10 +2154,7 @@ int Platform::Clamp(int val, int minVal, int maxVal) {
 }
 
 void Platform_Initialise() {
-       FontMutexAllocate();
 }
 
 void Platform_Finalise() {
-       FontCached::ReleaseAll();
-       FontMutexFree();
 }
diff --git a/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx 
b/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx
index 82ca0b3..0737b71 100644
--- a/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx
+++ b/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx
@@ -3,34 +3,50 @@
 // Copyright 1998-2004 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cctype>
+#include <cstdio>
+#include <ctime>
+#include <cmath>
+
+#include <stdexcept>
 #include <new>
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <assert.h>
-#include <ctype.h>
-#include <time.h>
-
 #include <string>
 #include <vector>
 #include <map>
 #include <algorithm>
+#include <memory>
 
+#include <glib.h>
+#include <gmodule.h>
+#include <gdk/gdk.h>
 #include <gtk/gtk.h>
 #include <gdk/gdkkeysyms.h>
+#if defined(GDK_WINDOWING_WAYLAND)
+#include <gdk/gdkwayland.h>
+#endif
 
-#include "Platform.h"
-
-#if PLAT_GTK_WIN32
+#if defined(__WIN32__) || defined(_MSC_VER)
 #include <windows.h>
 #endif
 
+#include "Platform.h"
+
 #include "ILexer.h"
 #include "Scintilla.h"
 #include "ScintillaWidget.h"
 #ifdef SCI_LEXER
 #include "SciLexer.h"
 #endif
+#include "StringCopy.h"
+#ifdef SCI_LEXER
+#include "LexerModule.h"
+#endif
+#include "Position.h"
+#include "UniqueString.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
@@ -42,60 +58,48 @@
 #include "XPM.h"
 #include "LineMarker.h"
 #include "Style.h"
-#include "AutoComplete.h"
 #include "ViewStyle.h"
-#include "Decoration.h"
 #include "CharClassify.h"
+#include "Decoration.h"
 #include "CaseFolder.h"
 #include "Document.h"
+#include "CaseConvert.h"
+#include "UniConversion.h"
+#include "UnicodeFromUTF8.h"
 #include "Selection.h"
 #include "PositionCache.h"
+#include "EditModel.h"
+#include "MarginView.h"
+#include "EditView.h"
 #include "Editor.h"
+#include "AutoComplete.h"
 #include "ScintillaBase.h"
-#include "UniConversion.h"
-#include "CaseConvert.h"
-
-#include "scintilla-marshal.h"
 
 #ifdef SCI_LEXER
-#include <glib.h>
-#include <gmodule.h>
-#include "LexerModule.h"
 #include "ExternalLexer.h"
 #endif
 
-#include "Converter.h"
+#include "ScintillaGTK.h"
+#include "scintilla-marshal.h"
+#include "ScintillaGTKAccessible.h"
 
-#if defined(__clang__)
-// Clang 3.0 incorrectly displays  sentinel warnings. Fixed by clang 3.1.
-#pragma GCC diagnostic ignored "-Wsentinel"
-#endif
+#include "Converter.h"
 
 #if GTK_CHECK_VERSION(2,20,0)
 #define IS_WIDGET_REALIZED(w) (gtk_widget_get_realized(GTK_WIDGET(w)))
 #define IS_WIDGET_MAPPED(w) (gtk_widget_get_mapped(GTK_WIDGET(w)))
-#define IS_WIDGET_VISIBLE(w) (gtk_widget_get_visible(GTK_WIDGET(w)))
 #else
 #define IS_WIDGET_REALIZED(w) (GTK_WIDGET_REALIZED(w))
 #define IS_WIDGET_MAPPED(w) (GTK_WIDGET_MAPPED(w))
-#define IS_WIDGET_VISIBLE(w) (GTK_WIDGET_VISIBLE(w))
 #endif
 
+#define SC_INDICATOR_INPUT INDIC_IME
+#define SC_INDICATOR_TARGET INDIC_IME+1
+#define SC_INDICATOR_CONVERTED INDIC_IME+2
+#define SC_INDICATOR_UNKNOWN INDIC_IME_MAX
+
 static GdkWindow *WindowFromWidget(GtkWidget *w) {
-#if GTK_CHECK_VERSION(3,0,0)
        return gtk_widget_get_window(w);
-#else
-       return w->window;
-#endif
-}
-
-static GdkWindow *PWindow(const Window &w) {
-       GtkWidget *widget = reinterpret_cast<GtkWidget *>(w.GetID());
-#if GTK_CHECK_VERSION(3,0,0)
-       return gtk_widget_get_window(widget);
-#else
-       return widget->window;
-#endif
 }
 
 #ifdef _MSC_VER
@@ -105,212 +109,16 @@ static GdkWindow *PWindow(const Window &w) {
 #pragma warning(disable: 4505)
 #endif
 
-#define OBJECT_CLASS GObjectClass
-
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
-extern std::string UTF8FromLatin1(const char *s, int len);
-
-class ScintillaGTK : public ScintillaBase {
-       _ScintillaObject *sci;
-       Window wText;
-       Window scrollbarv;
-       Window scrollbarh;
-       GtkAdjustment *adjustmentv;
-       GtkAdjustment *adjustmenth;
-       int verticalScrollBarWidth;
-       int horizontalScrollBarHeight;
-
-       SelectionText primary;
-
-       GdkEventButton *evbtn;
-       bool capturedMouse;
-       bool dragWasDropped;
-       int lastKey;
-       int rectangularSelectionModifier;
-
-       GtkWidgetClass *parentClass;
-
-       static GdkAtom atomClipboard;
-       static GdkAtom atomUTF8;
-       static GdkAtom atomString;
-       static GdkAtom atomUriList;
-       static GdkAtom atomDROPFILES_DND;
-       GdkAtom atomSought;
-
-#if PLAT_GTK_WIN32
-       CLIPFORMAT cfColumnSelect;
-#endif
-
-       Window wPreedit;
-       Window wPreeditDraw;
-       GtkIMContext *im_context;
-
-       // Wheel mouse support
-       unsigned int linesPerScroll;
-       GTimeVal lastWheelMouseTime;
-       gint lastWheelMouseDirection;
-       gint wheelMouseIntensity;
-
-#if GTK_CHECK_VERSION(3,0,0)
-       cairo_rectangle_list_t *rgnUpdate;
-#else
-       GdkRegion *rgnUpdate;
-#endif
-
-       // Private so ScintillaGTK objects can not be copied
-       ScintillaGTK(const ScintillaGTK &);
-       ScintillaGTK &operator=(const ScintillaGTK &);
-
-public:
-       ScintillaGTK(_ScintillaObject *sci_);
-       virtual ~ScintillaGTK();
-       static void ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass 
*container_class);
-private:
-       virtual void Initialise();
-       virtual void Finalise();
-       virtual void DisplayCursor(Window::Cursor c);
-       virtual bool DragThreshold(Point ptStart, Point ptNow);
-       virtual void StartDrag();
-       int TargetAsUTF8(char *text);
-       int EncodedFromUTF8(char *utf8, char *encoded) const;
-       virtual bool ValidCodePage(int codePage) const;
-public:        // Public for scintilla_send_message
-       virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
-private:
-       virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
-       virtual void SetTicking(bool on);
-       virtual bool SetIdle(bool on);
-       virtual void SetMouseCapture(bool on);
-       virtual bool HaveMouseCapture();
-       virtual bool PaintContains(PRectangle rc);
-       void FullPaint();
-       virtual PRectangle GetClientRectangle();
-       virtual void ScrollText(int linesToMove);
-       virtual void SetVerticalScrollPos();
-       virtual void SetHorizontalScrollPos();
-       virtual bool ModifyScrollBars(int nMax, int nPage);
-       void ReconfigureScrollBars();
-       virtual void NotifyChange();
-       virtual void NotifyFocus(bool focus);
-       virtual void NotifyParent(SCNotification scn);
-       void NotifyKey(int key, int modifiers);
-       void NotifyURIDropped(const char *list);
-       const char *CharacterSetID() const;
-       virtual CaseFolder *CaseFolderForEncoding();
-       virtual std::string CaseMapString(const std::string &s, int caseMapping);
-       virtual int KeyDefault(int key, int modifiers);
-       virtual void CopyToClipboard(const SelectionText &selectedText);
-       virtual void Copy();
-       virtual void Paste();
-       virtual void CreateCallTipWindow(PRectangle rc);
-       virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
-       bool OwnPrimarySelection();
-       virtual void ClaimSelection();
-       void GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText);
-       void ReceivedSelection(GtkSelectionData *selection_data);
-       void ReceivedDrop(GtkSelectionData *selection_data);
-       static void GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *selected);
-       void StoreOnClipboard(SelectionText *clipText);
-       static void ClipboardGetSelection(GtkClipboard* clip, GtkSelectionData *selection_data, guint info, 
void *data);
-       static void ClipboardClearSelection(GtkClipboard* clip, void *data);
-
-       void UnclaimSelection(GdkEventSelection *selection_event);
-       void Resize(int width, int height);
-
-       // Callback functions
-       void RealizeThis(GtkWidget *widget);
-       static void Realize(GtkWidget *widget);
-       void UnRealizeThis(GtkWidget *widget);
-       static void UnRealize(GtkWidget *widget);
-       void MapThis();
-       static void Map(GtkWidget *widget);
-       void UnMapThis();
-       static void UnMap(GtkWidget *widget);
-       gint FocusInThis(GtkWidget *widget);
-       static gint FocusIn(GtkWidget *widget, GdkEventFocus *event);
-       gint FocusOutThis(GtkWidget *widget);
-       static gint FocusOut(GtkWidget *widget, GdkEventFocus *event);
-       static void SizeRequest(GtkWidget *widget, GtkRequisition *requisition);
-#if GTK_CHECK_VERSION(3,0,0)
-       static void GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth);
-       static void GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight);
-#endif
-       static void SizeAllocate(GtkWidget *widget, GtkAllocation *allocation);
-#if GTK_CHECK_VERSION(3,0,0)
-       gboolean DrawTextThis(cairo_t *cr);
-       static gboolean DrawText(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
-       gboolean DrawThis(cairo_t *cr);
-       static gboolean DrawMain(GtkWidget *widget, cairo_t *cr);
-#else
-       gboolean ExposeTextThis(GtkWidget *widget, GdkEventExpose *ose);
-       static gboolean ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
-       gboolean Expose(GtkWidget *widget, GdkEventExpose *ose);
-       static gboolean ExposeMain(GtkWidget *widget, GdkEventExpose *ose);
-#endif
-       static void Draw(GtkWidget *widget, GdkRectangle *area);
-       void ForAll(GtkCallback callback, gpointer callback_data);
-       static void MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, 
gpointer callback_data);
-
-       static void ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
-       static void ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
-       gint PressThis(GdkEventButton *event);
-       static gint Press(GtkWidget *widget, GdkEventButton *event);
-       static gint MouseRelease(GtkWidget *widget, GdkEventButton *event);
-       static gint ScrollEvent(GtkWidget *widget, GdkEventScroll *event);
-       static gint Motion(GtkWidget *widget, GdkEventMotion *event);
-       gboolean KeyThis(GdkEventKey *event);
-       static gboolean KeyPress(GtkWidget *widget, GdkEventKey *event);
-       static gboolean KeyRelease(GtkWidget *widget, GdkEventKey *event);
-#if GTK_CHECK_VERSION(3,0,0)
-       gboolean DrawPreeditThis(GtkWidget *widget, cairo_t *cr);
-       static gboolean DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
-#else
-       gboolean ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose);
-       static gboolean ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
-#endif
-       void CommitThis(char *str);
-       static void Commit(GtkIMContext *context, char *str, ScintillaGTK *sciThis);
-       void PreeditChangedThis();
-       static void PreeditChanged(GtkIMContext *context, ScintillaGTK *sciThis);
-       static void StyleSetText(GtkWidget *widget, GtkStyle *previous, void*);
-       static void RealizeText(GtkWidget *widget, void*);
-       static void Destroy(GObject *object);
-       static void SelectionReceived(GtkWidget *widget, GtkSelectionData *selection_data,
-                                     guint time);
-       static void SelectionGet(GtkWidget *widget, GtkSelectionData *selection_data,
-                                guint info, guint time);
-       static gint SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event);
-       gboolean DragMotionThis(GdkDragContext *context, gint x, gint y, guint dragtime);
-       static gboolean DragMotion(GtkWidget *widget, GdkDragContext *context,
-                                  gint x, gint y, guint dragtime);
-       static void DragLeave(GtkWidget *widget, GdkDragContext *context,
-                             guint time);
-       static void DragEnd(GtkWidget *widget, GdkDragContext *context);
-       static gboolean Drop(GtkWidget *widget, GdkDragContext *context,
-                            gint x, gint y, guint time);
-       static void DragDataReceived(GtkWidget *widget, GdkDragContext *context,
-                                    gint x, gint y, GtkSelectionData *selection_data, guint info, guint 
time);
-       static void DragDataGet(GtkWidget *widget, GdkDragContext *context,
-                               GtkSelectionData *selection_data, guint info, guint time);
-       static gboolean TimeOut(ScintillaGTK *sciThis);
-       static gboolean IdleCallback(ScintillaGTK *sciThis);
-       static gboolean StyleIdle(ScintillaGTK *sciThis);
-       virtual void QueueIdleWork(WorkNeeded::workItems items, int upTo);
-       static void PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis);
-
-#if GTK_CHECK_VERSION(3,0,0)
-       static gboolean DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip);
-#else
-       static gboolean ExposeCT(GtkWidget *widget, GdkEventExpose *ose, CallTip *ct);
-#endif
-       static gboolean PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis);
+static GdkWindow *PWindow(const Window &w) {
+       GtkWidget *widget = static_cast<GtkWidget *>(w.GetID());
+       return gtk_widget_get_window(widget);
+}
 
-       static sptr_t DirectFunction(ScintillaGTK *sciThis,
-                                    unsigned int iMessage, uptr_t wParam, sptr_t lParam);
-};
+extern std::string UTF8FromLatin1(const char *s, int len);
 
 enum {
     COMMAND_SIGNAL,
@@ -338,22 +146,22 @@ static const GtkTargetEntry clipboardCopyTargets[] = {
        { (gchar *) "UTF8_STRING", 0, TARGET_UTF8_STRING },
        { (gchar *) "STRING", 0, TARGET_STRING },
 };
-static const gint nClipboardCopyTargets = sizeof(clipboardCopyTargets) / sizeof(clipboardCopyTargets[0]);
+static const gint nClipboardCopyTargets = ELEMENTS(clipboardCopyTargets);
 
 static const GtkTargetEntry clipboardPasteTargets[] = {
        { (gchar *) "text/uri-list", 0, TARGET_URI },
        { (gchar *) "UTF8_STRING", 0, TARGET_UTF8_STRING },
        { (gchar *) "STRING", 0, TARGET_STRING },
 };
-static const gint nClipboardPasteTargets = sizeof(clipboardPasteTargets) / sizeof(clipboardPasteTargets[0]);
+static const gint nClipboardPasteTargets = ELEMENTS(clipboardPasteTargets);
 
 static GtkWidget *PWidget(Window &w) {
-       return reinterpret_cast<GtkWidget *>(w.GetID());
+       return static_cast<GtkWidget *>(w.GetID());
 }
 
-static ScintillaGTK *ScintillaFromWidget(GtkWidget *widget) {
-       ScintillaObject *scio = reinterpret_cast<ScintillaObject *>(widget);
-       return reinterpret_cast<ScintillaGTK *>(scio->pscin);
+ScintillaGTK *ScintillaGTK::FromWidget(GtkWidget *widget) {
+       ScintillaObject *scio = SCINTILLA(widget);
+       return static_cast<ScintillaGTK *>(scio->pscin);
 }
 
 ScintillaGTK::ScintillaGTK(_ScintillaObject *sci_) :
@@ -361,10 +169,16 @@ ScintillaGTK::ScintillaGTK(_ScintillaObject *sci_) :
                verticalScrollBarWidth(30), horizontalScrollBarHeight(30),
                evbtn(0), capturedMouse(false), dragWasDropped(false),
                lastKey(0), rectangularSelectionModifier(SCMOD_CTRL), parentClass(0),
-               im_context(NULL),
+               im_context(NULL), lastNonCommonScript(PANGO_SCRIPT_INVALID_CODE),
                lastWheelMouseDirection(0),
                wheelMouseIntensity(0),
-               rgnUpdate(0) {
+               smoothScrollY(0),
+               smoothScrollX(0),
+               rgnUpdate(0),
+               repaintFullWindow(false),
+               styleIdleID(0),
+               accessibilityEnabled(SC_ACCESSIBILITY_ENABLED),
+               accessible(0) {
        sci = sci_;
        wMain = GTK_WIDGET(sci);
 
@@ -392,15 +206,19 @@ ScintillaGTK::ScintillaGTK(_ScintillaObject *sci_) :
        lastWheelMouseTime.tv_sec = 0;
        lastWheelMouseTime.tv_usec = 0;
 
-       Initialise();
+       Init();
 }
 
 ScintillaGTK::~ScintillaGTK() {
-       g_idle_remove_by_data(this);
+       if (styleIdleID) {
+               g_source_remove(styleIdleID);
+               styleIdleID = 0;
+       }
        if (evbtn) {
                gdk_event_free(reinterpret_cast<GdkEvent *>(evbtn));
                evbtn = 0;
        }
+       wPreedit.Destroy();
 }
 
 static void UnRefCursor(GdkCursor *cursor) {
@@ -421,11 +239,7 @@ void ScintillaGTK::RealizeThis(GtkWidget *widget) {
        GdkWindowAttr attrs;
        attrs.window_type = GDK_WINDOW_CHILD;
        GtkAllocation allocation;
-#if GTK_CHECK_VERSION(3,0,0)
        gtk_widget_get_allocation(widget, &allocation);
-#else
-       allocation = widget->allocation;
-#endif
        attrs.x = allocation.x;
        attrs.y = allocation.y;
        attrs.width = allocation.width;
@@ -436,18 +250,21 @@ void ScintillaGTK::RealizeThis(GtkWidget *widget) {
        attrs.colormap = gtk_widget_get_colormap(widget);
 #endif
        attrs.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
-       GdkCursor *cursor = gdk_cursor_new(GDK_XTERM);
+       GdkDisplay *pdisplay = gtk_widget_get_display(widget);
+       GdkCursor *cursor = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
        attrs.cursor = cursor;
 #if GTK_CHECK_VERSION(3,0,0)
        gtk_widget_set_window(widget, gdk_window_new(gtk_widget_get_parent_window(widget), &attrs,
                GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_CURSOR));
+#if GTK_CHECK_VERSION(3,8,0)
+       gtk_widget_register_window(widget, gtk_widget_get_window(widget));
+#else
        gdk_window_set_user_data(gtk_widget_get_window(widget), widget);
-       GtkStyleContext *styleContext = gtk_widget_get_style_context(widget);
-       if (styleContext) {
-               GdkRGBA colourBackWidget;
-               gtk_style_context_get_background_color(styleContext, GTK_STATE_FLAG_NORMAL, 
&colourBackWidget);
-               gdk_window_set_background_rgba(gtk_widget_get_window(widget), &colourBackWidget);
-       }
+#endif
+#if !GTK_CHECK_VERSION(3,18,0)
+       gtk_style_context_set_background(gtk_widget_get_style_context(widget),
+               gtk_widget_get_window(widget));
+#endif
        gdk_window_show(gtk_widget_get_window(widget));
        UnRefCursor(cursor);
 #else
@@ -459,20 +276,8 @@ void ScintillaGTK::RealizeThis(GtkWidget *widget) {
        gdk_window_show(widget->window);
        UnRefCursor(cursor);
 #endif
-       wPreedit = gtk_window_new(GTK_WINDOW_POPUP);
-       wPreeditDraw = gtk_drawing_area_new();
-       GtkWidget *predrw = PWidget(wPreeditDraw);      // No code inside the G_OBJECT macro
-#if GTK_CHECK_VERSION(3,0,0)
-       g_signal_connect(G_OBJECT(predrw), "draw",
-               G_CALLBACK(DrawPreedit), this);
-#else
-       g_signal_connect(G_OBJECT(predrw), "expose_event",
-               G_CALLBACK(ExposePreedit), this);
-#endif
-       gtk_container_add(GTK_CONTAINER(PWidget(wPreedit)), predrw);
        gtk_widget_realize(PWidget(wPreedit));
-       gtk_widget_realize(predrw);
-       gtk_widget_show(predrw);
+       gtk_widget_realize(PWidget(wPreeditDraw));
 
        im_context = gtk_im_multicontext_new();
        g_signal_connect(G_OBJECT(im_context), "commit",
@@ -489,15 +294,15 @@ void ScintillaGTK::RealizeThis(GtkWidget *widget) {
        gtk_widget_realize(PWidget(scrollbarv));
        gtk_widget_realize(PWidget(scrollbarh));
 
-       cursor = gdk_cursor_new(GDK_XTERM);
+       cursor = gdk_cursor_new_for_display(pdisplay, GDK_XTERM);
        gdk_window_set_cursor(PWindow(wText), cursor);
        UnRefCursor(cursor);
 
-       cursor = gdk_cursor_new(GDK_LEFT_PTR);
+       cursor = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
        gdk_window_set_cursor(PWindow(scrollbarv), cursor);
        UnRefCursor(cursor);
 
-       cursor = gdk_cursor_new(GDK_LEFT_PTR);
+       cursor = gdk_cursor_new_for_display(pdisplay, GDK_LEFT_PTR);
        gdk_window_set_cursor(PWindow(scrollbarh), cursor);
        UnRefCursor(cursor);
 
@@ -506,7 +311,7 @@ void ScintillaGTK::RealizeThis(GtkWidget *widget) {
 }
 
 void ScintillaGTK::Realize(GtkWidget *widget) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        sciThis->RealizeThis(widget);
 }
 
@@ -523,8 +328,10 @@ void ScintillaGTK::UnRealizeThis(GtkWidget *widget) {
                GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);
 #endif
                gtk_widget_unrealize(PWidget(wText));
-               gtk_widget_unrealize(PWidget(scrollbarv));
-               gtk_widget_unrealize(PWidget(scrollbarh));
+               if (PWidget(scrollbarv))
+                       gtk_widget_unrealize(PWidget(scrollbarv));
+               if (PWidget(scrollbarh))
+                       gtk_widget_unrealize(PWidget(scrollbarh));
                gtk_widget_unrealize(PWidget(wPreedit));
                gtk_widget_unrealize(PWidget(wPreeditDraw));
                g_object_unref(im_context);
@@ -539,13 +346,13 @@ void ScintillaGTK::UnRealizeThis(GtkWidget *widget) {
 }
 
 void ScintillaGTK::UnRealize(GtkWidget *widget) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        sciThis->UnRealizeThis(widget);
 }
 
 static void MapWidget(GtkWidget *widget) {
        if (widget &&
-               IS_WIDGET_VISIBLE(widget) &&
+               gtk_widget_get_visible(GTK_WIDGET(widget)) &&
                !IS_WIDGET_MAPPED(widget)) {
                gtk_widget_map(widget);
        }
@@ -573,7 +380,7 @@ void ScintillaGTK::MapThis() {
 }
 
 void ScintillaGTK::Map(GtkWidget *widget) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        sciThis->MapThis();
 }
 
@@ -588,52 +395,79 @@ void ScintillaGTK::UnMapThis() {
                DropGraphics(false);
                gdk_window_hide(PWindow(wMain));
                gtk_widget_unmap(PWidget(wText));
-               gtk_widget_unmap(PWidget(scrollbarh));
-               gtk_widget_unmap(PWidget(scrollbarv));
+               if (PWidget(scrollbarh))
+                       gtk_widget_unmap(PWidget(scrollbarh));
+               if (PWidget(scrollbarv))
+                       gtk_widget_unmap(PWidget(scrollbarv));
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
        }
 }
 
 void ScintillaGTK::UnMap(GtkWidget *widget) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        sciThis->UnMapThis();
 }
 
 void ScintillaGTK::ForAll(GtkCallback callback, gpointer callback_data) {
        try {
                (*callback) (PWidget(wText), callback_data);
-               (*callback) (PWidget(scrollbarv), callback_data);
-               (*callback) (PWidget(scrollbarh), callback_data);
+               if (PWidget(scrollbarv))
+                       (*callback) (PWidget(scrollbarv), callback_data);
+               if (PWidget(scrollbarh))
+                       (*callback) (PWidget(scrollbarh), callback_data);
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
        }
 }
 
 void ScintillaGTK::MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, 
gpointer callback_data) {
-       ScintillaGTK *sciThis = ScintillaFromWidget((GtkWidget *)container);
+       ScintillaGTK *sciThis = FromWidget((GtkWidget *)container);
 
        if (callback != NULL && include_internals) {
                sciThis->ForAll(callback, callback_data);
        }
 }
 
-gint ScintillaGTK::FocusInThis(GtkWidget *widget) {
+namespace {
+
+class PreEditString {
+public:
+       gchar *str;
+       gint cursor_pos;
+       PangoAttrList *attrs;
+       gboolean validUTF8;
+       glong uniStrLen;
+       gunichar *uniStr;
+       PangoScript pscript;
+
+       explicit PreEditString(GtkIMContext *im_context) {
+               gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
+               validUTF8 = g_utf8_validate(str, strlen(str), NULL);
+               uniStr = g_utf8_to_ucs4_fast(str, strlen(str), &uniStrLen);
+               pscript = pango_script_for_unichar(uniStr[0]);
+       }
+       ~PreEditString() {
+               g_free(str);
+               g_free(uniStr);
+               pango_attr_list_unref(attrs);
+       }
+};
+
+}
+
+gint ScintillaGTK::FocusInThis(GtkWidget *) {
        try {
                SetFocusState(true);
                if (im_context != NULL) {
-                       gchar *str = NULL;
-                       gint cursor_pos;
-
-                       gtk_im_context_get_preedit_string(im_context, &str, NULL, &cursor_pos);
+                       PreEditString pes(im_context);
                        if (PWidget(wPreedit) != NULL) {
-                               if (strlen(str) > 0) {
+                               if (strlen(pes.str) > 0) {
                                        gtk_widget_show(PWidget(wPreedit));
                                } else {
                                        gtk_widget_hide(PWidget(wPreedit));
                                }
                        }
-                       g_free(str);
                        gtk_im_context_focus_in(im_context);
                }
 
@@ -644,11 +478,11 @@ gint ScintillaGTK::FocusInThis(GtkWidget *widget) {
 }
 
 gint ScintillaGTK::FocusIn(GtkWidget *widget, GdkEventFocus * /*event*/) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        return sciThis->FocusInThis(widget);
 }
 
-gint ScintillaGTK::FocusOutThis(GtkWidget *widget) {
+gint ScintillaGTK::FocusOutThis(GtkWidget *) {
        try {
                SetFocusState(false);
 
@@ -664,12 +498,12 @@ gint ScintillaGTK::FocusOutThis(GtkWidget *widget) {
 }
 
 gint ScintillaGTK::FocusOut(GtkWidget *widget, GdkEventFocus * /*event*/) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        return sciThis->FocusOutThis(widget);
 }
 
 void ScintillaGTK::SizeRequest(GtkWidget *widget, GtkRequisition *requisition) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        requisition->width = 1;
        requisition->height = 1;
        GtkRequisition child_requisition;
@@ -699,13 +533,9 @@ void ScintillaGTK::GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gi
 #endif
 
 void ScintillaGTK::SizeAllocate(GtkWidget *widget, GtkAllocation *allocation) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
-#if GTK_CHECK_VERSION(2,20,0)
                gtk_widget_set_allocation(widget, allocation);
-#else
-               widget->allocation = *allocation;
-#endif
                if (IS_WIDGET_REALIZED(widget))
                        gdk_window_move_resize(WindowFromWidget(widget),
                                allocation->x,
@@ -720,21 +550,25 @@ void ScintillaGTK::SizeAllocate(GtkWidget *widget, GtkAllocation *allocation) {
        }
 }
 
-void ScintillaGTK::Initialise() {
-       //Platform::DebugPrintf("ScintillaGTK::Initialise\n");
+void ScintillaGTK::Init() {
        parentClass = reinterpret_cast<GtkWidgetClass *>(
                          g_type_class_ref(gtk_container_get_type()));
 
-#if GTK_CHECK_VERSION(2,20,0)
+       gint maskSmooth = 0;
+#if defined(GDK_WINDOWING_WAYLAND)
+       GdkDisplay *pdisplay = gdk_display_get_default();
+       if (GDK_IS_WAYLAND_DISPLAY(pdisplay)) {
+               // On Wayland, touch pads only produce smooth scroll events
+               maskSmooth = GDK_SMOOTH_SCROLL_MASK;
+       }
+#endif
+
        gtk_widget_set_can_focus(PWidget(wMain), TRUE);
        gtk_widget_set_sensitive(PWidget(wMain), TRUE);
-#else
-       GTK_WIDGET_SET_FLAGS(PWidget(wMain), GTK_CAN_FOCUS);
-       GTK_WIDGET_SET_FLAGS(GTK_WIDGET(PWidget(wMain)), GTK_SENSITIVE);
-#endif
        gtk_widget_set_events(PWidget(wMain),
                              GDK_EXPOSURE_MASK
                              | GDK_SCROLL_MASK
+                             | maskSmooth
                              | GDK_STRUCTURE_MASK
                              | GDK_KEY_PRESS_MASK
                              | GDK_KEY_RELEASE_MASK
@@ -756,9 +590,18 @@ void ScintillaGTK::Initialise() {
        g_signal_connect(G_OBJECT(widtxt), "expose_event",
                           G_CALLBACK(ScintillaGTK::ExposeText), this);
 #endif
+#if GTK_CHECK_VERSION(3,0,0)
+       // we need a runtime check because we don't want double buffering when
+       // running on >= 3.9.2
+       if (gtk_check_version(3,9,2) != NULL /* on < 3.9.2 */)
+#endif
+       {
+#if !GTK_CHECK_VERSION(3,14,0)
+               // Avoid background drawing flash/missing redraws
+               gtk_widget_set_double_buffered(widtxt, FALSE);
+#endif
+       }
        gtk_widget_set_events(widtxt, GDK_EXPOSURE_MASK);
-       // Avoid background drawing flash
-       gtk_widget_set_double_buffered(widtxt, FALSE);
        gtk_widget_set_size_request(widtxt, 100, 100);
        adjustmentv = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 201.0, 1.0, 20.0, 20.0));
 #if GTK_CHECK_VERSION(3,0,0)
@@ -766,11 +609,7 @@ void ScintillaGTK::Initialise() {
 #else
        scrollbarv = gtk_vscrollbar_new(GTK_ADJUSTMENT(adjustmentv));
 #endif
-#if GTK_CHECK_VERSION(2,20,0)
        gtk_widget_set_can_focus(PWidget(scrollbarv), FALSE);
-#else
-       GTK_WIDGET_UNSET_FLAGS(PWidget(scrollbarv), GTK_CAN_FOCUS);
-#endif
        g_signal_connect(G_OBJECT(adjustmentv), "value_changed",
                           G_CALLBACK(ScrollSignal), this);
        gtk_widget_set_parent(PWidget(scrollbarv), PWidget(wMain));
@@ -782,11 +621,7 @@ void ScintillaGTK::Initialise() {
 #else
        scrollbarh = gtk_hscrollbar_new(GTK_ADJUSTMENT(adjustmenth));
 #endif
-#if GTK_CHECK_VERSION(2,20,0)
        gtk_widget_set_can_focus(PWidget(scrollbarh), FALSE);
-#else
-       GTK_WIDGET_UNSET_FLAGS(PWidget(scrollbarh), GTK_CAN_FOCUS);
-#endif
        g_signal_connect(G_OBJECT(adjustmenth), "value_changed",
                           G_CALLBACK(ScrollHSignal), this);
        gtk_widget_set_parent(PWidget(scrollbarh), PWidget(wMain));
@@ -798,6 +633,20 @@ void ScintillaGTK::Initialise() {
                          GTK_DEST_DEFAULT_ALL, clipboardPasteTargets, nClipboardPasteTargets,
                          static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE));
 
+       /* create pre-edit window */
+       wPreedit = gtk_window_new(GTK_WINDOW_POPUP);
+       wPreeditDraw = gtk_drawing_area_new();
+       GtkWidget *predrw = PWidget(wPreeditDraw);      // No code inside the G_OBJECT macro
+#if GTK_CHECK_VERSION(3,0,0)
+       g_signal_connect(G_OBJECT(predrw), "draw",
+               G_CALLBACK(DrawPreedit), this);
+#else
+       g_signal_connect(G_OBJECT(predrw), "expose_event",
+               G_CALLBACK(ExposePreedit), this);
+#endif
+       gtk_container_add(GTK_CONTAINER(PWidget(wPreedit)), predrw);
+       gtk_widget_show(predrw);
+
        // Set caret period based on GTK settings
        gboolean blinkOn = false;
        if (g_object_class_find_property(G_OBJECT_GET_CLASS(
@@ -816,14 +665,36 @@ void ScintillaGTK::Initialise() {
                caret.period = 0;
        }
 
-       SetTicking(true);
+       for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
+               timers[tr].reason = tr;
+               timers[tr].scintilla = this;
+       }
+       vs.indicators[SC_INDICATOR_UNKNOWN] = Indicator(INDIC_HIDDEN, ColourDesired(0, 0, 0xff));
+       vs.indicators[SC_INDICATOR_INPUT] = Indicator(INDIC_DOTS, ColourDesired(0, 0, 0xff));
+       vs.indicators[SC_INDICATOR_CONVERTED] = Indicator(INDIC_COMPOSITIONTHICK, ColourDesired(0, 0, 0xff));
+       vs.indicators[SC_INDICATOR_TARGET] = Indicator(INDIC_STRAIGHTBOX, ColourDesired(0, 0, 0xff));
 }
 
 void ScintillaGTK::Finalise() {
-       SetTicking(false);
+       for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
+               FineTickerCancel(tr);
+       }
+       if (accessible) {
+               gtk_accessible_set_widget(GTK_ACCESSIBLE(accessible), NULL);
+               g_object_unref(accessible);
+               accessible = 0;
+       }
+
        ScintillaBase::Finalise();
 }
 
+bool ScintillaGTK::AbandonPaint() {
+       if ((paintState == painting) && !paintingAllText) {
+               repaintFullWindow = true;
+       }
+       return false;
+}
+
 void ScintillaGTK::DisplayCursor(Window::Cursor c) {
        if (cursorMode == SC_CURSORNORMAL)
                wText.SetCursor(c);
@@ -841,28 +712,40 @@ void ScintillaGTK::StartDrag() {
        dragWasDropped = false;
        inDragDrop = ddDragging;
        GtkTargetList *tl = gtk_target_list_new(clipboardCopyTargets, nClipboardCopyTargets);
+#if GTK_CHECK_VERSION(3,10,0)
+       gtk_drag_begin_with_coordinates(GTK_WIDGET(PWidget(wMain)),
+                      tl,
+                      static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE),
+                      evbtn->button,
+                      reinterpret_cast<GdkEvent *>(evbtn),
+                       -1, -1);
+#else
        gtk_drag_begin(GTK_WIDGET(PWidget(wMain)),
                       tl,
                       static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE),
                       evbtn->button,
                       reinterpret_cast<GdkEvent *>(evbtn));
+#endif
 }
 
-static std::string ConvertText(const char *s, size_t len, const char *charSetDest,
-       const char *charSetSource, bool transliterations, bool silent=false) {
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+std::string ConvertText(const char *s, size_t len, const char *charSetDest,
+       const char *charSetSource, bool transliterations, bool silent) {
        // s is not const because of different versions of iconv disagreeing about const
        std::string destForm;
        Converter conv(charSetDest, charSetSource, transliterations);
        if (conv) {
-               size_t outLeft = len*3+1;
+               gsize outLeft = len*3+1;
                destForm = std::string(outLeft, '\0');
                // g_iconv does not actually write to its input argument so safe to cast away const
                char *pin = const_cast<char *>(s);
-               size_t inLeft = len;
+               gsize inLeft = len;
                char *putf = &destForm[0];
                char *pout = putf;
-               size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
-               if (conversions == ((size_t)(-1))) {
+               gsize conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
+               if (conversions == sizeFailure) {
                        if (!silent) {
                                if (len == 1)
                                        fprintf(stderr, "iconv %s->%s failed for %0x '%s'\n",
@@ -880,6 +763,9 @@ static std::string ConvertText(const char *s, size_t len, const char *charSetDes
        }
        return destForm;
 }
+#ifdef SCI_NAMESPACE
+}
+#endif
 
 // Returns the target converted to UTF8.
 // Return the length in bytes.
@@ -980,6 +866,30 @@ sptr_t ScintillaGTK::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam
                case SCI_GETRECTANGULARSELECTIONMODIFIER:
                        return rectangularSelectionModifier;
 
+               case SCI_SETREADONLY: {
+                       sptr_t ret = ScintillaBase::WndProc(iMessage, wParam, lParam);
+                       if (accessible) {
+                               ScintillaGTKAccessible *sciAccessible = 
ScintillaGTKAccessible::FromAccessible(accessible);
+                               if (sciAccessible) {
+                                       sciAccessible->NotifyReadOnly();
+                               }
+                       }
+                       return ret;
+               }
+
+               case SCI_GETACCESSIBILITY:
+                       return accessibilityEnabled;
+
+               case SCI_SETACCESSIBILITY:
+                       accessibilityEnabled = wParam;
+                       if (accessible) {
+                               ScintillaGTKAccessible *sciAccessible = 
ScintillaGTKAccessible::FromAccessible(accessible);
+                               if (sciAccessible) {
+                                       sciAccessible->SetAccessibility();
+                               }
+                       }
+                       break;
+
                default:
                        return ScintillaBase::WndProc(iMessage, wParam, lParam);
                }
@@ -995,17 +905,27 @@ sptr_t ScintillaGTK::DefWndProc(unsigned int, uptr_t, sptr_t) {
        return 0;
 }
 
-void ScintillaGTK::SetTicking(bool on) {
-       if (timer.ticking != on) {
-               timer.ticking = on;
-               if (timer.ticking) {
-                       timer.tickerID = reinterpret_cast<TickerID>(g_timeout_add(timer.tickSize,
-                               reinterpret_cast<GSourceFunc>(TimeOut), this));
-               } else {
-                       g_source_remove(GPOINTER_TO_UINT(timer.tickerID));
-               }
+/**
+* Report that this Editor subclass has a working implementation of FineTickerStart.
+*/
+bool ScintillaGTK::FineTickerAvailable() {
+       return true;
+}
+
+bool ScintillaGTK::FineTickerRunning(TickReason reason) {
+       return timers[reason].timer != 0;
+}
+
+void ScintillaGTK::FineTickerStart(TickReason reason, int millis, int /* tolerance */) {
+       FineTickerCancel(reason);
+       timers[reason].timer = gdk_threads_add_timeout(millis, TimeOut, &timers[reason]);
+}
+
+void ScintillaGTK::FineTickerCancel(TickReason reason) {
+       if (timers[reason].timer) {
+               g_source_remove(timers[reason].timer);
+               timers[reason].timer = 0;
        }
-       timer.ticksToWait = caret.period;
 }
 
 bool ScintillaGTK::SetIdle(bool on) {
@@ -1014,8 +934,7 @@ bool ScintillaGTK::SetIdle(bool on) {
                if (!idler.state) {
                        idler.state = true;
                        idler.idlerID = reinterpret_cast<IdlerID>(
-                               g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
-                                       reinterpret_cast<GSourceFunc>(IdleCallback), this, NULL));
+                               gdk_threads_add_idle_full(G_PRIORITY_DEFAULT_IDLE, IdleCallback, this, NULL));
                }
        } else {
                // Stop idler, if it's running
@@ -1092,31 +1011,38 @@ void ScintillaGTK::FullPaint() {
        wText.InvalidateAll();
 }
 
-PRectangle ScintillaGTK::GetClientRectangle() {
-       PRectangle rc = wMain.GetClientPosition();
+PRectangle ScintillaGTK::GetClientRectangle() const {
+       Window win = wMain;
+       PRectangle rc = win.GetClientPosition();
        if (verticalScrollBarVisible)
                rc.right -= verticalScrollBarWidth;
-       if (horizontalScrollBarVisible && (wrapState == eWrapNone))
+       if (horizontalScrollBarVisible && !Wrapping())
                rc.bottom -= horizontalScrollBarHeight;
        // Move to origin
        rc.right -= rc.left;
        rc.bottom -= rc.top;
+       if (rc.bottom < 0)
+               rc.bottom = 0;
+       if (rc.right < 0)
+               rc.right = 0;
        rc.left = 0;
        rc.top = 0;
        return rc;
 }
 
-void ScintillaGTK::ScrollText(int linesToMove) {
-       int diff = vs.lineHeight * -linesToMove;
-       //Platform::DebugPrintf("ScintillaGTK::ScrollText %d %d %0d,%0d %0d,%0d\n", linesToMove, diff,
-       //      rc.left, rc.top, rc.right, rc.bottom);
-       GtkWidget *wi = PWidget(wText);
+void ScintillaGTK::ScrollText(Sci::Line linesToMove) {
        NotifyUpdateUI();
 
+#if GTK_CHECK_VERSION(3,22,0)
+       Redraw();
+#else
+       GtkWidget *wi = PWidget(wText);
        if (IS_WIDGET_REALIZED(wi)) {
+               const int diff = vs.lineHeight * -linesToMove;
                gdk_window_scroll(WindowFromWidget(wi), 0, -diff);
                gdk_window_process_updates(WindowFromWidget(wi), FALSE);
        }
+#endif
 }
 
 void ScintillaGTK::SetVerticalScrollPos() {
@@ -1126,34 +1052,24 @@ void ScintillaGTK::SetVerticalScrollPos() {
 
 void ScintillaGTK::SetHorizontalScrollPos() {
        DwellEnd(true);
-       gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmenth), xOffset / 2);
+       gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmenth), xOffset);
 }
 
-bool ScintillaGTK::ModifyScrollBars(int nMax, int nPage) {
+bool ScintillaGTK::ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) {
        bool modified = false;
        int pageScroll = LinesToScroll();
 
-#if GTK_CHECK_VERSION(3,0,0)
        if (gtk_adjustment_get_upper(adjustmentv) != (nMax + 1) ||
                gtk_adjustment_get_page_size(adjustmentv) != nPage ||
                gtk_adjustment_get_page_increment(adjustmentv) != pageScroll) {
                gtk_adjustment_set_upper(adjustmentv, nMax + 1);
                gtk_adjustment_set_page_size(adjustmentv, nPage);
                gtk_adjustment_set_page_increment(adjustmentv, pageScroll);
+#if !GTK_CHECK_VERSION(3,18,0)
                gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmentv));
+#endif
                modified = true;
        }
-#else
-       if (GTK_ADJUSTMENT(adjustmentv)->upper != (nMax + 1) ||
-               GTK_ADJUSTMENT(adjustmentv)->page_size != nPage ||
-               GTK_ADJUSTMENT(adjustmentv)->page_increment != pageScroll) {
-               GTK_ADJUSTMENT(adjustmentv)->upper = nMax + 1;
-               GTK_ADJUSTMENT(adjustmentv)->page_size = nPage;
-               GTK_ADJUSTMENT(adjustmentv)->page_increment = pageScroll;
-               gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmentv));
-               modified = true;
-       }
-#endif
 
        PRectangle rcText = GetTextRectangle();
        int horizEndPreferred = scrollWidth;
@@ -1162,7 +1078,6 @@ bool ScintillaGTK::ModifyScrollBars(int nMax, int nPage) {
        unsigned int pageWidth = rcText.Width();
        unsigned int pageIncrement = pageWidth / 3;
        unsigned int charWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
-#if GTK_CHECK_VERSION(3,0,0)
        if (gtk_adjustment_get_upper(adjustmenth) != horizEndPreferred ||
                gtk_adjustment_get_page_size(adjustmenth) != pageWidth ||
                gtk_adjustment_get_page_increment(adjustmenth) != pageIncrement ||
@@ -1171,24 +1086,13 @@ bool ScintillaGTK::ModifyScrollBars(int nMax, int nPage) {
                gtk_adjustment_set_page_size(adjustmenth, pageWidth);
                gtk_adjustment_set_page_increment(adjustmenth, pageIncrement);
                gtk_adjustment_set_step_increment(adjustmenth, charWidth);
+#if !GTK_CHECK_VERSION(3,18,0)
                gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmenth));
+#endif
                modified = true;
        }
-#else
-       if (GTK_ADJUSTMENT(adjustmenth)->upper != horizEndPreferred ||
-               GTK_ADJUSTMENT(adjustmenth)->page_size != pageWidth ||
-               GTK_ADJUSTMENT(adjustmenth)->page_increment != pageIncrement ||
-               GTK_ADJUSTMENT(adjustmenth)->step_increment != charWidth) {
-               GTK_ADJUSTMENT(adjustmenth)->upper = horizEndPreferred;
-               GTK_ADJUSTMENT(adjustmenth)->step_increment = charWidth;
-               GTK_ADJUSTMENT(adjustmenth)->page_size = pageWidth;
-               GTK_ADJUSTMENT(adjustmenth)->page_increment = pageIncrement;
-               gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmenth));
-               modified = true;
-       }
-#endif
        if (modified && (paintState == painting)) {
-               paintState = paintAbandoned;
+               repaintFullWindow = true;
        }
 
        return modified;
@@ -1208,6 +1112,7 @@ void ScintillaGTK::NotifyFocus(bool focus) {
        g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0,
                        Platform::LongFromTwoShorts
                                        (GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS), 
PWidget(wMain));
+       Editor::NotifyFocus(focus);
 }
 
 void ScintillaGTK::NotifyParent(SCNotification scn) {
@@ -1218,7 +1123,7 @@ void ScintillaGTK::NotifyParent(SCNotification scn) {
 }
 
 void ScintillaGTK::NotifyKey(int key, int modifiers) {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_KEY;
        scn.ch = key;
        scn.modifiers = modifiers;
@@ -1227,7 +1132,7 @@ void ScintillaGTK::NotifyKey(int key, int modifiers) {
 }
 
 void ScintillaGTK::NotifyURIDropped(const char *list) {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_URIDROPPED;
        scn.text = list;
 
@@ -1243,10 +1148,10 @@ const char *ScintillaGTK::CharacterSetID() const {
 class CaseFolderDBCS : public CaseFolderTable {
        const char *charSet;
 public:
-       CaseFolderDBCS(const char *charSet_) : charSet(charSet_) {
+       explicit CaseFolderDBCS(const char *charSet_) : charSet(charSet_) {
                StandardASCII();
        }
-       virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
+       size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) override {
                if ((lenMixed == 1) && (sizeFolded > 0)) {
                        folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
                        return 1;
@@ -1333,7 +1238,7 @@ std::string ScintillaGTK::CaseMapString(const std::string &s, int caseMapping) {
 
        if (IsUnicodeMode()) {
                std::string retMapped(s.length() * maxExpansionCaseConversion, 0);
-               size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), 
s.length(), 
+               size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), s.length(),
                        (caseMapping == cmUpper) ? CaseConversionUpper : CaseConversionLower);
                retMapped.resize(lenMapped);
                return retMapped;
@@ -1382,8 +1287,35 @@ void ScintillaGTK::Copy() {
 
 void ScintillaGTK::Paste() {
        atomSought = atomUTF8;
-       gtk_selection_convert(GTK_WIDGET(PWidget(wMain)),
-                             atomClipboard, atomSought, GDK_CURRENT_TIME);
+       GtkClipboard *clipBoard =
+               gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomClipboard);
+       if (clipBoard == NULL)
+               return;
+
+       // helper class for the asynchronous paste not to risk calling in a destroyed ScintillaGTK
+       class Helper : GObjectWatcher {
+               ScintillaGTK *sci;
+
+               void Destroyed() override {
+                       sci = 0;
+               }
+
+       public:
+               Helper(ScintillaGTK *sci_) :
+                               GObjectWatcher(G_OBJECT(PWidget(sci_->wMain))),
+                               sci(sci_) {
+               }
+
+               static void ClipboardReceived(GtkClipboard *, GtkSelectionData *selection_data, gpointer 
data) {
+                       Helper *self = static_cast<Helper*>(data);
+                       if (self->sci != 0) {
+                               self->sci->ReceivedSelection(selection_data);
+                       }
+                       delete self;
+               }
+       };
+
+       gtk_clipboard_request_contents(clipBoard, atomSought, Helper::ClipboardReceived, new Helper(this));
 }
 
 void ScintillaGTK::CreateCallTipWindow(PRectangle rc) {
@@ -1403,6 +1335,9 @@ void ScintillaGTK::CreateCallTipWindow(PRectangle rc) {
                                   G_CALLBACK(ScintillaGTK::PressCT), static_cast<void *>(this));
                gtk_widget_set_events(widcdrw,
                        GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK);
+               GtkWidget *top = gtk_widget_get_toplevel(static_cast<GtkWidget *>(wMain.GetID()));
+               gtk_window_set_transient_for(GTK_WINDOW(static_cast<GtkWidget *>(PWidget(ct.wCallTip))),
+                       GTK_WINDOW(top));
        }
        gtk_widget_set_size_request(PWidget(ct.wDraw), rc.Width(), rc.Height());
        ct.wDraw.Show();
@@ -1418,7 +1353,7 @@ void ScintillaGTK::AddToPopUp(const char *label, int cmd, bool enabled) {
        else
                menuItem = gtk_separator_menu_item_new();
        gtk_menu_shell_append(GTK_MENU_SHELL(popup.GetID()), menuItem);
-       g_object_set_data(G_OBJECT(menuItem), "CmdNum", reinterpret_cast<void *>(cmd));
+       g_object_set_data(G_OBJECT(menuItem), "CmdNum", GINT_TO_POINTER(cmd));
        g_signal_connect(G_OBJECT(menuItem),"activate", G_CALLBACK(PopUpCB), this);
 
        if (cmd) {
@@ -1451,17 +1386,10 @@ void ScintillaGTK::ClaimSelection() {
        }
 }
 
-#if GTK_CHECK_VERSION(3,0,0)
 static const guchar *DataOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data(sd); }
 static gint LengthOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_length(sd); }
 static GdkAtom TypeOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_data_type(sd); }
 static GdkAtom SelectionOfGSD(GtkSelectionData *sd) { return gtk_selection_data_get_selection(sd); }
-#else
-static const guchar *DataOfGSD(GtkSelectionData *sd) { return sd->data; }
-static gint LengthOfGSD(GtkSelectionData *sd) { return sd->length; }
-static GdkAtom TypeOfGSD(GtkSelectionData *sd) { return sd->type; }
-static GdkAtom SelectionOfGSD(GtkSelectionData *sd) { return sd->selection; }
-#endif
 
 // Detect rectangular text, convert line ends to current mode, convert from or to UTF-8
 void ScintillaGTK::GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText) {
@@ -1485,7 +1413,14 @@ void ScintillaGTK::GetGtkSelectionText(GtkSelectionData *selectionData, Selectio
                len--;  // Forget the extra '\0'
 #endif
 
-       std::string dest = Document::TransformLineEnds(data, len, pdoc->eolMode);
+#if PLAT_GTK_WIN32
+       // Win32 includes an ending '\0' byte in 'len' for clipboard text from
+       // external applications; ignore it.
+       if ((len > 0) && (data[len - 1] == '\0'))
+               len--;
+#endif
+
+       std::string dest(data, len);
        if (selectionTypeData == GDK_TARGET_STRING) {
                if (IsUnicodeMode()) {
                        // Unknown encoding so assume in Latin1
@@ -1526,15 +1461,9 @@ void ScintillaGTK::ReceivedSelection(GtkSelectionData *selection_data) {
                                if (SelectionOfGSD(selection_data) != GDK_SELECTION_PRIMARY) {
                                        ClearSelection(multiPasteMode == SC_MULTIPASTE_EACH);
                                }
-                               SelectionPosition selStart = sel.IsRectangular() ?
-                                       sel.Rectangular().Start() :
-                                       sel.Range(sel.Main()).Start();
 
-                               if (selText.rectangular) {
-                                       PasteRectangular(selStart, selText.Data(), selText.Length());
-                               } else {
-                                       InsertPaste(selStart, selText.Data(), selText.Length());
-                               }
+                               InsertPasteShape(selText.Data(), selText.Length(),
+                                       selText.rectangular ? pasteRectangular : pasteStream);
                                EnsureCaretVisible();
                        }
                }
@@ -1554,7 +1483,7 @@ void ScintillaGTK::ReceivedDrop(GtkSelectionData *selection_data) {
                drop.push_back('\0');
                NotifyURIDropped(&drop[0]);
        } else if ((TypeOfGSD(selection_data) == GDK_TARGET_STRING) || (TypeOfGSD(selection_data) == 
atomUTF8)) {
-               if (TypeOfGSD(selection_data) > 0) {
+               if (LengthOfGSD(selection_data) > 0) {
                        SelectionText selText;
                        GetGtkSelectionText(selection_data, selText);
                        DropAt(posDrop, selText.Data(), selText.Length(), false, selText.rectangular);
@@ -1572,24 +1501,24 @@ void ScintillaGTK::GetSelection(GtkSelectionData *selection_data, guint info, Se
        // GDK on Win32 expands any \n into \r\n, so make a copy of
        // the clip text now with newlines converted to \n.  Use { } to hide symbols
        // from code below
-       SelectionText *newline_normalized = NULL;
+       std::unique_ptr<SelectionText> newline_normalized;
        {
                std::string tmpstr = Document::TransformLineEnds(text->Data(), text->Length(), SC_EOL_LF);
-               newline_normalized = new SelectionText();
+               newline_normalized.reset(new SelectionText());
                newline_normalized->Copy(tmpstr, SC_CP_UTF8, 0, text->rectangular, false);
-               text = newline_normalized;
+               text = newline_normalized.get();
        }
 #endif
 
        // Convert text to utf8 if it isn't already
-       SelectionText *converted = 0;
+       std::unique_ptr<SelectionText> converted;
        if ((text->codePage != SC_CP_UTF8) && (info == TARGET_UTF8_STRING)) {
                const char *charSet = ::CharacterSetID(text->characterSet);
                if (*charSet) {
                        std::string tmputf = ConvertText(text->Data(), text->Length(), "UTF-8", charSet, 
false);
-                       converted = new SelectionText();
+                       converted.reset(new SelectionText());
                        converted->Copy(tmputf, SC_CP_UTF8, 0, text->rectangular, false);
-                       text = converted;
+                       text = converted.get();
                }
        }
 
@@ -1614,11 +1543,6 @@ void ScintillaGTK::GetSelection(GtkSelectionData *selection_data, guint info, Se
                        static_cast<GdkAtom>(GDK_SELECTION_TYPE_STRING),
                        8, reinterpret_cast<const unsigned char *>(textData), len);
        }
-       delete converted;
-
-#if PLAT_GTK_WIN32
-       delete newline_normalized;
-#endif
 }
 
 void ScintillaGTK::StoreOnClipboard(SelectionText *clipText) {
@@ -1662,28 +1586,35 @@ void ScintillaGTK::Resize(int width, int height) {
        //Platform::DebugPrintf("Resize %d %d\n", width, height);
        //printf("Resize %d %d\n", width, height);
 
+       // GTK+ 3 warns when we allocate smaller than the minimum allocation,
+       // so we use these variables to store the minimum scrollbar lengths.
+       int minVScrollBarHeight, minHScrollBarWidth;
+
        // Not always needed, but some themes can have different sizes of scrollbars
 #if GTK_CHECK_VERSION(3,0,0)
-       GtkRequisition requisition;
-       gtk_widget_get_requisition(PWidget(scrollbarv), &requisition);
+       GtkRequisition minimum, requisition;
+       gtk_widget_get_preferred_size(PWidget(scrollbarv), &minimum, &requisition);
+       minVScrollBarHeight = minimum.height;
        verticalScrollBarWidth = requisition.width;
-       gtk_widget_get_requisition(PWidget(scrollbarh), &requisition);
+       gtk_widget_get_preferred_size(PWidget(scrollbarh), &minimum, &requisition);
+       minHScrollBarWidth = minimum.width;
        horizontalScrollBarHeight = requisition.height;
 #else
+       minVScrollBarHeight = minHScrollBarWidth = 1;
        verticalScrollBarWidth = GTK_WIDGET(PWidget(scrollbarv))->requisition.width;
        horizontalScrollBarHeight = GTK_WIDGET(PWidget(scrollbarh))->requisition.height;
 #endif
 
        // These allocations should never produce negative sizes as they would wrap around to huge
        // unsigned numbers inside GTK+ causing warnings.
-       bool showSBHorizontal = horizontalScrollBarVisible && (wrapState == eWrapNone);
+       bool showSBHorizontal = horizontalScrollBarVisible && !Wrapping();
 
        GtkAllocation alloc;
        if (showSBHorizontal) {
                gtk_widget_show(GTK_WIDGET(PWidget(scrollbarh)));
                alloc.x = 0;
                alloc.y = height - horizontalScrollBarHeight;
-               alloc.width = Platform::Maximum(1, width - verticalScrollBarWidth);
+               alloc.width = Platform::Maximum(minHScrollBarWidth, width - verticalScrollBarWidth);
                alloc.height = horizontalScrollBarHeight;
                gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarh)), &alloc);
        } else {
@@ -1696,7 +1627,7 @@ void ScintillaGTK::Resize(int width, int height) {
                alloc.x = width - verticalScrollBarWidth;
                alloc.y = 0;
                alloc.width = verticalScrollBarWidth;
-               alloc.height = Platform::Maximum(1, height - horizontalScrollBarHeight);
+               alloc.height = Platform::Maximum(minVScrollBarHeight, height - horizontalScrollBarHeight);
                gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarv)), &alloc);
        } else {
                gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarv)));
@@ -1708,20 +1639,24 @@ void ScintillaGTK::Resize(int width, int height) {
 
        alloc.x = 0;
        alloc.y = 0;
-       alloc.width = Platform::Maximum(1, width - verticalScrollBarWidth);
-       alloc.height = Platform::Maximum(1, height - horizontalScrollBarHeight);
+       alloc.width = 1;
+       alloc.height = 1;
+#if GTK_CHECK_VERSION(3, 0, 0)
+       // please GTK 3.20 and ask wText what size it wants, although we know it doesn't really need
+       // anything special as it's ours.
+       gtk_widget_get_preferred_size(PWidget(wText), &requisition, NULL);
+       alloc.width = requisition.width;
+       alloc.height = requisition.height;
+#endif
+       alloc.width = Platform::Maximum(alloc.width, width - verticalScrollBarWidth);
+       alloc.height = Platform::Maximum(alloc.height, height - horizontalScrollBarHeight);
        gtk_widget_size_allocate(GTK_WIDGET(PWidget(wText)), &alloc);
 }
 
 static void SetAdjustmentValue(GtkAdjustment *object, int value) {
        GtkAdjustment *adjustment = GTK_ADJUSTMENT(object);
-#if GTK_CHECK_VERSION(3,0,0)
        int maxValue = static_cast<int>(
                gtk_adjustment_get_upper(adjustment) - gtk_adjustment_get_page_size(adjustment));
-#else
-       int maxValue = static_cast<int>(
-               adjustment->upper - adjustment->page_size);
-#endif
 
        if (value > maxValue)
                value = maxValue;
@@ -1768,17 +1703,24 @@ gint ScintillaGTK::PressThis(GdkEventButton *event) {
                        return FALSE;
                }
 
+               bool shift = (event->state & GDK_SHIFT_MASK) != 0;
                bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
+               // On X, instead of sending literal modifiers use the user specified
+               // modifier, defaulting to control instead of alt.
+               // This is because most X window managers grab alt + click for moving
+               bool alt = (event->state & modifierTranslated(rectangularSelectionModifier)) != 0;
 
                gtk_widget_grab_focus(PWidget(wMain));
                if (event->button == 1) {
-                       // On X, instead of sending literal modifiers use the user specified
-                       // modifier, defaulting to control instead of alt.
-                       // This is because most X window managers grab alt + click for moving
-                       ButtonDown(pt, event->time,
-                               (event->state & GDK_SHIFT_MASK) != 0,
-                               (event->state & GDK_CONTROL_MASK) != 0,
-                               (event->state & modifierTranslated(rectangularSelectionModifier)) != 0);
+#if PLAT_GTK_MACOSX
+                       bool meta = ctrl;
+                       // GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
+                       // not GDK_META_MASK like in key events.
+                       ctrl = (event->state & GDK_MOD2_MASK) != 0;
+#else
+                       bool meta = false;
+#endif
+                       ButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, meta));
                } else if (event->button == 2) {
                        // Grab the primary selection if it exists
                        SelectionPosition pos = SPositionFromLocation(pt, false, false, UserVirtualSpace());
@@ -1793,7 +1735,7 @@ gint ScintillaGTK::PressThis(GdkEventButton *event) {
                } else if (event->button == 3) {
                        if (!PointInSelection(pt))
                                SetEmptySelection(PositionFromLocation(pt));
-                       if (displayPopupMenu) {
+                       if (ShouldDisplayPopup(pt)) {
                                // PopUp menu
                                // Convert to screen
                                int ox = 0;
@@ -1801,18 +1743,27 @@ gint ScintillaGTK::PressThis(GdkEventButton *event) {
                                gdk_window_get_origin(PWindow(wMain), &ox, &oy);
                                ContextMenu(Point(pt.x + ox, pt.y + oy));
                        } else {
+#if PLAT_GTK_MACOSX
+                               bool meta = ctrl;
+                               // GDK reports the Command modifer key as GDK_MOD2_MASK for button events,
+                               // not GDK_META_MASK like in key events.
+                               ctrl = (event->state & GDK_MOD2_MASK) != 0;
+#else
+                               bool meta = false;
+#endif
+                               RightButtonDownWithModifiers(pt, event->time, ModifierFlags(shift, ctrl, alt, 
meta));
                                return FALSE;
                        }
                } else if (event->button == 4) {
                        // Wheel scrolling up (only GTK 1.x does it this way)
                        if (ctrl)
-                               SetAdjustmentValue(adjustmenth, (xOffset / 2) - 6);
+                               SetAdjustmentValue(adjustmenth, xOffset - 6);
                        else
                                SetAdjustmentValue(adjustmentv, topLine - 3);
                } else if (event->button == 5) {
                        // Wheel scrolling down (only GTK 1.x does it this way)
                        if (ctrl)
-                               SetAdjustmentValue(adjustmenth, (xOffset / 2) + 6);
+                               SetAdjustmentValue(adjustmenth, xOffset + 6);
                        else
                                SetAdjustmentValue(adjustmentv, topLine + 3);
                }
@@ -1825,12 +1776,12 @@ gint ScintillaGTK::PressThis(GdkEventButton *event) {
 gint ScintillaGTK::Press(GtkWidget *widget, GdkEventButton *event) {
        if (event->window != WindowFromWidget(widget))
                return FALSE;
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        return sciThis->PressThis(event);
 }
 
 gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                //Platform::DebugPrintf("Release %x %d %d\n",sciThis,event->time,event->state);
                if (!sciThis->HaveMouseCapture())
@@ -1845,7 +1796,7 @@ gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
                                // If mouse released on scroll bar then the position is relative to the
                                // scrollbar, not the drawing window so just repeat the most recent point.
                                pt = sciThis->ptMouseLast;
-                       sciThis->ButtonUp(pt, event->time, (event->state & 4) != 0);
+                       sciThis->ButtonUp(pt, event->time, (event->state & GDK_CONTROL_MASK) != 0);
                }
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
@@ -1856,19 +1807,39 @@ gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) {
 // win32gtk and GTK >= 2 use SCROLL_* events instead of passing the
 // button4/5/6/7 events to the GTK app
 gint ScintillaGTK::ScrollEvent(GtkWidget *widget, GdkEventScroll *event) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
 
                if (widget == NULL || event == NULL)
                        return FALSE;
 
+#if defined(GDK_WINDOWING_WAYLAND)
+               if (event->direction == GDK_SCROLL_SMOOTH && GDK_IS_WAYLAND_WINDOW(event->window)) {
+                       const int smoothScrollFactor = 4;
+                       sciThis->smoothScrollY += event->delta_y * smoothScrollFactor;
+                       sciThis->smoothScrollX += event->delta_x * smoothScrollFactor;;
+                       if (ABS(sciThis->smoothScrollY) >= 1.0) {
+                               const int scrollLines = trunc(sciThis->smoothScrollY);
+                               sciThis->ScrollTo(sciThis->topLine + scrollLines);
+                               sciThis->smoothScrollY -= scrollLines;
+                       }
+                       if (ABS(sciThis->smoothScrollX) >= 1.0) {
+                               const int scrollPixels = trunc(sciThis->smoothScrollX);
+                               sciThis->HorizontalScrollTo(sciThis->xOffset + scrollPixels);
+                               sciThis->smoothScrollX -= scrollPixels;
+                       }
+                       return TRUE;
+               }
+#endif
+
                // Compute amount and direction to scroll (even tho on win32 there is
                // intensity of scrolling info in the native message, gtk doesn't
                // support this so we simulate similarly adaptive scrolling)
-               // Note that this is disabled on OS X (Darwin) where the X11 server already has
-               // and adaptive scrolling algorithm that fights with this one
+               // Note that this is disabled on OS X (Darwin) with the X11 backend
+               // where the X11 server already has an adaptive scrolling algorithm
+               // that fights with this one
                int cLineScroll;
-#if defined(__MWERKS__) || defined(__APPLE_CPP__) || defined(__APPLE_CC__)
+#if defined(__APPLE__) && !defined(GDK_WINDOWING_QUARTZ)
                cLineScroll = sciThis->linesPerScroll;
                if (cLineScroll == 0)
                        cLineScroll = 4;
@@ -1939,7 +1910,7 @@ gint ScintillaGTK::ScrollEvent(GtkWidget *widget, GdkEventScroll *event) {
 }
 
 gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                //Platform::DebugPrintf("Motion %x %d\n",sciThis,event->time);
                if (event->window != WindowFromWidget(widget))
@@ -1949,7 +1920,7 @@ gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
                GdkModifierType state;
                if (event->is_hint) {
 #if GTK_CHECK_VERSION(3,0,0)
-                       gdk_window_get_device_position(event->window, 
+                       gdk_window_get_device_position(event->window,
                                event->device, &x, &y, &state);
 #else
                        gdk_window_get_pointer(event->window, &x, &y, &state);
@@ -1962,7 +1933,10 @@ gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
                //Platform::DebugPrintf("Move %x %x %d %c %d %d\n",
                //      sciThis,event->window,event->time,event->is_hint? 'h' :'.', x, y);
                Point pt(x, y);
-               sciThis->ButtonMove(pt);
+               int modifiers = ((event->state & GDK_SHIFT_MASK) != 0 ? SCI_SHIFT : 0) |
+                               ((event->state & GDK_CONTROL_MASK) != 0 ? SCI_CTRL : 0) |
+                               ((event->state & modifierTranslated(sciThis->rectangularSelectionModifier)) 
!= 0 ? SCI_ALT : 0);
+               sciThis->ButtonMoveWithModifiers(pt, modifiers);
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
        }
@@ -2126,6 +2100,7 @@ gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
                bool shift = (event->state & GDK_SHIFT_MASK) != 0;
                bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
                bool alt = (event->state & GDK_MOD1_MASK) != 0;
+               bool super = (event->state & GDK_MOD4_MASK) != 0;
                guint key = event->keyval;
                if ((ctrl || alt) && (key < 128))
                        key = toupper(key);
@@ -2142,22 +2117,20 @@ gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
 
                bool consumed = false;
 #if !(PLAT_GTK_MACOSX)
-               bool added = KeyDown(key, shift, ctrl, alt, &consumed) != 0;
+               bool meta = false;
 #else
                bool meta = ctrl;
                ctrl = (event->state & GDK_META_MASK) != 0;
-               bool added = KeyDownWithModifiers(key, (shift ? SCI_SHIFT : 0) |
-                                                      (ctrl ? SCI_CTRL : 0) |
-                                                      (alt ? SCI_ALT : 0) |
-                                                      (meta ? SCI_META : 0), &consumed) != 0;
 #endif
+               bool added = KeyDownWithModifiers(key, ModifierFlags(shift, ctrl, alt, meta, super), 
&consumed) != 0;
                if (!consumed)
                        consumed = added;
                //fprintf(stderr, "SK-key: %d %x %x\n",event->keyval, event->state, consumed);
                if (event->keyval == 0xffffff && event->length > 0) {
                        ClearSelection();
-                       if (pdoc->InsertCString(CurrentPosition(), event->string)) {
-                               MovePositionTo(CurrentPosition() + event->length);
+                       const int lengthInserted = pdoc->InsertString(CurrentPosition(), event->string, 
strlen(event->string));
+                       if (lengthInserted > 0) {
+                               MovePositionTo(CurrentPosition() + lengthInserted);
                        }
                }
                return consumed;
@@ -2168,13 +2141,13 @@ gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
 }
 
 gboolean ScintillaGTK::KeyPress(GtkWidget *widget, GdkEventKey *event) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        return sciThis->KeyThis(event);
 }
 
 gboolean ScintillaGTK::KeyRelease(GtkWidget *widget, GdkEventKey *event) {
        //Platform::DebugPrintf("SC-keyrel: %d %x %3s\n",event->keyval, event->state, event->string);
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        if (gtk_im_context_filter_keypress(sciThis->im_context, event)) {
                return TRUE;
        }
@@ -2183,21 +2156,15 @@ gboolean ScintillaGTK::KeyRelease(GtkWidget *widget, GdkEventKey *event) {
 
 #if GTK_CHECK_VERSION(3,0,0)
 
-gboolean ScintillaGTK::DrawPreeditThis(GtkWidget *widget, cairo_t *cr) {
+gboolean ScintillaGTK::DrawPreeditThis(GtkWidget *, cairo_t *cr) {
        try {
-               gchar *str;
-               gint cursor_pos;
-               PangoAttrList *attrs;
-
-               gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
-               PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), str);
-               pango_layout_set_attributes(layout, attrs);
+               PreEditString pes(im_context);
+               PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
+               pango_layout_set_attributes(layout, pes.attrs);
 
                cairo_move_to(cr, 0, 0);
                pango_cairo_show_layout(cr, layout);
 
-               g_free(str);
-               pango_attr_list_unref(attrs);
                g_object_unref(layout);
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
@@ -2211,22 +2178,16 @@ gboolean ScintillaGTK::DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK
 
 #else
 
-gboolean ScintillaGTK::ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose) {
+gboolean ScintillaGTK::ExposePreeditThis(GtkWidget *widget, GdkEventExpose *) {
        try {
-               gchar *str;
-               gint cursor_pos;
-               PangoAttrList *attrs;
-
-               gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
-               PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), str);
-               pango_layout_set_attributes(layout, attrs);
+               PreEditString pes(im_context);
+               PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
+               pango_layout_set_attributes(layout, pes.attrs);
 
                cairo_t *context = gdk_cairo_create(reinterpret_cast<GdkDrawable 
*>(WindowFromWidget(widget)));
                cairo_move_to(context, 0, 0);
                pango_cairo_show_layout(context, layout);
                cairo_destroy(context);
-               g_free(str);
-               pango_attr_list_unref(attrs);
                g_object_unref(layout);
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
@@ -2240,33 +2201,121 @@ gboolean ScintillaGTK::ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, Sci
 
 #endif
 
-void ScintillaGTK::CommitThis(char *utfVal) {
-       try {
-               //~ fprintf(stderr, "Commit '%s'\n", utfVal);
-               if (IsUnicodeMode()) {
-                       AddCharUTF(utfVal, strlen(utfVal));
-               } else {
-                       const char *source = CharacterSetID();
-                       if (*source) {
-                               Converter conv(source, "UTF-8", true);
-                               if (conv) {
-                                       char localeVal[4] = "\0\0\0";
-                                       char *pin = utfVal;
-                                       size_t inLeft = strlen(utfVal);
-                                       char *pout = localeVal;
-                                       size_t outLeft = sizeof(localeVal);
-                                       size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft);
-                                       if (conversions != ((size_t)(-1))) {
-                                               *pout = '\0';
-                                               for (int i = 0; localeVal[i]; i++) {
-                                                       AddChar(localeVal[i]);
-                                               }
-                                       } else {
-                                               fprintf(stderr, "Conversion failed '%s'\n", utfVal);
+bool ScintillaGTK::KoreanIME() {
+       PreEditString pes(im_context);
+       if (pes.pscript != PANGO_SCRIPT_COMMON)
+               lastNonCommonScript = pes.pscript;
+       return lastNonCommonScript == PANGO_SCRIPT_HANGUL;
+}
+
+void ScintillaGTK::MoveImeCarets(int pos) {
+       // Move carets relatively by bytes
+       for (size_t r=0; r<sel.Count(); r++) {
+               int positionInsert = sel.Range(r).Start().Position();
+               sel.Range(r).caret.SetPosition(positionInsert + pos);
+               sel.Range(r).anchor.SetPosition(positionInsert + pos);
+       }
+}
+
+void ScintillaGTK::DrawImeIndicator(int indicator, int len) {
+       // Emulate the visual style of IME characters with indicators.
+       // Draw an indicator on the character before caret by the character bytes of len
+       // so it should be called after addCharUTF().
+       // It does not affect caret positions.
+       if (indicator < 8 || indicator > INDIC_MAX) {
+               return;
+       }
+       pdoc->DecorationSetCurrentIndicator(indicator);
+       for (size_t r=0; r<sel.Count(); r++) {
+               int positionInsert = sel.Range(r).Start().Position();
+               pdoc->DecorationFillRange(positionInsert - len, 1, len);
+       }
+}
+
+static std::vector<int> MapImeIndicators(PangoAttrList *attrs, const char *u8Str) {
+       // Map input style to scintilla ime indicator.
+       // Attrs position points between UTF-8 bytes.
+       // Indicator index to be returned is character based though.
+       glong charactersLen = g_utf8_strlen(u8Str, strlen(u8Str));
+       std::vector<int> indicator(charactersLen, SC_INDICATOR_UNKNOWN);
+
+       PangoAttrIterator *iterunderline = pango_attr_list_get_iterator(attrs);
+       if (iterunderline) {
+               do {
+                       PangoAttribute  *attrunderline = pango_attr_iterator_get(iterunderline, 
PANGO_ATTR_UNDERLINE);
+                       if (attrunderline) {
+                               glong start = g_utf8_strlen(u8Str, attrunderline->start_index);
+                               glong end = g_utf8_strlen(u8Str, attrunderline->end_index);
+                               PangoUnderline uline = (PangoUnderline)((PangoAttrInt *)attrunderline)->value;
+                               for (glong i=start; i < end; ++i) {
+                                       switch (uline) {
+                                       case PANGO_UNDERLINE_NONE:
+                                               indicator[i] = SC_INDICATOR_UNKNOWN;
+                                               break;
+                                       case PANGO_UNDERLINE_SINGLE: // normal input
+                                               indicator[i] = SC_INDICATOR_INPUT;
+                                               break;
+                                       case PANGO_UNDERLINE_DOUBLE:
+                                       case PANGO_UNDERLINE_LOW:
+                                       case PANGO_UNDERLINE_ERROR:
+                                               break;
                                        }
                                }
                        }
+               } while (pango_attr_iterator_next(iterunderline));
+               pango_attr_iterator_destroy(iterunderline);
+       }
+
+       PangoAttrIterator *itercolor = pango_attr_list_get_iterator(attrs);
+       if (itercolor) {
+               do {
+                       PangoAttribute  *backcolor = pango_attr_iterator_get(itercolor, 
PANGO_ATTR_BACKGROUND);
+                       if (backcolor) {
+                               glong start = g_utf8_strlen(u8Str, backcolor->start_index);
+                               glong end = g_utf8_strlen(u8Str, backcolor->end_index);
+                               for (glong i=start; i < end; ++i) {
+                                       indicator[i] = SC_INDICATOR_TARGET;  // target converted
+                               }
+                       }
+               } while (pango_attr_iterator_next(itercolor));
+               pango_attr_iterator_destroy(itercolor);
+       }
+       return indicator;
+}
+
+void ScintillaGTK::SetCandidateWindowPos() {
+       // Composition box accompanies candidate box.
+       Point pt = PointMainCaret();
+       GdkRectangle imeBox = {0}; // No need to set width
+       imeBox.x = pt.x;           // Only need positiion
+       imeBox.y = pt.y + vs.lineHeight; // underneath the first charater
+       gtk_im_context_set_cursor_location(im_context, &imeBox);
+}
+
+void ScintillaGTK::CommitThis(char *commitStr) {
+       try {
+               //~ fprintf(stderr, "Commit '%s'\n", commitStr);
+               view.imeCaretBlockOverride = false;
+
+               if (pdoc->TentativeActive()) {
+                       pdoc->TentativeUndo();
                }
+
+               const char *charSetSource = CharacterSetID();
+
+               glong uniStrLen = 0;
+               gunichar *uniStr = g_utf8_to_ucs4_fast(commitStr, strlen(commitStr), &uniStrLen);
+               for (glong i = 0; i < uniStrLen; i++) {
+                       gchar u8Char[UTF8MaxBytes+2] = {0};
+                       gint u8CharLen = g_unichar_to_utf8(uniStr[i], u8Char);
+                       std::string docChar = u8Char;
+                       if (!IsUnicodeMode())
+                               docChar = ConvertText(u8Char, u8CharLen, charSetSource, "UTF-8", true);
+
+                       AddCharUTF(docChar.c_str(), docChar.size());
+               }
+               g_free(uniStr);
+               ShowCaretAtCurrentPosition();
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
        }
@@ -2276,15 +2325,91 @@ void ScintillaGTK::Commit(GtkIMContext *, char  *str, ScintillaGTK *sciThis) {
        sciThis->CommitThis(str);
 }
 
-void ScintillaGTK::PreeditChangedThis() {
+void ScintillaGTK::PreeditChangedInlineThis() {
+       // Copy & paste by johnsonj with a lot of helps of Neil
+       // Great thanks for my foreruners, jiniya and BLUEnLIVE
        try {
-               gchar *str;
-               PangoAttrList *attrs;
-               gint cursor_pos;
-               gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos);
-               if (strlen(str) > 0) {
-                       PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), str);
-                       pango_layout_set_attributes(layout, attrs);
+               if (pdoc->IsReadOnly() || SelectionContainsProtected()) {
+                       gtk_im_context_reset(im_context);
+                       return;
+               }
+
+               view.imeCaretBlockOverride = false; // If backspace.
+
+               bool initialCompose = false;
+               if (pdoc->TentativeActive()) {
+                       pdoc->TentativeUndo();
+               } else {
+                       // No tentative undo means start of this composition so
+                       // fill in any virtual spaces.
+                       initialCompose = true;
+               }
+
+               PreEditString preeditStr(im_context);
+               const char *charSetSource = CharacterSetID();
+
+               if (!preeditStr.validUTF8 || (charSetSource == NULL)) {
+                       ShowCaretAtCurrentPosition();
+                       return;
+               }
+
+               if (preeditStr.uniStrLen == 0 || preeditStr.uniStrLen > maxLenInputIME) {
+                       //fprintf(stderr, "Do not allow over 200 chars: %i\n", preeditStr.uniStrLen);
+                       ShowCaretAtCurrentPosition();
+                       return;
+               }
+
+               if (initialCompose)
+                       ClearBeforeTentativeStart();
+               pdoc->TentativeStart(); // TentativeActive() from now on
+
+               std::vector<int> indicator = MapImeIndicators(preeditStr.attrs, preeditStr.str);
+
+               bool tmpRecordingMacro = recordingMacro;
+               recordingMacro = false;
+               for (glong i = 0; i < preeditStr.uniStrLen; i++) {
+                       gchar u8Char[UTF8MaxBytes+2] = {0};
+                       gint u8CharLen = g_unichar_to_utf8(preeditStr.uniStr[i], u8Char);
+                       std::string docChar = u8Char;
+                       if (!IsUnicodeMode())
+                               docChar = ConvertText(u8Char, u8CharLen, charSetSource, "UTF-8", true);
+
+                       AddCharUTF(docChar.c_str(), docChar.size());
+
+                       DrawImeIndicator(indicator[i], docChar.size());
+               }
+               recordingMacro = tmpRecordingMacro;
+
+               // Move caret to ime cursor position.
+               int imeEndToImeCaretU32 = preeditStr.cursor_pos - preeditStr.uniStrLen;
+               int imeCaretPosDoc = pdoc->GetRelativePosition(CurrentPosition(), imeEndToImeCaretU32);
+
+               MoveImeCarets(- CurrentPosition() + imeCaretPosDoc);
+
+               if (KoreanIME()) {
+#if !PLAT_GTK_WIN32
+                       if (preeditStr.cursor_pos > 0) {
+                               int oneCharBefore = pdoc->GetRelativePosition(CurrentPosition(), -1);
+                               MoveImeCarets(- CurrentPosition() + oneCharBefore);
+                       }
+#endif
+                       view.imeCaretBlockOverride = true;
+               }
+
+               EnsureCaretVisible();
+               SetCandidateWindowPos();
+               ShowCaretAtCurrentPosition();
+       } catch (...) {
+               errorStatus = SC_STATUS_FAILURE;
+       }
+}
+
+void ScintillaGTK::PreeditChangedWindowedThis() {
+       try {
+               PreEditString pes(im_context);
+               if (strlen(pes.str) > 0) {
+                       PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), pes.str);
+                       pango_layout_set_attributes(layout, pes.attrs);
 
                        gint w, h;
                        pango_layout_get_pixel_size(layout, &w, &h);
@@ -2306,15 +2431,17 @@ void ScintillaGTK::PreeditChangedThis() {
                } else {
                        gtk_widget_hide(PWidget(wPreedit));
                }
-               g_free(str);
-               pango_attr_list_unref(attrs);
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
        }
 }
 
 void ScintillaGTK::PreeditChanged(GtkIMContext *, ScintillaGTK *sciThis) {
-       sciThis->PreeditChangedThis();
+       if ((sciThis->imeInteraction == imeInline) || (sciThis->KoreanIME())) {
+               sciThis->PreeditChangedInlineThis();
+       } else {
+               sciThis->PreeditChangedWindowedThis();
+       }
 }
 
 void ScintillaGTK::StyleSetText(GtkWidget *widget, GtkStyle *, void*) {
@@ -2324,7 +2451,9 @@ void ScintillaGTK::StyleSetText(GtkWidget *widget, GtkStyle *, void*) {
 void ScintillaGTK::RealizeText(GtkWidget *widget, void*) {
        // Set NULL background to avoid automatic clearing so Scintilla responsible for all drawing
        if (WindowFromWidget(widget)) {
-#if GTK_CHECK_VERSION(3,0,0)
+#if GTK_CHECK_VERSION(3,22,0)
+               // Appears unnecessary
+#elif GTK_CHECK_VERSION(3,0,0)
                gdk_window_set_background_pattern(WindowFromWidget(widget), NULL);
 #else
                gdk_window_set_back_pixmap(WindowFromWidget(widget), NULL, FALSE);
@@ -2332,18 +2461,43 @@ void ScintillaGTK::RealizeText(GtkWidget *widget, void*) {
        }
 }
 
-void ScintillaGTK::Destroy(GObject *object) {
+static GObjectClass *scintilla_class_parent_class;
+
+void ScintillaGTK::Dispose(GObject *object) {
        try {
                ScintillaObject *scio = reinterpret_cast<ScintillaObject *>(object);
+               ScintillaGTK *sciThis = reinterpret_cast<ScintillaGTK *>(scio->pscin);
+
+               if (PWidget(sciThis->scrollbarv)) {
+                       gtk_widget_unparent(PWidget(sciThis->scrollbarv));
+                       sciThis->scrollbarv = NULL;
+               }
+
+               if (PWidget(sciThis->scrollbarh)) {
+                       gtk_widget_unparent(PWidget(sciThis->scrollbarh));
+                       sciThis->scrollbarh = NULL;
+               }
+
+               scintilla_class_parent_class->dispose(object);
+       } catch (...) {
+               // Its dying so nowhere to save the status
+       }
+}
+
+void ScintillaGTK::Destroy(GObject *object) {
+       try {
+               ScintillaObject *scio = SCINTILLA(object);
+
                // This avoids a double destruction
                if (!scio->pscin)
                        return;
-               ScintillaGTK *sciThis = reinterpret_cast<ScintillaGTK *>(scio->pscin);
+               ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(scio->pscin);
                //Platform::DebugPrintf("Destroying %x %x\n", sciThis, object);
                sciThis->Finalise();
 
                delete sciThis;
                scio->pscin = 0;
+               scintilla_class_parent_class->finalize(object);
        } catch (...) {
                // Its dead so nowhere to save the status
        }
@@ -2354,6 +2508,7 @@ void ScintillaGTK::Destroy(GObject *object) {
 gboolean ScintillaGTK::DrawTextThis(cairo_t *cr) {
        try {
                paintState = painting;
+               repaintFullWindow = false;
 
                rcPaint = GetClientRectangle();
 
@@ -2374,18 +2529,16 @@ gboolean ScintillaGTK::DrawTextThis(cairo_t *cr) {
                rcPaint.bottom = y2;
                PRectangle rcClient = GetClientRectangle();
                paintingAllText = rcPaint.Contains(rcClient);
-               Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
-               if (surfaceWindow) {
-                       surfaceWindow->Init(cr, PWidget(wText));
-                       Paint(surfaceWindow, rcPaint);
-                       surfaceWindow->Release();
-                       delete surfaceWindow;
-               }
-               if (paintState == paintAbandoned) {
+               std::unique_ptr<Surface> surfaceWindow(Surface::Allocate(SC_TECHNOLOGY_DEFAULT));
+               surfaceWindow->Init(cr, PWidget(wText));
+               Paint(surfaceWindow.get(), rcPaint);
+               surfaceWindow->Release();
+               if ((paintState == paintAbandoned) || repaintFullWindow) {
                        // Painting area was insufficient to cover new styling or brace highlight positions
                        FullPaint();
                }
                paintState = notPainting;
+               repaintFullWindow = false;
 
                if (rgnUpdate) {
                        cairo_rectangle_list_destroy(rgnUpdate);
@@ -2405,10 +2558,38 @@ gboolean ScintillaGTK::DrawText(GtkWidget *, cairo_t *cr, ScintillaGTK *sciThis)
 
 gboolean ScintillaGTK::DrawThis(cairo_t *cr) {
        try {
+#ifdef GTK_STYLE_CLASS_SCROLLBARS_JUNCTION /* GTK >= 3.4 */
+               // if both scrollbars are visible, paint the little square on the bottom right corner
+               if (verticalScrollBarVisible && horizontalScrollBarVisible && !Wrapping()) {
+                       GtkStyleContext *styleContext = gtk_widget_get_style_context(PWidget(wMain));
+                       PRectangle rc = GetClientRectangle();
+
+                       gtk_style_context_save(styleContext);
+                       gtk_style_context_add_class(styleContext, GTK_STYLE_CLASS_SCROLLBARS_JUNCTION);
+
+                       gtk_render_background(styleContext, cr, rc.right, rc.bottom,
+                                       verticalScrollBarWidth, horizontalScrollBarHeight);
+                       gtk_render_frame(styleContext, cr, rc.right, rc.bottom,
+                                       verticalScrollBarWidth, horizontalScrollBarHeight);
+
+                       gtk_style_context_restore(styleContext);
+               }
+#endif
+
                gtk_container_propagate_draw(
                    GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), cr);
                gtk_container_propagate_draw(
                    GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), cr);
+// Starting from the following version, the expose event are not propagated
+// for double buffered non native windows, so we need to call it ourselves
+// or keep the default handler
+#if GTK_CHECK_VERSION(3,0,0)
+               // we want to forward on any >= 3.9.2 runtime
+               if (gtk_check_version(3,9,2) == NULL) {
+                       gtk_container_propagate_draw(
+                                       GTK_CONTAINER(PWidget(wMain)), PWidget(wText), cr);
+               }
+#endif
        } catch (...) {
                errorStatus = SC_STATUS_FAILURE;
        }
@@ -2416,7 +2597,7 @@ gboolean ScintillaGTK::DrawThis(cairo_t *cr) {
 }
 
 gboolean ScintillaGTK::DrawMain(GtkWidget *widget, cairo_t *cr) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        return sciThis->DrawThis(cr);
 }
 
@@ -2435,15 +2616,12 @@ gboolean ScintillaGTK::ExposeTextThis(GtkWidget * /*widget*/, GdkEventExpose *os
                rgnUpdate = gdk_region_copy(ose->region);
                PRectangle rcClient = GetClientRectangle();
                paintingAllText = rcPaint.Contains(rcClient);
-               Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
-               if (surfaceWindow) {
-                       cairo_t *cr = gdk_cairo_create(PWindow(wText));
-                       surfaceWindow->Init(cr, PWidget(wText));
-                       Paint(surfaceWindow, rcPaint);
-                       surfaceWindow->Release();
-                       delete surfaceWindow;
-                       cairo_destroy(cr);
-               }
+               std::unique_ptr<Surface> surfaceWindow(Surface::Allocate(SC_TECHNOLOGY_DEFAULT));
+               cairo_t *cr = gdk_cairo_create(PWindow(wText));
+               surfaceWindow->Init(cr, PWidget(wText));
+               Paint(surfaceWindow.get(), rcPaint);
+               surfaceWindow->Release();
+               cairo_destroy(cr);
                if (paintState == paintAbandoned) {
                        // Painting area was insufficient to cover new styling or brace highlight positions
                        FullPaint();
@@ -2466,7 +2644,7 @@ gboolean ScintillaGTK::ExposeText(GtkWidget *widget, GdkEventExpose *ose, Scinti
 }
 
 gboolean ScintillaGTK::ExposeMain(GtkWidget *widget, GdkEventExpose *ose) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        //Platform::DebugPrintf("Expose Main %0d,%0d %0d,%0d\n",
        //ose->area.x, ose->area.y, ose->area.width, ose->area.height);
        return sciThis->Expose(widget, ose);
@@ -2493,11 +2671,7 @@ gboolean ScintillaGTK::Expose(GtkWidget *, GdkEventExpose *ose) {
 
 void ScintillaGTK::ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
        try {
-#if GTK_CHECK_VERSION(3,0,0)
                sciThis->ScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)), false);
-#else
-               sciThis->ScrollTo(static_cast<int>(adj->value), false);
-#endif
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
        }
@@ -2505,11 +2679,7 @@ void ScintillaGTK::ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
 
 void ScintillaGTK::ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
        try {
-#if GTK_CHECK_VERSION(3,0,0)
-               sciThis->HorizontalScrollTo(static_cast<int>(gtk_adjustment_get_value(adj) * 2));
-#else
-               sciThis->HorizontalScrollTo(static_cast<int>(adj->value * 2));
-#endif
+               sciThis->HorizontalScrollTo(static_cast<int>(gtk_adjustment_get_value(adj)));
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
        }
@@ -2517,14 +2687,14 @@ void ScintillaGTK::ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) {
 
 void ScintillaGTK::SelectionReceived(GtkWidget *widget,
                                      GtkSelectionData *selection_data, guint) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        //Platform::DebugPrintf("Selection received\n");
        sciThis->ReceivedSelection(selection_data);
 }
 
 void ScintillaGTK::SelectionGet(GtkWidget *widget,
                                 GtkSelectionData *selection_data, guint info, guint) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                //Platform::DebugPrintf("Selection get\n");
                if (SelectionOfGSD(selection_data) == GDK_SELECTION_PRIMARY) {
@@ -2539,7 +2709,7 @@ void ScintillaGTK::SelectionGet(GtkWidget *widget,
 }
 
 gint ScintillaGTK::SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        //Platform::DebugPrintf("Selection clear\n");
        sciThis->UnclaimSelection(selection_event);
        if (GTK_WIDGET_CLASS(sciThis->parentClass)->selection_clear_event) {
@@ -2553,7 +2723,7 @@ gboolean ScintillaGTK::DragMotionThis(GdkDragContext *context,
        try {
                Point npt(x, y);
                SetDragPosition(SPositionFromLocation(npt, false, false, UserVirtualSpace()));
-#if GTK_CHECK_VERSION(3,0,0)
+#if GTK_CHECK_VERSION(2,22,0)
                GdkDragAction preferredAction = gdk_drag_context_get_suggested_action(context);
                GdkDragAction actions = gdk_drag_context_get_actions(context);
 #else
@@ -2578,14 +2748,14 @@ gboolean ScintillaGTK::DragMotionThis(GdkDragContext *context,
 
 gboolean ScintillaGTK::DragMotion(GtkWidget *widget, GdkDragContext *context,
                                  gint x, gint y, guint dragtime) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        return sciThis->DragMotionThis(context, x, y, dragtime);
 }
 
 void ScintillaGTK::DragLeave(GtkWidget *widget, GdkDragContext * /*context*/, guint) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
-               sciThis->SetDragPosition(SelectionPosition(invalidPosition));
+               sciThis->SetDragPosition(SelectionPosition(Sci::invalidPosition));
                //Platform::DebugPrintf("DragLeave %x\n", sciThis);
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
@@ -2593,12 +2763,12 @@ void ScintillaGTK::DragLeave(GtkWidget *widget, GdkDragContext * /*context*/, gu
 }
 
 void ScintillaGTK::DragEnd(GtkWidget *widget, GdkDragContext * /*context*/) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                // If drag did not result in drop here or elsewhere
                if (!sciThis->dragWasDropped)
                        sciThis->SetEmptySelection(sciThis->posDrag);
-               sciThis->SetDragPosition(SelectionPosition(invalidPosition));
+               sciThis->SetDragPosition(SelectionPosition(Sci::invalidPosition));
                //Platform::DebugPrintf("DragEnd %x %d\n", sciThis, sciThis->dragWasDropped);
                sciThis->inDragDrop = ddNone;
        } catch (...) {
@@ -2608,10 +2778,10 @@ void ScintillaGTK::DragEnd(GtkWidget *widget, GdkDragContext * /*context*/) {
 
 gboolean ScintillaGTK::Drop(GtkWidget *widget, GdkDragContext * /*context*/,
                             gint, gint, guint) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                //Platform::DebugPrintf("Drop %x\n", sciThis);
-               sciThis->SetDragPosition(SelectionPosition(invalidPosition));
+               sciThis->SetDragPosition(SelectionPosition(Sci::invalidPosition));
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
        }
@@ -2620,10 +2790,10 @@ gboolean ScintillaGTK::Drop(GtkWidget *widget, GdkDragContext * /*context*/,
 
 void ScintillaGTK::DragDataReceived(GtkWidget *widget, GdkDragContext * /*context*/,
                                     gint, gint, GtkSelectionData *selection_data, guint /*info*/, guint) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                sciThis->ReceivedDrop(selection_data);
-               sciThis->SetDragPosition(SelectionPosition(invalidPosition));
+               sciThis->SetDragPosition(SelectionPosition(Sci::invalidPosition));
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
        }
@@ -2631,13 +2801,13 @@ void ScintillaGTK::DragDataReceived(GtkWidget *widget, GdkDragContext * /*contex
 
 void ScintillaGTK::DragDataGet(GtkWidget *widget, GdkDragContext *context,
                                GtkSelectionData *selection_data, guint info, guint) {
-       ScintillaGTK *sciThis = ScintillaFromWidget(widget);
+       ScintillaGTK *sciThis = FromWidget(widget);
        try {
                sciThis->dragWasDropped = true;
                if (!sciThis->sel.Empty()) {
                        sciThis->GetSelection(selection_data, info, &sciThis->drag);
                }
-#if GTK_CHECK_VERSION(3,0,0)
+#if GTK_CHECK_VERSION(2,22,0)
                GdkDragAction action = gdk_drag_context_get_selected_action(context);
 #else
                GdkDragAction action = context->action;
@@ -2654,23 +2824,22 @@ void ScintillaGTK::DragDataGet(GtkWidget *widget, GdkDragContext *context,
                        }
                        sciThis->ClearSelection();
                }
-               sciThis->SetDragPosition(SelectionPosition(invalidPosition));
+               sciThis->SetDragPosition(SelectionPosition(Sci::invalidPosition));
        } catch (...) {
                sciThis->errorStatus = SC_STATUS_FAILURE;
        }
 }
 
-int ScintillaGTK::TimeOut(ScintillaGTK *sciThis) {
-       sciThis->Tick();
+int ScintillaGTK::TimeOut(gpointer ptt) {
+       TimeThunk *tt = static_cast<TimeThunk *>(ptt);
+       tt->scintilla->TickFor(tt->reason);
        return 1;
 }
 
-gboolean ScintillaGTK::IdleCallback(ScintillaGTK *sciThis) {
+gboolean ScintillaGTK::IdleCallback(gpointer pSci) {
+       ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(pSci);
        // Idler will be automatically stopped, if there is nothing
        // to do while idle.
-#ifndef GDK_VERSION_3_6
-       gdk_threads_enter();
-#endif
        bool ret = sciThis->Idle();
        if (ret == false) {
                // FIXME: This will remove the idler from GTK, we don't want to
@@ -2678,36 +2847,53 @@ gboolean ScintillaGTK::IdleCallback(ScintillaGTK *sciThis) {
                // returns false (although, it should be harmless).
                sciThis->SetIdle(false);
        }
-#ifndef GDK_VERSION_3_6
-       gdk_threads_leave();
-#endif
        return ret;
 }
 
-gboolean ScintillaGTK::StyleIdle(ScintillaGTK *sciThis) {
-#ifndef GDK_VERSION_3_6
-       gdk_threads_enter();
-#endif
+gboolean ScintillaGTK::StyleIdle(gpointer pSci) {
+       ScintillaGTK *sciThis = static_cast<ScintillaGTK *>(pSci);
        sciThis->IdleWork();
-#ifndef GDK_VERSION_3_6
-       gdk_threads_leave();
-#endif
        // Idler will be automatically stopped
        return FALSE;
 }
 
-void ScintillaGTK::QueueIdleWork(WorkNeeded::workItems items, int upTo) {
+void ScintillaGTK::IdleWork() {
+       Editor::IdleWork();
+       styleIdleID = 0;
+}
+
+void ScintillaGTK::QueueIdleWork(WorkNeeded::workItems items, Sci::Position upTo) {
        Editor::QueueIdleWork(items, upTo);
-       if (!workNeeded.active) {
+       if (!styleIdleID) {
                // Only allow one style needed to be queued
-               workNeeded.active = true;
-               g_idle_add_full(G_PRIORITY_HIGH_IDLE,
-                       reinterpret_cast<GSourceFunc>(StyleIdle), this, NULL);
+               styleIdleID = gdk_threads_add_idle_full(G_PRIORITY_HIGH_IDLE, StyleIdle, this, NULL);
+       }
+}
+
+void ScintillaGTK::SetDocPointer(Document *document) {
+       Document *oldDoc = 0;
+       ScintillaGTKAccessible *sciAccessible = 0;
+       if (accessible) {
+               sciAccessible = ScintillaGTKAccessible::FromAccessible(accessible);
+               if (sciAccessible && pdoc) {
+                       oldDoc = pdoc;
+                       oldDoc->AddRef();
+               }
+       }
+
+       Editor::SetDocPointer(document);
+
+       if (sciAccessible) {
+               // the accessible needs have the old Document, but also the new one active
+               sciAccessible->ChangeDocument(oldDoc, pdoc);
+       }
+       if (oldDoc) {
+               oldDoc->Release();
        }
 }
 
 void ScintillaGTK::PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis) {
-       guint action = (sptr_t)(g_object_get_data(G_OBJECT(menuItem), "CmdNum"));
+       guint action = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(menuItem), "CmdNum"));
        if (action) {
                sciThis->Command(action);
        }
@@ -2733,15 +2919,12 @@ gboolean ScintillaGTK::PressCT(GtkWidget *widget, GdkEventButton *event, Scintil
 
 gboolean ScintillaGTK::DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip) {
        try {
-               Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
-               if (surfaceWindow) {
-                       surfaceWindow->Init(cr, widget);
-                       surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
-                       surfaceWindow->SetDBCSMode(ctip->codePage);
-                       ctip->PaintCT(surfaceWindow);
-                       surfaceWindow->Release();
-                       delete surfaceWindow;
-               }
+               std::unique_ptr<Surface> surfaceWindow(Surface::Allocate(SC_TECHNOLOGY_DEFAULT));
+               surfaceWindow->Init(cr, widget);
+               surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
+               surfaceWindow->SetDBCSMode(ctip->codePage);
+               ctip->PaintCT(surfaceWindow.get());
+               surfaceWindow->Release();
        } catch (...) {
                // No pointer back to Scintilla to save status
        }
@@ -2752,17 +2935,14 @@ gboolean ScintillaGTK::DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip) {
 
 gboolean ScintillaGTK::ExposeCT(GtkWidget *widget, GdkEventExpose * /*ose*/, CallTip *ctip) {
        try {
-               Surface *surfaceWindow = Surface::Allocate(SC_TECHNOLOGY_DEFAULT);
-               if (surfaceWindow) {
-                       cairo_t *cr = gdk_cairo_create(WindowFromWidget(widget));
-                       surfaceWindow->Init(cr, widget);
-                       surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
-                       surfaceWindow->SetDBCSMode(ctip->codePage);
-                       ctip->PaintCT(surfaceWindow);
-                       surfaceWindow->Release();
-                       delete surfaceWindow;
-                       cairo_destroy(cr);
-               }
+               std::unique_ptr<Surface> surfaceWindow(Surface::Allocate(SC_TECHNOLOGY_DEFAULT));
+               cairo_t *cr = gdk_cairo_create(WindowFromWidget(widget));
+               surfaceWindow->Init(cr, widget);
+               surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == ctip->codePage);
+               surfaceWindow->SetDBCSMode(ctip->codePage);
+               ctip->PaintCT(surfaceWindow.get());
+               surfaceWindow->Release();
+               cairo_destroy(cr);
        } catch (...) {
                // No pointer back to Scintilla to save status
        }
@@ -2771,31 +2951,45 @@ gboolean ScintillaGTK::ExposeCT(GtkWidget *widget, GdkEventExpose * /*ose*/, Cal
 
 #endif
 
+AtkObject* ScintillaGTK::GetAccessibleThis(GtkWidget *widget) {
+       return ScintillaGTKAccessible::WidgetGetAccessibleImpl(widget, &accessible, 
scintilla_class_parent_class);
+}
+
+AtkObject* ScintillaGTK::GetAccessible(GtkWidget *widget) {
+       return FromWidget(widget)->GetAccessibleThis(widget);
+}
+
 sptr_t ScintillaGTK::DirectFunction(
-    ScintillaGTK *sciThis, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
-       return sciThis->WndProc(iMessage, wParam, lParam);
+    sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
+       return reinterpret_cast<ScintillaGTK *>(ptr)->WndProc(iMessage, wParam, lParam);
 }
 
+/* legacy name for scintilla_object_send_message */
 sptr_t scintilla_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
-       ScintillaGTK *psci = reinterpret_cast<ScintillaGTK *>(sci->pscin);
+       ScintillaGTK *psci = static_cast<ScintillaGTK *>(sci->pscin);
        return psci->WndProc(iMessage, wParam, lParam);
 }
 
+gintptr scintilla_object_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t 
lParam) {
+       return scintilla_send_message(sci, iMessage, wParam, lParam);
+}
+
 static void scintilla_class_init(ScintillaClass *klass);
 static void scintilla_init(ScintillaObject *sci);
 
 extern void Platform_Initialise();
 extern void Platform_Finalise();
 
+/* legacy name for scintilla_object_get_type */
 GType scintilla_get_type() {
        static GType scintilla_type = 0;
        try {
 
                if (!scintilla_type) {
-                       scintilla_type = g_type_from_name("Scintilla");
+                       scintilla_type = g_type_from_name("ScintillaObject");
                        if (!scintilla_type) {
                                static GTypeInfo scintilla_info = {
-                                       (guint16) sizeof (ScintillaClass),
+                                       (guint16) sizeof (ScintillaObjectClass),
                                        NULL, //(GBaseInitFunc)
                                        NULL, //(GBaseFinalizeFunc)
                                        (GClassInitFunc) scintilla_class_init,
@@ -2806,9 +3000,8 @@ GType scintilla_get_type() {
                                        (GInstanceInitFunc) scintilla_init,
                                        NULL //(GTypeValueTable*)
                                };
-
                                scintilla_type = g_type_register_static(
-                                           GTK_TYPE_CONTAINER, "Scintilla", &scintilla_info, (GTypeFlags) 0);
+                                           GTK_TYPE_CONTAINER, "ScintillaObject", &scintilla_info, 
(GTypeFlags) 0);
                        }
                }
 
@@ -2817,6 +3010,10 @@ GType scintilla_get_type() {
        return scintilla_type;
 }
 
+GType scintilla_object_get_type() {
+       return scintilla_get_type();
+}
+
 void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass 
*container_class) {
        Platform_Initialise();
 #ifdef SCI_LEXER
@@ -2830,8 +3027,9 @@ void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_
 
        // Define default signal handlers for the class:  Could move more
        // of the signal handlers here (those that currently attached to wDraw
-       // in Initialise() may require coordinate translation?)
+       // in Init() may require coordinate translation?)
 
+       object_class->dispose = Dispose;
        object_class->finalize = Destroy;
 #if GTK_CHECK_VERSION(3,0,0)
        widget_class->get_preferred_width = GetPreferredWidth;
@@ -2869,12 +3067,11 @@ void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_
        widget_class->map = Map;
        widget_class->unmap = UnMap;
 
+       widget_class->get_accessible = GetAccessible;
+
        container_class->forall = MainForAll;
 }
 
-#define SIG_MARSHAL scintilla_marshal_NONE__INT_POINTER
-#define MARSHAL_ARGUMENTS G_TYPE_INT, G_TYPE_POINTER
-
 static void scintilla_class_init(ScintillaClass *klass) {
        try {
                OBJECT_CLASS *object_class = (OBJECT_CLASS*) klass;
@@ -2889,24 +3086,24 @@ static void scintilla_class_init(ScintillaClass *klass) {
                            G_STRUCT_OFFSET(ScintillaClass, command),
                            NULL, //(GSignalAccumulator)
                            NULL, //(gpointer)
-                           SIG_MARSHAL,
+                           scintilla_marshal_VOID__INT_OBJECT,
                            G_TYPE_NONE,
-                           2, MARSHAL_ARGUMENTS);
+                           2, G_TYPE_INT, GTK_TYPE_WIDGET);
 
                scintilla_signals[NOTIFY_SIGNAL] = g_signal_new(
                            SCINTILLA_NOTIFY,
                            G_TYPE_FROM_CLASS(object_class),
                            sigflags,
                            G_STRUCT_OFFSET(ScintillaClass, notify),
-                           NULL,
-                           NULL,
-                           SIG_MARSHAL,
+                           NULL, //(GSignalAccumulator)
+                           NULL, //(gpointer)
+                           scintilla_marshal_VOID__INT_BOXED,
                            G_TYPE_NONE,
-                           2, MARSHAL_ARGUMENTS);
+                           2, G_TYPE_INT, SCINTILLA_TYPE_NOTIFICATION);
 
                klass->command = NULL;
                klass->notify = NULL;
-
+               scintilla_class_parent_class = G_OBJECT_CLASS(g_type_class_peek_parent(klass));
                ScintillaGTK::ClassInit(object_class, widget_class, container_class);
        } catch (...) {
        }
@@ -2914,16 +3111,13 @@ static void scintilla_class_init(ScintillaClass *klass) {
 
 static void scintilla_init(ScintillaObject *sci) {
        try {
-#if GTK_CHECK_VERSION(2,20,0)
                gtk_widget_set_can_focus(GTK_WIDGET(sci), TRUE);
-#else
-               GTK_WIDGET_SET_FLAGS(sci, GTK_CAN_FOCUS);
-#endif
                sci->pscin = new ScintillaGTK(sci);
        } catch (...) {
        }
 }
 
+/* legacy name for scintilla_object_new */
 GtkWidget* scintilla_new() {
        GtkWidget *widget = GTK_WIDGET(g_object_new(scintilla_get_type(), NULL));
        gtk_widget_set_direction(widget, GTK_TEXT_DIR_LTR);
@@ -2931,8 +3125,12 @@ GtkWidget* scintilla_new() {
        return widget;
 }
 
+GtkWidget *scintilla_object_new() {
+       return scintilla_new();
+}
+
 void scintilla_set_id(ScintillaObject *sci, uptr_t id) {
-       ScintillaGTK *psci = reinterpret_cast<ScintillaGTK *>(sci->pscin);
+       ScintillaGTK *psci = static_cast<ScintillaGTK *>(sci->pscin);
        psci->ctrlID = id;
 }
 
@@ -2942,3 +3140,21 @@ void scintilla_release_resources(void) {
        } catch (...) {
        }
 }
+
+/* Define a dummy boxed type because g-ir-scanner is unable to
+ * recognize gpointer-derived types. Note that SCNotificaiton
+ * is always allocated on stack so copying is not appropriate. */
+static void *copy_(void *src) { return src; }
+static void free_(void *) { }
+
+GType scnotification_get_type(void) {
+       static gsize type_id = 0;
+       if (g_once_init_enter(&type_id)) {
+               gsize id = (gsize) g_boxed_type_register_static(
+                                           g_intern_static_string("SCNotification"),
+                                           (GBoxedCopyFunc) copy_,
+                                           (GBoxedFreeFunc) free_);
+               g_once_init_leave(&type_id, id);
+       }
+       return (GType) type_id;
+}
diff --git a/plugins/scintilla/scintilla/gtk/ScintillaGTK.h b/plugins/scintilla/scintilla/gtk/ScintillaGTK.h
new file mode 100644
index 0000000..a20f3bc
--- /dev/null
+++ b/plugins/scintilla/scintilla/gtk/ScintillaGTK.h
@@ -0,0 +1,289 @@
+// Scintilla source code edit control
+// ScintillaGTK.h - GTK+ specific subclass of ScintillaBase
+// Copyright 1998-2004 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef SCINTILLAGTK_H
+#define SCINTILLAGTK_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+class ScintillaGTKAccessible;
+
+#define OBJECT_CLASS GObjectClass
+
+class ScintillaGTK : public ScintillaBase {
+       friend class ScintillaGTKAccessible;
+
+       _ScintillaObject *sci;
+       Window wText;
+       Window scrollbarv;
+       Window scrollbarh;
+       GtkAdjustment *adjustmentv;
+       GtkAdjustment *adjustmenth;
+       int verticalScrollBarWidth;
+       int horizontalScrollBarHeight;
+
+       SelectionText primary;
+
+       GdkEventButton *evbtn;
+       bool capturedMouse;
+       bool dragWasDropped;
+       int lastKey;
+       int rectangularSelectionModifier;
+
+       GtkWidgetClass *parentClass;
+
+       static GdkAtom atomClipboard;
+       static GdkAtom atomUTF8;
+       static GdkAtom atomString;
+       static GdkAtom atomUriList;
+       static GdkAtom atomDROPFILES_DND;
+       GdkAtom atomSought;
+
+#if PLAT_GTK_WIN32
+       CLIPFORMAT cfColumnSelect;
+#endif
+
+       Window wPreedit;
+       Window wPreeditDraw;
+       GtkIMContext *im_context;
+       PangoScript lastNonCommonScript;
+
+       // Wheel mouse support
+       unsigned int linesPerScroll;
+       GTimeVal lastWheelMouseTime;
+       gint lastWheelMouseDirection;
+       gint wheelMouseIntensity;
+       gdouble smoothScrollY;
+       gdouble smoothScrollX;
+
+#if GTK_CHECK_VERSION(3,0,0)
+       cairo_rectangle_list_t *rgnUpdate;
+#else
+       GdkRegion *rgnUpdate;
+#endif
+       bool repaintFullWindow;
+
+       guint styleIdleID;
+       int accessibilityEnabled;
+       AtkObject *accessible;
+
+public:
+       explicit ScintillaGTK(_ScintillaObject *sci_);
+       // Deleted so ScintillaGTK objects can not be copied.
+       ScintillaGTK(const ScintillaGTK &) = delete;
+       ScintillaGTK &operator=(const ScintillaGTK &) = delete;
+       virtual ~ScintillaGTK();
+       static ScintillaGTK *FromWidget(GtkWidget *widget);
+       static void ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass 
*container_class);
+private:
+       void Init();
+       void Finalise() override;
+       bool AbandonPaint() override;
+       void DisplayCursor(Window::Cursor c) override;
+       bool DragThreshold(Point ptStart, Point ptNow) override;
+       void StartDrag() override;
+       int TargetAsUTF8(char *text);
+       int EncodedFromUTF8(char *utf8, char *encoded) const;
+       bool ValidCodePage(int codePage) const override;
+public:        // Public for scintilla_send_message
+       sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) override;
+private:
+       sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) override;
+       struct TimeThunk {
+               TickReason reason;
+               ScintillaGTK *scintilla;
+               guint timer;
+               TimeThunk() : reason(tickCaret), scintilla(NULL), timer(0) {}
+       };
+       TimeThunk timers[tickDwell+1];
+       bool FineTickerAvailable() override;
+       bool FineTickerRunning(TickReason reason) override;
+       void FineTickerStart(TickReason reason, int millis, int tolerance) override;
+       void FineTickerCancel(TickReason reason) override;
+       bool SetIdle(bool on) override;
+       void SetMouseCapture(bool on) override;
+       bool HaveMouseCapture() override;
+       bool PaintContains(PRectangle rc) override;
+       void FullPaint();
+       PRectangle GetClientRectangle() const override;
+       void ScrollText(Sci::Line linesToMove) override;
+       void SetVerticalScrollPos() override;
+       void SetHorizontalScrollPos() override;
+       bool ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) override;
+       void ReconfigureScrollBars() override;
+       void NotifyChange() override;
+       void NotifyFocus(bool focus) override;
+       void NotifyParent(SCNotification scn) override;
+       void NotifyKey(int key, int modifiers);
+       void NotifyURIDropped(const char *list);
+       const char *CharacterSetID() const;
+       CaseFolder *CaseFolderForEncoding() override;
+       std::string CaseMapString(const std::string &s, int caseMapping) override;
+       int KeyDefault(int key, int modifiers) override;
+       void CopyToClipboard(const SelectionText &selectedText) override;
+       void Copy() override;
+       void Paste() override;
+       void CreateCallTipWindow(PRectangle rc) override;
+       void AddToPopUp(const char *label, int cmd = 0, bool enabled = true) override;
+       bool OwnPrimarySelection();
+       void ClaimSelection() override;
+       void GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText);
+       void ReceivedSelection(GtkSelectionData *selection_data);
+       void ReceivedDrop(GtkSelectionData *selection_data);
+       static void GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *text);
+       void StoreOnClipboard(SelectionText *clipText);
+       static void ClipboardGetSelection(GtkClipboard* clip, GtkSelectionData *selection_data, guint info, 
void *data);
+       static void ClipboardClearSelection(GtkClipboard* clip, void *data);
+
+       void UnclaimSelection(GdkEventSelection *selection_event);
+       void Resize(int width, int height);
+
+       // Callback functions
+       void RealizeThis(GtkWidget *widget);
+       static void Realize(GtkWidget *widget);
+       void UnRealizeThis(GtkWidget *widget);
+       static void UnRealize(GtkWidget *widget);
+       void MapThis();
+       static void Map(GtkWidget *widget);
+       void UnMapThis();
+       static void UnMap(GtkWidget *widget);
+       gint FocusInThis(GtkWidget *widget);
+       static gint FocusIn(GtkWidget *widget, GdkEventFocus *event);
+       gint FocusOutThis(GtkWidget *widget);
+       static gint FocusOut(GtkWidget *widget, GdkEventFocus *event);
+       static void SizeRequest(GtkWidget *widget, GtkRequisition *requisition);
+#if GTK_CHECK_VERSION(3,0,0)
+       static void GetPreferredWidth(GtkWidget *widget, gint *minimalWidth, gint *naturalWidth);
+       static void GetPreferredHeight(GtkWidget *widget, gint *minimalHeight, gint *naturalHeight);
+#endif
+       static void SizeAllocate(GtkWidget *widget, GtkAllocation *allocation);
+#if GTK_CHECK_VERSION(3,0,0)
+       gboolean DrawTextThis(cairo_t *cr);
+       static gboolean DrawText(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
+       gboolean DrawThis(cairo_t *cr);
+       static gboolean DrawMain(GtkWidget *widget, cairo_t *cr);
+#else
+       gboolean ExposeTextThis(GtkWidget *widget, GdkEventExpose *ose);
+       static gboolean ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
+       gboolean Expose(GtkWidget *widget, GdkEventExpose *ose);
+       static gboolean ExposeMain(GtkWidget *widget, GdkEventExpose *ose);
+#endif
+       void ForAll(GtkCallback callback, gpointer callback_data);
+       static void MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, 
gpointer callback_data);
+
+       static void ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
+       static void ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis);
+       gint PressThis(GdkEventButton *event);
+       static gint Press(GtkWidget *widget, GdkEventButton *event);
+       static gint MouseRelease(GtkWidget *widget, GdkEventButton *event);
+       static gint ScrollEvent(GtkWidget *widget, GdkEventScroll *event);
+       static gint Motion(GtkWidget *widget, GdkEventMotion *event);
+       gboolean KeyThis(GdkEventKey *event);
+       static gboolean KeyPress(GtkWidget *widget, GdkEventKey *event);
+       static gboolean KeyRelease(GtkWidget *widget, GdkEventKey *event);
+#if GTK_CHECK_VERSION(3,0,0)
+       gboolean DrawPreeditThis(GtkWidget *widget, cairo_t *cr);
+       static gboolean DrawPreedit(GtkWidget *widget, cairo_t *cr, ScintillaGTK *sciThis);
+#else
+       gboolean ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose);
+       static gboolean ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis);
+#endif
+       AtkObject* GetAccessibleThis(GtkWidget *widget);
+       static AtkObject* GetAccessible(GtkWidget *widget);
+
+       bool KoreanIME();
+       void CommitThis(char *commitStr);
+       static void Commit(GtkIMContext *context, char *str, ScintillaGTK *sciThis);
+       void PreeditChangedInlineThis();
+       void PreeditChangedWindowedThis();
+       static void PreeditChanged(GtkIMContext *context, ScintillaGTK *sciThis);
+       void MoveImeCarets(int pos);
+       void DrawImeIndicator(int indicator, int len);
+       void SetCandidateWindowPos();
+
+       static void StyleSetText(GtkWidget *widget, GtkStyle *previous, void*);
+       static void RealizeText(GtkWidget *widget, void*);
+       static void Dispose(GObject *object);
+       static void Destroy(GObject *object);
+       static void SelectionReceived(GtkWidget *widget, GtkSelectionData *selection_data,
+                                     guint time);
+       static void SelectionGet(GtkWidget *widget, GtkSelectionData *selection_data,
+                                guint info, guint time);
+       static gint SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event);
+       gboolean DragMotionThis(GdkDragContext *context, gint x, gint y, guint dragtime);
+       static gboolean DragMotion(GtkWidget *widget, GdkDragContext *context,
+                                  gint x, gint y, guint dragtime);
+       static void DragLeave(GtkWidget *widget, GdkDragContext *context,
+                             guint time);
+       static void DragEnd(GtkWidget *widget, GdkDragContext *context);
+       static gboolean Drop(GtkWidget *widget, GdkDragContext *context,
+                            gint x, gint y, guint time);
+       static void DragDataReceived(GtkWidget *widget, GdkDragContext *context,
+                                    gint x, gint y, GtkSelectionData *selection_data, guint info, guint 
time);
+       static void DragDataGet(GtkWidget *widget, GdkDragContext *context,
+                               GtkSelectionData *selection_data, guint info, guint time);
+       static gboolean TimeOut(gpointer ptt);
+       static gboolean IdleCallback(gpointer pSci);
+       static gboolean StyleIdle(gpointer pSci);
+       void IdleWork() override;
+       void QueueIdleWork(WorkNeeded::workItems items, Sci::Position upTo) override;
+       void SetDocPointer(Document *document) override;
+       static void PopUpCB(GtkMenuItem *menuItem, ScintillaGTK *sciThis);
+
+#if GTK_CHECK_VERSION(3,0,0)
+       static gboolean DrawCT(GtkWidget *widget, cairo_t *cr, CallTip *ctip);
+#else
+       static gboolean ExposeCT(GtkWidget *widget, GdkEventExpose *ose, CallTip *ctip);
+#endif
+       static gboolean PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis);
+
+       static sptr_t DirectFunction(sptr_t ptr,
+                                    unsigned int iMessage, uptr_t wParam, sptr_t lParam);
+};
+
+// helper class to watch a GObject lifetime and get notified when it dies
+class GObjectWatcher {
+       GObject *weakRef;
+
+       void WeakNotifyThis(GObject *obj G_GNUC_UNUSED) {
+               PLATFORM_ASSERT(obj == weakRef);
+
+               Destroyed();
+               weakRef = 0;
+       }
+
+       static void WeakNotify(gpointer data, GObject *obj) {
+               static_cast<GObjectWatcher*>(data)->WeakNotifyThis(obj);
+       }
+
+public:
+       GObjectWatcher(GObject *obj) :
+                       weakRef(obj) {
+               g_object_weak_ref(weakRef, WeakNotify, this);
+       }
+
+       virtual ~GObjectWatcher() {
+               if (weakRef) {
+                       g_object_weak_unref(weakRef, WeakNotify, this);
+               }
+       }
+
+       virtual void Destroyed() {}
+
+       bool IsDestroyed() const {
+               return weakRef != 0;
+       }
+};
+
+std::string ConvertText(const char *s, size_t len, const char *charSetDest,
+                        const char *charSetSource, bool transliterations, bool silent=false);
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/gtk/ScintillaGTKAccessible.cxx 
b/plugins/scintilla/scintilla/gtk/ScintillaGTKAccessible.cxx
new file mode 100644
index 0000000..fdcc20d
--- /dev/null
+++ b/plugins/scintilla/scintilla/gtk/ScintillaGTKAccessible.cxx
@@ -0,0 +1,1263 @@
+/* Scintilla source code edit control */
+/* ScintillaGTKAccessible.c - GTK+ accessibility for ScintillaGTK */
+/* Copyright 2016 by Colomban Wendling <colomban geany org>
+ * The License.txt file describes the conditions under which this software may be distributed. */
+
+// REFERENCES BETWEEN THE DIFFERENT OBJECTS
+//
+// ScintillaGTKAccessible is the actual implementation, as a C++ class.
+// ScintillaObjectAccessible is the GObject derived from AtkObject that
+// implements the various ATK interfaces, through ScintillaGTKAccessible.
+// This follows the same pattern as ScintillaGTK and ScintillaObject.
+//
+// ScintillaGTK owns a strong reference to the ScintillaObjectAccessible, and
+// is both responsible for creating and destroying that object.
+//
+// ScintillaObjectAccessible owns a strong reference to ScintillaGTKAccessible,
+// and is responsible for creating and destroying that object.
+//
+// ScintillaGTKAccessible has weak references to both the ScintillaGTK and
+// the ScintillaObjectAccessible objects associated, but does not own any
+// strong references to those objects.
+//
+// The chain of ownership is as follows:
+// ScintillaGTK -> ScintillaObjectAccessible -> ScintillaGTKAccessible
+
+// DETAILS ON THE GOBJECT TYPE IMPLEMENTATION
+//
+// On GTK < 3.2, we need to use the AtkObjectFactory.  We need to query
+// the factory to see what type we should derive from, thus making use of
+// dynamic inheritance.  It's tricky, but it works so long as it's done
+// carefully enough.
+//
+// On GTK 3.2 through 3.6, we need to hack around because GTK stopped
+// registering its accessible types in the factory, so we can't query
+// them that way.  Unfortunately, the accessible types aren't exposed
+// yet (not until 3.8), so there's no proper way to know which type to
+// inherit from.  To work around this, we instantiate the parent's
+// AtkObject temporarily, and use it's type.  It means creating an extra
+// throwaway object and being able to pass the type information up to the
+// type registration code, but it's the only solution I could find.
+//
+// On GTK 3.8 onward, we use the proper exposed GtkContainerAccessible as
+// parent, and so a straightforward class.
+//
+// To hide and contain the complexity in type creation arising from the
+// hackish support for GTK 3.2 to 3.8, the actual implementation for the
+// widget's get_accessible() is located in the accessibility layer itself.
+
+// Initially based on GtkTextViewAccessible from GTK 3.20
+// Inspiration for the GTK < 3.2 part comes from Evince 2.24, thanks.
+
+// FIXME: optimize character/byte offset conversion (with a cache?)
+
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+
+#include <stdexcept>
+#include <new>
+#include <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+#include <memory>
+
+#include <glib.h>
+#include <gtk/gtk.h>
+
+// whether we have widget_set() and widget_unset()
+#define HAVE_WIDGET_SET_UNSET (GTK_CHECK_VERSION(3, 3, 6))
+// whether GTK accessibility is available through the ATK factory
+#define HAVE_GTK_FACTORY (! GTK_CHECK_VERSION(3, 1, 9))
+// whether we have gtk-a11y.h and the public GTK accessible types
+#define HAVE_GTK_A11Y_H (GTK_CHECK_VERSION(3, 7, 6))
+
+#if HAVE_GTK_A11Y_H
+# include <gtk/gtk-a11y.h>
+#endif
+
+#if defined(__WIN32__) || defined(_MSC_VER)
+#include <windows.h>
+#endif
+
+// ScintillaGTK.h and stuff it needs
+#include "Platform.h"
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "ScintillaWidget.h"
+#ifdef SCI_LEXER
+#include "SciLexer.h"
+#endif
+#include "StringCopy.h"
+#ifdef SCI_LEXER
+#include "LexerModule.h"
+#endif
+#include "Position.h"
+#include "UniqueString.h"
+#include "SplitVector.h"
+#include "Partitioning.h"
+#include "RunStyles.h"
+#include "ContractionState.h"
+#include "CellBuffer.h"
+#include "CallTip.h"
+#include "KeyMap.h"
+#include "Indicator.h"
+#include "XPM.h"
+#include "LineMarker.h"
+#include "Style.h"
+#include "ViewStyle.h"
+#include "CharClassify.h"
+#include "Decoration.h"
+#include "CaseFolder.h"
+#include "Document.h"
+#include "CaseConvert.h"
+#include "UniConversion.h"
+#include "UnicodeFromUTF8.h"
+#include "Selection.h"
+#include "PositionCache.h"
+#include "EditModel.h"
+#include "MarginView.h"
+#include "EditView.h"
+#include "Editor.h"
+#include "AutoComplete.h"
+#include "ScintillaBase.h"
+
+#include "ScintillaGTK.h"
+#include "ScintillaGTKAccessible.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+struct ScintillaObjectAccessiblePrivate {
+       ScintillaGTKAccessible *pscin;
+};
+
+typedef GtkAccessible ScintillaObjectAccessible;
+typedef GtkAccessibleClass ScintillaObjectAccessibleClass;
+
+#define SCINTILLA_OBJECT_ACCESSIBLE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), 
SCINTILLA_TYPE_OBJECT_ACCESSIBLE, ScintillaObjectAccessible))
+#define SCINTILLA_TYPE_OBJECT_ACCESSIBLE (scintilla_object_accessible_get_type(0))
+
+// We can't use priv member because of dynamic inheritance, so we don't actually know the offset.  Meh.
+#define SCINTILLA_OBJECT_ACCESSIBLE_GET_PRIVATE(inst) (G_TYPE_INSTANCE_GET_PRIVATE((inst), 
SCINTILLA_TYPE_OBJECT_ACCESSIBLE, ScintillaObjectAccessiblePrivate))
+
+static GType scintilla_object_accessible_get_type(GType parent_type);
+
+ScintillaGTKAccessible *ScintillaGTKAccessible::FromAccessible(GtkAccessible *accessible) {
+       // FIXME: do we need the check below?  GTK checks that in all methods, so maybe
+       GtkWidget *widget = gtk_accessible_get_widget(accessible);
+       if (! widget) {
+               return 0;
+       }
+
+       return SCINTILLA_OBJECT_ACCESSIBLE_GET_PRIVATE(accessible)->pscin;
+}
+
+ScintillaGTKAccessible::ScintillaGTKAccessible(GtkAccessible *accessible_, GtkWidget *widget_) :
+               accessible(accessible_),
+               sci(ScintillaGTK::FromWidget(widget_)),
+               deletionLengthChar(0),
+               old_pos(-1) {
+       g_signal_connect(widget_, "sci-notify", G_CALLBACK(SciNotify), this);
+}
+
+ScintillaGTKAccessible::~ScintillaGTKAccessible() {
+       if (gtk_accessible_get_widget(accessible)) {
+               g_signal_handlers_disconnect_matched(sci->sci, G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, this);
+       }
+}
+
+gchar *ScintillaGTKAccessible::GetTextRangeUTF8(Sci::Position startByte, Sci::Position endByte) {
+       g_return_val_if_fail(startByte >= 0, NULL);
+       // FIXME: should we swap start/end if necessary?
+       g_return_val_if_fail(endByte >= startByte, NULL);
+
+       gchar *utf8Text = NULL;
+       const char *charSetBuffer;
+
+       // like TargetAsUTF8, but avoids a double conversion
+       if (sci->IsUnicodeMode() || ! *(charSetBuffer = sci->CharacterSetID())) {
+               int len = endByte - startByte;
+               utf8Text = (char *) g_malloc(len + 1);
+               sci->pdoc->GetCharRange(utf8Text, startByte, len);
+               utf8Text[len] = '\0';
+       } else {
+               // Need to convert
+               std::string s = sci->RangeText(startByte, endByte);
+               std::string tmputf = ConvertText(&s[0], s.length(), "UTF-8", charSetBuffer, false);
+               size_t len = tmputf.length();
+               utf8Text = (char *) g_malloc(len + 1);
+               memcpy(utf8Text, tmputf.c_str(), len);
+               utf8Text[len] = '\0';
+       }
+
+       return utf8Text;
+}
+
+gchar *ScintillaGTKAccessible::GetText(int startChar, int endChar) {
+       Sci::Position startByte, endByte;
+       if (endChar == -1) {
+               startByte = ByteOffsetFromCharacterOffset(startChar);
+               endByte = sci->pdoc->Length();
+       } else {
+               ByteRangeFromCharacterRange(startChar, endChar, startByte, endByte);
+       }
+       return GetTextRangeUTF8(startByte, endByte);
+}
+
+gchar *ScintillaGTKAccessible::GetTextAfterOffset(int charOffset,
+               AtkTextBoundary boundaryType, int *startChar, int *endChar) {
+       g_return_val_if_fail(charOffset >= 0, NULL);
+
+       Sci::Position startByte, endByte;
+       Sci::Position byteOffset = ByteOffsetFromCharacterOffset(charOffset);
+
+       switch (boundaryType) {
+               case ATK_TEXT_BOUNDARY_CHAR:
+                       startByte = PositionAfter(byteOffset);
+                       endByte = PositionAfter(startByte);
+                       // FIXME: optimize conversion back, as we can reasonably assume +1 char?
+                       break;
+
+               case ATK_TEXT_BOUNDARY_WORD_START:
+                       startByte = sci->WndProc(SCI_WORDENDPOSITION, byteOffset, 1);
+                       startByte = sci->WndProc(SCI_WORDENDPOSITION, startByte, 0);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, startByte, 1);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, endByte, 0);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_WORD_END:
+                       startByte = sci->WndProc(SCI_WORDENDPOSITION, byteOffset, 0);
+                       startByte = sci->WndProc(SCI_WORDENDPOSITION, startByte, 1);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, startByte, 0);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, endByte, 1);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_LINE_START: {
+                       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       startByte = sci->WndProc(SCI_POSITIONFROMLINE, line + 1, 0);
+                       endByte = sci->WndProc(SCI_POSITIONFROMLINE, line + 2, 0);
+                       break;
+               }
+
+               case ATK_TEXT_BOUNDARY_LINE_END: {
+                       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       startByte = sci->WndProc(SCI_GETLINEENDPOSITION, line, 0);
+                       endByte = sci->WndProc(SCI_GETLINEENDPOSITION, line + 1, 0);
+                       break;
+               }
+
+               default:
+                       *startChar = *endChar = -1;
+                       return NULL;
+       }
+
+       CharacterRangeFromByteRange(startByte, endByte, startChar, endChar);
+       return GetTextRangeUTF8(startByte, endByte);
+}
+
+gchar *ScintillaGTKAccessible::GetTextBeforeOffset(int charOffset,
+               AtkTextBoundary boundaryType, int *startChar, int *endChar) {
+       g_return_val_if_fail(charOffset >= 0, NULL);
+
+       Sci::Position startByte, endByte;
+       Sci::Position byteOffset = ByteOffsetFromCharacterOffset(charOffset);
+
+       switch (boundaryType) {
+               case ATK_TEXT_BOUNDARY_CHAR:
+                       endByte = PositionBefore(byteOffset);
+                       startByte = PositionBefore(endByte);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_WORD_START:
+                       endByte = sci->WndProc(SCI_WORDSTARTPOSITION, byteOffset, 0);
+                       endByte = sci->WndProc(SCI_WORDSTARTPOSITION, endByte, 1);
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, endByte, 0);
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, startByte, 1);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_WORD_END:
+                       endByte = sci->WndProc(SCI_WORDSTARTPOSITION, byteOffset, 1);
+                       endByte = sci->WndProc(SCI_WORDSTARTPOSITION, endByte, 0);
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, endByte, 1);
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, startByte, 0);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_LINE_START: {
+                       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       endByte = sci->WndProc(SCI_POSITIONFROMLINE, line, 0);
+                       if (line > 0) {
+                               startByte = sci->WndProc(SCI_POSITIONFROMLINE, line - 1, 0);
+                       } else {
+                               startByte = endByte;
+                       }
+                       break;
+               }
+
+               case ATK_TEXT_BOUNDARY_LINE_END: {
+                       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       if (line > 0) {
+                               endByte = sci->WndProc(SCI_GETLINEENDPOSITION, line - 1, 0);
+                       } else {
+                               endByte = 0;
+                       }
+                       if (line > 1) {
+                               startByte = sci->WndProc(SCI_GETLINEENDPOSITION, line - 2, 0);
+                       } else {
+                               startByte = endByte;
+                       }
+                       break;
+               }
+
+               default:
+                       *startChar = *endChar = -1;
+                       return NULL;
+       }
+
+       CharacterRangeFromByteRange(startByte, endByte, startChar, endChar);
+       return GetTextRangeUTF8(startByte, endByte);
+}
+
+gchar *ScintillaGTKAccessible::GetTextAtOffset(int charOffset,
+               AtkTextBoundary boundaryType, int *startChar, int *endChar) {
+       g_return_val_if_fail(charOffset >= 0, NULL);
+
+       Sci::Position startByte, endByte;
+       Sci::Position byteOffset = ByteOffsetFromCharacterOffset(charOffset);
+
+       switch (boundaryType) {
+               case ATK_TEXT_BOUNDARY_CHAR:
+                       startByte = byteOffset;
+                       endByte = sci->WndProc(SCI_POSITIONAFTER, byteOffset, 0);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_WORD_START:
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, byteOffset, 1);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, byteOffset, 1);
+                       if (! sci->WndProc(SCI_ISRANGEWORD, startByte, endByte)) {
+                               // if the cursor was not on a word, forward back
+                               startByte = sci->WndProc(SCI_WORDSTARTPOSITION, startByte, 0);
+                               startByte = sci->WndProc(SCI_WORDSTARTPOSITION, startByte, 1);
+                       }
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, endByte, 0);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_WORD_END:
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, byteOffset, 1);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, byteOffset, 1);
+                       if (! sci->WndProc(SCI_ISRANGEWORD, startByte, endByte)) {
+                               // if the cursor was not on a word, forward back
+                               endByte = sci->WndProc(SCI_WORDENDPOSITION, endByte, 0);
+                               endByte = sci->WndProc(SCI_WORDENDPOSITION, endByte, 1);
+                       }
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, startByte, 0);
+                       break;
+
+               case ATK_TEXT_BOUNDARY_LINE_START: {
+                       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       startByte = sci->WndProc(SCI_POSITIONFROMLINE, line, 0);
+                       endByte = sci->WndProc(SCI_POSITIONFROMLINE, line + 1, 0);
+                       break;
+               }
+
+               case ATK_TEXT_BOUNDARY_LINE_END: {
+                       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       if (line > 0) {
+                               startByte = sci->WndProc(SCI_GETLINEENDPOSITION, line - 1, 0);
+                       } else {
+                               startByte = 0;
+                       }
+                       endByte = sci->WndProc(SCI_GETLINEENDPOSITION, line, 0);
+                       break;
+               }
+
+               default:
+                       *startChar = *endChar = -1;
+                       return NULL;
+       }
+
+       CharacterRangeFromByteRange(startByte, endByte, startChar, endChar);
+       return GetTextRangeUTF8(startByte, endByte);
+}
+
+#if ATK_CHECK_VERSION(2, 10, 0)
+gchar *ScintillaGTKAccessible::GetStringAtOffset(int charOffset,
+               AtkTextGranularity granularity, int *startChar, int *endChar) {
+       g_return_val_if_fail(charOffset >= 0, NULL);
+
+       Sci::Position startByte, endByte;
+       Sci::Position byteOffset = ByteOffsetFromCharacterOffset(charOffset);
+
+       switch (granularity) {
+               case ATK_TEXT_GRANULARITY_CHAR:
+                       startByte = byteOffset;
+                       endByte = sci->WndProc(SCI_POSITIONAFTER, byteOffset, 0);
+                       break;
+               case ATK_TEXT_GRANULARITY_WORD:
+                       startByte = sci->WndProc(SCI_WORDSTARTPOSITION, byteOffset, 1);
+                       endByte = sci->WndProc(SCI_WORDENDPOSITION, byteOffset, 1);
+                       break;
+               case ATK_TEXT_GRANULARITY_LINE: {
+                       gint line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+                       startByte = sci->WndProc(SCI_POSITIONFROMLINE, line, 0);
+                       endByte = sci->WndProc(SCI_GETLINEENDPOSITION, line, 0);
+                       break;
+               }
+               default:
+                       *startChar = *endChar = -1;
+                       return NULL;
+       }
+
+       CharacterRangeFromByteRange(startByte, endByte, startChar, endChar);
+       return GetTextRangeUTF8(startByte, endByte);
+}
+#endif
+
+gunichar ScintillaGTKAccessible::GetCharacterAtOffset(int charOffset) {
+       g_return_val_if_fail(charOffset >= 0, 0);
+
+       Sci::Position startByte = ByteOffsetFromCharacterOffset(charOffset);
+       Sci::Position endByte = PositionAfter(startByte);
+       gchar *ch = GetTextRangeUTF8(startByte, endByte);
+       gunichar unichar = g_utf8_get_char_validated(ch, -1);
+       g_free(ch);
+
+       return unichar;
+}
+
+gint ScintillaGTKAccessible::GetCharacterCount() {
+       return sci->pdoc->CountCharacters(0, sci->pdoc->Length());
+}
+
+gint ScintillaGTKAccessible::GetCaretOffset() {
+       return CharacterOffsetFromByteOffset(sci->WndProc(SCI_GETCURRENTPOS, 0, 0));
+}
+
+gboolean ScintillaGTKAccessible::SetCaretOffset(int charOffset) {
+       sci->WndProc(SCI_GOTOPOS, ByteOffsetFromCharacterOffset(charOffset), 0);
+       return TRUE;
+}
+
+gint ScintillaGTKAccessible::GetOffsetAtPoint(gint x, gint y, AtkCoordType coords) {
+       gint x_widget, y_widget, x_window, y_window;
+       GtkWidget *widget = gtk_accessible_get_widget(accessible);
+
+       GdkWindow *window = gtk_widget_get_window(widget);
+       gdk_window_get_origin(window, &x_widget, &y_widget);
+       if (coords == ATK_XY_SCREEN) {
+               x = x - x_widget;
+               y = y - y_widget;
+       } else if (coords == ATK_XY_WINDOW) {
+               window = gdk_window_get_toplevel(window);
+               gdk_window_get_origin(window, &x_window, &y_window);
+
+               x = x - x_widget + x_window;
+               y = y - y_widget + y_window;
+       } else {
+               return -1;
+       }
+
+       // FIXME: should we handle scrolling?
+       return CharacterOffsetFromByteOffset(sci->WndProc(SCI_CHARPOSITIONFROMPOINTCLOSE, x, y));
+}
+
+void ScintillaGTKAccessible::GetCharacterExtents(int charOffset,
+               gint *x, gint *y, gint *width, gint *height, AtkCoordType coords) {
+       *x = *y = *height = *width = 0;
+
+       Sci::Position byteOffset = ByteOffsetFromCharacterOffset(charOffset);
+
+       // FIXME: should we handle scrolling?
+       *x = sci->WndProc(SCI_POINTXFROMPOSITION, 0, byteOffset);
+       *y = sci->WndProc(SCI_POINTYFROMPOSITION, 0, byteOffset);
+
+       int line = sci->WndProc(SCI_LINEFROMPOSITION, byteOffset, 0);
+       *height = sci->WndProc(SCI_TEXTHEIGHT, line, 0);
+
+       int nextByteOffset = PositionAfter(byteOffset);
+       int next_x = sci->WndProc(SCI_POINTXFROMPOSITION, 0, nextByteOffset);
+       if (next_x > *x) {
+               *width = next_x - *x;
+       } else if (nextByteOffset > byteOffset) {
+               /* maybe next position was on the next line or something.
+                * just compute the expected character width */
+               int style = StyleAt(byteOffset, true);
+               int len = nextByteOffset - byteOffset;
+               char *ch = new char[len + 1];
+               sci->pdoc->GetCharRange(ch, byteOffset, len);
+               ch[len] = '\0';
+               *width = sci->TextWidth(style, ch);
+               delete[] ch;
+       }
+
+       GtkWidget *widget = gtk_accessible_get_widget(accessible);
+       GdkWindow *window = gtk_widget_get_window(widget);
+       int x_widget, y_widget;
+       gdk_window_get_origin(window, &x_widget, &y_widget);
+       if (coords == ATK_XY_SCREEN) {
+               *x += x_widget;
+               *y += y_widget;
+       } else if (coords == ATK_XY_WINDOW) {
+               window = gdk_window_get_toplevel(window);
+               int x_window, y_window;
+               gdk_window_get_origin(window, &x_window, &y_window);
+
+               *x += x_widget - x_window;
+               *y += y_widget - y_window;
+       } else {
+               *x = *y = *height = *width = 0;
+       }
+}
+
+static AtkAttributeSet *AddTextAttribute(AtkAttributeSet *attributes, AtkTextAttribute attr, gchar *value) {
+       AtkAttribute *at = g_new(AtkAttribute, 1);
+       at->name = g_strdup(atk_text_attribute_get_name(attr));
+       at->value = value;
+
+       return g_slist_prepend(attributes, at);
+}
+
+static AtkAttributeSet *AddTextIntAttribute(AtkAttributeSet *attributes, AtkTextAttribute attr, gint i) {
+       return AddTextAttribute(attributes, attr, g_strdup(atk_text_attribute_get_value(attr, i)));
+}
+
+static AtkAttributeSet *AddTextColorAttribute(AtkAttributeSet *attributes, AtkTextAttribute attr, const 
ColourDesired &colour) {
+       return AddTextAttribute(attributes, attr,
+               g_strdup_printf("%u,%u,%u", colour.GetRed() * 257, colour.GetGreen() * 257, colour.GetBlue() 
* 257));
+}
+
+AtkAttributeSet *ScintillaGTKAccessible::GetAttributesForStyle(unsigned int styleNum) {
+       AtkAttributeSet *attr_set = NULL;
+
+       if (styleNum >= sci->vs.styles.size())
+               return NULL;
+       Style &style = sci->vs.styles[styleNum];
+
+       attr_set = AddTextAttribute(attr_set, ATK_TEXT_ATTR_FAMILY_NAME, g_strdup(style.fontName));
+       attr_set = AddTextAttribute(attr_set, ATK_TEXT_ATTR_SIZE, g_strdup_printf("%d", style.size / 
SC_FONT_SIZE_MULTIPLIER));
+       attr_set = AddTextIntAttribute(attr_set, ATK_TEXT_ATTR_WEIGHT, CLAMP(style.weight, 100, 1000));
+       attr_set = AddTextIntAttribute(attr_set, ATK_TEXT_ATTR_STYLE, style.italic ? PANGO_STYLE_ITALIC : 
PANGO_STYLE_NORMAL);
+       attr_set = AddTextIntAttribute(attr_set, ATK_TEXT_ATTR_UNDERLINE, style.underline ? 
PANGO_UNDERLINE_SINGLE : PANGO_UNDERLINE_NONE);
+       attr_set = AddTextColorAttribute(attr_set, ATK_TEXT_ATTR_FG_COLOR, style.fore);
+       attr_set = AddTextColorAttribute(attr_set, ATK_TEXT_ATTR_BG_COLOR, style.back);
+       attr_set = AddTextIntAttribute(attr_set, ATK_TEXT_ATTR_INVISIBLE, style.visible ? 0 : 1);
+       attr_set = AddTextIntAttribute(attr_set, ATK_TEXT_ATTR_EDITABLE, style.changeable ? 1 : 0);
+
+       return attr_set;
+}
+
+AtkAttributeSet *ScintillaGTKAccessible::GetRunAttributes(int charOffset, int *startChar, int *endChar) {
+       g_return_val_if_fail(charOffset >= -1, NULL);
+
+       Sci::Position byteOffset;
+       if (charOffset == -1) {
+               byteOffset = sci->WndProc(SCI_GETCURRENTPOS, 0, 0);
+       } else {
+               byteOffset = ByteOffsetFromCharacterOffset(charOffset);
+       }
+       int length = sci->pdoc->Length();
+
+       g_return_val_if_fail(byteOffset <= length, NULL);
+
+       const char style = StyleAt(byteOffset, true);
+       // compute the range for this style
+       Sci::Position startByte = byteOffset;
+       // when going backwards, we know the style is already computed
+       while (startByte > 0 && sci->pdoc->StyleAt((startByte) - 1) == style)
+               (startByte)--;
+       Sci::Position endByte = byteOffset + 1;
+       while (endByte < length && StyleAt(endByte, true) == style)
+               (endByte)++;
+
+       CharacterRangeFromByteRange(startByte, endByte, startChar, endChar);
+       return GetAttributesForStyle((unsigned int) style);
+}
+
+AtkAttributeSet *ScintillaGTKAccessible::GetDefaultAttributes() {
+       return GetAttributesForStyle(0);
+}
+
+gint ScintillaGTKAccessible::GetNSelections() {
+       return sci->sel.Empty() ? 0 : sci->sel.Count();
+}
+
+gchar *ScintillaGTKAccessible::GetSelection(gint selection_num, int *startChar, int *endChar) {
+       if (selection_num < 0 || (unsigned int) selection_num >= sci->sel.Count())
+               return NULL;
+
+       Sci::Position startByte = sci->sel.Range(selection_num).Start().Position();
+       Sci::Position endByte = sci->sel.Range(selection_num).End().Position();
+
+       CharacterRangeFromByteRange(startByte, endByte, startChar, endChar);
+       return GetTextRangeUTF8(startByte, endByte);
+}
+
+gboolean ScintillaGTKAccessible::AddSelection(int startChar, int endChar) {
+       size_t n_selections = sci->sel.Count();
+       Sci::Position startByte, endByte;
+       ByteRangeFromCharacterRange(startChar, endChar, startByte, endByte);
+       // use WndProc() to set the selections so it notifies as needed
+       if (n_selections > 1 || ! sci->sel.Empty()) {
+               sci->WndProc(SCI_ADDSELECTION, startByte, endByte);
+       } else {
+               sci->WndProc(SCI_SETSELECTION, startByte, endByte);
+       }
+
+       return TRUE;
+}
+
+gboolean ScintillaGTKAccessible::RemoveSelection(gint selection_num) {
+       size_t n_selections = sci->sel.Count();
+       if (selection_num < 0 || (unsigned int) selection_num >= n_selections)
+               return FALSE;
+
+       if (n_selections > 1) {
+               sci->WndProc(SCI_DROPSELECTIONN, selection_num, 0);
+       } else if (sci->sel.Empty()) {
+               return FALSE;
+       } else {
+               sci->WndProc(SCI_CLEARSELECTIONS, 0, 0);
+       }
+
+       return TRUE;
+}
+
+gboolean ScintillaGTKAccessible::SetSelection(gint selection_num, int startChar, int endChar) {
+       if (selection_num < 0 || (unsigned int) selection_num >= sci->sel.Count())
+               return FALSE;
+
+       Sci::Position startByte, endByte;
+       ByteRangeFromCharacterRange(startChar, endChar, startByte, endByte);
+
+       sci->WndProc(SCI_SETSELECTIONNSTART, selection_num, startByte);
+       sci->WndProc(SCI_SETSELECTIONNEND, selection_num, endByte);
+
+       return TRUE;
+}
+
+void ScintillaGTKAccessible::AtkTextIface::init(::AtkTextIface *iface) {
+       iface->get_text = GetText;
+       iface->get_text_after_offset = GetTextAfterOffset;
+       iface->get_text_at_offset = GetTextAtOffset;
+       iface->get_text_before_offset = GetTextBeforeOffset;
+#if ATK_CHECK_VERSION(2, 10, 0)
+       iface->get_string_at_offset = GetStringAtOffset;
+#endif
+       iface->get_character_at_offset = GetCharacterAtOffset;
+       iface->get_character_count = GetCharacterCount;
+       iface->get_caret_offset = GetCaretOffset;
+       iface->set_caret_offset = SetCaretOffset;
+       iface->get_offset_at_point = GetOffsetAtPoint;
+       iface->get_character_extents = GetCharacterExtents;
+       iface->get_n_selections = GetNSelections;
+       iface->get_selection = GetSelection;
+       iface->add_selection = AddSelection;
+       iface->remove_selection = RemoveSelection;
+       iface->set_selection = SetSelection;
+       iface->get_run_attributes = GetRunAttributes;
+       iface->get_default_attributes = GetDefaultAttributes;
+}
+
+/* atkeditabletext.h */
+
+void ScintillaGTKAccessible::SetTextContents(const gchar *contents) {
+       // FIXME: it's probably useless to check for READONLY here, SETTEXT probably does it just fine?
+       if (! sci->pdoc->IsReadOnly()) {
+               sci->WndProc(SCI_SETTEXT, 0, (sptr_t) contents);
+       }
+}
+
+bool ScintillaGTKAccessible::InsertStringUTF8(Sci::Position bytePos, const gchar *utf8, Sci::Position 
lengthBytes) {
+       if (sci->pdoc->IsReadOnly()) {
+               return false;
+       }
+
+       // like EncodedFromUTF8(), but avoids an extra copy
+       // FIXME: update target?
+       const char *charSetBuffer;
+       if (sci->IsUnicodeMode() || ! *(charSetBuffer = sci->CharacterSetID())) {
+               sci->pdoc->InsertString(bytePos, utf8, lengthBytes);
+       } else {
+               // conversion needed
+               std::string encoded = ConvertText(utf8, lengthBytes, charSetBuffer, "UTF-8", true);
+               sci->pdoc->InsertString(bytePos, encoded.c_str(), encoded.length());
+       }
+
+       return true;
+}
+
+void ScintillaGTKAccessible::InsertText(const gchar *text, int lengthBytes, int *charPosition) {
+       Sci::Position bytePosition = ByteOffsetFromCharacterOffset(*charPosition);
+
+       // FIXME: should we update the target?
+       if (InsertStringUTF8(bytePosition, text, lengthBytes)) {
+               (*charPosition) += sci->pdoc->CountCharacters(bytePosition, lengthBytes);
+       }
+}
+
+void ScintillaGTKAccessible::CopyText(int startChar, int endChar) {
+       Sci::Position startByte, endByte;
+       ByteRangeFromCharacterRange(startChar, endChar, startByte, endByte);
+       sci->CopyRangeToClipboard(startByte, endByte);
+}
+
+void ScintillaGTKAccessible::CutText(int startChar, int endChar) {
+       g_return_if_fail(endChar >= startChar);
+
+       if (! sci->pdoc->IsReadOnly()) {
+               // FIXME: have a byte variant of those and convert only once?
+               CopyText(startChar, endChar);
+               DeleteText(startChar, endChar);
+       }
+}
+
+void ScintillaGTKAccessible::DeleteText(int startChar, int endChar) {
+       g_return_if_fail(endChar >= startChar);
+
+       if (! sci->pdoc->IsReadOnly()) {
+               Sci::Position startByte, endByte;
+               ByteRangeFromCharacterRange(startChar, endChar, startByte, endByte);
+
+               if (! sci->RangeContainsProtected(startByte, endByte)) {
+                       // FIXME: restore the target?
+                       sci->pdoc->DeleteChars(startByte, endByte - startByte);
+               }
+       }
+}
+
+void ScintillaGTKAccessible::PasteText(int charPosition) {
+       if (sci->pdoc->IsReadOnly())
+               return;
+
+       // Helper class holding the position for the asynchronous paste operation.
+       // We can only hope that when the callback gets called scia is still valid, but ScintillaGTK
+       // has always done that without problems, so let's guess it's a fairly safe bet.
+       struct Helper : GObjectWatcher {
+               ScintillaGTKAccessible *scia;
+               Sci::Position bytePosition;
+
+               void Destroyed() override {
+                       scia = 0;
+               }
+
+               Helper(ScintillaGTKAccessible *scia_, Sci::Position bytePos_) :
+                       GObjectWatcher(G_OBJECT(scia_->sci->sci)),
+                       scia(scia_),
+                       bytePosition(bytePos_) {
+               }
+
+               void TextReceived(GtkClipboard *, const gchar *text) {
+                       if (text) {
+                               size_t len = strlen(text);
+                               std::string convertedText;
+                               if (len > 0 && scia->sci->convertPastes) {
+                                       // Convert line endings of the paste into our local line-endings mode
+                                       convertedText = Document::TransformLineEnds(text, len, 
scia->sci->pdoc->eolMode);
+                                       len = convertedText.length();
+                                       text = convertedText.c_str();
+                               }
+                               scia->InsertStringUTF8(bytePosition, text, static_cast<Sci::Position>(len));
+                       }
+               }
+
+               static void TextReceivedCallback(GtkClipboard *clipboard, const gchar *text, gpointer data) {
+                       Helper *helper = reinterpret_cast<Helper*>(data);
+                       try {
+                               if (helper->scia != 0) {
+                                       helper->TextReceived(clipboard, text);
+                               }
+                       } catch (...) {}
+                       delete helper;
+               }
+       };
+
+       Helper *helper = new Helper(this, ByteOffsetFromCharacterOffset(charPosition));
+       GtkWidget *widget = gtk_accessible_get_widget(accessible);
+       GtkClipboard *clipboard = gtk_widget_get_clipboard(widget, GDK_SELECTION_CLIPBOARD);
+       gtk_clipboard_request_text(clipboard, helper->TextReceivedCallback, helper);
+}
+
+void ScintillaGTKAccessible::AtkEditableTextIface::init(::AtkEditableTextIface *iface) {
+       iface->set_text_contents = SetTextContents;
+       iface->insert_text = InsertText;
+       iface->copy_text = CopyText;
+       iface->cut_text = CutText;
+       iface->delete_text = DeleteText;
+       iface->paste_text = PasteText;
+       //~ iface->set_run_attributes = SetRunAttributes;
+}
+
+bool ScintillaGTKAccessible::Enabled() const {
+       return sci->accessibilityEnabled == SC_ACCESSIBILITY_ENABLED;
+}
+
+// Callbacks
+
+void ScintillaGTKAccessible::UpdateCursor() {
+       Sci::Position pos = sci->WndProc(SCI_GETCURRENTPOS, 0, 0);
+       if (old_pos != pos) {
+               int charPosition = CharacterOffsetFromByteOffset(pos);
+               g_signal_emit_by_name(accessible, "text-caret-moved", charPosition);
+               old_pos = pos;
+       }
+
+       size_t n_selections = sci->sel.Count();
+       size_t prev_n_selections = old_sels.size();
+       bool selection_changed = n_selections != prev_n_selections;
+
+       old_sels.resize(n_selections);
+       for (size_t i = 0; i < n_selections; i++) {
+               SelectionRange &sel = sci->sel.Range(i);
+
+               if (i < prev_n_selections && ! selection_changed) {
+                       SelectionRange &old_sel = old_sels[i];
+                       // do not consider a caret move to be a selection change
+                       selection_changed = ((! old_sel.Empty() || ! sel.Empty()) && ! (old_sel == sel));
+               }
+
+               old_sels[i] = sel;
+       }
+
+       if (selection_changed)
+               g_signal_emit_by_name(accessible, "text-selection-changed");
+}
+
+void ScintillaGTKAccessible::ChangeDocument(Document *oldDoc, Document *newDoc) {
+       if (!Enabled()) {
+               return;
+       }
+
+       if (oldDoc == newDoc) {
+               return;
+       }
+
+       if (oldDoc) {
+               int charLength = oldDoc->CountCharacters(0, oldDoc->Length());
+               g_signal_emit_by_name(accessible, "text-changed::delete", 0, charLength);
+       }
+
+       if (newDoc) {
+               PLATFORM_ASSERT(newDoc == sci->pdoc);
+
+               int charLength = newDoc->CountCharacters(0, newDoc->Length());
+               g_signal_emit_by_name(accessible, "text-changed::insert", 0, charLength);
+
+               if ((oldDoc ? oldDoc->IsReadOnly() : false) != newDoc->IsReadOnly()) {
+                       NotifyReadOnly();
+               }
+
+               // update cursor and selection
+               old_pos = -1;
+               old_sels.clear();
+               UpdateCursor();
+       }
+}
+
+void ScintillaGTKAccessible::NotifyReadOnly() {
+       bool readonly = sci->pdoc->IsReadOnly();
+       atk_object_notify_state_change(ATK_OBJECT(accessible), ATK_STATE_EDITABLE, ! readonly);
+#if ATK_CHECK_VERSION(2, 16, 0)
+       atk_object_notify_state_change(ATK_OBJECT(accessible), ATK_STATE_READ_ONLY, readonly);
+#endif
+}
+
+void ScintillaGTKAccessible::SetAccessibility() {
+       // Called by ScintillaGTK when application has enabled or disabled accessibility
+       character_offsets.resize(0);
+       character_offsets.push_back(0);
+}
+
+void ScintillaGTKAccessible::Notify(GtkWidget *, gint, SCNotification *nt) {
+       if (!Enabled())
+               return;
+       switch (nt->nmhdr.code) {
+               case SCN_MODIFIED: {
+                       if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) {
+                               // invalidate character offset cache if applicable
+                               const Sci::Line line = sci->pdoc->LineFromPosition(nt->position);
+                               if (character_offsets.size() > static_cast<size_t>(line + 1)) {
+                                       character_offsets.resize(line + 1);
+                               }
+                       }
+                       if (nt->modificationType & SC_MOD_INSERTTEXT) {
+                               int startChar = CharacterOffsetFromByteOffset(nt->position);
+                               int lengthChar = sci->pdoc->CountCharacters(nt->position, nt->position + 
nt->length);
+                               g_signal_emit_by_name(accessible, "text-changed::insert", startChar, 
lengthChar);
+                               UpdateCursor();
+                       }
+                       if (nt->modificationType & SC_MOD_BEFOREDELETE) {
+                               // We cannot compute the deletion length in DELETETEXT as it requires 
accessing the
+                               // buffer, so that the character are still present.  So, we cache the value 
here,
+                               // and use it in DELETETEXT that fires quickly after.
+                               deletionLengthChar = sci->pdoc->CountCharacters(nt->position, nt->position + 
nt->length);
+                       }
+                       if (nt->modificationType & SC_MOD_DELETETEXT) {
+                               int startChar = CharacterOffsetFromByteOffset(nt->position);
+                               g_signal_emit_by_name(accessible, "text-changed::delete", startChar, 
deletionLengthChar);
+                               UpdateCursor();
+                       }
+                       if (nt->modificationType & SC_MOD_CHANGESTYLE) {
+                               g_signal_emit_by_name(accessible, "text-attributes-changed");
+                       }
+               } break;
+               case SCN_UPDATEUI: {
+                       if (nt->updated & SC_UPDATE_SELECTION) {
+                               UpdateCursor();
+                       }
+               } break;
+       }
+}
+
+// ATK method wrappers
+
+// wraps a call from the accessible object to the ScintillaGTKAccessible, and avoid leaking any exception
+#define WRAPPER_METHOD_BODY(accessible, call, defret) \
+       try { \
+               ScintillaGTKAccessible *thisAccessible = 
FromAccessible(reinterpret_cast<GtkAccessible*>(accessible)); \
+               if (thisAccessible) { \
+                       return thisAccessible->call; \
+               } else { \
+                       return defret; \
+               } \
+       } catch (...) { \
+               return defret; \
+       }
+
+// AtkText
+gchar *ScintillaGTKAccessible::AtkTextIface::GetText(AtkText *text, int start_offset, int end_offset) {
+       WRAPPER_METHOD_BODY(text, GetText(start_offset, end_offset), NULL);
+}
+gchar *ScintillaGTKAccessible::AtkTextIface::GetTextAfterOffset(AtkText *text, int offset, AtkTextBoundary 
boundary_type, int *start_offset, int *end_offset) {
+       WRAPPER_METHOD_BODY(text, GetTextAfterOffset(offset, boundary_type, start_offset, end_offset), NULL)
+}
+gchar *ScintillaGTKAccessible::AtkTextIface::GetTextBeforeOffset(AtkText *text, int offset, AtkTextBoundary 
boundary_type, int *start_offset, int *end_offset) {
+       WRAPPER_METHOD_BODY(text, GetTextBeforeOffset(offset, boundary_type, start_offset, end_offset), NULL)
+}
+gchar *ScintillaGTKAccessible::AtkTextIface::GetTextAtOffset(AtkText *text, gint offset, AtkTextBoundary 
boundary_type, gint *start_offset, gint *end_offset) {
+       WRAPPER_METHOD_BODY(text, GetTextAtOffset(offset, boundary_type, start_offset, end_offset), NULL)
+}
+#if ATK_CHECK_VERSION(2, 10, 0)
+gchar *ScintillaGTKAccessible::AtkTextIface::GetStringAtOffset(AtkText *text, gint offset, 
AtkTextGranularity granularity, gint *start_offset, gint *end_offset) {
+       WRAPPER_METHOD_BODY(text, GetStringAtOffset(offset, granularity, start_offset, end_offset), NULL)
+}
+#endif
+gunichar ScintillaGTKAccessible::AtkTextIface::GetCharacterAtOffset(AtkText *text, gint offset) {
+       WRAPPER_METHOD_BODY(text, GetCharacterAtOffset(offset), 0)
+}
+gint ScintillaGTKAccessible::AtkTextIface::GetCharacterCount(AtkText *text) {
+       WRAPPER_METHOD_BODY(text, GetCharacterCount(), 0)
+}
+gint ScintillaGTKAccessible::AtkTextIface::GetCaretOffset(AtkText *text) {
+       WRAPPER_METHOD_BODY(text, GetCaretOffset(), 0)
+}
+gboolean ScintillaGTKAccessible::AtkTextIface::SetCaretOffset(AtkText *text, gint offset) {
+       WRAPPER_METHOD_BODY(text, SetCaretOffset(offset), FALSE)
+}
+gint ScintillaGTKAccessible::AtkTextIface::GetOffsetAtPoint(AtkText *text, gint x, gint y, AtkCoordType 
coords) {
+       WRAPPER_METHOD_BODY(text, GetOffsetAtPoint(x, y, coords), -1)
+}
+void ScintillaGTKAccessible::AtkTextIface::GetCharacterExtents(AtkText *text, gint offset, gint *x, gint *y, 
gint *width, gint *height, AtkCoordType coords) {
+       WRAPPER_METHOD_BODY(text, GetCharacterExtents(offset, x, y, width, height, coords), )
+}
+AtkAttributeSet *ScintillaGTKAccessible::AtkTextIface::GetRunAttributes(AtkText *text, gint offset, gint 
*start_offset, gint *end_offset) {
+       WRAPPER_METHOD_BODY(text, GetRunAttributes(offset, start_offset, end_offset), NULL)
+}
+AtkAttributeSet *ScintillaGTKAccessible::AtkTextIface::GetDefaultAttributes(AtkText *text) {
+       WRAPPER_METHOD_BODY(text, GetDefaultAttributes(), NULL)
+}
+gint ScintillaGTKAccessible::AtkTextIface::GetNSelections(AtkText *text) {
+       WRAPPER_METHOD_BODY(text, GetNSelections(), 0)
+}
+gchar *ScintillaGTKAccessible::AtkTextIface::GetSelection(AtkText *text, gint selection_num, gint 
*start_pos, gint *end_pos) {
+       WRAPPER_METHOD_BODY(text, GetSelection(selection_num, start_pos, end_pos), NULL)
+}
+gboolean ScintillaGTKAccessible::AtkTextIface::AddSelection(AtkText *text, gint start, gint end) {
+       WRAPPER_METHOD_BODY(text, AddSelection(start, end), FALSE)
+}
+gboolean ScintillaGTKAccessible::AtkTextIface::RemoveSelection(AtkText *text, gint selection_num) {
+       WRAPPER_METHOD_BODY(text, RemoveSelection(selection_num), FALSE)
+}
+gboolean ScintillaGTKAccessible::AtkTextIface::SetSelection(AtkText *text, gint selection_num, gint start, 
gint end) {
+       WRAPPER_METHOD_BODY(text, SetSelection(selection_num, start, end), FALSE)
+}
+// AtkEditableText
+void ScintillaGTKAccessible::AtkEditableTextIface::SetTextContents(AtkEditableText *text, const gchar 
*contents) {
+       WRAPPER_METHOD_BODY(text, SetTextContents(contents), )
+}
+void ScintillaGTKAccessible::AtkEditableTextIface::InsertText(AtkEditableText *text, const gchar *contents, 
gint length, gint *position) {
+       WRAPPER_METHOD_BODY(text, InsertText(contents, length, position), )
+}
+void ScintillaGTKAccessible::AtkEditableTextIface::CopyText(AtkEditableText *text, gint start, gint end) {
+       WRAPPER_METHOD_BODY(text, CopyText(start, end), )
+}
+void ScintillaGTKAccessible::AtkEditableTextIface::CutText(AtkEditableText *text, gint start, gint end) {
+       WRAPPER_METHOD_BODY(text, CutText(start, end), )
+}
+void ScintillaGTKAccessible::AtkEditableTextIface::DeleteText(AtkEditableText *text, gint start, gint end) {
+       WRAPPER_METHOD_BODY(text, DeleteText(start, end), )
+}
+void ScintillaGTKAccessible::AtkEditableTextIface::PasteText(AtkEditableText *text, gint position) {
+       WRAPPER_METHOD_BODY(text, PasteText(position), )
+}
+
+// GObject glue
+
+#if HAVE_GTK_FACTORY
+static GType scintilla_object_accessible_factory_get_type(void);
+#endif
+
+static void scintilla_object_accessible_init(ScintillaObjectAccessible *accessible);
+static void scintilla_object_accessible_class_init(ScintillaObjectAccessibleClass *klass);
+static gpointer scintilla_object_accessible_parent_class = NULL;
+
+
+// @p parent_type is only required on GTK 3.2 to 3.6, and only on the first call
+static GType scintilla_object_accessible_get_type(GType parent_type G_GNUC_UNUSED) {
+       static volatile gsize type_id_result = 0;
+
+       if (g_once_init_enter(&type_id_result)) {
+               GTypeInfo tinfo = {
+                       0,                                                                                    
                                  /* class size */
+                       (GBaseInitFunc) NULL,                                                                 
          /* base init */
+                       (GBaseFinalizeFunc) NULL,                                                             
          /* base finalize */
+                       (GClassInitFunc) scintilla_object_accessible_class_init,        /* class init */
+                       (GClassFinalizeFunc) NULL,                                                            
          /* class finalize */
+                       NULL,                                                                                 
                          /* class data */
+                       0,                                                                                    
                                  /* instance size */
+                       0,                                                                                    
                                  /* nb preallocs */
+                       (GInstanceInitFunc) scintilla_object_accessible_init,           /* instance init */
+                       NULL                                                                                  
                          /* value table */
+               };
+
+               const GInterfaceInfo atk_text_info = {
+                       (GInterfaceInitFunc) ScintillaGTKAccessible::AtkTextIface::init,
+                       (GInterfaceFinalizeFunc) NULL,
+                       NULL
+               };
+
+               const GInterfaceInfo atk_editable_text_info = {
+                       (GInterfaceInitFunc) ScintillaGTKAccessible::AtkEditableTextIface::init,
+                       (GInterfaceFinalizeFunc) NULL,
+                       NULL
+               };
+
+#if HAVE_GTK_A11Y_H
+               // good, we have gtk-a11y.h, we can use that
+               GType derived_atk_type = GTK_TYPE_CONTAINER_ACCESSIBLE;
+               tinfo.class_size = sizeof (GtkContainerAccessibleClass);
+               tinfo.instance_size = sizeof (GtkContainerAccessible);
+#else // ! HAVE_GTK_A11Y_H
+# if HAVE_GTK_FACTORY
+               // Figure out the size of the class and instance we are deriving from through the registry
+               GType derived_type = g_type_parent(SCINTILLA_TYPE_OBJECT);
+               AtkObjectFactory *factory = atk_registry_get_factory(atk_get_default_registry(), 
derived_type);
+               GType derived_atk_type = atk_object_factory_get_accessible_type(factory);
+# else // ! HAVE_GTK_FACTORY
+               // We're kind of screwed and can't determine the parent (no registry, and no public type)
+               // Hack your way around by requiring the caller to give us our parent type.  The caller
+               // might be able to trick its way into doing that, by e.g. instantiating the parent's
+               // accessible type and get its GType.  It's ugly but we can't do better on GTK 3.2 to 3.6.
+               g_assert(parent_type != 0);
+
+               GType derived_atk_type = parent_type;
+# endif // ! HAVE_GTK_FACTORY
+
+               GTypeQuery query;
+               g_type_query(derived_atk_type, &query);
+               tinfo.class_size = query.class_size;
+               tinfo.instance_size = query.instance_size;
+#endif // ! HAVE_GTK_A11Y_H
+
+               GType type_id = g_type_register_static(derived_atk_type, "ScintillaObjectAccessible", &tinfo, 
(GTypeFlags) 0);
+               g_type_add_interface_static(type_id, ATK_TYPE_TEXT, &atk_text_info);
+               g_type_add_interface_static(type_id, ATK_TYPE_EDITABLE_TEXT, &atk_editable_text_info);
+
+               g_once_init_leave(&type_id_result, type_id);
+       }
+
+       return type_id_result;
+}
+
+static AtkObject *scintilla_object_accessible_new(GType parent_type, GObject *obj) {
+       g_return_val_if_fail(SCINTILLA_IS_OBJECT(obj), NULL);
+
+       AtkObject *accessible = (AtkObject *) g_object_new(scintilla_object_accessible_get_type(parent_type),
+#if HAVE_WIDGET_SET_UNSET
+               "widget", obj,
+#endif
+               NULL);
+       atk_object_initialize(accessible, obj);
+
+       return accessible;
+}
+
+// implementation for gtk_widget_get_accessible().
+// See the comment at the top of the file for details on the implementation
+// @p widget the widget.
+// @p cache pointer to store the AtkObject between repeated calls.  Might or might not be filled.
+// @p widget_parent_class pointer to the widget's parent class (to chain up method calls).
+AtkObject *ScintillaGTKAccessible::WidgetGetAccessibleImpl(GtkWidget *widget, AtkObject **cache, gpointer 
widget_parent_class G_GNUC_UNUSED) {
+       if (*cache != NULL) {
+               return *cache;
+       }
+
+#if HAVE_GTK_A11Y_H // just instantiate the accessible
+       *cache = scintilla_object_accessible_new(0, G_OBJECT(widget));
+#elif HAVE_GTK_FACTORY // register in the factory and let GTK instantiate
+       static volatile gsize registered = 0;
+
+       if (g_once_init_enter(&registered)) {
+               // Figure out whether accessibility is enabled by looking at the type of the accessible
+               // object which would be created for the parent type of ScintillaObject.
+               GType derived_type = g_type_parent(SCINTILLA_TYPE_OBJECT);
+
+               AtkRegistry *registry = atk_get_default_registry();
+               AtkObjectFactory *factory = atk_registry_get_factory(registry, derived_type);
+               GType derived_atk_type = atk_object_factory_get_accessible_type(factory);
+               if (g_type_is_a(derived_atk_type, GTK_TYPE_ACCESSIBLE)) {
+                       atk_registry_set_factory_type(registry, SCINTILLA_TYPE_OBJECT,
+                                                     scintilla_object_accessible_factory_get_type());
+               }
+               g_once_init_leave(&registered, 1);
+       }
+       AtkObject *obj = GTK_WIDGET_CLASS(widget_parent_class)->get_accessible(widget);
+       *cache = static_cast<AtkObject*>(g_object_ref(obj));
+#else // no public API, no factory, so guess from the parent and instantiate
+       static GType parent_atk_type = 0;
+
+       if (parent_atk_type == 0) {
+               AtkObject *parent_obj = GTK_WIDGET_CLASS(widget_parent_class)->get_accessible(widget);
+               if (parent_obj) {
+                       GType parent_atk_type = G_OBJECT_TYPE(parent_obj);
+
+                       // Figure out whether accessibility is enabled by looking at the type of the 
accessible
+                       // object which would be created for the parent type of ScintillaObject.
+                       if (g_type_is_a(parent_atk_type, GTK_TYPE_ACCESSIBLE)) {
+                               *cache = scintilla_object_accessible_new(parent_atk_type, G_OBJECT(widget));
+                       } else {
+                               *cache = static_cast<AtkObject*>(g_object_ref(parent_obj));
+                       }
+               }
+       }
+#endif
+       return *cache;
+}
+
+static AtkStateSet *scintilla_object_accessible_ref_state_set(AtkObject *accessible) {
+       AtkStateSet *state_set = 
ATK_OBJECT_CLASS(scintilla_object_accessible_parent_class)->ref_state_set(accessible);
+
+       GtkWidget *widget = gtk_accessible_get_widget(GTK_ACCESSIBLE(accessible));
+       if (widget == NULL) {
+               atk_state_set_add_state(state_set, ATK_STATE_DEFUNCT);
+       } else {
+               if (! scintilla_send_message(SCINTILLA_OBJECT(widget), SCI_GETREADONLY, 0, 0))
+                       atk_state_set_add_state(state_set, ATK_STATE_EDITABLE);
+#if ATK_CHECK_VERSION(2, 16, 0)
+               else
+                       atk_state_set_add_state(state_set, ATK_STATE_READ_ONLY);
+#endif
+               atk_state_set_add_state(state_set, ATK_STATE_MULTI_LINE);
+               atk_state_set_add_state(state_set, ATK_STATE_MULTISELECTABLE);
+               atk_state_set_add_state(state_set, ATK_STATE_SELECTABLE_TEXT);
+               /*atk_state_set_add_state(state_set, ATK_STATE_SUPPORTS_AUTOCOMPLETION);*/
+       }
+
+       return state_set;
+}
+
+static void scintilla_object_accessible_widget_set(GtkAccessible *accessible) {
+       GtkWidget *widget = gtk_accessible_get_widget(accessible);
+       if (widget == NULL)
+               return;
+
+       ScintillaObjectAccessiblePrivate *priv = SCINTILLA_OBJECT_ACCESSIBLE_GET_PRIVATE(accessible);
+       if (priv->pscin != 0)
+               delete priv->pscin;
+       priv->pscin = new ScintillaGTKAccessible(accessible, widget);
+}
+
+#if HAVE_WIDGET_SET_UNSET
+static void scintilla_object_accessible_widget_unset(GtkAccessible *accessible) {
+       GtkWidget *widget = gtk_accessible_get_widget(accessible);
+       if (widget == NULL)
+               return;
+
+       ScintillaObjectAccessiblePrivate *priv = SCINTILLA_OBJECT_ACCESSIBLE_GET_PRIVATE(accessible);
+       delete priv->pscin;
+       priv->pscin = 0;
+}
+#endif
+
+static void scintilla_object_accessible_initialize(AtkObject *obj, gpointer data) {
+       ATK_OBJECT_CLASS(scintilla_object_accessible_parent_class)->initialize(obj, data);
+
+#if ! HAVE_WIDGET_SET_UNSET
+       scintilla_object_accessible_widget_set(GTK_ACCESSIBLE(obj));
+#endif
+
+       obj->role = ATK_ROLE_TEXT;
+}
+
+static void scintilla_object_accessible_finalize(GObject *object) {
+       ScintillaObjectAccessiblePrivate *priv = SCINTILLA_OBJECT_ACCESSIBLE_GET_PRIVATE(object);
+
+       if (priv->pscin) {
+               delete priv->pscin;
+               priv->pscin = 0;
+       }
+
+       G_OBJECT_CLASS(scintilla_object_accessible_parent_class)->finalize(object);
+}
+
+static void scintilla_object_accessible_class_init(ScintillaObjectAccessibleClass *klass) {
+       GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
+       AtkObjectClass *object_class = ATK_OBJECT_CLASS(klass);
+
+#if HAVE_WIDGET_SET_UNSET
+       GtkAccessibleClass *accessible_class = GTK_ACCESSIBLE_CLASS(klass);
+       accessible_class->widget_set = scintilla_object_accessible_widget_set;
+       accessible_class->widget_unset = scintilla_object_accessible_widget_unset;
+#endif
+
+       object_class->ref_state_set = scintilla_object_accessible_ref_state_set;
+       object_class->initialize = scintilla_object_accessible_initialize;
+
+       gobject_class->finalize = scintilla_object_accessible_finalize;
+
+       scintilla_object_accessible_parent_class = g_type_class_peek_parent(klass);
+
+       g_type_class_add_private(klass, sizeof (ScintillaObjectAccessiblePrivate));
+}
+
+static void scintilla_object_accessible_init(ScintillaObjectAccessible *accessible) {
+       ScintillaObjectAccessiblePrivate *priv = SCINTILLA_OBJECT_ACCESSIBLE_GET_PRIVATE(accessible);
+
+       priv->pscin = 0;
+}
+
+#if HAVE_GTK_FACTORY
+// Object factory
+typedef AtkObjectFactory ScintillaObjectAccessibleFactory;
+typedef AtkObjectFactoryClass ScintillaObjectAccessibleFactoryClass;
+
+G_DEFINE_TYPE(ScintillaObjectAccessibleFactory, scintilla_object_accessible_factory, ATK_TYPE_OBJECT_FACTORY)
+
+static void scintilla_object_accessible_factory_init(ScintillaObjectAccessibleFactory *) {
+}
+
+static GType scintilla_object_accessible_factory_get_accessible_type(void) {
+       return SCINTILLA_TYPE_OBJECT_ACCESSIBLE;
+}
+
+static AtkObject *scintilla_object_accessible_factory_create_accessible(GObject *obj) {
+       return scintilla_object_accessible_new(0, obj);
+}
+
+static void scintilla_object_accessible_factory_class_init(AtkObjectFactoryClass * klass) {
+       klass->create_accessible = scintilla_object_accessible_factory_create_accessible;
+       klass->get_accessible_type = scintilla_object_accessible_factory_get_accessible_type;
+}
+#endif
diff --git a/plugins/scintilla/scintilla/gtk/ScintillaGTKAccessible.h 
b/plugins/scintilla/scintilla/gtk/ScintillaGTKAccessible.h
new file mode 100644
index 0000000..bb47ddf
--- /dev/null
+++ b/plugins/scintilla/scintilla/gtk/ScintillaGTKAccessible.h
@@ -0,0 +1,196 @@
+/* Scintilla source code edit control */
+/* ScintillaGTKAccessible.h - GTK+ accessibility for ScintillaGTK */
+/* Copyright 2016 by Colomban Wendling <colomban geany org>
+ * The License.txt file describes the conditions under which this software may be distributed. */
+
+#ifndef SCINTILLAGTKACCESSIBLE_H
+#define SCINTILLAGTKACCESSIBLE_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+#ifndef ATK_CHECK_VERSION
+# define ATK_CHECK_VERSION(x, y, z) 0
+#endif
+
+class ScintillaGTKAccessible {
+private:
+       // weak references to related objects
+       GtkAccessible *accessible;
+       ScintillaGTK *sci;
+
+       // cache holding character offset for each line start, see CharacterOffsetFromByteOffset()
+       std::vector<Sci::Position> character_offsets;
+
+       // cached length of the deletion, in characters (see Notify())
+       int deletionLengthChar;
+       // local state for comparing
+       Sci::Position old_pos;
+       std::vector<SelectionRange> old_sels;
+
+       bool Enabled() const;
+       void UpdateCursor();
+       void Notify(GtkWidget *widget, gint code, SCNotification *nt);
+       static void SciNotify(GtkWidget *widget, gint code, SCNotification *nt, gpointer data) {
+               try {
+                       reinterpret_cast<ScintillaGTKAccessible*>(data)->Notify(widget, code, nt);
+               } catch (...) {}
+       }
+
+       Sci::Position ByteOffsetFromCharacterOffset(Sci::Position startByte, int characterOffset) {
+               Sci::Position pos = sci->pdoc->GetRelativePosition(startByte, characterOffset);
+               if (pos == INVALID_POSITION) {
+                       // clamp invalid positions inside the document
+                       if (characterOffset > 0) {
+                               return sci->pdoc->Length();
+                       } else {
+                               return 0;
+                       }
+               }
+               return pos;
+       }
+
+       Sci::Position ByteOffsetFromCharacterOffset(Sci::Position characterOffset) {
+               return ByteOffsetFromCharacterOffset(0, characterOffset);
+       }
+
+       Sci::Position CharacterOffsetFromByteOffset(Sci::Position byteOffset) {
+               const Sci::Line line = sci->pdoc->LineFromPosition(byteOffset);
+               if (character_offsets.size() <= static_cast<size_t>(line)) {
+                       if (character_offsets.empty())
+                               character_offsets.push_back(0);
+                       for (Sci::Position i = character_offsets.size(); i <= line; i++) {
+                               const Sci::Position start = sci->pdoc->LineStart(i - 1);
+                               const Sci::Position end = sci->pdoc->LineStart(i);
+                               character_offsets.push_back(character_offsets[i - 1] + 
sci->pdoc->CountCharacters(start, end));
+                       }
+               }
+               const Sci::Position lineStart = sci->pdoc->LineStart(line);
+               return character_offsets[line] + sci->pdoc->CountCharacters(lineStart, byteOffset);
+       }
+
+       void CharacterRangeFromByteRange(Sci::Position startByte, Sci::Position endByte, int *startChar, int 
*endChar) {
+               *startChar = CharacterOffsetFromByteOffset(startByte);
+               *endChar = *startChar + sci->pdoc->CountCharacters(startByte, endByte);
+       }
+
+       void ByteRangeFromCharacterRange(int startChar, int endChar, Sci::Position& startByte, Sci::Position& 
endByte) {
+               startByte = ByteOffsetFromCharacterOffset(startChar);
+               endByte = ByteOffsetFromCharacterOffset(startByte, endChar - startChar);
+       }
+
+       Sci::Position PositionBefore(Sci::Position pos) {
+               return sci->pdoc->MovePositionOutsideChar(pos - 1, -1, true);
+       }
+
+       Sci::Position PositionAfter(Sci::Position pos) {
+               return sci->pdoc->MovePositionOutsideChar(pos + 1, 1, true);
+       }
+
+       int StyleAt(Sci::Position position, bool ensureStyle = false) {
+               if (ensureStyle)
+                       sci->pdoc->EnsureStyledTo(position);
+               return sci->pdoc->StyleAt(position);
+       }
+
+       // For AtkText
+       gchar *GetTextRangeUTF8(Sci::Position startByte, Sci::Position endByte);
+       gchar *GetText(int startChar, int endChar);
+       gchar *GetTextAfterOffset(int charOffset, AtkTextBoundary boundaryType, int *startChar, int *endChar);
+       gchar *GetTextBeforeOffset(int charOffset, AtkTextBoundary boundaryType, int *startChar, int 
*endChar);
+       gchar *GetTextAtOffset(int charOffset, AtkTextBoundary boundaryType, int *startChar, int *endChar);
+#if ATK_CHECK_VERSION(2, 10, 0)
+       gchar *GetStringAtOffset(int charOffset, AtkTextGranularity granularity, int *startChar, int 
*endChar);
+#endif
+       gunichar GetCharacterAtOffset(int charOffset);
+       gint GetCharacterCount();
+       gint GetCaretOffset();
+       gboolean SetCaretOffset(int charOffset);
+       gint GetOffsetAtPoint(gint x, gint y, AtkCoordType coords);
+       void GetCharacterExtents(int charOffset, gint *x, gint *y, gint *width, gint *height, AtkCoordType 
coords);
+       AtkAttributeSet *GetAttributesForStyle(unsigned int styleNum);
+       AtkAttributeSet *GetRunAttributes(int charOffset, int *startChar, int *endChar);
+       AtkAttributeSet *GetDefaultAttributes();
+       gint GetNSelections();
+       gchar *GetSelection(gint selection_num, int *startChar, int *endChar);
+       gboolean AddSelection(int startChar, int endChar);
+       gboolean RemoveSelection(int selection_num);
+       gboolean SetSelection(gint selection_num, int startChar, int endChar);
+       // for AtkEditableText
+       bool InsertStringUTF8(Sci::Position bytePos, const gchar *utf8, Sci::Position lengthBytes);
+       void SetTextContents(const gchar *contents);
+       void InsertText(const gchar *text, int lengthBytes, int *charPosition);
+       void CopyText(int startChar, int endChar);
+       void CutText(int startChar, int endChar);
+       void DeleteText(int startChar, int endChar);
+       void PasteText(int charPosition);
+
+public:
+       ScintillaGTKAccessible(GtkAccessible *accessible_, GtkWidget *widget_);
+       ~ScintillaGTKAccessible();
+
+       static ScintillaGTKAccessible *FromAccessible(GtkAccessible *accessible);
+       static ScintillaGTKAccessible *FromAccessible(AtkObject *accessible) {
+               return FromAccessible(GTK_ACCESSIBLE(accessible));
+       }
+       // So ScintillaGTK can notify us
+       void ChangeDocument(Document *oldDoc, Document *newDoc);
+       void NotifyReadOnly();
+       void SetAccessibility();
+
+       // Helper GtkWidget methods
+       static AtkObject *WidgetGetAccessibleImpl(GtkWidget *widget, AtkObject **cache, gpointer 
widget_parent_class);
+
+       // ATK methods
+
+       class AtkTextIface {
+       public:
+               static void init(::AtkTextIface *iface);
+
+       private:
+               AtkTextIface();
+
+               static gchar *GetText(AtkText *text, int start_offset, int end_offset);
+               static gchar *GetTextAfterOffset(AtkText *text, int offset, AtkTextBoundary boundary_type, 
int *start_offset, int *end_offset);
+               static gchar *GetTextBeforeOffset(AtkText *text, int offset, AtkTextBoundary boundary_type, 
int *start_offset, int *end_offset);
+               static gchar *GetTextAtOffset(AtkText *text, gint offset, AtkTextBoundary boundary_type, gint 
*start_offset, gint *end_offset);
+#if ATK_CHECK_VERSION(2, 10, 0)
+               static gchar *GetStringAtOffset(AtkText *text, gint offset, AtkTextGranularity granularity, 
gint *start_offset, gint *end_offset);
+#endif
+               static gunichar GetCharacterAtOffset(AtkText *text, gint offset);
+               static gint GetCharacterCount(AtkText *text);
+               static gint GetCaretOffset(AtkText *text);
+               static gboolean SetCaretOffset(AtkText *text, gint offset);
+               static gint GetOffsetAtPoint(AtkText *text, gint x, gint y, AtkCoordType coords);
+               static void GetCharacterExtents(AtkText *text, gint offset, gint *x, gint *y, gint *width, 
gint *height, AtkCoordType coords);
+               static AtkAttributeSet *GetRunAttributes(AtkText *text, gint offset, gint *start_offset, gint 
*end_offset);
+               static AtkAttributeSet *GetDefaultAttributes(AtkText *text);
+               static gint GetNSelections(AtkText *text);
+               static gchar *GetSelection(AtkText *text, gint selection_num, gint *start_pos, gint *end_pos);
+               static gboolean AddSelection(AtkText *text, gint start, gint end);
+               static gboolean RemoveSelection(AtkText *text, gint selection_num);
+               static gboolean SetSelection(AtkText *text, gint selection_num, gint start, gint end);
+       };
+       class AtkEditableTextIface {
+       public:
+               static void init(::AtkEditableTextIface *iface);
+
+       private:
+               AtkEditableTextIface();
+
+               static void SetTextContents(AtkEditableText *text, const gchar *contents);
+               static void InsertText(AtkEditableText *text, const gchar *contents, gint length, gint 
*position);
+               static void CopyText(AtkEditableText *text, gint start, gint end);
+               static void CutText(AtkEditableText *text, gint start, gint end);
+               static void DeleteText(AtkEditableText *text, gint start, gint end);
+               static void PasteText(AtkEditableText *text, gint position);
+       };
+};
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+
+#endif /* SCINTILLAGTKACCESSIBLE_H */
diff --git a/plugins/scintilla/scintilla/gtk/scintilla-marshal.list 
b/plugins/scintilla/scintilla/gtk/scintilla-marshal.list
index e5750ec..ddc8ae8 100644
--- a/plugins/scintilla/scintilla/gtk/scintilla-marshal.list
+++ b/plugins/scintilla/scintilla/gtk/scintilla-marshal.list
@@ -1 +1,2 @@
-NONE:INT,POINTER
+NONE:INT,OBJECT
+NONE:INT,BOXED
diff --git a/plugins/scintilla/scintilla/include/ILexer.h b/plugins/scintilla/scintilla/include/ILexer.h
index e93de81..f010291 100644
--- a/plugins/scintilla/scintilla/include/ILexer.h
+++ b/plugins/scintilla/scintilla/include/ILexer.h
@@ -8,6 +8,8 @@
 #ifndef ILEXER_H
 #define ILEXER_H
 
+#include "Sci_Position.h"
+
 #ifdef SCI_NAMESPACE
 namespace Scintilla {
 #endif
@@ -24,32 +26,32 @@ class IDocument {
 public:
        virtual int SCI_METHOD Version() const = 0;
        virtual void SCI_METHOD SetErrorStatus(int status) = 0;
-       virtual int SCI_METHOD Length() const = 0;
-       virtual void SCI_METHOD GetCharRange(char *buffer, int position, int lengthRetrieve) const = 0;
-       virtual char SCI_METHOD StyleAt(int position) const = 0;
-       virtual int SCI_METHOD LineFromPosition(int position) const = 0;
-       virtual int SCI_METHOD LineStart(int line) const = 0;
-       virtual int SCI_METHOD GetLevel(int line) const = 0;
-       virtual int SCI_METHOD SetLevel(int line, int level) = 0;
-       virtual int SCI_METHOD GetLineState(int line) const = 0;
-       virtual int SCI_METHOD SetLineState(int line, int state) = 0;
-       virtual void SCI_METHOD StartStyling(int position, char mask) = 0;
-       virtual bool SCI_METHOD SetStyleFor(int length, char style) = 0;
-       virtual bool SCI_METHOD SetStyles(int length, const char *styles) = 0;
+       virtual Sci_Position SCI_METHOD Length() const = 0;
+       virtual void SCI_METHOD GetCharRange(char *buffer, Sci_Position position, Sci_Position 
lengthRetrieve) const = 0;
+       virtual char SCI_METHOD StyleAt(Sci_Position position) const = 0;
+       virtual Sci_Position SCI_METHOD LineFromPosition(Sci_Position position) const = 0;
+       virtual Sci_Position SCI_METHOD LineStart(Sci_Position line) const = 0;
+       virtual int SCI_METHOD GetLevel(Sci_Position line) const = 0;
+       virtual int SCI_METHOD SetLevel(Sci_Position line, int level) = 0;
+       virtual int SCI_METHOD GetLineState(Sci_Position line) const = 0;
+       virtual int SCI_METHOD SetLineState(Sci_Position line, int state) = 0;
+       virtual void SCI_METHOD StartStyling(Sci_Position position, char mask) = 0;
+       virtual bool SCI_METHOD SetStyleFor(Sci_Position length, char style) = 0;
+       virtual bool SCI_METHOD SetStyles(Sci_Position length, const char *styles) = 0;
        virtual void SCI_METHOD DecorationSetCurrentIndicator(int indicator) = 0;
-       virtual void SCI_METHOD DecorationFillRange(int position, int value, int fillLength) = 0;
-       virtual void SCI_METHOD ChangeLexerState(int start, int end) = 0;
+       virtual void SCI_METHOD DecorationFillRange(Sci_Position position, int value, Sci_Position 
fillLength) = 0;
+       virtual void SCI_METHOD ChangeLexerState(Sci_Position start, Sci_Position end) = 0;
        virtual int SCI_METHOD CodePage() const = 0;
        virtual bool SCI_METHOD IsDBCSLeadByte(char ch) const = 0;
        virtual const char * SCI_METHOD BufferPointer() = 0;
-       virtual int SCI_METHOD GetLineIndentation(int line) = 0;
+       virtual int SCI_METHOD GetLineIndentation(Sci_Position line) = 0;
 };
 
 class IDocumentWithLineEnd : public IDocument {
 public:
-       virtual int SCI_METHOD LineEnd(int line) const = 0;
-       virtual int SCI_METHOD GetRelativePosition(int positionStart, int characterOffset) const = 0;
-       virtual int SCI_METHOD GetCharacterAndWidth(int position, int *pWidth) const = 0;
+       virtual Sci_Position SCI_METHOD LineEnd(Sci_Position line) const = 0;
+       virtual Sci_Position SCI_METHOD GetRelativePosition(Sci_Position positionStart, Sci_Position 
characterOffset) const = 0;
+       virtual int SCI_METHOD GetCharacterAndWidth(Sci_Position position, Sci_Position *pWidth) const = 0;
 };
 
 enum { lvOriginal=0, lvSubStyles=1 };
@@ -61,11 +63,11 @@ public:
        virtual const char * SCI_METHOD PropertyNames() = 0;
        virtual int SCI_METHOD PropertyType(const char *name) = 0;
        virtual const char * SCI_METHOD DescribeProperty(const char *name) = 0;
-       virtual int SCI_METHOD PropertySet(const char *key, const char *val) = 0;
+       virtual Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) = 0;
        virtual const char * SCI_METHOD DescribeWordListSets() = 0;
-       virtual int SCI_METHOD WordListSet(int n, const char *wl) = 0;
-       virtual void SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess) 
= 0;
-       virtual void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess) 
= 0;
+       virtual Sci_Position SCI_METHOD WordListSet(int n, const char *wl) = 0;
+       virtual void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) = 0;
+       virtual void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) = 0;
        virtual void * SCI_METHOD PrivateCall(int operation, void *pointer) = 0;
 };
 
@@ -75,6 +77,8 @@ public:
        virtual int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) = 0;
        virtual int SCI_METHOD SubStylesStart(int styleBase) = 0;
        virtual int SCI_METHOD SubStylesLength(int styleBase) = 0;
+       virtual int SCI_METHOD StyleFromSubStyle(int subStyle) = 0;
+       virtual int SCI_METHOD PrimaryStyleFromStyle(int style) = 0;
        virtual void SCI_METHOD FreeSubStyles() = 0;
        virtual void SCI_METHOD SetIdentifiers(int style, const char *identifiers) = 0;
        virtual int SCI_METHOD DistanceToSecondaryStyles() = 0;
@@ -85,7 +89,7 @@ class ILoader {
 public:
        virtual int SCI_METHOD Release() = 0;
        // Returns a status code from SC_STATUS_*
-       virtual int SCI_METHOD AddData(char *data, int length) = 0;
+       virtual int SCI_METHOD AddData(char *data, Sci_Position length) = 0;
        virtual void * SCI_METHOD ConvertToDocument() = 0;
 };
 
diff --git a/plugins/scintilla/scintilla/include/Platform.h b/plugins/scintilla/scintilla/include/Platform.h
index 311b1c4..570ba73 100644
--- a/plugins/scintilla/scintilla/include/Platform.h
+++ b/plugins/scintilla/scintilla/include/Platform.h
@@ -77,7 +77,9 @@ namespace Scintilla {
 
 typedef float XYPOSITION;
 typedef double XYACCUMULATOR;
-//#define XYPOSITION int
+inline int RoundXYPosition(XYPOSITION xyPos) {
+       return static_cast<int>(xyPos + 0.5);
+}
 
 // Underlying the implementation of the platform classes are platform specific types.
 // Sometimes these need to be passed around by client code so they are defined here
@@ -92,7 +94,7 @@ typedef void *IdlerID;
 
 /**
  * A geometric point class.
- * Point is exactly the same as the Win32 POINT and GTK+ GdkPoint so can be used interchangeably.
+ * Point is similar to the Win32 POINT and GTK+ GdkPoint types.
  */
 class Point {
 public:
@@ -102,6 +104,10 @@ public:
        explicit Point(XYPOSITION x_=0, XYPOSITION y_=0) : x(x_), y(y_) {
        }
 
+       static Point FromInts(int x_, int y_) {
+               return Point(static_cast<XYPOSITION>(x_), static_cast<XYPOSITION>(y_));
+       }
+
        // Other automatically defined methods (assignment, copy constructor, destructor) are fine
 
        static Point FromLong(long lpoint);
@@ -109,7 +115,7 @@ public:
 
 /**
  * A geometric rectangle class.
- * PRectangle is exactly the same as the Win32 RECT so can be used interchangeably.
+ * PRectangle is similar to the Win32 RECT.
  * PRectangles contain their top and left sides, but not their right and bottom sides.
  */
 class PRectangle {
@@ -119,13 +125,18 @@ public:
        XYPOSITION right;
        XYPOSITION bottom;
 
-       PRectangle(XYPOSITION left_=0, XYPOSITION top_=0, XYPOSITION right_=0, XYPOSITION bottom_ = 0) :
+       explicit PRectangle(XYPOSITION left_=0, XYPOSITION top_=0, XYPOSITION right_=0, XYPOSITION bottom_ = 
0) :
                left(left_), top(top_), right(right_), bottom(bottom_) {
        }
 
+       static PRectangle FromInts(int left_, int top_, int right_, int bottom_) {
+               return PRectangle(static_cast<XYPOSITION>(left_), static_cast<XYPOSITION>(top_),
+                       static_cast<XYPOSITION>(right_), static_cast<XYPOSITION>(bottom_));
+       }
+
        // Other automatically defined methods (assignment, copy constructor, destructor) are fine
 
-       bool operator==(PRectangle &rc) const {
+       bool operator==(const PRectangle &rc) const {
                return (rc.left == left) && (rc.right == right) &&
                        (rc.top == top) && (rc.bottom == bottom);
        }
@@ -133,6 +144,11 @@ public:
                return (pt.x >= left) && (pt.x <= right) &&
                        (pt.y >= top) && (pt.y <= bottom);
        }
+       bool ContainsWholePixel(Point pt) const {
+               // Does the rectangle contain all of the pixel to left/below the point
+               return (pt.x >= left) && ((pt.x+1) <= right) &&
+                       (pt.y >= top) && ((pt.y+1) <= bottom);
+       }
        bool Contains(PRectangle rc) const {
                return (rc.left >= left) && (rc.right <= right) &&
                        (rc.top >= top) && (rc.bottom <= bottom);
@@ -255,9 +271,6 @@ struct FontParameters {
 class Font {
 protected:
        FontID fid;
-#if PLAT_WX
-       int ascent;
-#endif
        // Private so Font objects can not be copied
        Font(const Font &);
        Font &operator=(const Font &);
@@ -271,9 +284,6 @@ public:
        FontID GetID() { return fid; }
        // Alias another font - caller guarantees not to Release
        void SetID(FontID fid_) { fid = fid_; }
-#if PLAT_WX
-       void SetAscent(int ascent_) { ascent = ascent_; }
-#endif
        friend class Surface;
        friend class SurfaceImpl;
 };
@@ -345,26 +355,22 @@ typedef void (*CallBackAction)(void*);
 class Window {
 protected:
        WindowID wid;
-#if PLAT_MACOSX
-       void *windowRef;
-       void *control;
-#endif
 public:
        Window() : wid(0), cursorLast(cursorInvalid) {
-#if PLAT_MACOSX
-         windowRef = 0;
-         control = 0;
-#endif
        }
        Window(const Window &source) : wid(source.wid), cursorLast(cursorInvalid) {
-#if PLAT_MACOSX
-         windowRef = 0;
-         control = 0;
-#endif
        }
        virtual ~Window();
        Window &operator=(WindowID wid_) {
                wid = wid_;
+               cursorLast = cursorInvalid;
+               return *this;
+       }
+       Window &operator=(const Window &other) {
+               if (this != &other) {
+                       wid = other.wid;
+                       cursorLast = other.cursorLast;
+               }
                return *this;
        }
        WindowID GetID() const { return wid; }
@@ -383,10 +389,6 @@ public:
        void SetCursor(Cursor curs);
        void SetTitle(const char *s);
        PRectangle GetMonitorRect(Point pt);
-#if PLAT_MACOSX
-       void SetWindow(void *ref) { windowRef = ref; }
-       void SetControl(void *_control) { control = _control; }
-#endif
 private:
        Cursor cursorLast;
 };
@@ -460,6 +462,16 @@ public:
        static DynamicLibrary *Load(const char *modulePath);
 };
 
+#if defined(__clang__)
+# if __has_feature(attribute_analyzer_noreturn)
+#  define CLANG_ANALYZER_NORETURN __attribute__((analyzer_noreturn))
+# else
+#  define CLANG_ANALYZER_NORETURN
+# endif
+#else
+# define CLANG_ANALYZER_NORETURN
+#endif
+
 /**
  * Platform class used to retrieve system wide parameters such as double click speed
  * and chrome colour. Not a creatable object, more of a module with several functions.
@@ -504,7 +516,7 @@ public:
        }
        static void DebugPrintf(const char *format, ...);
        static bool ShowAssertionPopUps(bool assertionPopUps_);
-       static void Assert(const char *c, const char *file, int line);
+       static void Assert(const char *c, const char *file, int line) CLANG_ANALYZER_NORETURN;
        static int Clamp(int val, int minVal, int maxVal);
 };
 
@@ -522,15 +534,4 @@ public:
 }
 #endif
 
-// Shut up annoying Visual C++ warnings:
-#ifdef _MSC_VER
-#pragma warning(disable: 4244 4309 4514 4710)
-#endif
-
-#if defined(__GNUC__) && defined(SCINTILLA_QT)
-#pragma GCC diagnostic ignored "-Wmissing-braces"
-#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
-#pragma GCC diagnostic ignored "-Wchar-subscripts"
-#endif
-
 #endif
diff --git a/plugins/scintilla/scintilla/include/SciLexer.h b/plugins/scintilla/scintilla/include/SciLexer.h
index 18cdb98..cc5139e 100644
--- a/plugins/scintilla/scintilla/include/SciLexer.h
+++ b/plugins/scintilla/scintilla/include/SciLexer.h
@@ -122,6 +122,19 @@
 #define SCLEX_VISUALPROLOG 107
 #define SCLEX_LITERATEHASKELL 108
 #define SCLEX_STTXT 109
+#define SCLEX_KVIRC 110
+#define SCLEX_RUST 111
+#define SCLEX_DMAP 112
+#define SCLEX_AS 113
+#define SCLEX_DMIS 114
+#define SCLEX_REGISTRY 115
+#define SCLEX_BIBTEX 116
+#define SCLEX_SREC 117
+#define SCLEX_IHEX 118
+#define SCLEX_TEHEX 119
+#define SCLEX_JSON 120
+#define SCLEX_EDIFACT 121
+#define SCLEX_INDENT 122
 #define SCLEX_AUTOMATIC 1000
 #define SCE_P_DEFAULT 0
 #define SCE_P_COMMENTLINE 1
@@ -139,6 +152,10 @@
 #define SCE_P_STRINGEOL 13
 #define SCE_P_WORD2 14
 #define SCE_P_DECORATOR 15
+#define SCE_P_FSTRING 16
+#define SCE_P_FCHARACTER 17
+#define SCE_P_FTRIPLE 18
+#define SCE_P_FTRIPLEDOUBLE 19
 #define SCE_C_DEFAULT 0
 #define SCE_C_COMMENT 1
 #define SCE_C_COMMENTLINE 2
@@ -164,6 +181,9 @@
 #define SCE_C_HASHQUOTEDSTRING 22
 #define SCE_C_PREPROCESSORCOMMENT 23
 #define SCE_C_PREPROCESSORCOMMENTDOC 24
+#define SCE_C_USERLITERAL 25
+#define SCE_C_TASKMARKER 26
+#define SCE_C_ESCAPESEQUENCE 27
 #define SCE_D_DEFAULT 0
 #define SCE_D_COMMENT 1
 #define SCE_D_COMMENTLINE 2
@@ -418,6 +438,10 @@
 #define SCE_B_ERROR 16
 #define SCE_B_HEXNUMBER 17
 #define SCE_B_BINNUMBER 18
+#define SCE_B_COMMENTBLOCK 19
+#define SCE_B_DOCLINE 20
+#define SCE_B_DOCBLOCK 21
+#define SCE_B_DOCKEYWORD 22
 #define SCE_PROPS_DEFAULT 0
 #define SCE_PROPS_COMMENT 1
 #define SCE_PROPS_SECTION 2
@@ -481,6 +505,24 @@
 #define SCE_ERR_JAVA_STACK 20
 #define SCE_ERR_VALUE 21
 #define SCE_ERR_GCC_INCLUDED_FROM 22
+#define SCE_ERR_ESCSEQ 23
+#define SCE_ERR_ESCSEQ_UNKNOWN 24
+#define SCE_ERR_ES_BLACK 40
+#define SCE_ERR_ES_RED 41
+#define SCE_ERR_ES_GREEN 42
+#define SCE_ERR_ES_BROWN 43
+#define SCE_ERR_ES_BLUE 44
+#define SCE_ERR_ES_MAGENTA 45
+#define SCE_ERR_ES_CYAN 46
+#define SCE_ERR_ES_GRAY 47
+#define SCE_ERR_ES_DARK_GRAY 48
+#define SCE_ERR_ES_BRIGHT_RED 49
+#define SCE_ERR_ES_BRIGHT_GREEN 50
+#define SCE_ERR_ES_YELLOW 51
+#define SCE_ERR_ES_BRIGHT_BLUE 52
+#define SCE_ERR_ES_BRIGHT_MAGENTA 53
+#define SCE_ERR_ES_BRIGHT_CYAN 54
+#define SCE_ERR_ES_WHITE 55
 #define SCE_BAT_DEFAULT 0
 #define SCE_BAT_COMMENT 1
 #define SCE_BAT_WORD 2
@@ -563,6 +605,20 @@
 #define SCE_BAAN_IDENTIFIER 8
 #define SCE_BAAN_STRINGEOL 9
 #define SCE_BAAN_WORD2 10
+#define SCE_BAAN_WORD3 11
+#define SCE_BAAN_WORD4 12
+#define SCE_BAAN_WORD5 13
+#define SCE_BAAN_WORD6 14
+#define SCE_BAAN_WORD7 15
+#define SCE_BAAN_WORD8 16
+#define SCE_BAAN_WORD9 17
+#define SCE_BAAN_TABLEDEF 18
+#define SCE_BAAN_TABLESQL 19
+#define SCE_BAAN_FUNCTION 20
+#define SCE_BAAN_DOMDEF 21
+#define SCE_BAAN_FUNCDEF 22
+#define SCE_BAAN_OBJECTDEF 23
+#define SCE_BAAN_DEFINEDEF 24
 #define SCE_LISP_DEFAULT 0
 #define SCE_LISP_COMMENT 1
 #define SCE_LISP_NUMBER 2
@@ -884,6 +940,11 @@
 #define SCE_V_IDENTIFIER 11
 #define SCE_V_STRINGEOL 12
 #define SCE_V_USER 19
+#define SCE_V_COMMENT_WORD 20
+#define SCE_V_INPUT 21
+#define SCE_V_OUTPUT 22
+#define SCE_V_INOUT 23
+#define SCE_V_PORT_CONNECT 24
 #define SCE_KIX_DEFAULT 0
 #define SCE_KIX_COMMENT 1
 #define SCE_KIX_STRING1 2
@@ -894,6 +955,7 @@
 #define SCE_KIX_KEYWORD 7
 #define SCE_KIX_FUNCTIONS 8
 #define SCE_KIX_OPERATOR 9
+#define SCE_KIX_COMMENTSTREAM 10
 #define SCE_KIX_IDENTIFIER 31
 #define SCE_GC_DEFAULT 0
 #define SCE_GC_COMMENTLINE 1
@@ -990,6 +1052,7 @@
 #define SCE_VHDL_STDPACKAGE 12
 #define SCE_VHDL_STDTYPE 13
 #define SCE_VHDL_USERWORD 14
+#define SCE_VHDL_BLOCK_COMMENT 15
 #define SCE_CAML_DEFAULT 0
 #define SCE_CAML_IDENTIFIER 1
 #define SCE_CAML_TAGNAME 2
@@ -1101,6 +1164,7 @@
 #define SCE_SQL_USER3 21
 #define SCE_SQL_USER4 22
 #define SCE_SQL_QUOTEDIDENTIFIER 23
+#define SCE_SQL_QOPERATOR 24
 #define SCE_ST_DEFAULT 0
 #define SCE_ST_STRING 1
 #define SCE_ST_NUMBER 2
@@ -1233,38 +1297,19 @@
 #define SCE_PLM_OPERATOR 5
 #define SCE_PLM_CONTROL 6
 #define SCE_PLM_KEYWORD 7
-#define SCE_4GL_DEFAULT 0
-#define SCE_4GL_NUMBER 1
-#define SCE_4GL_WORD 2
-#define SCE_4GL_STRING 3
-#define SCE_4GL_CHARACTER 4
-#define SCE_4GL_PREPROCESSOR 5
-#define SCE_4GL_OPERATOR 6
-#define SCE_4GL_IDENTIFIER 7
-#define SCE_4GL_BLOCK 8
-#define SCE_4GL_END 9
-#define SCE_4GL_COMMENT1 10
-#define SCE_4GL_COMMENT2 11
-#define SCE_4GL_COMMENT3 12
-#define SCE_4GL_COMMENT4 13
-#define SCE_4GL_COMMENT5 14
-#define SCE_4GL_COMMENT6 15
-#define SCE_4GL_DEFAULT_ 16
-#define SCE_4GL_NUMBER_ 17
-#define SCE_4GL_WORD_ 18
-#define SCE_4GL_STRING_ 19
-#define SCE_4GL_CHARACTER_ 20
-#define SCE_4GL_PREPROCESSOR_ 21
-#define SCE_4GL_OPERATOR_ 22
-#define SCE_4GL_IDENTIFIER_ 23
-#define SCE_4GL_BLOCK_ 24
-#define SCE_4GL_END_ 25
-#define SCE_4GL_COMMENT1_ 26
-#define SCE_4GL_COMMENT2_ 27
-#define SCE_4GL_COMMENT3_ 28
-#define SCE_4GL_COMMENT4_ 29
-#define SCE_4GL_COMMENT5_ 30
-#define SCE_4GL_COMMENT6_ 31
+#define SCE_ABL_DEFAULT 0
+#define SCE_ABL_NUMBER 1
+#define SCE_ABL_WORD 2
+#define SCE_ABL_STRING 3
+#define SCE_ABL_CHARACTER 4
+#define SCE_ABL_PREPROCESSOR 5
+#define SCE_ABL_OPERATOR 6
+#define SCE_ABL_IDENTIFIER 7
+#define SCE_ABL_BLOCK 8
+#define SCE_ABL_END 9
+#define SCE_ABL_COMMENT 10
+#define SCE_ABL_TASKMARKER 11
+#define SCE_ABL_LINECOMMENT 12
 #define SCE_ABAQUS_DEFAULT 0
 #define SCE_ABAQUS_COMMENT 1
 #define SCE_ABAQUS_COMMENTBLOCK 2
@@ -1539,10 +1584,10 @@
 #define SCE_COFFEESCRIPT_GLOBALCLASS 19
 #define SCE_COFFEESCRIPT_STRINGRAW 20
 #define SCE_COFFEESCRIPT_TRIPLEVERBATIM 21
-#define SCE_COFFEESCRIPT_HASHQUOTEDSTRING 22
 #define SCE_COFFEESCRIPT_COMMENTBLOCK 22
 #define SCE_COFFEESCRIPT_VERBOSE_REGEX 23
 #define SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT 24
+#define SCE_COFFEESCRIPT_INSTANCEPROPERTY 25
 #define SCE_AVS_DEFAULT 0
 #define SCE_AVS_COMMENTBLOCK 1
 #define SCE_AVS_COMMENTBLOCKN 2
@@ -1647,6 +1692,126 @@
 #define SCE_STTXT_DATETIME 16
 #define SCE_STTXT_VARS 17
 #define SCE_STTXT_PRAGMAS 18
+#define SCE_KVIRC_DEFAULT 0
+#define SCE_KVIRC_COMMENT 1
+#define SCE_KVIRC_COMMENTBLOCK 2
+#define SCE_KVIRC_STRING 3
+#define SCE_KVIRC_WORD 4
+#define SCE_KVIRC_KEYWORD 5
+#define SCE_KVIRC_FUNCTION_KEYWORD 6
+#define SCE_KVIRC_FUNCTION 7
+#define SCE_KVIRC_VARIABLE 8
+#define SCE_KVIRC_NUMBER 9
+#define SCE_KVIRC_OPERATOR 10
+#define SCE_KVIRC_STRING_FUNCTION 11
+#define SCE_KVIRC_STRING_VARIABLE 12
+#define SCE_RUST_DEFAULT 0
+#define SCE_RUST_COMMENTBLOCK 1
+#define SCE_RUST_COMMENTLINE 2
+#define SCE_RUST_COMMENTBLOCKDOC 3
+#define SCE_RUST_COMMENTLINEDOC 4
+#define SCE_RUST_NUMBER 5
+#define SCE_RUST_WORD 6
+#define SCE_RUST_WORD2 7
+#define SCE_RUST_WORD3 8
+#define SCE_RUST_WORD4 9
+#define SCE_RUST_WORD5 10
+#define SCE_RUST_WORD6 11
+#define SCE_RUST_WORD7 12
+#define SCE_RUST_STRING 13
+#define SCE_RUST_STRINGR 14
+#define SCE_RUST_CHARACTER 15
+#define SCE_RUST_OPERATOR 16
+#define SCE_RUST_IDENTIFIER 17
+#define SCE_RUST_LIFETIME 18
+#define SCE_RUST_MACRO 19
+#define SCE_RUST_LEXERROR 20
+#define SCE_RUST_BYTESTRING 21
+#define SCE_RUST_BYTESTRINGR 22
+#define SCE_RUST_BYTECHARACTER 23
+#define SCE_DMAP_DEFAULT 0
+#define SCE_DMAP_COMMENT 1
+#define SCE_DMAP_NUMBER 2
+#define SCE_DMAP_STRING1 3
+#define SCE_DMAP_STRING2 4
+#define SCE_DMAP_STRINGEOL 5
+#define SCE_DMAP_OPERATOR 6
+#define SCE_DMAP_IDENTIFIER 7
+#define SCE_DMAP_WORD 8
+#define SCE_DMAP_WORD2 9
+#define SCE_DMAP_WORD3 10
+#define SCE_DMIS_DEFAULT 0
+#define SCE_DMIS_COMMENT 1
+#define SCE_DMIS_STRING 2
+#define SCE_DMIS_NUMBER 3
+#define SCE_DMIS_KEYWORD 4
+#define SCE_DMIS_MAJORWORD 5
+#define SCE_DMIS_MINORWORD 6
+#define SCE_DMIS_UNSUPPORTED_MAJOR 7
+#define SCE_DMIS_UNSUPPORTED_MINOR 8
+#define SCE_DMIS_LABEL 9
+#define SCE_REG_DEFAULT 0
+#define SCE_REG_COMMENT 1
+#define SCE_REG_VALUENAME 2
+#define SCE_REG_STRING 3
+#define SCE_REG_HEXDIGIT 4
+#define SCE_REG_VALUETYPE 5
+#define SCE_REG_ADDEDKEY 6
+#define SCE_REG_DELETEDKEY 7
+#define SCE_REG_ESCAPED 8
+#define SCE_REG_KEYPATH_GUID 9
+#define SCE_REG_STRING_GUID 10
+#define SCE_REG_PARAMETER 11
+#define SCE_REG_OPERATOR 12
+#define SCE_BIBTEX_DEFAULT 0
+#define SCE_BIBTEX_ENTRY 1
+#define SCE_BIBTEX_UNKNOWN_ENTRY 2
+#define SCE_BIBTEX_KEY 3
+#define SCE_BIBTEX_PARAMETER 4
+#define SCE_BIBTEX_VALUE 5
+#define SCE_BIBTEX_COMMENT 6
+#define SCE_HEX_DEFAULT 0
+#define SCE_HEX_RECSTART 1
+#define SCE_HEX_RECTYPE 2
+#define SCE_HEX_RECTYPE_UNKNOWN 3
+#define SCE_HEX_BYTECOUNT 4
+#define SCE_HEX_BYTECOUNT_WRONG 5
+#define SCE_HEX_NOADDRESS 6
+#define SCE_HEX_DATAADDRESS 7
+#define SCE_HEX_RECCOUNT 8
+#define SCE_HEX_STARTADDRESS 9
+#define SCE_HEX_ADDRESSFIELD_UNKNOWN 10
+#define SCE_HEX_EXTENDEDADDRESS 11
+#define SCE_HEX_DATA_ODD 12
+#define SCE_HEX_DATA_EVEN 13
+#define SCE_HEX_DATA_UNKNOWN 14
+#define SCE_HEX_DATA_EMPTY 15
+#define SCE_HEX_CHECKSUM 16
+#define SCE_HEX_CHECKSUM_WRONG 17
+#define SCE_HEX_GARBAGE 18
+#define SCE_JSON_DEFAULT 0
+#define SCE_JSON_NUMBER 1
+#define SCE_JSON_STRING 2
+#define SCE_JSON_STRINGEOL 3
+#define SCE_JSON_PROPERTYNAME 4
+#define SCE_JSON_ESCAPESEQUENCE 5
+#define SCE_JSON_LINECOMMENT 6
+#define SCE_JSON_BLOCKCOMMENT 7
+#define SCE_JSON_OPERATOR 8
+#define SCE_JSON_URI 9
+#define SCE_JSON_COMPACTIRI 10
+#define SCE_JSON_KEYWORD 11
+#define SCE_JSON_LDKEYWORD 12
+#define SCE_JSON_ERROR 13
+#define SCE_EDI_DEFAULT 0
+#define SCE_EDI_SEGMENTSTART 1
+#define SCE_EDI_SEGMENTEND 2
+#define SCE_EDI_SEP_ELEMENT 3
+#define SCE_EDI_SEP_COMPOSITE 4
+#define SCE_EDI_SEP_RELEASE 5
+#define SCE_EDI_UNA 6
+#define SCE_EDI_UNH 7
+#define SCE_EDI_BADSEGMENT 8
 /* --Autogenerated -- end of section automatically generated from Scintilla.iface */
 
 #endif
diff --git a/plugins/scintilla/scintilla/include/Sci_Position.h 
b/plugins/scintilla/scintilla/include/Sci_Position.h
new file mode 100644
index 0000000..a83e286
--- /dev/null
+++ b/plugins/scintilla/scintilla/include/Sci_Position.h
@@ -0,0 +1,21 @@
+// Scintilla source code edit control
+/** @file Sci_Position.h
+ ** Define the Sci_Position type used in Scintilla's external interfaces.
+ ** These need to be available to clients written in C so are not in a C++ namespace.
+ **/
+// Copyright 2015 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef SCI_POSITION_H
+#define SCI_POSITION_H
+
+// Basic signed type used throughout interface
+typedef int Sci_Position;
+
+// Unsigned variant used for ILexer::Lex and ILexer::Fold
+typedef unsigned int Sci_PositionU;
+
+// For Sci_CharacterRange  which is defined as long to be compatible with Win32 CHARRANGE
+typedef long Sci_PositionCR;
+
+#endif
diff --git a/plugins/scintilla/scintilla/include/Scintilla.h b/plugins/scintilla/scintilla/include/Scintilla.h
index a229e4c..58643a8 100644
--- a/plugins/scintilla/scintilla/include/Scintilla.h
+++ b/plugins/scintilla/scintilla/include/Scintilla.h
@@ -18,33 +18,28 @@ extern "C" {
 #if defined(_WIN32)
 /* Return false on failure: */
 int Scintilla_RegisterClasses(void *hInstance);
-int Scintilla_ReleaseResources();
+int Scintilla_ReleaseResources(void);
 #endif
-int Scintilla_LinkLexers();
+int Scintilla_LinkLexers(void);
 
 #ifdef __cplusplus
 }
 #endif
 
-/* Here should be placed typedefs for uptr_t, an unsigned integer type large enough to
- * hold a pointer and sptr_t, a signed integer large enough to hold a pointer.
- * May need to be changed for 64 bit platforms. */
-#if defined(_WIN32)
-#include <basetsd.h>
-#endif
-#ifdef HAVE_STDINT_H
+// Include header that defines basic numeric types.
+#if defined(_MSC_VER)
+// Older releases of MSVC did not have stdint.h.
+#include <stddef.h>
+#else
 #include <stdint.h>
+#endif
+
+// Define uptr_t, an unsigned integer type large enough to hold a pointer.
 typedef uintptr_t uptr_t;
+// Define sptr_t, a signed integer large enough to hold a pointer.
 typedef intptr_t sptr_t;
-#else
-#ifdef MAXULONG_PTR
-typedef ULONG_PTR uptr_t;
-typedef LONG_PTR sptr_t;
-#else
-typedef unsigned long uptr_t;
-typedef long sptr_t;
-#endif
-#endif
+
+#include "Sci_Position.h"
 
 typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam);
 
@@ -56,6 +51,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_ADDTEXT 2001
 #define SCI_ADDSTYLEDTEXT 2002
 #define SCI_INSERTTEXT 2003
+#define SCI_CHANGEINSERTION 2672
 #define SCI_CLEARALL 2004
 #define SCI_DELETERANGE 2645
 #define SCI_CLEARDOCUMENTSTYLE 2005
@@ -76,8 +72,13 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCWS_INVISIBLE 0
 #define SCWS_VISIBLEALWAYS 1
 #define SCWS_VISIBLEAFTERINDENT 2
+#define SCWS_VISIBLEONLYININDENT 3
 #define SCI_GETVIEWWS 2020
 #define SCI_SETVIEWWS 2021
+#define SCTD_LONGARROW 0
+#define SCTD_STRIKEOUT 1
+#define SCI_GETTABDRAWMODE 2698
+#define SCI_SETTABDRAWMODE 2699
 #define SCI_POSITIONFROMPOINT 2022
 #define SCI_POSITIONFROMPOINTCLOSE 2023
 #define SCI_GOTOLINE 2024
@@ -97,8 +98,15 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SETBUFFEREDDRAW 2035
 #define SCI_SETTABWIDTH 2036
 #define SCI_GETTABWIDTH 2121
+#define SCI_CLEARTABSTOPS 2675
+#define SCI_ADDTABSTOP 2676
+#define SCI_GETNEXTTABSTOP 2677
 #define SC_CP_UTF8 65001
 #define SCI_SETCODEPAGE 2037
+#define SC_IME_WINDOWED 0
+#define SC_IME_INLINE 1
+#define SCI_GETIMEINTERACTION 2678
+#define SCI_SETIMEINTERACTION 2679
 #define MARKER_MAX 31
 #define SC_MARK_CIRCLE 0
 #define SC_MARK_ROUNDRECT 1
@@ -131,6 +139,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_MARK_AVAILABLE 28
 #define SC_MARK_UNDERLINE 29
 #define SC_MARK_RGBAIMAGE 30
+#define SC_MARK_BOOKMARK 31
 #define SC_MARK_CHARACTER 10000
 #define SC_MARKNUM_FOLDEREND 25
 #define SC_MARKNUM_FOLDEROPENMID 26
@@ -161,6 +170,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_MARGIN_FORE 3
 #define SC_MARGIN_TEXT 4
 #define SC_MARGIN_RTEXT 5
+#define SC_MARGIN_COLOUR 6
 #define SCI_SETMARGINTYPEN 2240
 #define SCI_GETMARGINTYPEN 2241
 #define SCI_SETMARGINWIDTHN 2242
@@ -171,6 +181,10 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_GETMARGINSENSITIVEN 2247
 #define SCI_SETMARGINCURSORN 2248
 #define SCI_GETMARGINCURSORN 2249
+#define SCI_SETMARGINBACKN 2250
+#define SCI_GETMARGINBACKN 2251
+#define SCI_SETMARGINS 2252
+#define SCI_GETMARGINS 2253
 #define STYLE_DEFAULT 32
 #define STYLE_LINENUMBER 33
 #define STYLE_BRACELIGHT 34
@@ -178,6 +192,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define STYLE_CONTROLCHAR 36
 #define STYLE_INDENTGUIDE 37
 #define STYLE_CALLTIP 38
+#define STYLE_FOLDDISPLAYTEXT 39
 #define STYLE_LASTPREDEFINED 39
 #define STYLE_MAX 255
 #define SC_CHARSET_ANSI 0
@@ -191,6 +206,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_CHARSET_MAC 77
 #define SC_CHARSET_OEM 255
 #define SC_CHARSET_RUSSIAN 204
+#define SC_CHARSET_OEM866 866
 #define SC_CHARSET_CYRILLIC 1251
 #define SC_CHARSET_SHIFTJIS 128
 #define SC_CHARSET_SYMBOL 2
@@ -214,6 +230,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_CASE_MIXED 0
 #define SC_CASE_UPPER 1
 #define SC_CASE_LOWER 2
+#define SC_CASE_CAMEL 3
 #define SCI_STYLEGETFORE 2481
 #define SCI_STYLEGETBACK 2482
 #define SCI_STYLEGETBOLD 2483
@@ -271,7 +288,14 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define INDIC_DOTBOX 12
 #define INDIC_SQUIGGLEPIXMAP 13
 #define INDIC_COMPOSITIONTHICK 14
-#define INDIC_MAX 31
+#define INDIC_COMPOSITIONTHIN 15
+#define INDIC_FULLBOX 16
+#define INDIC_TEXTFORE 17
+#define INDIC_POINT 18
+#define INDIC_POINTCHARACTER 19
+#define INDIC_IME 32
+#define INDIC_IME_MAX 35
+#define INDIC_MAX 35
 #define INDIC_CONTAINER 8
 #define INDIC0_MASK 0x20
 #define INDIC1_MASK 0x40
@@ -283,6 +307,15 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_INDICGETFORE 2083
 #define SCI_INDICSETUNDER 2510
 #define SCI_INDICGETUNDER 2511
+#define SCI_INDICSETHOVERSTYLE 2680
+#define SCI_INDICGETHOVERSTYLE 2681
+#define SCI_INDICSETHOVERFORE 2682
+#define SCI_INDICGETHOVERFORE 2683
+#define SC_INDICVALUEBIT 0x1000000
+#define SC_INDICVALUEMASK 0xFFFFFF
+#define SC_INDICFLAG_VALUEFORE 1
+#define SCI_INDICSETFLAGS 2684
+#define SCI_INDICGETFLAGS 2685
 #define SCI_SETWHITESPACEFORE 2084
 #define SCI_SETWHITESPACEBACK 2085
 #define SCI_SETWHITESPACESIZE 2086
@@ -296,6 +329,8 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SETCARETLINEVISIBLE 2096
 #define SCI_GETCARETLINEBACK 2097
 #define SCI_SETCARETLINEBACK 2098
+#define SCI_GETCARETLINEFRAME 2704
+#define SCI_SETCARETLINEFRAME 2705
 #define SCI_STYLESETCHANGEABLE 2099
 #define SCI_AUTOCSHOW 2100
 #define SCI_AUTOCCANCEL 2101
@@ -364,11 +399,12 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_PRINT_COLOURONWHITEDEFAULTBG 4
 #define SCI_SETPRINTCOLOURMODE 2148
 #define SCI_GETPRINTCOLOURMODE 2149
-#define SCFIND_WHOLEWORD 2
-#define SCFIND_MATCHCASE 4
+#define SCFIND_WHOLEWORD 0x2
+#define SCFIND_MATCHCASE 0x4
 #define SCFIND_WORDSTART 0x00100000
 #define SCFIND_REGEXP 0x00200000
 #define SCFIND_POSIX 0x00400000
+#define SCFIND_CXX11REGEX 0x00800000
 #define SCI_FINDTEXT 2150
 #define SCI_FORMATRANGE 2151
 #define SCI_GETFIRSTVISIBLELINE 2152
@@ -414,6 +450,10 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_GETTARGETSTART 2191
 #define SCI_SETTARGETEND 2192
 #define SCI_GETTARGETEND 2193
+#define SCI_SETTARGETRANGE 2686
+#define SCI_GETTARGETTEXT 2687
+#define SCI_TARGETFROMSELECTION 2287
+#define SCI_TARGETWHOLEDOCUMENT 2690
 #define SCI_REPLACETARGET 2194
 #define SCI_REPLACETARGETRE 2195
 #define SCI_SEARCHINTARGET 2197
@@ -423,6 +463,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_CALLTIPCANCEL 2201
 #define SCI_CALLTIPACTIVE 2202
 #define SCI_CALLTIPPOSSTART 2203
+#define SCI_CALLTIPSETPOSSTART 2214
 #define SCI_CALLTIPSETHLT 2204
 #define SCI_CALLTIPSETBACK 2205
 #define SCI_CALLTIPSETFORE 2206
@@ -447,6 +488,11 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SETFOLDEXPANDED 2229
 #define SCI_GETFOLDEXPANDED 2230
 #define SCI_TOGGLEFOLD 2231
+#define SCI_TOGGLEFOLDSHOWTEXT 2700
+#define SC_FOLDDISPLAYTEXT_HIDDEN 0
+#define SC_FOLDDISPLAYTEXT_STANDARD 1
+#define SC_FOLDDISPLAYTEXT_BOXED 2
+#define SCI_FOLDDISPLAYTEXTSETSTYLE 2701
 #define SC_FOLDACTION_CONTRACT 0
 #define SC_FOLDACTION_EXPAND 1
 #define SC_FOLDACTION_TOGGLE 2
@@ -465,6 +511,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_FOLDFLAG_LINEAFTER_EXPANDED 0x0008
 #define SC_FOLDFLAG_LINEAFTER_CONTRACTED 0x0010
 #define SC_FOLDFLAG_LEVELNUMBERS 0x0040
+#define SC_FOLDFLAG_LINESTATE 0x0080
 #define SCI_SETFOLDFLAGS 2233
 #define SCI_ENSUREVISIBLEENFORCEPOLICY 2234
 #define SCI_SETTABINDENTS 2260
@@ -476,9 +523,17 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_GETMOUSEDWELLTIME 2265
 #define SCI_WORDSTARTPOSITION 2266
 #define SCI_WORDENDPOSITION 2267
+#define SCI_ISRANGEWORD 2691
+#define SC_IDLESTYLING_NONE 0
+#define SC_IDLESTYLING_TOVISIBLE 1
+#define SC_IDLESTYLING_AFTERVISIBLE 2
+#define SC_IDLESTYLING_ALL 3
+#define SCI_SETIDLESTYLING 2692
+#define SCI_GETIDLESTYLING 2693
 #define SC_WRAP_NONE 0
 #define SC_WRAP_WORD 1
 #define SC_WRAP_CHAR 2
+#define SC_WRAP_WHITESPACE 3
 #define SCI_SETWRAPMODE 2268
 #define SCI_GETWRAPMODE 2269
 #define SC_WRAPVISUALFLAG_NONE 0x0000
@@ -518,6 +573,11 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_APPENDTEXT 2282
 #define SCI_GETTWOPHASEDRAW 2283
 #define SCI_SETTWOPHASEDRAW 2284
+#define SC_PHASES_ONE 0
+#define SC_PHASES_TWO 1
+#define SC_PHASES_MULTIPLE 2
+#define SCI_GETPHASESDRAW 2673
+#define SCI_SETPHASESDRAW 2674
 #define SC_EFF_QUALITY_MASK 0xF
 #define SC_EFF_QUALITY_DEFAULT 0
 #define SC_EFF_QUALITY_NON_ANTIALIASED 1
@@ -531,11 +591,14 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SETMULTIPASTE 2614
 #define SCI_GETMULTIPASTE 2615
 #define SCI_GETTAG 2616
-#define SCI_TARGETFROMSELECTION 2287
 #define SCI_LINESJOIN 2288
 #define SCI_LINESSPLIT 2289
 #define SCI_SETFOLDMARGINCOLOUR 2290
 #define SCI_SETFOLDMARGINHICOLOUR 2291
+#define SC_ACCESSIBILITY_DISABLED 0
+#define SC_ACCESSIBILITY_ENABLED 1
+#define SCI_SETACCESSIBILITY 2702
+#define SCI_GETACCESSIBILITY 2703
 #define SCI_LINEDOWN 2300
 #define SCI_LINEDOWNEXTEND 2301
 #define SCI_LINEUP 2302
@@ -577,6 +640,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_LINECUT 2337
 #define SCI_LINEDELETE 2338
 #define SCI_LINETRANSPOSE 2339
+#define SCI_LINEREVERSE 2354
 #define SCI_LINEDUPLICATE 2404
 #define SCI_LOWERCASE 2340
 #define SCI_UPPERCASE 2341
@@ -609,16 +673,22 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define EDGE_NONE 0
 #define EDGE_LINE 1
 #define EDGE_BACKGROUND 2
+#define EDGE_MULTILINE 3
 #define SCI_GETEDGECOLUMN 2360
 #define SCI_SETEDGECOLUMN 2361
 #define SCI_GETEDGEMODE 2362
 #define SCI_SETEDGEMODE 2363
 #define SCI_GETEDGECOLOUR 2364
 #define SCI_SETEDGECOLOUR 2365
+#define SCI_MULTIEDGEADDLINE 2694
+#define SCI_MULTIEDGECLEARALL 2695
 #define SCI_SEARCHANCHOR 2366
 #define SCI_SEARCHNEXT 2367
 #define SCI_SEARCHPREV 2368
 #define SCI_LINESONSCREEN 2370
+#define SC_POPUP_NEVER 0
+#define SC_POPUP_ALL 1
+#define SC_POPUP_TEXT 2
 #define SCI_USEPOPUP 2371
 #define SCI_SELECTIONISRECTANGLE 2372
 #define SCI_SETZOOM 2373
@@ -632,10 +702,14 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_STATUS_OK 0
 #define SC_STATUS_FAILURE 1
 #define SC_STATUS_BADALLOC 2
+#define SC_STATUS_WARN_START 1000
+#define SC_STATUS_WARN_REGEX 1001
 #define SCI_SETSTATUS 2382
 #define SCI_GETSTATUS 2383
 #define SCI_SETMOUSEDOWNCAPTURES 2384
 #define SCI_GETMOUSEDOWNCAPTURES 2385
+#define SCI_SETMOUSEWHEELCAPTURES 2696
+#define SCI_GETMOUSEWHEELCAPTURES 2697
 #define SC_CURSORNORMAL -1
 #define SC_CURSORARROW 2
 #define SC_CURSORWAIT 4
@@ -679,6 +753,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_PARAUPEXTEND 2416
 #define SCI_POSITIONBEFORE 2417
 #define SCI_POSITIONAFTER 2418
+#define SCI_POSITIONRELATIVE 2670
 #define SCI_COPYRANGE 2419
 #define SCI_COPYTEXT 2420
 #define SC_SEL_STREAM 0
@@ -717,6 +792,10 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_CASEINSENSITIVEBEHAVIOUR_IGNORECASE 1
 #define SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR 2634
 #define SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR 2635
+#define SC_MULTIAUTOC_ONCE 0
+#define SC_MULTIAUTOC_EACH 1
+#define SCI_AUTOCSETMULTI 2636
+#define SCI_AUTOCGETMULTI 2637
 #define SC_ORDER_PRESORTED 0
 #define SC_ORDER_PERFORMSORT 1
 #define SC_ORDER_CUSTOM 2
@@ -762,8 +841,6 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_GETCHARACTERPOINTER 2520
 #define SCI_GETRANGEPOINTER 2643
 #define SCI_GETGAPPOSITION 2644
-#define SCI_SETKEYSUNICODE 2521
-#define SCI_GETKEYSUNICODE 2522
 #define SCI_INDICSETALPHA 2523
 #define SCI_INDICGETALPHA 2524
 #define SCI_INDICSETOUTLINEALPHA 2558
@@ -797,6 +874,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define ANNOTATION_HIDDEN 0
 #define ANNOTATION_STANDARD 1
 #define ANNOTATION_BOXED 2
+#define ANNOTATION_INDENTED 3
 #define SCI_ANNOTATIONSETVISIBLE 2548
 #define SCI_ANNOTATIONGETVISIBLE 2549
 #define SCI_ANNOTATIONSETSTYLEOFFSET 2550
@@ -807,6 +885,8 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_ADDUNDOACTION 2560
 #define SCI_CHARPOSITIONFROMPOINT 2561
 #define SCI_CHARPOSITIONFROMPOINTCLOSE 2562
+#define SCI_SETMOUSESELECTIONRECTANGULARSWITCH 2668
+#define SCI_GETMOUSESELECTIONRECTANGULARSWITCH 2669
 #define SCI_SETMULTIPLESELECTION 2563
 #define SCI_GETMULTIPLESELECTION 2564
 #define SCI_SETADDITIONALSELECTIONTYPING 2565
@@ -820,6 +900,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_CLEARSELECTIONS 2571
 #define SCI_SETSELECTION 2572
 #define SCI_ADDSELECTION 2573
+#define SCI_DROPSELECTIONN 2671
 #define SCI_SETMAINSELECTION 2574
 #define SCI_GETMAINSELECTION 2575
 #define SCI_SETSELECTIONNCARET 2576
@@ -845,6 +926,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCVS_NONE 0
 #define SCVS_RECTANGULARSELECTION 1
 #define SCVS_USERACCESSIBLE 2
+#define SCVS_NOWRAPLINESTART 4
 #define SCI_SETVIRTUALSPACEOPTIONS 2596
 #define SCI_GETVIRTUALSPACEOPTIONS 2597
 #define SCI_SETRECTANGULARSELECTIONMODIFIER 2598
@@ -857,6 +939,8 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_GETADDITIONALCARETFORE 2605
 #define SCI_ROTATESELECTION 2606
 #define SCI_SWAPMAINANCHORCARET 2607
+#define SCI_MULTIPLESELECTADDNEXT 2688
+#define SCI_MULTIPLESELECTADDEACH 2689
 #define SCI_CHANGELEXERSTATE 2617
 #define SCI_CONTRACTEDFOLDNEXT 2618
 #define SCI_VERTICALCENTRECARET 2619
@@ -873,6 +957,8 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SCROLLTOEND 2629
 #define SC_TECHNOLOGY_DEFAULT 0
 #define SC_TECHNOLOGY_DIRECTWRITE 1
+#define SC_TECHNOLOGY_DIRECTWRITERETAIN 2
+#define SC_TECHNOLOGY_DIRECTWRITEDC 3
 #define SCI_SETTECHNOLOGY 2630
 #define SCI_GETTECHNOLOGY 2631
 #define SCI_CREATELOADER 2632
@@ -883,6 +969,14 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_VCHOMEDISPLAYEXTEND 2653
 #define SCI_GETCARETLINEVISIBLEALWAYS 2654
 #define SCI_SETCARETLINEVISIBLEALWAYS 2655
+#define SC_LINE_END_TYPE_DEFAULT 0
+#define SC_LINE_END_TYPE_UNICODE 1
+#define SCI_SETLINEENDTYPESALLOWED 2656
+#define SCI_GETLINEENDTYPESALLOWED 2657
+#define SCI_GETLINEENDTYPESACTIVE 2658
+#define SCI_SETREPRESENTATION 2665
+#define SCI_GETREPRESENTATION 2666
+#define SCI_CLEARREPRESENTATION 2667
 #define SCI_STARTRECORD 3001
 #define SCI_STOPRECORD 3002
 #define SCI_SETLEXER 4001
@@ -906,6 +1000,16 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_PROPERTYTYPE 4015
 #define SCI_DESCRIBEPROPERTY 4016
 #define SCI_DESCRIBEKEYWORDSETS 4017
+#define SCI_GETLINEENDTYPESSUPPORTED 4018
+#define SCI_ALLOCATESUBSTYLES 4020
+#define SCI_GETSUBSTYLESSTART 4021
+#define SCI_GETSUBSTYLESLENGTH 4022
+#define SCI_GETSTYLEFROMSUBSTYLE 4027
+#define SCI_GETPRIMARYSTYLEFROMSTYLE 4028
+#define SCI_FREESUBSTYLES 4023
+#define SCI_SETIDENTIFIERS 4024
+#define SCI_DISTANCETOSECONDARYSTYLES 4025
+#define SCI_GETSUBSTYLEBASES 4026
 #define SC_MOD_INSERTTEXT 0x1
 #define SC_MOD_DELETETEXT 0x2
 #define SC_MOD_CHANGESTYLE 0x4
@@ -926,7 +1030,9 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_MOD_CHANGEANNOTATION 0x20000
 #define SC_MOD_CONTAINER 0x40000
 #define SC_MOD_LEXERSTATE 0x80000
-#define SC_MODEVENTMASKALL 0xFFFFF
+#define SC_MOD_INSERTCHECK 0x100000
+#define SC_MOD_CHANGETABSTOPS 0x200000
+#define SC_MODEVENTMASKALL 0x3FFFFF
 #define SC_UPDATE_CONTENT 0x1
 #define SC_UPDATE_SELECTION 0x2
 #define SC_UPDATE_V_SCROLL 0x4
@@ -960,6 +1066,11 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCMOD_ALT 4
 #define SCMOD_SUPER 8
 #define SCMOD_META 16
+#define SC_AC_FILLUP 1
+#define SC_AC_DOUBLECLICK 2
+#define SC_AC_TAB 3
+#define SC_AC_NEWLINE 4
+#define SC_AC_COMMAND 5
 #define SCN_STYLENEEDED 2000
 #define SCN_CHARADDED 2001
 #define SCN_SAVEPOINTREACHED 2002
@@ -987,34 +1098,19 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCN_AUTOCCANCELLED 2025
 #define SCN_AUTOCCHARDELETED 2026
 #define SCN_HOTSPOTRELEASECLICK 2027
-#ifndef SCI_DISABLE_PROVISIONAL
-#define SC_LINE_END_TYPE_DEFAULT 0
-#define SC_LINE_END_TYPE_UNICODE 1
-#define SCI_SETLINEENDTYPESALLOWED 2656
-#define SCI_GETLINEENDTYPESALLOWED 2657
-#define SCI_GETLINEENDTYPESACTIVE 2658
-#define SCI_GETLINEENDTYPESSUPPORTED 4018
-#define SCI_ALLOCATESUBSTYLES 4020
-#define SCI_GETSUBSTYLESSTART 4021
-#define SCI_GETSUBSTYLESLENGTH 4022
-#define SCI_FREESUBSTYLES 4023
-#define SCI_SETIDENTIFIERS 4024
-#define SCI_DISTANCETOSECONDARYSTYLES 4025
-#define SCI_GETSUBSTYLEBASES 4026
-#endif
+#define SCN_FOCUSIN 2028
+#define SCN_FOCUSOUT 2029
+#define SCN_AUTOCCOMPLETED 2030
+#define SCN_MARGINRIGHTCLICK 2031
 /* --Autogenerated -- end of section automatically generated from Scintilla.iface */
 
 /* These structures are defined to be exactly the same shape as the Win32
  * CHARRANGE, TEXTRANGE, FINDTEXTEX, FORMATRANGE, and NMHDR structs.
  * So older code that treats Scintilla as a RichEdit will work. */
 
-#ifdef SCI_NAMESPACE
-namespace Scintilla {
-#endif
-
 struct Sci_CharacterRange {
-       long cpMin;
-       long cpMax;
+       Sci_PositionCR cpMin;
+       Sci_PositionCR cpMax;
 };
 
 struct Sci_TextRange {
@@ -1024,14 +1120,10 @@ struct Sci_TextRange {
 
 struct Sci_TextToFind {
        struct Sci_CharacterRange chrg;
-       char *lpstrText;
+       const char *lpstrText;
        struct Sci_CharacterRange chrgText;
 };
 
-#define CharacterRange Sci_CharacterRange
-#define TextRange Sci_TextRange
-#define TextToFind Sci_TextToFind
-
 typedef void *Sci_SurfaceID;
 
 struct Sci_Rectangle {
@@ -1052,7 +1144,12 @@ struct Sci_RangeToFormat {
        struct Sci_CharacterRange chrg;
 };
 
-#define RangeToFormat Sci_RangeToFormat
+#ifndef __cplusplus
+/* For the GTK+ platform, g-ir-scanner needs to have these typedefs. This
+ * is not required in C++ code and actually seems to break ScintillaEditPy */
+typedef struct Sci_NotifyHeader Sci_NotifyHeader;
+typedef struct SCNotification SCNotification;
+#endif
 
 struct Sci_NotifyHeader {
        /* Compatible with Windows NMHDR.
@@ -1063,18 +1160,18 @@ struct Sci_NotifyHeader {
        unsigned int code;
 };
 
-#define NotifyHeader Sci_NotifyHeader
-
 struct SCNotification {
-       struct Sci_NotifyHeader nmhdr;
-       int position;
+       Sci_NotifyHeader nmhdr;
+       Sci_Position position;
        /* SCN_STYLENEEDED, SCN_DOUBLECLICK, SCN_MODIFIED, SCN_MARGINCLICK, */
        /* SCN_NEEDSHOWN, SCN_DWELLSTART, SCN_DWELLEND, SCN_CALLTIPCLICK, */
        /* SCN_HOTSPOTCLICK, SCN_HOTSPOTDOUBLECLICK, SCN_HOTSPOTRELEASECLICK, */
        /* SCN_INDICATORCLICK, SCN_INDICATORRELEASE, */
        /* SCN_USERLISTSELECTION, SCN_AUTOCSELECTION */
 
-       int ch;         /* SCN_CHARADDED, SCN_KEY */
+       int ch;
+       /* SCN_CHARADDED, SCN_KEY, SCN_AUTOCCOMPLETED, SCN_AUTOCSELECTION, */
+       /* SCN_USERLISTSELECTION */
        int modifiers;
        /* SCN_KEY, SCN_DOUBLECLICK, SCN_HOTSPOTCLICK, SCN_HOTSPOTDOUBLECLICK, */
        /* SCN_HOTSPOTRELEASECLICK, SCN_INDICATORCLICK, SCN_INDICATORRELEASE, */
@@ -1083,12 +1180,12 @@ struct SCNotification {
        const char *text;
        /* SCN_MODIFIED, SCN_USERLISTSELECTION, SCN_AUTOCSELECTION, SCN_URIDROPPED */
 
-       int length;             /* SCN_MODIFIED */
-       int linesAdded; /* SCN_MODIFIED */
+       Sci_Position length;            /* SCN_MODIFIED */
+       Sci_Position linesAdded;        /* SCN_MODIFIED */
        int message;    /* SCN_MACRORECORD */
        uptr_t wParam;  /* SCN_MACRORECORD */
        sptr_t lParam;  /* SCN_MACRORECORD */
-       int line;               /* SCN_MODIFIED */
+       Sci_Position line;              /* SCN_MODIFIED */
        int foldLevelNow;       /* SCN_MODIFIED */
        int foldLevelPrev;      /* SCN_MODIFIED */
        int margin;             /* SCN_MARGINCLICK */
@@ -1096,19 +1193,22 @@ struct SCNotification {
        int x;                  /* SCN_DWELLSTART, SCN_DWELLEND */
        int y;          /* SCN_DWELLSTART, SCN_DWELLEND */
        int token;              /* SCN_MODIFIED with SC_MOD_CONTAINER */
-       int annotationLinesAdded;       /* SCN_MODIFIED with SC_MOD_CHANGEANNOTATION */
+       Sci_Position annotationLinesAdded;      /* SCN_MODIFIED with SC_MOD_CHANGEANNOTATION */
        int updated;    /* SCN_UPDATEUI */
+       int listCompletionMethod;
+       /* SCN_AUTOCSELECTION, SCN_AUTOCCOMPLETED, SCN_USERLISTSELECTION, */
 };
 
-#ifdef SCI_NAMESPACE
-}
-#endif
-
 #ifdef INCLUDE_DEPRECATED_FEATURES
 
-#define SC_CP_DBCS 1
-#define SCI_SETUSEPALETTE 2039
-#define SCI_GETUSEPALETTE 2139
+#define SCI_SETKEYSUNICODE 2521
+#define SCI_GETKEYSUNICODE 2522
+
+#define CharacterRange Sci_CharacterRange
+#define TextRange Sci_TextRange
+#define TextToFind Sci_TextToFind
+#define RangeToFormat Sci_RangeToFormat
+#define NotifyHeader Sci_NotifyHeader
 
 #endif
 
diff --git a/plugins/scintilla/scintilla/include/Scintilla.iface 
b/plugins/scintilla/scintilla/include/Scintilla.iface
index 120a543..f352069 100644
--- a/plugins/scintilla/scintilla/include/Scintilla.iface
+++ b/plugins/scintilla/scintilla/include/Scintilla.iface
@@ -72,11 +72,11 @@
 
 ## Line numbers and positions start at 0.
 ## String arguments may contain NUL ('\0') characters where the calls provide a length
-## argument and retrieve NUL characters. All retrieved strings except for those retrieved
-## by GetLine also have a NUL appended but client code should calculate the size that
-## will be returned rather than relying upon the NUL whenever possible. Allow for the
-## extra NUL character when allocating buffers. The size to allocate for a stringresult
-## can be determined by calling with a NULL (0) pointer.
+## argument and retrieve NUL characters. APIs marked as NUL-terminated also have a
+## NUL appended but client code should calculate the size that will be returned rather
+## than relying upon the NUL whenever possible. Allow for the extra NUL character when
+## allocating buffers. The size to allocate for a stringresult (not including NUL) can be
+## determined by calling with a NULL (0) pointer.
 
 cat Basics
 
@@ -98,11 +98,14 @@ fun void AddStyledText=2002(int length, cells c)
 # Insert string at a position.
 fun void InsertText=2003(position pos, string text)
 
+# Change the text that is being inserted in response to SC_MOD_INSERTCHECK
+fun void ChangeInsertion=2672(int length, string text)
+
 # Delete all text in the document.
 fun void ClearAll=2004(,)
 
 # Delete a range of text in the document.
-fun void DeleteRange=2645(position pos, int deleteLength)
+fun void DeleteRange=2645(position start, int lengthDelete)
 
 # Set all style bytes to 0, remove all folding information.
 fun void ClearDocumentStyle=2005(,)
@@ -144,10 +147,10 @@ fun int GetStyledText=2015(, textrange tr)
 fun bool CanRedo=2016(,)
 
 # Retrieve the line number at which a particular marker is located.
-fun int MarkerLineFromHandle=2017(int handle,)
+fun int MarkerLineFromHandle=2017(int markerHandle,)
 
 # Delete a marker.
-fun void MarkerDeleteHandle=2018(int handle,)
+fun void MarkerDeleteHandle=2018(int markerHandle,)
 
 # Is undo history being collected?
 get bool GetUndoCollection=2019(,)
@@ -156,6 +159,7 @@ enu WhiteSpace=SCWS_
 val SCWS_INVISIBLE=0
 val SCWS_VISIBLEALWAYS=1
 val SCWS_VISIBLEAFTERINDENT=2
+val SCWS_VISIBLEONLYININDENT=3
 
 # Are white space characters currently visible?
 # Returns one of SCWS_* constants.
@@ -164,6 +168,17 @@ get int GetViewWS=2020(,)
 # Make white space characters invisible, always visible or visible outside indentation.
 set void SetViewWS=2021(int viewWS,)
 
+enu TabDrawMode=SCTD_
+val SCTD_LONGARROW=0
+val SCTD_STRIKEOUT=1
+
+# Retrieve the current tab draw mode.
+# Returns one of SCTD_* constants.
+get int GetTabDrawMode=2698(,)
+
+# Set how tabs are drawn when visible.
+set void SetTabDrawMode=2699(int tabDrawMode,)
+
 # Find the position from a point within the window.
 fun position PositionFromPoint=2022(int x, int y)
 
@@ -175,14 +190,15 @@ fun position PositionFromPointClose=2023(int x, int y)
 fun void GotoLine=2024(int line,)
 
 # Set caret to a position and ensure it is visible.
-fun void GotoPos=2025(position pos,)
+fun void GotoPos=2025(position caret,)
 
 # Set the selection anchor to a position. The anchor is the opposite
 # end of the selection from the caret.
-set void SetAnchor=2026(position posAnchor,)
+set void SetAnchor=2026(position anchor,)
 
 # Retrieve the text of the line containing the caret.
 # Returns the index of the caret on the line.
+# Result is NUL-terminated.
 fun int GetCurLine=2027(int length, stringresult text)
 
 # Retrieve the position of the last correctly styled character.
@@ -202,9 +218,9 @@ get int GetEOLMode=2030(,)
 # Set the current end of line mode.
 set void SetEOLMode=2031(int eolMode,)
 
-# Set the current styling position to pos and the styling mask to mask.
-# The styling mask can be used to protect some bits in each styling byte from modification.
-fun void StartStyling=2032(position pos, int mask)
+# Set the current styling position to start.
+# The unused parameter is no longer used and should be set to 0.
+fun void StartStyling=2032(position start, int unused)
 
 # Change style from current styling position for length characters to a style
 # and move the current styling position to after this newly styled segment.
@@ -223,6 +239,15 @@ set void SetTabWidth=2036(int tabWidth,)
 # Retrieve the visible size of a tab.
 get int GetTabWidth=2121(,)
 
+# Clear explicit tabstops on a line.
+fun void ClearTabStops=2675(int line,)
+
+# Add an explicit tab stop for a line.
+fun void AddTabStop=2676(int line, int x)
+
+# Find the next explicit tab stop position on a line after a position.
+fun int GetNextTabStop=2677(int line, int x)
+
 # The SC_CP_UTF8 value can be used to enter Unicode mode.
 # This is the same value as CP_UTF8 in Windows
 val SC_CP_UTF8=65001
@@ -231,6 +256,16 @@ val SC_CP_UTF8=65001
 # The SC_CP_UTF8 value can be used to enter Unicode mode.
 set void SetCodePage=2037(int codePage,)
 
+enu IMEInteraction=SC_IME_
+val SC_IME_WINDOWED=0
+val SC_IME_INLINE=1
+
+# Is the IME displayed in a window or inline?
+get int GetIMEInteraction=2678(,)
+
+# Choose to display the the IME in a winow or inline.
+set void SetIMEInteraction=2679(int imeInteraction,)
+
 enu MarkerSymbol=SC_MARK_
 val MARKER_MAX=31
 val SC_MARK_CIRCLE=0
@@ -268,6 +303,7 @@ val SC_MARK_LEFTRECT=27
 val SC_MARK_AVAILABLE=28
 val SC_MARK_UNDERLINE=29
 val SC_MARK_RGBAIMAGE=30
+val SC_MARK_BOOKMARK=31
 
 val SC_MARK_CHARACTER=10000
 
@@ -321,7 +357,7 @@ fun int MarkerPrevious=2048(int lineStart, int markerMask)
 fun void MarkerDefinePixmap=2049(int markerNumber, string pixmap)
 
 # Add a set of markers to a line.
-fun void MarkerAddSet=2466(int line, int set)
+fun void MarkerAddSet=2466(int line, int markerSet)
 
 # Set the alpha used for a marker that is drawn in the text area, not the margin.
 set void MarkerSetAlpha=2476(int markerNumber, int alpha)
@@ -335,6 +371,7 @@ val SC_MARGIN_BACK=2
 val SC_MARGIN_FORE=3
 val SC_MARGIN_TEXT=4
 val SC_MARGIN_RTEXT=5
+val SC_MARGIN_COLOUR=6
 
 # Set a margin to be either numeric or symbolic.
 set void SetMarginTypeN=2240(int margin, int marginType)
@@ -366,8 +403,19 @@ set void SetMarginCursorN=2248(int margin, int cursor)
 # Retrieve the cursor shown in a margin.
 get int GetMarginCursorN=2249(int margin,)
 
-# Styles in range 32..38 are predefined for parts of the UI and are not used as normal styles.
-# Style 39 is for future use.
+# Set the background colour of a margin. Only visible for SC_MARGIN_COLOUR.
+set void SetMarginBackN=2250(int margin, colour back)
+
+# Retrieve the background colour of a margin
+get colour GetMarginBackN=2251(int margin,)
+
+# Allocate a non-standard number of margins.
+set void SetMargins=2252(int margins,)
+
+# How many margins are there?.
+get int GetMargins=2253(,)
+
+# Styles in range 32..39 are predefined for parts of the UI and are not used as normal styles.
 enu StylesCommon=STYLE_
 val STYLE_DEFAULT=32
 val STYLE_LINENUMBER=33
@@ -376,6 +424,7 @@ val STYLE_BRACEBAD=35
 val STYLE_CONTROLCHAR=36
 val STYLE_INDENTGUIDE=37
 val STYLE_CALLTIP=38
+val STYLE_FOLDDISPLAYTEXT=39
 val STYLE_LASTPREDEFINED=39
 val STYLE_MAX=255
 
@@ -393,6 +442,7 @@ val SC_CHARSET_HANGUL=129
 val SC_CHARSET_MAC=77
 val SC_CHARSET_OEM=255
 val SC_CHARSET_RUSSIAN=204
+val SC_CHARSET_OEM866=866
 val SC_CHARSET_CYRILLIC=1251
 val SC_CHARSET_SHIFTJIS=128
 val SC_CHARSET_SYMBOL=2
@@ -426,7 +476,7 @@ set void StyleSetSize=2055(int style, int sizePoints)
 set void StyleSetFont=2056(int style, string fontName)
 
 # Set a style to have its end of line filled or not.
-set void StyleSetEOLFilled=2057(int style, bool filled)
+set void StyleSetEOLFilled=2057(int style, bool eolFilled)
 
 # Reset the default style to its state at startup
 fun void StyleResetDefault=2058(,)
@@ -438,6 +488,7 @@ enu CaseVisible=SC_CASE_
 val SC_CASE_MIXED=0
 val SC_CASE_UPPER=1
 val SC_CASE_LOWER=2
+val SC_CASE_CAMEL=3
 
 # Get the foreground colour of a style.
 get colour StyleGetFore=2481(int style,)
@@ -456,6 +507,7 @@ get int StyleGetSize=2485(int style,)
 
 # Get the font of a style.
 # Returns the length of the fontName
+# Result is NUL-terminated.
 get int StyleGetFont=2486(int style, stringresult fontName)
 
 # Get is a style to have its end of line filled or not.
@@ -481,12 +533,12 @@ get bool StyleGetChangeable=2492(int style,)
 get bool StyleGetHotSpot=2493(int style,)
 
 # Set a style to be mixed case, or to force upper or lower case.
-set void StyleSetCase=2060(int style, int caseForce)
+set void StyleSetCase=2060(int style, int caseVisible)
 
 val SC_FONT_SIZE_MULTIPLIER=100
 
 # Set the size of characters of a style. Size is in points multiplied by 100.
-set void StyleSetSizeFractional=2061(int style, int caseForce)
+set void StyleSetSizeFractional=2061(int style, int sizeHundredthPoints)
 
 # Get the size of characters of a style in points multiplied by 100
 get int StyleGetSizeFractional=2062(int style,)
@@ -529,11 +581,11 @@ set void SetSelEOLFilled=2480(bool filled,)
 # Set the foreground colour of the caret.
 set void SetCaretFore=2069(colour fore,)
 
-# When key+modifier combination km is pressed perform msg.
-fun void AssignCmdKey=2070(keymod km, int msg)
+# When key+modifier combination keyDefinition is pressed perform sciCommand.
+fun void AssignCmdKey=2070(keymod keyDefinition, int sciCommand)
 
-# When key+modifier combination km is pressed do nothing.
-fun void ClearCmdKey=2071(keymod km,)
+# When key+modifier combination keyDefinition is pressed do nothing.
+fun void ClearCmdKey=2071(keymod keyDefinition,)
 
 # Drop all key mappings.
 fun void ClearAllCmdKeys=2072(,)
@@ -555,7 +607,7 @@ set void SetCaretPeriod=2076(int periodMilliseconds,)
 set void SetWordChars=2077(, string characters)
 
 # Get the set of characters making up words for when moving or selecting by word.
-# Retuns the number of characters
+# Returns the number of characters
 get int GetWordChars=2646(, stringresult characters)
 
 # Start a sequence of actions that is undone and redone as a unit.
@@ -582,7 +634,14 @@ val INDIC_SQUIGGLELOW=11
 val INDIC_DOTBOX=12
 val INDIC_SQUIGGLEPIXMAP=13
 val INDIC_COMPOSITIONTHICK=14
-val INDIC_MAX=31
+val INDIC_COMPOSITIONTHIN=15
+val INDIC_FULLBOX=16
+val INDIC_TEXTFORE=17
+val INDIC_POINT=18
+val INDIC_POINTCHARACTER=19
+val INDIC_IME=32
+val INDIC_IME_MAX=35
+val INDIC_MAX=35
 val INDIC_CONTAINER=8
 val INDIC0_MASK=0x20
 val INDIC1_MASK=0x40
@@ -590,22 +649,46 @@ val INDIC2_MASK=0x80
 val INDICS_MASK=0xE0
 
 # Set an indicator to plain, squiggle or TT.
-set void IndicSetStyle=2080(int indic, int style)
+set void IndicSetStyle=2080(int indicator, int indicatorStyle)
 
 # Retrieve the style of an indicator.
-get int IndicGetStyle=2081(int indic,)
+get int IndicGetStyle=2081(int indicator,)
 
 # Set the foreground colour of an indicator.
-set void IndicSetFore=2082(int indic, colour fore)
+set void IndicSetFore=2082(int indicator, colour fore)
 
 # Retrieve the foreground colour of an indicator.
-get colour IndicGetFore=2083(int indic,)
+get colour IndicGetFore=2083(int indicator,)
 
 # Set an indicator to draw under text or over(default).
-set void IndicSetUnder=2510(int indic, bool under)
+set void IndicSetUnder=2510(int indicator, bool under)
 
 # Retrieve whether indicator drawn under or over text.
-get bool IndicGetUnder=2511(int indic,)
+get bool IndicGetUnder=2511(int indicator,)
+
+# Set a hover indicator to plain, squiggle or TT.
+set void IndicSetHoverStyle=2680(int indicator, int indicatorStyle)
+
+# Retrieve the hover style of an indicator.
+get int IndicGetHoverStyle=2681(int indicator,)
+
+# Set the foreground hover colour of an indicator.
+set void IndicSetHoverFore=2682(int indicator, colour fore)
+
+# Retrieve the foreground hover colour of an indicator.
+get colour IndicGetHoverFore=2683(int indicator,)
+
+val SC_INDICVALUEBIT=0x1000000
+val SC_INDICVALUEMASK=0xFFFFFF
+
+enu IndicFlag=SC_INDICFLAG_
+val SC_INDICFLAG_VALUEFORE=1
+
+# Set the attributes of an indicator.
+set void IndicSetFlags=2684(int indicator, int flags)
+
+# Retrieve the attributes of an indicator.
+get int IndicGetFlags=2685(int indicator,)
 
 # Set the foreground colour of all whitespace and whether to use this setting.
 fun void SetWhitespaceFore=2084(bool useSetting, colour fore)
@@ -648,14 +731,22 @@ get colour GetCaretLineBack=2097(,)
 # Set the colour of the background of the line containing the caret.
 set void SetCaretLineBack=2098(colour back,)
 
+# Retrieve the caret line frame width.
+# Width = 0 means this option is disabled.
+get int GetCaretLineFrame=2704(,)
+
+# Display the caret line framed.
+# Set width != 0 to enable this option and width = 0 to disable it.
+set void SetCaretLineFrame=2705(int width,)
+
 # Set a style to be changeable or not (read only).
 # Experimental feature, currently buggy.
 set void StyleSetChangeable=2099(int style, bool changeable)
 
 # Display a auto-completion list.
-# The lenEntered parameter indicates how many characters before
+# The lengthEntered parameter indicates how many characters before
 # the caret should be used to provide context.
-fun void AutoCShow=2100(int lenEntered, string itemList)
+fun void AutoCShow=2100(int lengthEntered, string itemList)
 
 # Remove the auto-completion list from the screen.
 fun void AutoCCancel=2101(,)
@@ -680,7 +771,7 @@ set void AutoCSetSeparator=2106(int separatorCharacter,)
 get int AutoCGetSeparator=2107(,)
 
 # Select the item in the auto-completion list that starts with a string.
-fun void AutoCSelect=2108(, string text)
+fun void AutoCSelect=2108(, string select)
 
 # Should the auto-completion list be cancelled if the user backspaces to a
 # position before where the box was created.
@@ -763,7 +854,7 @@ set void SetUseTabs=2124(bool useTabs,)
 get bool GetUseTabs=2125(,)
 
 # Change the indentation of a line to a number of columns.
-set void SetLineIndentation=2126(int line, int indentSize)
+set void SetLineIndentation=2126(int line, int indentation)
 
 # Retrieve the number of columns that a line is indented.
 get int GetLineIndentation=2127(int line,)
@@ -775,10 +866,10 @@ get position GetLineIndentPosition=2128(int line,)
 get int GetColumn=2129(position pos,)
 
 # Count characters between two positions.
-fun int CountCharacters=2633(int startPos, int endPos)
+fun int CountCharacters=2633(position start, position end)
 
 # Show or hide the horizontal scroll bar.
-set void SetHScrollBar=2130(bool show,)
+set void SetHScrollBar=2130(bool visible,)
 # Is the horizontal scroll bar visible?
 get bool GetHScrollBar=2131(,)
 
@@ -814,22 +905,22 @@ get colour GetCaretFore=2138(,)
 get bool GetReadOnly=2140(,)
 
 # Sets the position of the caret.
-set void SetCurrentPos=2141(position pos,)
+set void SetCurrentPos=2141(position caret,)
 
 # Sets the position that starts the selection - this becomes the anchor.
-set void SetSelectionStart=2142(position pos,)
+set void SetSelectionStart=2142(position anchor,)
 
 # Returns the position at the start of the selection.
 get position GetSelectionStart=2143(,)
 
-# Sets the position that ends the selection - this becomes the currentPosition.
-set void SetSelectionEnd=2144(position pos,)
+# Sets the position that ends the selection - this becomes the caret.
+set void SetSelectionEnd=2144(position caret,)
 
 # Returns the position at the end of the selection.
 get position GetSelectionEnd=2145(,)
 
 # Set caret to a position, while removing any existing selection.
-fun void SetEmptySelection=2556(position pos,)
+fun void SetEmptySelection=2556(position caret,)
 
 # Sets the print magnification added to the point size of each style for printing.
 set void SetPrintMagnification=2146(int magnification,)
@@ -856,14 +947,15 @@ set void SetPrintColourMode=2148(int mode,)
 get int GetPrintColourMode=2149(,)
 
 enu FindOption=SCFIND_
-val SCFIND_WHOLEWORD=2
-val SCFIND_MATCHCASE=4
+val SCFIND_WHOLEWORD=0x2
+val SCFIND_MATCHCASE=0x4
 val SCFIND_WORDSTART=0x00100000
 val SCFIND_REGEXP=0x00200000
 val SCFIND_POSIX=0x00400000
+val SCFIND_CXX11REGEX=0x00800000
 
 # Find some text in the document.
-fun position FindText=2150(int flags, findtext ft)
+fun position FindText=2150(int searchFlags, findtext ft)
 
 # On Windows, will draw the document into a display context such as a printer.
 fun position FormatRange=2151(bool draw, formatrange fr)
@@ -894,10 +986,11 @@ get int GetMarginRight=2158(,)
 get bool GetModify=2159(,)
 
 # Select a range of text.
-fun void SetSel=2160(position start, position end)
+fun void SetSel=2160(position anchor, position caret)
 
 # Retrieve the selected text.
 # Return the length of the text.
+# Result is NUL-terminated.
 fun int GetSelText=2161(, stringresult text)
 
 # Retrieve a range of text.
@@ -905,7 +998,7 @@ fun int GetSelText=2161(, stringresult text)
 fun int GetTextRange=2162(, textrange tr)
 
 # Draw the selection in normal style or with selection highlighted.
-fun void HideSelection=2163(bool normal,)
+fun void HideSelection=2163(bool hide,)
 
 # Retrieve the x value of the point in the window where a position is displayed.
 fun int PointXFromPosition=2164(, position pos)
@@ -968,6 +1061,7 @@ fun void SetText=2181(, string text)
 
 # Retrieve all the text in the document.
 # Returns number of characters retrieved.
+# Result is NUL-terminated.
 fun int GetText=2182(int length, stringresult text)
 
 # Retrieve the number of characters in the document.
@@ -981,7 +1075,7 @@ get int GetDirectFunction=2184(,)
 get int GetDirectPointer=2185(,)
 
 # Set to overtype (true) or insert mode.
-set void SetOvertype=2186(bool overtype,)
+set void SetOvertype=2186(bool overType,)
 
 # Returns true if overtype mode is active otherwise false is returned.
 get bool GetOvertype=2187(,)
@@ -994,18 +1088,30 @@ get int GetCaretWidth=2189(,)
 
 # Sets the position that starts the target which is used for updating the
 # document without affecting the scroll position.
-set void SetTargetStart=2190(position pos,)
+set void SetTargetStart=2190(position start,)
 
 # Get the position that starts the target.
 get position GetTargetStart=2191(,)
 
 # Sets the position that ends the target which is used for updating the
 # document without affecting the scroll position.
-set void SetTargetEnd=2192(position pos,)
+set void SetTargetEnd=2192(position end,)
 
 # Get the position that ends the target.
 get position GetTargetEnd=2193(,)
 
+# Sets both the start and end of the target in one call.
+fun void SetTargetRange=2686(position start, position end)
+
+# Retrieve the text in the target.
+get int GetTargetText=2687(, stringresult text)
+
+# Make the target range start and end be the same as the selection range start and end.
+fun void TargetFromSelection=2287(,)
+
+# Sets the target to the whole document.
+fun void TargetWholeDocument=2690(,)
+
 # Replace the target text with the argument text.
 # Text is counted so it can contain NULs.
 # Returns the length of the replacement text.
@@ -1025,7 +1131,7 @@ fun int ReplaceTargetRE=2195(int length, string text)
 fun int SearchInTarget=2197(int length, string text)
 
 # Set the search flags used by SearchInTarget.
-set void SetSearchFlags=2198(int flags,)
+set void SetSearchFlags=2198(int searchFlags,)
 
 # Get the search flags used by SearchInTarget.
 get int GetSearchFlags=2199(,)
@@ -1042,8 +1148,11 @@ fun bool CallTipActive=2202(,)
 # Retrieve the position where the caret was before displaying the call tip.
 fun position CallTipPosStart=2203(,)
 
+# Set the start position in order to change when backspacing removes the calltip.
+set void CallTipSetPosStart=2214(int posStart,)
+
 # Highlight a segment of the definition.
-fun void CallTipSetHlt=2204(int start, int end)
+fun void CallTipSetHlt=2204(int highlightStart, int highlightEnd)
 
 # Set the background colour for the call tip.
 set void CallTipSetBack=2205(colour back,)
@@ -1061,13 +1170,13 @@ set void CallTipUseStyle=2212(int tabSize,)
 set void CallTipSetPosition=2213(bool above,)
 
 # Find the display line of a document line taking hidden lines into account.
-fun int VisibleFromDocLine=2220(int line,)
+fun int VisibleFromDocLine=2220(int docLine,)
 
 # Find the document line of a display line taking hidden lines into account.
-fun int DocLineFromVisible=2221(int lineDisplay,)
+fun int DocLineFromVisible=2221(int displayLine,)
 
 # The number of display lines needed to wrap a document line
-fun int WrapCount=2235(int line,)
+fun int WrapCount=2235(int docLine,)
 
 enu FoldLevel=SC_FOLDLEVEL
 val SC_FOLDLEVELBASE=0x400
@@ -1110,7 +1219,18 @@ get bool GetFoldExpanded=2230(int line,)
 # Switch a header line between expanded and contracted.
 fun void ToggleFold=2231(int line,)
 
-enu FoldAction=SC_FOLDACTION
+# Switch a header line between expanded and contracted and show some text after the line.
+fun void ToggleFoldShowText=2700(int line, string text)
+
+enu FoldDisplayTextStyle=SC_FOLDDISPLAYTEXT_
+val SC_FOLDDISPLAYTEXT_HIDDEN=0
+val SC_FOLDDISPLAYTEXT_STANDARD=1
+val SC_FOLDDISPLAYTEXT_BOXED=2
+
+# Set the style of fold display text
+set void FoldDisplayTextSetStyle=2701(int style,)
+
+enu FoldAction=SC_FOLDACTION_
 val SC_FOLDACTION_CONTRACT=0
 val SC_FOLDACTION_EXPAND=1
 val SC_FOLDACTION_TOGGLE=2
@@ -1147,6 +1267,7 @@ val SC_FOLDFLAG_LINEBEFORE_CONTRACTED=0x0004
 val SC_FOLDFLAG_LINEAFTER_EXPANDED=0x0008
 val SC_FOLDFLAG_LINEAFTER_CONTRACTED=0x0010
 val SC_FOLDFLAG_LEVELNUMBERS=0x0040
+val SC_FOLDFLAG_LINESTATE=0x0080
 
 # Set some style options for folding.
 set void SetFoldFlags=2233(int flags,)
@@ -1181,13 +1302,29 @@ fun int WordStartPosition=2266(position pos, bool onlyWordCharacters)
 # Get position of end of word.
 fun int WordEndPosition=2267(position pos, bool onlyWordCharacters)
 
+# Is the range start..end considered a word?
+fun bool IsRangeWord=2691(position start, position end)
+
+enu IdleStyling=SC_IDLESTYLING_
+val SC_IDLESTYLING_NONE=0
+val SC_IDLESTYLING_TOVISIBLE=1
+val SC_IDLESTYLING_AFTERVISIBLE=2
+val SC_IDLESTYLING_ALL=3
+
+# Sets limits to idle styling.
+set void SetIdleStyling=2692(int idleStyling,)
+
+# Retrieve the limits to idle styling.
+get int GetIdleStyling=2693(,)
+
 enu Wrap=SC_WRAP_
 val SC_WRAP_NONE=0
 val SC_WRAP_WORD=1
 val SC_WRAP_CHAR=2
+val SC_WRAP_WHITESPACE=3
 
 # Sets whether text is word wrapped.
-set void SetWrapMode=2268(int mode,)
+set void SetWrapMode=2268(int wrapMode,)
 
 # Retrieve whether text is word wrapped.
 get int GetWrapMode=2269(,)
@@ -1227,7 +1364,7 @@ val SC_WRAPINDENT_SAME=1
 val SC_WRAPINDENT_INDENT=2
 
 # Sets how wrapped sublines are placed. Default is fixed.
-set void SetWrapIndentMode=2472(int mode,)
+set void SetWrapIndentMode=2472(int wrapIndentMode,)
 
 # Retrieve how wrapped sublines are placed. Default is fixed.
 get int GetWrapIndentMode=2473(,)
@@ -1239,7 +1376,7 @@ val SC_CACHE_PAGE=2
 val SC_CACHE_DOCUMENT=3
 
 # Sets the degree of caching of layout information.
-set void SetLayoutCache=2272(int mode,)
+set void SetLayoutCache=2272(int cacheMode,)
 
 # Retrieve the degree of caching of layout information.
 get int GetLayoutCache=2273(,)
@@ -1274,7 +1411,7 @@ get bool GetEndAtLastLine=2278(,)
 fun int TextHeight=2279(int line,)
 
 # Show or hide the vertical scroll bar.
-set void SetVScrollBar=2280(bool show,)
+set void SetVScrollBar=2280(bool visible,)
 
 # Is the vertical scroll bar visible?
 get bool GetVScrollBar=2281(,)
@@ -1282,13 +1419,27 @@ get bool GetVScrollBar=2281(,)
 # Append a string to the end of the document without changing the selection.
 fun void AppendText=2282(int length, string text)
 
-# Is drawing done in two phases with backgrounds drawn before faoregrounds?
+# Is drawing done in two phases with backgrounds drawn before foregrounds?
 get bool GetTwoPhaseDraw=2283(,)
 
 # In twoPhaseDraw mode, drawing is performed in two phases, first the background
 # and then the foreground. This avoids chopping off characters that overlap the next run.
 set void SetTwoPhaseDraw=2284(bool twoPhase,)
 
+enu PhasesDraw=SC_PHASES_
+val SC_PHASES_ONE=0
+val SC_PHASES_TWO=1
+val SC_PHASES_MULTIPLE=2
+
+# How many phases is drawing done in?
+get int GetPhasesDraw=2673(,)
+
+# In one phase draw, text is drawn in a series of rectangular blocks with no overlap.
+# In two phase draw, text is drawn in a series of lines allowing runs to overlap horizontally.
+# In multiple phase draw, each element is drawn over the whole drawing area, allowing text
+# to overlap from one line to the next.
+set void SetPhasesDraw=2674(int phases,)
+
 # Control font anti-aliasing.
 
 enu FontQuality=SC_EFF_
@@ -1305,7 +1456,7 @@ set void SetFontQuality=2611(int fontQuality,)
 get int GetFontQuality=2612(,)
 
 # Scroll so that a display line is at the top of the display.
-set void SetFirstVisibleLine=2613(int lineDisplay,)
+set void SetFirstVisibleLine=2613(int displayLine,)
 
 enu MultiPaste=SC_MULTIPASTE_
 val SC_MULTIPASTE_ONCE=0
@@ -1314,15 +1465,13 @@ val SC_MULTIPASTE_EACH=1
 # Change the effect of pasting when there are multiple selections.
 set void SetMultiPaste=2614(int multiPaste,)
 
-# Retrieve the effect of pasting when there are multiple selections..
+# Retrieve the effect of pasting when there are multiple selections.
 get int GetMultiPaste=2615(,)
 
 # Retrieve the value of a tag from a regular expression search.
+# Result is NUL-terminated.
 get int GetTag=2616(int tagNumber, stringresult tagValue)
 
-# Make the target range start and end be the same as the selection range start and end.
-fun void TargetFromSelection=2287(,)
-
 # Join the lines in the target.
 fun void LinesJoin=2288(,)
 
@@ -1330,10 +1479,21 @@ fun void LinesJoin=2288(,)
 # where possible.
 fun void LinesSplit=2289(int pixelWidth,)
 
-# Set the colours used as a chequerboard pattern in the fold margin
+# Set one of the colours used as a chequerboard pattern in the fold margin
 fun void SetFoldMarginColour=2290(bool useSetting, colour back)
+# Set the other colour used as a chequerboard pattern in the fold margin
 fun void SetFoldMarginHiColour=2291(bool useSetting, colour fore)
 
+enu Accessibility=SC_ACCESSIBILITY_
+val SC_ACCESSIBILITY_DISABLED=0
+val SC_ACCESSIBILITY_ENABLED=1
+
+# Enable or disable accessibility.
+set void SetAccessibility=2702(int accessibility,)
+
+# Report accessibility status.
+get int GetAccessibility=2703(,)
+
 ## New messages go here
 
 ## Start of key messages
@@ -1462,6 +1622,9 @@ fun void LineDelete=2338(,)
 # Switch the current line with the previous.
 fun void LineTranspose=2339(,)
 
+# Reverse order of selected lines.
+fun void LineReverse=2354(,)
+
 # Duplicate the current line.
 fun void LineDuplicate=2404(,)
 
@@ -1495,17 +1658,28 @@ fun void LineEndDisplay=2347(,)
 # caret position.
 fun void LineEndDisplayExtend=2348(,)
 
-# These are like their namesakes Home(Extend)?, LineEnd(Extend)?, VCHome(Extend)?
-# except they behave differently when word-wrap is enabled:
-# They go first to the start / end of the display line, like (Home|LineEnd)Display
-# The difference is that, the cursor is already at the point, it goes on to the start
-# or end of the document line, as appropriate for (Home|LineEnd|VCHome)(Extend)?.
-
+# Like Home but when word-wrap is enabled goes first to start of display line
+# HomeDisplay, then to start of document line Home.
 fun void HomeWrap=2349(,)
+
+# Like HomeExtend but when word-wrap is enabled extends first to start of display line
+# HomeDisplayExtend, then to start of document line HomeExtend.
 fun void HomeWrapExtend=2450(,)
+
+# Like LineEnd but when word-wrap is enabled goes first to end of display line
+# LineEndDisplay, then to start of document line LineEnd.
 fun void LineEndWrap=2451(,)
+
+# Like LineEndExtend but when word-wrap is enabled extends first to end of display line
+# LineEndDisplayExtend, then to start of document line LineEndExtend.
 fun void LineEndWrapExtend=2452(,)
+
+# Like VCHome but when word-wrap is enabled goes first to start of display line
+# VCHomeDisplay, then behaves like VCHome.
 fun void VCHomeWrap=2453(,)
+
+# Like VCHomeExtend but when word-wrap is enabled extends first to start of display line
+# VCHomeDisplayExtend, then behaves like VCHomeExtend.
 fun void VCHomeWrapExtend=2454(,)
 
 # Copy the line containing the caret.
@@ -1518,19 +1692,20 @@ fun void MoveCaretInsideView=2401(,)
 fun int LineLength=2350(int line,)
 
 # Highlight the characters at two positions.
-fun void BraceHighlight=2351(position pos1, position pos2)
+fun void BraceHighlight=2351(position posA, position posB)
 
 # Use specified indicator to highlight matching braces instead of changing their style.
-fun void BraceHighlightIndicator=2498(bool useBraceHighlightIndicator, int indicator)
+fun void BraceHighlightIndicator=2498(bool useSetting, int indicator)
 
 # Highlight the character at a position indicating there is no matching brace.
 fun void BraceBadLight=2352(position pos,)
 
 # Use specified indicator to highlight non matching brace instead of changing its style.
-fun void BraceBadLightIndicator=2499(bool useBraceBadLightIndicator, int indicator)
+fun void BraceBadLightIndicator=2499(bool useSetting, int indicator)
 
 # Find the position of a matching brace or INVALID_POSITION if no match.
-fun position BraceMatch=2353(position pos,)
+# The maxReStyle must be 0 for now. It may be defined in a future release.
+fun position BraceMatch=2353(position pos, int maxReStyle)
 
 # Are the end of line characters visible?
 get bool GetViewEOL=2355(,)
@@ -1542,15 +1717,16 @@ set void SetViewEOL=2356(bool visible,)
 get int GetDocPointer=2357(,)
 
 # Change the document object used.
-set void SetDocPointer=2358(, int pointer)
+set void SetDocPointer=2358(, int doc)
 
 # Set which document modification events are sent to the container.
-set void SetModEventMask=2359(int mask,)
+set void SetModEventMask=2359(int eventMask,)
 
 enu EdgeVisualStyle=EDGE_
 val EDGE_NONE=0
 val EDGE_LINE=1
 val EDGE_BACKGROUND=2
+val EDGE_MULTILINE=3
 
 # Retrieve the column number which text should be kept within.
 get int GetEdgeColumn=2360(,)
@@ -1562,9 +1738,9 @@ set void SetEdgeColumn=2361(int column,)
 # Retrieve the edge highlight mode.
 get int GetEdgeMode=2362(,)
 
-# The edge may be displayed by a line (EDGE_LINE) or by highlighting text that
+# The edge may be displayed by a line (EDGE_LINE/EDGE_MULTILINE) or by highlighting text that
 # goes beyond it (EDGE_BACKGROUND) or not displayed at all (EDGE_NONE).
-set void SetEdgeMode=2363(int mode,)
+set void SetEdgeMode=2363(int edgeMode,)
 
 # Retrieve the colour used in edge indication.
 get colour GetEdgeColour=2364(,)
@@ -1572,30 +1748,41 @@ get colour GetEdgeColour=2364(,)
 # Change the colour used in edge indication.
 set void SetEdgeColour=2365(colour edgeColour,)
 
+# Add a new vertical edge to the view.
+fun void MultiEdgeAddLine=2694(int column, colour edgeColour)
+
+# Clear all vertical edges.
+fun void MultiEdgeClearAll=2695(,)
+
 # Sets the current caret position to be the search anchor.
 fun void SearchAnchor=2366(,)
 
 # Find some text starting at the search anchor.
 # Does not ensure the selection is visible.
-fun int SearchNext=2367(int flags, string text)
+fun int SearchNext=2367(int searchFlags, string text)
 
 # Find some text starting at the search anchor and moving backwards.
 # Does not ensure the selection is visible.
-fun int SearchPrev=2368(int flags, string text)
+fun int SearchPrev=2368(int searchFlags, string text)
 
 # Retrieves the number of lines completely visible.
 get int LinesOnScreen=2370(,)
 
+enu PopUp=SC_POPUP_
+val SC_POPUP_NEVER=0
+val SC_POPUP_ALL=1
+val SC_POPUP_TEXT=2
+
 # Set whether a pop up menu is displayed automatically when the user presses
-# the wrong mouse button.
-fun void UsePopUp=2371(bool allowPopUp,)
+# the wrong mouse button on certain areas.
+fun void UsePopUp=2371(int popUpMode,)
 
 # Is the selection rectangular? The alternative is the more common stream selection.
 get bool SelectionIsRectangle=2372(,)
 
 # Set the zoom level. This number of points is added to the size of all fonts.
 # It may be positive to magnify or negative to reduce.
-set void SetZoom=2373(int zoom,)
+set void SetZoom=2373(int zoomInPoints,)
 # Retrieve the zoom level.
 get int GetZoom=2374(,)
 
@@ -1619,9 +1806,11 @@ enu Status=SC_STATUS_
 val SC_STATUS_OK=0
 val SC_STATUS_FAILURE=1
 val SC_STATUS_BADALLOC=2
+val SC_STATUS_WARN_START=1000
+val SC_STATUS_WARN_REGEX=1001
 
 # Change error status - 0 = OK.
-set void SetStatus=2382(int statusCode,)
+set void SetStatus=2382(int status,)
 # Get error status.
 get int GetStatus=2383(,)
 
@@ -1630,6 +1819,11 @@ set void SetMouseDownCaptures=2384(bool captures,)
 # Get whether mouse gets captured.
 get bool GetMouseDownCaptures=2385(,)
 
+# Set whether the mouse wheel can be active outside the window.
+set void SetMouseWheelCaptures=2696(bool captures,)
+# Get whether mouse wheel can be active outside the window.
+get bool GetMouseWheelCaptures=2697(,)
+
 enu CursorShape=SC_CURSOR
 val SC_CURSORNORMAL=-1
 val SC_CURSORARROW=2
@@ -1658,6 +1852,7 @@ fun void WordPartRight=2392(,)
 fun void WordPartRightExtend=2393(,)
 
 # Constants for use with SetVisiblePolicy, similar to SetCaretPolicy.
+enu VisiblePolicy=VISIBLE_
 val VISIBLE_SLOP=0x01
 val VISIBLE_STRICT=0x04
 # Set the way the display area is determined when a particular line
@@ -1670,8 +1865,10 @@ fun void DelLineLeft=2395(,)
 # Delete forwards from the current position to the end of the line.
 fun void DelLineRight=2396(,)
 
-# Get and Set the xOffset (ie, horizontal scroll position).
-set void SetXOffset=2397(int newOffset,)
+# Set the xOffset (ie, horizontal scroll position).
+set void SetXOffset=2397(int xOffset,)
+
+# Get the xOffset (ie, horizontal scroll position).
 get int GetXOffset=2398(,)
 
 # Set the last x chosen value to be the caret x position.
@@ -1700,7 +1897,7 @@ val CARET_STRICT=0x04
 val CARET_JUMPS=0x10
 # If CARET_EVEN is not set, instead of having symmetrical UZs,
 # the left and bottom UZs are extended up to right and top UZs respectively.
-# This way, we favour the displaying of useful information: the begining of lines,
+# This way, we favour the displaying of useful information: the beginning of lines,
 # where most code reside, and the lines after the caret, eg. the body of a function.
 val CARET_EVEN=0x08
 
@@ -1713,7 +1910,7 @@ fun void SetXCaretPolicy=2402(int caretPolicy, int caretSlop)
 fun void SetYCaretPolicy=2403(int caretPolicy, int caretSlop)
 
 # Set printing to line wrapped (SC_WRAP_WORD) or not line wrapped (SC_WRAP_NONE).
-set void SetPrintWrapMode=2406(int mode,)
+set void SetPrintWrapMode=2406(int wrapMode,)
 
 # Is printing line wrapped?
 get int GetPrintWrapMode=2407(,)
@@ -1742,10 +1939,13 @@ set void SetHotspotSingleLine=2421(bool singleLine,)
 # Get the HotspotSingleLine property
 get bool GetHotspotSingleLine=2497(,)
 
-# Move caret between paragraphs (delimited by empty lines).
+# Move caret down one paragraph (delimited by empty lines).
 fun void ParaDown=2413(,)
+# Extend selection down one paragraph (delimited by empty lines).
 fun void ParaDownExtend=2414(,)
+# Move caret up one paragraph (delimited by empty lines).
 fun void ParaUp=2415(,)
+# Extend selection up one paragraph (delimited by empty lines).
 fun void ParaUpExtend=2416(,)
 
 # Given a valid document position, return the previous position taking code
@@ -1756,6 +1956,10 @@ fun position PositionBefore=2417(position pos,)
 # page into account. Maximum value returned is the last position in the document.
 fun position PositionAfter=2418(position pos,)
 
+# Given a valid document position, return a position that differs in a number
+# of characters. Returned value is always between 0 and last position in document.
+fun position PositionRelative=2670(position pos, int relative)
+
 # Copy a range of text to the clipboard. Positions are clipped into the document.
 fun void CopyRange=2419(position start, position end)
 
@@ -1770,7 +1974,7 @@ val SC_SEL_THIN=3
 
 # Set the selection mode to stream (SC_SEL_STREAM) or rectangular (SC_SEL_RECTANGLE/SC_SEL_THIN) or
 # by lines (SC_SEL_LINES).
-set void SetSelectionMode=2422(int mode,)
+set void SetSelectionMode=2422(int selectionMode,)
 
 # Get the mode of the current selection.
 get int GetSelectionMode=2423(,)
@@ -1859,7 +2063,8 @@ get int AutoCGetCurrent=2445(,)
 
 # Get currently selected item text in the auto-completion list
 # Returns the length of the item text
-get int AutoCGetCurrentText=2610(, stringresult s)
+# Result is NUL-terminated.
+get int AutoCGetCurrentText=2610(, stringresult text)
 
 enu CaseInsensitiveBehaviour=SC_CASEINSENSITIVEBEHAVIOUR_
 val SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE=0
@@ -1871,6 +2076,16 @@ set void AutoCSetCaseInsensitiveBehaviour=2634(int behaviour,)
 # Get auto-completion case insensitive behaviour.
 get int AutoCGetCaseInsensitiveBehaviour=2635(,)
 
+enu MultiAutoComplete=SC_MULTIAUTOC_
+val SC_MULTIAUTOC_ONCE=0
+val SC_MULTIAUTOC_EACH=1
+
+# Change the effect of autocompleting when there are multiple selections.
+set void AutoCSetMulti=2636(int multi,)
+
+# Retrieve the effect of autocompleting when there are multiple selections.
+get int AutoCGetMulti=2637(,)
+
 enu Ordering=SC_ORDER_
 val SC_ORDER_PRESORTED=0
 val SC_ORDER_PERFORMSORT=1
@@ -1925,6 +2140,7 @@ get bool GetPasteConvertEndings=2468(,)
 # Duplicate the selection. If selection empty duplicate the line containing the caret.
 fun void SelectionDuplicate=2469(,)
 
+enu Alpha=SC_ALPHA_
 val SC_ALPHA_TRANSPARENT=0
 val SC_ALPHA_OPAQUE=255
 val SC_ALPHA_NOALPHA=256
@@ -1959,22 +2175,22 @@ set void SetIndicatorValue=2502(int value,)
 get int GetIndicatorValue=2503(,)
 
 # Turn a indicator on over a range.
-fun void IndicatorFillRange=2504(int position, int fillLength)
+fun void IndicatorFillRange=2504(position start, int lengthFill)
 
 # Turn a indicator off over a range.
-fun void IndicatorClearRange=2505(int position, int clearLength)
+fun void IndicatorClearRange=2505(position start, int lengthClear)
 
-# Are any indicators present at position?
-fun int IndicatorAllOnFor=2506(int position,)
+# Are any indicators present at pos?
+fun int IndicatorAllOnFor=2506(position pos,)
 
-# What value does a particular indicator have at at a position?
-fun int IndicatorValueAt=2507(int indicator, int position)
+# What value does a particular indicator have at a position?
+fun int IndicatorValueAt=2507(int indicator, position pos)
 
 # Where does a particular indicator start?
-fun int IndicatorStart=2508(int indicator, int position)
+fun int IndicatorStart=2508(int indicator, position pos)
 
 # Where does a particular indicator end?
-fun int IndicatorEnd=2509(int indicator, int position)
+fun int IndicatorEnd=2509(int indicator, position pos)
 
 # Set number of entries in position cache
 set void SetPositionCache=2514(int size,)
@@ -1991,19 +2207,13 @@ get int GetCharacterPointer=2520(,)
 
 # Return a read-only pointer to a range of characters in the document.
 # May move the gap so that the range is contiguous, but will only move up
-# to rangeLength bytes.
-get int GetRangePointer=2643(int position, int rangeLength)
+# to lengthRange bytes.
+get int GetRangePointer=2643(position start, int lengthRange)
 
 # Return a position which, to avoid performance costs, should not be within
 # the range of a call to GetRangePointer.
 get position GetGapPosition=2644(,)
 
-# Always interpret keyboard input as Unicode
-set void SetKeysUnicode=2521(bool keysUnicode,)
-
-# Are keys always interpreted as Unicode?
-get bool GetKeysUnicode=2522(,)
-
 # Set the alpha fill colour of the given indicator.
 set void IndicSetAlpha=2523(int indicator, int alpha)
 
@@ -2096,6 +2306,7 @@ enu AnnotationVisible=ANNOTATION_
 val ANNOTATION_HIDDEN=0
 val ANNOTATION_STANDARD=1
 val ANNOTATION_BOXED=2
+val ANNOTATION_INDENTED=3
 
 # Set the visibility for the annotations for a view
 set void AnnotationSetVisible=2548(int visible,)
@@ -2127,6 +2338,12 @@ fun position CharPositionFromPoint=2561(int x, int y)
 # Return INVALID_POSITION if not close to text.
 fun position CharPositionFromPointClose=2562(int x, int y)
 
+# Set whether switching to rectangular mode while selecting with the mouse is allowed.
+set void SetMouseSelectionRectangularSwitch=2668(bool mouseSelectionRectangularSwitch,)
+
+# Whether switching to rectangular mode while selecting with the mouse is allowed.
+get bool GetMouseSelectionRectangularSwitch=2669(,)
+
 # Set whether multiple selections can be made
 set void SetMultipleSelection=2563(bool multipleSelection,)
 
@@ -2146,7 +2363,7 @@ set void SetAdditionalCaretsBlink=2567(bool additionalCaretsBlink,)
 get bool GetAdditionalCaretsBlink=2568(,)
 
 # Set whether additional carets are visible
-set void SetAdditionalCaretsVisible=2608(bool additionalCaretsBlink,)
+set void SetAdditionalCaretsVisible=2608(bool additionalCaretsVisible,)
 
 # Whether additional carets are visible
 get bool GetAdditionalCaretsVisible=2609(,)
@@ -2161,10 +2378,13 @@ get bool GetSelectionEmpty=2650(,)
 fun void ClearSelections=2571(,)
 
 # Set a simple selection
-fun int SetSelection=2572(int caret, int anchor)
+fun void SetSelection=2572(position caret, position anchor)
 
 # Add a selection
-fun int AddSelection=2573(int caret, int anchor)
+fun void AddSelection=2573(position caret, position anchor)
+
+# Drop one selection
+fun void DropSelectionN=2671(int selection,)
 
 # Set the main selection
 set void SetMainSelection=2574(int selection,)
@@ -2172,42 +2392,61 @@ set void SetMainSelection=2574(int selection,)
 # Which selection is the main selection
 get int GetMainSelection=2575(,)
 
-set void SetSelectionNCaret=2576(int selection, position pos)
+# Set the caret position of the nth selection.
+set void SetSelectionNCaret=2576(int selection, position caret)
+# Return the caret position of the nth selection.
 get position GetSelectionNCaret=2577(int selection,)
-set void SetSelectionNAnchor=2578(int selection, position posAnchor)
+# Set the anchor position of the nth selection.
+set void SetSelectionNAnchor=2578(int selection, position anchor)
+# Return the anchor position of the nth selection.
 get position GetSelectionNAnchor=2579(int selection,)
+# Set the virtual space of the caret of the nth selection.
 set void SetSelectionNCaretVirtualSpace=2580(int selection, int space)
+# Return the virtual space of the caret of the nth selection.
 get int GetSelectionNCaretVirtualSpace=2581(int selection,)
+# Set the virtual space of the anchor of the nth selection.
 set void SetSelectionNAnchorVirtualSpace=2582(int selection, int space)
+# Return the virtual space of the anchor of the nth selection.
 get int GetSelectionNAnchorVirtualSpace=2583(int selection,)
 
 # Sets the position that starts the selection - this becomes the anchor.
-set void SetSelectionNStart=2584(int selection, position pos)
+set void SetSelectionNStart=2584(int selection, position anchor)
 
 # Returns the position at the start of the selection.
 get position GetSelectionNStart=2585(int selection,)
 
 # Sets the position that ends the selection - this becomes the currentPosition.
-set void SetSelectionNEnd=2586(int selection, position pos)
+set void SetSelectionNEnd=2586(int selection, position caret)
 
 # Returns the position at the end of the selection.
 get position GetSelectionNEnd=2587(int selection,)
 
-set void SetRectangularSelectionCaret=2588(position pos,)
+# Set the caret position of the rectangular selection.
+set void SetRectangularSelectionCaret=2588(position caret,)
+# Return the caret position of the rectangular selection.
 get position GetRectangularSelectionCaret=2589(,)
-set void SetRectangularSelectionAnchor=2590(position posAnchor,)
+# Set the anchor position of the rectangular selection.
+set void SetRectangularSelectionAnchor=2590(position anchor,)
+# Return the anchor position of the rectangular selection.
 get position GetRectangularSelectionAnchor=2591(,)
+# Set the virtual space of the caret of the rectangular selection.
 set void SetRectangularSelectionCaretVirtualSpace=2592(int space,)
+# Return the virtual space of the caret of the rectangular selection.
 get int GetRectangularSelectionCaretVirtualSpace=2593(,)
+# Set the virtual space of the anchor of the rectangular selection.
 set void SetRectangularSelectionAnchorVirtualSpace=2594(int space,)
+# Return the virtual space of the anchor of the rectangular selection.
 get int GetRectangularSelectionAnchorVirtualSpace=2595(,)
 
 enu VirtualSpace=SCVS_
 val SCVS_NONE=0
 val SCVS_RECTANGULARSELECTION=1
 val SCVS_USERACCESSIBLE=2
+val SCVS_NOWRAPLINESTART=4
 
+# Set options for virtual space behaviour.
 set void SetVirtualSpaceOptions=2596(int virtualSpaceOptions,)
+# Return options for virtual space behaviour.
 get int GetVirtualSpaceOptions=2597(,)
 
 # On GTK+, allow selecting the modifier key to use for mouse-based
@@ -2246,6 +2485,14 @@ fun void RotateSelection=2606(,)
 # Swap that caret and anchor of the main selection.
 fun void SwapMainAnchorCaret=2607(,)
 
+# Add the next occurrence of the main selection to the set of selections as main.
+# If the current selection is empty then select word around caret.
+fun void MultipleSelectAddNext=2688(,)
+
+# Add each occurrence of the main selection in the target to the set of selections.
+# If the current selection is empty then select word around caret.
+fun void MultipleSelectAddEach=2689(,)
+
 # Indicate that the internal state of a lexer has changed over a range and therefore
 # there may be a need to redraw.
 fun int ChangeLexerState=2617(position start, position end)
@@ -2292,8 +2539,11 @@ fun void ScrollToStart=2628(,)
 # Scroll to end of document.
 fun void ScrollToEnd=2629(,)
 
+enu Technology=SC_TECHNOLOGY_
 val SC_TECHNOLOGY_DEFAULT=0
 val SC_TECHNOLOGY_DIRECTWRITE=1
+val SC_TECHNOLOGY_DIRECTWRITERETAIN=2
+val SC_TECHNOLOGY_DIRECTWRITEDC=3
 
 # Set the technology used.
 set void SetTechnology=2630(int technology,)
@@ -2326,6 +2576,32 @@ get bool GetCaretLineVisibleAlways=2654(,)
 # Sets the caret line to always visible.
 set void SetCaretLineVisibleAlways=2655(bool alwaysVisible,)
 
+# Line end types which may be used in addition to LF, CR, and CRLF
+# SC_LINE_END_TYPE_UNICODE includes U+2028 Line Separator,
+# U+2029 Paragraph Separator, and U+0085 Next Line
+enu LineEndType=SC_LINE_END_TYPE_
+val SC_LINE_END_TYPE_DEFAULT=0
+val SC_LINE_END_TYPE_UNICODE=1
+
+# Set the line end types that the application wants to use. May not be used if incompatible with lexer or 
encoding.
+set void SetLineEndTypesAllowed=2656(int lineEndBitSet,)
+
+# Get the line end types currently allowed.
+get int GetLineEndTypesAllowed=2657(,)
+
+# Get the line end types currently recognised. May be a subset of the allowed types due to lexer limitation.
+get int GetLineEndTypesActive=2658(,)
+
+# Set the way a character is drawn.
+set void SetRepresentation=2665(string encodedCharacter, string representation)
+
+# Set the way a character is drawn.
+# Result is NUL-terminated.
+get int GetRepresentation=2666(string encodedCharacter, stringresult representation)
+
+# Remove a character representation.
+fun void ClearRepresentation=2667(string encodedCharacter,)
+
 # Start notifying the container of all key presses and commands.
 fun void StartRecord=3001(,)
 
@@ -2348,7 +2624,7 @@ set void SetProperty=4004(string key, string value)
 val KEYWORDSET_MAX=8
 
 # Set up the key words used by the lexer.
-set void SetKeyWords=4005(int keywordSet, string keyWords)
+set void SetKeyWords=4005(int keyWordSet, string keyWords)
 
 # Set the lexing language of the document based on string name.
 set void SetLexerLanguage=4006(, string language)
@@ -2357,27 +2633,31 @@ set void SetLexerLanguage=4006(, string language)
 fun void LoadLexerLibrary=4007(, string path)
 
 # Retrieve a "property" value previously set with SetProperty.
-get int GetProperty=4008(string key, stringresult buf)
+# Result is NUL-terminated.
+get int GetProperty=4008(string key, stringresult value)
 
 # Retrieve a "property" value previously set with SetProperty,
 # with "$()" variable replacement on returned buffer.
-get int GetPropertyExpanded=4009(string key, stringresult buf)
+# Result is NUL-terminated.
+get int GetPropertyExpanded=4009(string key, stringresult value)
 
 # Retrieve a "property" value previously set with SetProperty,
 # interpreted as an int AFTER any "$()" variable replacement.
-get int GetPropertyInt=4010(string key,)
+get int GetPropertyInt=4010(string key, int defaultValue)
 
 # Retrieve the number of bits the current lexer needs for styling.
 get int GetStyleBitsNeeded=4011(,)
 
 # Retrieve the name of the lexer.
 # Return the length of the text.
-get int GetLexerLanguage=4012(, stringresult text)
+# Result is NUL-terminated.
+get int GetLexerLanguage=4012(, stringresult language)
 
 # For private communication between an application and a known lexer.
 fun int PrivateLexerCall=4013(int operation, int pointer)
 
 # Retrieve a '\n' separated list of properties understood by the current lexer.
+# Result is NUL-terminated.
 fun int PropertyNames=4014(, stringresult names)
 
 enu TypeProperty=SC_TYPE_
@@ -2389,11 +2669,46 @@ val SC_TYPE_STRING=2
 fun int PropertyType=4015(string name,)
 
 # Describe a property.
+# Result is NUL-terminated.
 fun int DescribeProperty=4016(string name, stringresult description)
 
 # Retrieve a '\n' separated list of descriptions of the keyword sets understood by the current lexer.
+# Result is NUL-terminated.
 fun int DescribeKeyWordSets=4017(, stringresult descriptions)
 
+# Bit set of LineEndType enumertion for which line ends beyond the standard
+# LF, CR, and CRLF are supported by the lexer.
+get int GetLineEndTypesSupported=4018(,)
+
+# Allocate a set of sub styles for a particular base style, returning start of range
+fun int AllocateSubStyles=4020(int styleBase, int numberStyles)
+
+# The starting style number for the sub styles associated with a base style
+get int GetSubStylesStart=4021(int styleBase,)
+
+# The number of sub styles associated with a base style
+get int GetSubStylesLength=4022(int styleBase,)
+
+# For a sub style, return the base style, else return the argument.
+get int GetStyleFromSubStyle=4027(int subStyle,)
+
+# For a secondary style, return the primary style, else return the argument.
+get int GetPrimaryStyleFromStyle=4028(int style,)
+
+# Free allocated sub styles
+fun void FreeSubStyles=4023(,)
+
+# Set the identifiers that are shown in a particular style
+set void SetIdentifiers=4024(int style, string identifiers)
+
+# Where styles are duplicated by a feature such as active/inactive code
+# return the distance between the two types.
+get int DistanceToSecondaryStyles=4025(,)
+
+# Get the set of base styles that can be extended with sub styles
+# Result is NUL-terminated.
+get int GetSubStyleBases=4026(, stringresult styles)
+
 # Notifications
 # Type of modification and the action which caused the modification.
 # These are defined as a bit mask to make it easy to specify which notifications are wanted.
@@ -2419,7 +2734,9 @@ val SC_MOD_CHANGEMARGIN=0x10000
 val SC_MOD_CHANGEANNOTATION=0x20000
 val SC_MOD_CONTAINER=0x40000
 val SC_MOD_LEXERSTATE=0x80000
-val SC_MODEVENTMASKALL=0xFFFFF
+val SC_MOD_INSERTCHECK=0x100000
+val SC_MOD_CHANGETABSTOPS=0x200000
+val SC_MODEVENTMASKALL=0x3FFFFF
 
 enu Update=SC_UPDATE_
 val SC_UPDATE_CONTENT=0x1
@@ -2469,6 +2786,13 @@ val SCMOD_ALT=4
 val SCMOD_SUPER=8
 val SCMOD_META=16
 
+enu CompletionMethods=SC_AC_
+val SC_AC_FILLUP=1
+val SC_AC_DOUBLECLICK=2
+val SC_AC_TAB=3
+val SC_AC_NEWLINE=4
+val SC_AC_COMMAND=5
+
 ################################################
 # For SciLexer.h
 enu Lexer=SCLEX_
@@ -2580,6 +2904,19 @@ val SCLEX_OSCRIPT=106
 val SCLEX_VISUALPROLOG=107
 val SCLEX_LITERATEHASKELL=108
 val SCLEX_STTXT=109
+val SCLEX_KVIRC=110
+val SCLEX_RUST=111
+val SCLEX_DMAP=112
+val SCLEX_AS=113
+val SCLEX_DMIS=114
+val SCLEX_REGISTRY=115
+val SCLEX_BIBTEX=116
+val SCLEX_SREC=117
+val SCLEX_IHEX=118
+val SCLEX_TEHEX=119
+val SCLEX_JSON=120
+val SCLEX_EDIFACT=121
+val SCLEX_INDENT=122
 
 # When a lexer specifies its language as SCLEX_AUTOMATIC it receives a
 # value assigned in sequence from SCLEX_AUTOMATIC+1.
@@ -2603,9 +2940,16 @@ val SCE_P_COMMENTBLOCK=12
 val SCE_P_STRINGEOL=13
 val SCE_P_WORD2=14
 val SCE_P_DECORATOR=15
-# Lexical states for SCLEX_CPP
+val SCE_P_FSTRING=16
+val SCE_P_FCHARACTER=17
+val SCE_P_FTRIPLE=18
+val SCE_P_FTRIPLEDOUBLE=19
+# Lexical states for SCLEX_CPP, SCLEX_BULLANT, SCLEX_COBOL, SCLEX_TACL, SCLEX_TAL
 lex Cpp=SCLEX_CPP SCE_C_
 lex BullAnt=SCLEX_BULLANT SCE_C_
+lex COBOL=SCLEX_COBOL SCE_C_
+lex TACL=SCLEX_TACL SCE_C_
+lex TAL=SCLEX_TAL SCE_C_
 val SCE_C_DEFAULT=0
 val SCE_C_COMMENT=1
 val SCE_C_COMMENTLINE=2
@@ -2631,6 +2975,9 @@ val SCE_C_TRIPLEVERBATIM=21
 val SCE_C_HASHQUOTEDSTRING=22
 val SCE_C_PREPROCESSORCOMMENT=23
 val SCE_C_PREPROCESSORCOMMENTDOC=24
+val SCE_C_USERLITERAL=25
+val SCE_C_TASKMARKER=26
+val SCE_C_ESCAPESEQUENCE=27
 # Lexical states for SCLEX_D
 lex D=SCLEX_D SCE_D_
 val SCE_D_DEFAULT=0
@@ -2683,8 +3030,6 @@ val SCE_TCL_BLOCK_COMMENT=21
 # Lexical states for SCLEX_HTML, SCLEX_XML
 lex HTML=SCLEX_HTML SCE_H_ SCE_HJ_ SCE_HJA_ SCE_HB_ SCE_HBA_ SCE_HP_ SCE_HPHP_ SCE_HPA_
 lex XML=SCLEX_XML SCE_H_ SCE_HJ_ SCE_HJA_ SCE_HB_ SCE_HBA_ SCE_HP_ SCE_HPHP_ SCE_HPA_
-lex ASP=SCLEX_ASP SCE_H_ SCE_HJ_ SCE_HJA_ SCE_HB_ SCE_HBA_ SCE_HP_ SCE_HPHP_ SCE_HPA_
-lex PHP=SCLEX_PHP SCE_H_ SCE_HJ_ SCE_HJA_ SCE_HB_ SCE_HBA_ SCE_HP_ SCE_HPHP_ SCE_HPA_
 val SCE_H_DEFAULT=0
 val SCE_H_TAG=1
 val SCE_H_TAGUNKNOWN=2
@@ -2891,10 +3236,13 @@ val SCE_RB_STDIN=30
 val SCE_RB_STDOUT=31
 val SCE_RB_STDERR=40
 val SCE_RB_UPPER_BOUND=41
-# Lexical states for SCLEX_VB, SCLEX_VBSCRIPT, SCLEX_POWERBASIC
+# Lexical states for SCLEX_VB, SCLEX_VBSCRIPT, SCLEX_POWERBASIC, SCLEX_BLITZBASIC, SCLEX_PUREBASIC, 
SCLEX_FREEBASIC
 lex VB=SCLEX_VB SCE_B_
 lex VBScript=SCLEX_VBSCRIPT SCE_B_
 lex PowerBasic=SCLEX_POWERBASIC SCE_B_
+lex BlitzBasic=SCLEX_BLITZBASIC SCE_B_
+lex PureBasic=SCLEX_PUREBASIC SCE_B_
+lex FreeBasic=SCLEX_FREEBASIC SCE_B_
 val SCE_B_DEFAULT=0
 val SCE_B_COMMENT=1
 val SCE_B_NUMBER=2
@@ -2914,6 +3262,10 @@ val SCE_B_LABEL=15
 val SCE_B_ERROR=16
 val SCE_B_HEXNUMBER=17
 val SCE_B_BINNUMBER=18
+val SCE_B_COMMENTBLOCK=19
+val SCE_B_DOCLINE=20
+val SCE_B_DOCBLOCK=21
+val SCE_B_DOCKEYWORD=22
 # Lexical states for SCLEX_PROPERTIES
 lex Properties=SCLEX_PROPERTIES SCE_PROPS_
 val SCE_PROPS_DEFAULT=0
@@ -2985,6 +3337,24 @@ val SCE_ERR_TIDY=19
 val SCE_ERR_JAVA_STACK=20
 val SCE_ERR_VALUE=21
 val SCE_ERR_GCC_INCLUDED_FROM=22
+val SCE_ERR_ESCSEQ=23
+val SCE_ERR_ESCSEQ_UNKNOWN=24
+val SCE_ERR_ES_BLACK=40
+val SCE_ERR_ES_RED=41
+val SCE_ERR_ES_GREEN=42
+val SCE_ERR_ES_BROWN=43
+val SCE_ERR_ES_BLUE=44
+val SCE_ERR_ES_MAGENTA=45
+val SCE_ERR_ES_CYAN=46
+val SCE_ERR_ES_GRAY=47
+val SCE_ERR_ES_DARK_GRAY=48
+val SCE_ERR_ES_BRIGHT_RED=49
+val SCE_ERR_ES_BRIGHT_GREEN=50
+val SCE_ERR_ES_YELLOW=51
+val SCE_ERR_ES_BRIGHT_BLUE=52
+val SCE_ERR_ES_BRIGHT_MAGENTA=53
+val SCE_ERR_ES_BRIGHT_CYAN=54
+val SCE_ERR_ES_WHITE=55
 # Lexical states for SCLEX_BATCH
 lex Batch=SCLEX_BATCH SCE_BAT_
 val SCE_BAT_DEFAULT=0
@@ -3083,6 +3453,20 @@ val SCE_BAAN_OPERATOR=7
 val SCE_BAAN_IDENTIFIER=8
 val SCE_BAAN_STRINGEOL=9
 val SCE_BAAN_WORD2=10
+val SCE_BAAN_WORD3=11
+val SCE_BAAN_WORD4=12
+val SCE_BAAN_WORD5=13
+val SCE_BAAN_WORD6=14
+val SCE_BAAN_WORD7=15
+val SCE_BAAN_WORD8=16
+val SCE_BAAN_WORD9=17
+val SCE_BAAN_TABLEDEF=18
+val SCE_BAAN_TABLESQL=19
+val SCE_BAAN_FUNCTION=20
+val SCE_BAAN_DOMDEF=21
+val SCE_BAAN_FUNCDEF=22
+val SCE_BAAN_OBJECTDEF=23
+val SCE_BAAN_DEFINEDEF=24
 # Lexical states for SCLEX_LISP
 lex Lisp=SCLEX_LISP SCE_LISP_
 val SCE_LISP_DEFAULT=0
@@ -3166,8 +3550,9 @@ val SCE_SCRIPTOL_IDENTIFIER=12
 val SCE_SCRIPTOL_TRIPLE=13
 val SCE_SCRIPTOL_CLASSNAME=14
 val SCE_SCRIPTOL_PREPROCESSOR=15
-# Lexical states for SCLEX_ASM
+# Lexical states for SCLEX_ASM, SCLEX_AS
 lex Asm=SCLEX_ASM SCE_ASM_
+lex As=SCLEX_AS SCE_ASM_
 val SCE_ASM_DEFAULT=0
 val SCE_ASM_COMMENT=1
 val SCE_ASM_NUMBER=2
@@ -3454,6 +3839,11 @@ val SCE_V_OPERATOR=10
 val SCE_V_IDENTIFIER=11
 val SCE_V_STRINGEOL=12
 val SCE_V_USER=19
+val SCE_V_COMMENT_WORD=20
+val SCE_V_INPUT=21
+val SCE_V_OUTPUT=22
+val SCE_V_INOUT=23
+val SCE_V_PORT_CONNECT=24
 # Lexical states for SCLEX_KIX
 lex Kix=SCLEX_KIX SCE_KIX_
 val SCE_KIX_DEFAULT=0
@@ -3466,6 +3856,7 @@ val SCE_KIX_MACRO=6
 val SCE_KIX_KEYWORD=7
 val SCE_KIX_FUNCTIONS=8
 val SCE_KIX_OPERATOR=9
+val SCE_KIX_COMMENTSTREAM=10
 val SCE_KIX_IDENTIFIER=31
 # Lexical states for SCLEX_GUI4CLI
 lex Gui4Cli=SCLEX_GUI4CLI SCE_GC_
@@ -3576,6 +3967,7 @@ val SCE_VHDL_STDFUNCTION=11
 val SCE_VHDL_STDPACKAGE=12
 val SCE_VHDL_STDTYPE=13
 val SCE_VHDL_USERWORD=14
+val SCE_VHDL_BLOCK_COMMENT=15
 # Lexical states for SCLEX_CAML
 lex Caml=SCLEX_CAML SCE_CAML_
 val SCE_CAML_DEFAULT=0
@@ -3697,6 +4089,7 @@ val SCE_SQL_USER2=20
 val SCE_SQL_USER3=21
 val SCE_SQL_USER4=22
 val SCE_SQL_QUOTEDIDENTIFIER=23
+val SCE_SQL_QOPERATOR=24
 # Lexical states for SCLEX_SMALLTALK
 lex Smalltalk=SCLEX_SMALLTALK SCE_ST_
 val SCE_ST_DEFAULT=0
@@ -3848,39 +4241,20 @@ val SCE_PLM_OPERATOR=5
 val SCE_PLM_CONTROL=6
 val SCE_PLM_KEYWORD=7
 # Lexical state for SCLEX_PROGRESS
-lex Progress=SCLEX_PROGRESS SCE_4GL_
-val SCE_4GL_DEFAULT=0
-val SCE_4GL_NUMBER=1
-val SCE_4GL_WORD=2
-val SCE_4GL_STRING=3
-val SCE_4GL_CHARACTER=4
-val SCE_4GL_PREPROCESSOR=5
-val SCE_4GL_OPERATOR=6
-val SCE_4GL_IDENTIFIER=7
-val SCE_4GL_BLOCK=8
-val SCE_4GL_END=9
-val SCE_4GL_COMMENT1=10
-val SCE_4GL_COMMENT2=11
-val SCE_4GL_COMMENT3=12
-val SCE_4GL_COMMENT4=13
-val SCE_4GL_COMMENT5=14
-val SCE_4GL_COMMENT6=15
-val SCE_4GL_DEFAULT_=16
-val SCE_4GL_NUMBER_=17
-val SCE_4GL_WORD_=18
-val SCE_4GL_STRING_=19
-val SCE_4GL_CHARACTER_=20
-val SCE_4GL_PREPROCESSOR_=21
-val SCE_4GL_OPERATOR_=22
-val SCE_4GL_IDENTIFIER_=23
-val SCE_4GL_BLOCK_=24
-val SCE_4GL_END_=25
-val SCE_4GL_COMMENT1_=26
-val SCE_4GL_COMMENT2_=27
-val SCE_4GL_COMMENT3_=28
-val SCE_4GL_COMMENT4_=29
-val SCE_4GL_COMMENT5_=30
-val SCE_4GL_COMMENT6_=31
+lex Progress=SCLEX_PROGRESS SCE_ABL_
+val SCE_ABL_DEFAULT=0
+val SCE_ABL_NUMBER=1
+val SCE_ABL_WORD=2
+val SCE_ABL_STRING=3
+val SCE_ABL_CHARACTER=4
+val SCE_ABL_PREPROCESSOR=5
+val SCE_ABL_OPERATOR=6
+val SCE_ABL_IDENTIFIER=7
+val SCE_ABL_BLOCK=8
+val SCE_ABL_END=9
+val SCE_ABL_COMMENT=10
+val SCE_ABL_TASKMARKER=11
+val SCE_ABL_LINECOMMENT=12
 # Lexical states for SCLEX_ABAQUS
 lex ABAQUS=SCLEX_ABAQUS SCE_ABAQUS_
 val SCE_ABAQUS_DEFAULT=0
@@ -3924,8 +4298,8 @@ val SCE_R_OPERATOR=8
 val SCE_R_IDENTIFIER=9
 val SCE_R_INFIX=10
 val SCE_R_INFIXEOL=11
-# Lexical state for SCLEX_MAGIKSF
-lex MagikSF=SCLEX_MAGIKSF SCE_MAGIK_
+# Lexical state for SCLEX_MAGIK
+lex MagikSF=SCLEX_MAGIK SCE_MAGIK_
 val SCE_MAGIK_DEFAULT=0
 val SCE_MAGIK_COMMENT=1
 val SCE_MAGIK_HYPER_COMMENT=16
@@ -4187,10 +4561,10 @@ val SCE_COFFEESCRIPT_COMMENTDOCKEYWORDERROR=18
 val SCE_COFFEESCRIPT_GLOBALCLASS=19
 val SCE_COFFEESCRIPT_STRINGRAW=20
 val SCE_COFFEESCRIPT_TRIPLEVERBATIM=21
-val SCE_COFFEESCRIPT_HASHQUOTEDSTRING=22
 val SCE_COFFEESCRIPT_COMMENTBLOCK=22
 val SCE_COFFEESCRIPT_VERBOSE_REGEX=23
 val SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT=24
+val SCE_COFFEESCRIPT_INSTANCEPROPERTY=25
 # Lexical states for SCLEX_AVS
 lex AVS=SCLEX_AVS SCE_AVS_
 val SCE_AVS_DEFAULT=0
@@ -4305,6 +4679,147 @@ val SCE_STTXT_IDENTIFIER=15
 val SCE_STTXT_DATETIME=16
 val SCE_STTXT_VARS=17
 val SCE_STTXT_PRAGMAS=18
+# Lexical states for SCLEX_KVIRC
+lex KVIrc=SCLEX_KVIRC SCE_KVIRC_
+val SCE_KVIRC_DEFAULT=0
+val SCE_KVIRC_COMMENT=1
+val SCE_KVIRC_COMMENTBLOCK=2
+val SCE_KVIRC_STRING=3
+val SCE_KVIRC_WORD=4
+val SCE_KVIRC_KEYWORD=5
+val SCE_KVIRC_FUNCTION_KEYWORD=6
+val SCE_KVIRC_FUNCTION=7
+val SCE_KVIRC_VARIABLE=8
+val SCE_KVIRC_NUMBER=9
+val SCE_KVIRC_OPERATOR=10
+val SCE_KVIRC_STRING_FUNCTION=11
+val SCE_KVIRC_STRING_VARIABLE=12
+# Lexical states for SCLEX_RUST
+lex Rust=SCLEX_RUST SCE_RUST_
+val SCE_RUST_DEFAULT=0
+val SCE_RUST_COMMENTBLOCK=1
+val SCE_RUST_COMMENTLINE=2
+val SCE_RUST_COMMENTBLOCKDOC=3
+val SCE_RUST_COMMENTLINEDOC=4
+val SCE_RUST_NUMBER=5
+val SCE_RUST_WORD=6
+val SCE_RUST_WORD2=7
+val SCE_RUST_WORD3=8
+val SCE_RUST_WORD4=9
+val SCE_RUST_WORD5=10
+val SCE_RUST_WORD6=11
+val SCE_RUST_WORD7=12
+val SCE_RUST_STRING=13
+val SCE_RUST_STRINGR=14
+val SCE_RUST_CHARACTER=15
+val SCE_RUST_OPERATOR=16
+val SCE_RUST_IDENTIFIER=17
+val SCE_RUST_LIFETIME=18
+val SCE_RUST_MACRO=19
+val SCE_RUST_LEXERROR=20
+val SCE_RUST_BYTESTRING=21
+val SCE_RUST_BYTESTRINGR=22
+val SCE_RUST_BYTECHARACTER=23
+# Lexical states for SCLEX_DMAP
+lex DMAP=SCLEX_DMAP SCE_DMAP_
+val SCE_DMAP_DEFAULT=0
+val SCE_DMAP_COMMENT=1
+val SCE_DMAP_NUMBER=2
+val SCE_DMAP_STRING1=3
+val SCE_DMAP_STRING2=4
+val SCE_DMAP_STRINGEOL=5
+val SCE_DMAP_OPERATOR=6
+val SCE_DMAP_IDENTIFIER=7
+val SCE_DMAP_WORD=8
+val SCE_DMAP_WORD2=9
+val SCE_DMAP_WORD3=10
+# Lexical states for SCLEX_DMIS
+lex DMIS=SCLEX_DMIS SCE_DMIS_
+val SCE_DMIS_DEFAULT=0
+val SCE_DMIS_COMMENT=1
+val SCE_DMIS_STRING=2
+val SCE_DMIS_NUMBER=3
+val SCE_DMIS_KEYWORD=4
+val SCE_DMIS_MAJORWORD=5
+val SCE_DMIS_MINORWORD=6
+val SCE_DMIS_UNSUPPORTED_MAJOR=7
+val SCE_DMIS_UNSUPPORTED_MINOR=8
+val SCE_DMIS_LABEL=9
+# Lexical states for SCLEX_REGISTRY
+lex REG=SCLEX_REGISTRY SCE_REG_
+val SCE_REG_DEFAULT=0
+val SCE_REG_COMMENT=1
+val SCE_REG_VALUENAME=2
+val SCE_REG_STRING=3
+val SCE_REG_HEXDIGIT=4
+val SCE_REG_VALUETYPE=5
+val SCE_REG_ADDEDKEY=6
+val SCE_REG_DELETEDKEY=7
+val SCE_REG_ESCAPED=8
+val SCE_REG_KEYPATH_GUID=9
+val SCE_REG_STRING_GUID=10
+val SCE_REG_PARAMETER=11
+val SCE_REG_OPERATOR=12
+# Lexical state for SCLEX_BIBTEX
+lex BibTeX=SCLEX_BIBTEX SCE_BIBTEX_
+val SCE_BIBTEX_DEFAULT=0
+val SCE_BIBTEX_ENTRY=1
+val SCE_BIBTEX_UNKNOWN_ENTRY=2
+val SCE_BIBTEX_KEY=3
+val SCE_BIBTEX_PARAMETER=4
+val SCE_BIBTEX_VALUE=5
+val SCE_BIBTEX_COMMENT=6
+# Lexical state for SCLEX_SREC
+lex Srec=SCLEX_SREC SCE_HEX_
+val SCE_HEX_DEFAULT=0
+val SCE_HEX_RECSTART=1
+val SCE_HEX_RECTYPE=2
+val SCE_HEX_RECTYPE_UNKNOWN=3
+val SCE_HEX_BYTECOUNT=4
+val SCE_HEX_BYTECOUNT_WRONG=5
+val SCE_HEX_NOADDRESS=6
+val SCE_HEX_DATAADDRESS=7
+val SCE_HEX_RECCOUNT=8
+val SCE_HEX_STARTADDRESS=9
+val SCE_HEX_ADDRESSFIELD_UNKNOWN=10
+val SCE_HEX_EXTENDEDADDRESS=11
+val SCE_HEX_DATA_ODD=12
+val SCE_HEX_DATA_EVEN=13
+val SCE_HEX_DATA_UNKNOWN=14
+val SCE_HEX_DATA_EMPTY=15
+val SCE_HEX_CHECKSUM=16
+val SCE_HEX_CHECKSUM_WRONG=17
+val SCE_HEX_GARBAGE=18
+# Lexical state for SCLEX_IHEX (shared with Srec)
+lex IHex=SCLEX_IHEX SCE_HEX_
+# Lexical state for SCLEX_TEHEX (shared with Srec)
+lex TEHex=SCLEX_TEHEX SCE_HEX_
+# Lexical states for SCLEX_JSON
+lex JSON=SCLEX_JSON SCE_JSON_
+val SCE_JSON_DEFAULT=0
+val SCE_JSON_NUMBER=1
+val SCE_JSON_STRING=2
+val SCE_JSON_STRINGEOL=3
+val SCE_JSON_PROPERTYNAME=4
+val SCE_JSON_ESCAPESEQUENCE=5
+val SCE_JSON_LINECOMMENT=6
+val SCE_JSON_BLOCKCOMMENT=7
+val SCE_JSON_OPERATOR=8
+val SCE_JSON_URI=9
+val SCE_JSON_COMPACTIRI=10
+val SCE_JSON_KEYWORD=11
+val SCE_JSON_LDKEYWORD=12
+val SCE_JSON_ERROR=13
+lex EDIFACT=SCLEX_EDIFACT SCE_EDI_
+val SCE_EDI_DEFAULT=0
+val SCE_EDI_SEGMENTSTART=1
+val SCE_EDI_SEGMENTEND=2
+val SCE_EDI_SEP_ELEMENT=3
+val SCE_EDI_SEP_COMPOSITE=4
+val SCE_EDI_SEP_RELEASE=5
+val SCE_EDI_UNA=6
+val SCE_EDI_UNH=7
+val SCE_EDI_BADSEGMENT=8
 
 # Events
 
@@ -4322,7 +4837,7 @@ evt void MacroRecord=2009(int message, int wParam, int lParam)
 evt void MarginClick=2010(int modifiers, int position, int margin)
 evt void NeedShown=2011(int position, int length)
 evt void Painted=2013(void)
-evt void UserListSelection=2014(int listType, string text, int position)
+evt void UserListSelection=2014(int listType, string text, int position, int ch, CompletionMethods 
listCompletionMethod)
 evt void URIDropped=2015(string text)
 evt void DwellStart=2016(int position, int x, int y)
 evt void DwellEnd=2017(int position, int x, int y)
@@ -4330,68 +4845,27 @@ evt void Zoom=2018(void)
 evt void HotSpotClick=2019(int modifiers, int position)
 evt void HotSpotDoubleClick=2020(int modifiers, int position)
 evt void CallTipClick=2021(int position)
-evt void AutoCSelection=2022(string text, int position)
+evt void AutoCSelection=2022(string text, int position, int ch, CompletionMethods listCompletionMethod)
 evt void IndicatorClick=2023(int modifiers, int position)
 evt void IndicatorRelease=2024(int modifiers, int position)
 evt void AutoCCancelled=2025(void)
 evt void AutoCCharDeleted=2026(void)
 evt void HotSpotReleaseClick=2027(int modifiers, int position)
+evt void FocusIn=2028(void)
+evt void FocusOut=2029(void)
+evt void AutoCCompleted=2030(string text, int position, int ch, CompletionMethods listCompletionMethod)
+evt void MarginRightClick=2031(int modifiers, int position, int margin)
 
-cat Provisional
+# There are no provisional APIs currently, but some arguments to SCI_SETTECHNOLOGY are provisional.
 
-# Line end types which may be used in addition to LF, CR, and CRLF
-# SC_LINE_END_TYPE_UNICODE includes U+2028 Line Separator,
-# U+2029 Paragraph Separator, and U+0085 Next Line
-enu LineEndType=SC_LINE_END_TYPE_
-val SC_LINE_END_TYPE_DEFAULT=0
-val SC_LINE_END_TYPE_UNICODE=1
-
-# Set the line end types that the application wants to use. May not be used if incompatible with lexer or 
encoding.
-set void SetLineEndTypesAllowed=2656(int lineEndBitSet,)
-
-# Get the line end types currently allowed.
-get int GetLineEndTypesAllowed=2657(,)
-
-# Get the line end types currently recognised. May be a subset of the allowed types due to lexer limitation.
-get int GetLineEndTypesActive=2658(,)
-
-# Bit set of LineEndType enumertion for which line ends beyond the standard
-# LF, CR, and CRLF are supported by the lexer.
-get int GetLineEndTypesSupported=4018(,)
-
-# Allocate a set of sub styles for a particular base style, returning start of range
-fun int AllocateSubStyles=4020(int styleBase, int numberStyles)
-
-# The starting style number for the sub styles associated with a base style
-get int GetSubStylesStart=4021(int styleBase,)
-
-# The number of sub styles associated with a base style
-get int GetSubStylesLength=4022(int styleBase,)
-
-# Free allocated sub styles
-fun void FreeSubStyles=4023(,)
-
-# Set the identifiers that are shown in a particular style
-set void SetIdentifiers=4024(int style, string identifiers)
-
-# Where styles are duplicated by a feature such as active/inactive code
-# return the distance between the two types.
-get int DistanceToSecondaryStyles=4025(,)
-
-# Get the set of base styles that can be extended with sub styles
-get int GetSubStyleBases=4026(, stringresult styles)
+cat Provisional
 
 cat Deprecated
 
-# Deprecated in 2.21
-# The SC_CP_DBCS value can be used to indicate a DBCS mode for GTK+.
-val SC_CP_DBCS=1
+# Deprecated in 3.5.5
 
-# Deprecated in 2.30
-
-# In palette mode?
-get bool GetUsePalette=2139(,)
+# Always interpret keyboard input as Unicode
+set void SetKeysUnicode=2521(bool keysUnicode,)
 
-# In palette mode, Scintilla uses the environment's palette calls to display
-# more colours. This may lead to ugly displays.
-set void SetUsePalette=2039(bool usePalette,)
+# Are keys always interpreted as Unicode?
+get bool GetKeysUnicode=2522(,)
diff --git a/plugins/scintilla/scintilla/include/ScintillaWidget.h 
b/plugins/scintilla/scintilla/include/ScintillaWidget.h
index f8cd212..1721f65 100644
--- a/plugins/scintilla/scintilla/include/ScintillaWidget.h
+++ b/plugins/scintilla/scintilla/include/ScintillaWidget.h
@@ -1,8 +1,9 @@
 /* Scintilla source code edit control */
-/** @file ScintillaWidget.h
- ** Definition of Scintilla widget for GTK+.
- ** Only needed by GTK+ code but is harmless on other platforms.
- **/
+/* @file ScintillaWidget.h
+ * Definition of Scintilla widget for GTK+.
+ * Only needed by GTK+ code but is harmless on other platforms.
+ * This comment is not a doc-comment as that causes warnings from g-ir-scanner.
+ */
 /* Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
  * The License.txt file describes the conditions under which this software may be distributed. */
 
@@ -19,8 +20,15 @@ extern "C" {
 #define SCINTILLA_CLASS(klass)  G_TYPE_CHECK_CLASS_CAST (klass, scintilla_get_type (), ScintillaClass)
 #define IS_SCINTILLA(obj)       G_TYPE_CHECK_INSTANCE_TYPE (obj, scintilla_get_type ())
 
+#define SCINTILLA_TYPE_OBJECT             (scintilla_object_get_type())
+#define SCINTILLA_OBJECT(obj)             (G_TYPE_CHECK_INSTANCE_CAST((obj), SCINTILLA_TYPE_OBJECT, 
ScintillaObject))
+#define SCINTILLA_IS_OBJECT(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SCINTILLA_TYPE_OBJECT))
+#define SCINTILLA_OBJECT_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass), SCINTILLA_TYPE_OBJECT, 
ScintillaObjectClass))
+#define SCINTILLA_IS_OBJECT_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass), SCINTILLA_TYPE_OBJECT))
+#define SCINTILLA_OBJECT_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS((obj), SCINTILLA_TYPE_OBJECT, 
ScintillaObjectClass))
+
 typedef struct _ScintillaObject ScintillaObject;
-typedef struct _ScintillaClass  ScintillaClass;
+typedef struct _ScintillaClass  ScintillaObjectClass;
 
 struct _ScintillaObject {
        GtkContainer cont;
@@ -30,15 +38,28 @@ struct _ScintillaObject {
 struct _ScintillaClass {
        GtkContainerClass parent_class;
 
-       void (* command) (ScintillaObject *ttt);
-       void (* notify) (ScintillaObject *ttt);
+       void (* command) (ScintillaObject *sci, int cmd, GtkWidget *window);
+       void (* notify) (ScintillaObject *sci, int id, SCNotification *scn);
 };
 
+GType          scintilla_object_get_type               (void);
+GtkWidget*     scintilla_object_new                    (void);
+gintptr                scintilla_object_send_message   (ScintillaObject *sci, unsigned int iMessage, 
guintptr wParam, gintptr lParam);
+
+
+GType          scnotification_get_type                 (void);
+#define SCINTILLA_TYPE_NOTIFICATION        (scnotification_get_type())
+
+#ifndef G_IR_SCANNING
+/* The legacy names confuse the g-ir-scanner program */
+typedef struct _ScintillaClass  ScintillaClass;
+
 GType          scintilla_get_type      (void);
 GtkWidget*     scintilla_new           (void);
 void           scintilla_set_id        (ScintillaObject *sci, uptr_t id);
 sptr_t         scintilla_send_message  (ScintillaObject *sci,unsigned int iMessage, uptr_t wParam, sptr_t 
lParam);
 void           scintilla_release_resources(void);
+#endif
 
 #define SCINTILLA_NOTIFY "sci-notify"
 
diff --git a/plugins/scintilla/scintilla/lexers.make b/plugins/scintilla/scintilla/lexers.make
index 1522e44..c42fc0b 100644
--- a/plugins/scintilla/scintilla/lexers.make
+++ b/plugins/scintilla/scintilla/lexers.make
@@ -13,6 +13,8 @@ LEXER_OBJS = \
        lexers/LexBaan.o\
        lexers/LexBash.o\
        lexers/LexBasic.o\
+       lexers/LexBatch.o\
+       lexers/LexBibTeX.o\
        lexers/LexBullant.o\
        lexers/LexCaml.o\
        lexers/LexCLW.o\
@@ -25,9 +27,14 @@ LEXER_OBJS = \
        lexers/LexCsound.o\
        lexers/LexCSS.o\
        lexers/LexD.o\
+       lexers/LexDiff.o\
+       lexers/LexDMAP.o\
+       lexers/LexDMIS.o\
        lexers/LexECL.o\
+       lexers/LexEDIFACT.o\
        lexers/LexEiffel.o\
        lexers/LexErlang.o\
+       lexers/LexErrorList.o\
        lexers/LexEScript.o\
        lexers/LexFlagship.o\
        lexers/LexForth.o\
@@ -35,14 +42,19 @@ LEXER_OBJS = \
        lexers/LexGAP.o\
        lexers/LexGui4Cli.o\
        lexers/LexHaskell.o\
+       lexers/LexHex.o\
        lexers/LexHTML.o\
+       lexers/LexIndent.o\
        lexers/LexInno.o\
+       lexers/LexJSON.o\
        lexers/LexKix.o\
+       lexers/LexKVIrc.o\
        lexers/LexLaTeX.o\
        lexers/LexLisp.o\
        lexers/LexLout.o\
        lexers/LexLua.o\
        lexers/LexMagik.o\
+       lexers/LexMake.o\
        lexers/LexMarkdown.o\
        lexers/LexMatlab.o\
        lexers/LexMetapost.o\
@@ -53,9 +65,9 @@ LEXER_OBJS = \
        lexers/LexMySQL.o\
        lexers/LexNimrod.o\
        lexers/LexNsis.o\
+       lexers/LexNull.o\
        lexers/LexOpal.o\
        lexers/LexOScript.o\
-       lexers/LexOthers.o\
        lexers/LexPascal.o\
        lexers/LexPB.o\
        lexers/LexPerl.o\
@@ -65,11 +77,14 @@ LEXER_OBJS = \
        lexers/LexPowerPro.o\
        lexers/LexPowerShell.o\
        lexers/LexProgress.o\
+       lexers/LexProps.o\
        lexers/LexPS.o\
        lexers/LexPython.o\
        lexers/LexR.o\
        lexers/LexRebol.o\
+       lexers/LexRegistry.o\
        lexers/LexRuby.o\
+       lexers/LexRust.o\
        lexers/LexScriptol.o\
        lexers/LexSmalltalk.o\
        lexers/LexSML.o\
@@ -105,6 +120,8 @@ LEXER_SRCS = \
        lexers/LexBaan.cxx\
        lexers/LexBash.cxx\
        lexers/LexBasic.cxx\
+       lexers/LexBatch.cxx\
+       lexers/LexBibTeX.cxx\
        lexers/LexBullant.cxx\
        lexers/LexCaml.cxx\
        lexers/LexCLW.cxx\
@@ -117,9 +134,14 @@ LEXER_SRCS = \
        lexers/LexCsound.cxx\
        lexers/LexCSS.cxx\
        lexers/LexD.cxx\
+       lexers/LexDiff.cxx\
+       lexers/LexDMAP.cxx\
+       lexers/LexDMIS.cxx\
        lexers/LexECL.cxx\
+       lexers/LexEDIFACT.cxx\
        lexers/LexEiffel.cxx\
        lexers/LexErlang.cxx\
+       lexers/LexErrorList.cxx\
        lexers/LexEScript.cxx\
        lexers/LexFlagship.cxx\
        lexers/LexForth.cxx\
@@ -127,14 +149,19 @@ LEXER_SRCS = \
        lexers/LexGAP.cxx\
        lexers/LexGui4Cli.cxx\
        lexers/LexHaskell.cxx\
+       lexers/LexHex.cxx\
        lexers/LexHTML.cxx\
+       lexers/LexIndent.cxx\
        lexers/LexInno.cxx\
+       lexers/LexJSON.cxx\
        lexers/LexKix.cxx\
+       lexers/LexKVIrc.cxx\
        lexers/LexLaTeX.cxx\
        lexers/LexLisp.cxx\
        lexers/LexLout.cxx\
        lexers/LexLua.cxx\
        lexers/LexMagik.cxx\
+       lexers/LexMake.cxx\
        lexers/LexMarkdown.cxx\
        lexers/LexMatlab.cxx\
        lexers/LexMetapost.cxx\
@@ -145,9 +172,9 @@ LEXER_SRCS = \
        lexers/LexMySQL.cxx\
        lexers/LexNimrod.cxx\
        lexers/LexNsis.cxx\
+       lexers/LexNull.cxx\
        lexers/LexOpal.cxx\
        lexers/LexOScript.cxx\
-       lexers/LexOthers.cxx\
        lexers/LexPascal.cxx\
        lexers/LexPB.cxx\
        lexers/LexPerl.cxx\
@@ -157,11 +184,14 @@ LEXER_SRCS = \
        lexers/LexPowerPro.cxx\
        lexers/LexPowerShell.cxx\
        lexers/LexProgress.cxx\
+       lexers/LexProps.cxx\
        lexers/LexPS.cxx\
        lexers/LexPython.cxx\
        lexers/LexR.cxx\
        lexers/LexRebol.cxx\
+       lexers/LexRegistry.cxx\
        lexers/LexRuby.cxx\
+       lexers/LexRust.cxx\
        lexers/LexScriptol.cxx\
        lexers/LexSmalltalk.cxx\
        lexers/LexSML.cxx\
diff --git a/plugins/scintilla/scintilla/lexers/LexA68k.cxx b/plugins/scintilla/scintilla/lexers/LexA68k.cxx
index 0b60019..b5f4898 100644
--- a/plugins/scintilla/scintilla/lexers/LexA68k.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexA68k.cxx
@@ -115,22 +115,22 @@ static inline bool IsDoxygenChar (const int ch)
  *  Main function, which colourises a 68k source
  */
 
-static void ColouriseA68kDoc (unsigned int startPos, int length, int initStyle, WordList *keywordlists[], 
Accessor &styler)
+static void ColouriseA68kDoc (Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[], Accessor &styler)
 {
-    // Used to buffer a string, to be able to compare it using built-in functions 
-    char Buffer[100]; 
- 
- 
-    // Used to know the length of an operator 
-    int OpType; 
- 
+    // Used to buffer a string, to be able to compare it using built-in functions
+    char Buffer[100];
+
+
+    // Used to know the length of an operator
+    int OpType;
+
 
     // Get references to keywords lists
     WordList &cpuInstruction = *keywordlists[0];
     WordList &registers = *keywordlists[1];
     WordList &directive = *keywordlists[2];
     WordList &extInstruction = *keywordlists[3];
-    WordList &alert          = *keywordlists[4]; 
+    WordList &alert          = *keywordlists[4];
     WordList &doxygenKeyword = *keywordlists[5];
 
 
@@ -140,109 +140,109 @@ static void ColouriseA68kDoc (unsigned int startPos, int length, int initStyle,
 
     /************************************************************
     *
-    *   Parse the source 
+    *   Parse the source
     *
     ************************************************************/
 
     for ( ; sc.More(); sc.Forward())
     {
-        /************************************************************ 
-        * 
-        *   A style always terminates at the end of a line, even for 
-        *   comments (no multi-lines comments) 
-        * 
-        ************************************************************/ 
-        if (sc.atLineStart) { 
+        /************************************************************
+        *
+        *   A style always terminates at the end of a line, even for
+        *   comments (no multi-lines comments)
+        *
+        ************************************************************/
+        if (sc.atLineStart) {
             sc.SetState(SCE_A68K_DEFAULT);
-        } 
+        }
 
 
         /************************************************************
         *
-        *   If we are not in "default style", check if the style continues 
-        *   In this case, we just have to loop 
+        *   If we are not in "default style", check if the style continues
+        *   In this case, we just have to loop
         *
         ************************************************************/
 
         if (sc.state != SCE_A68K_DEFAULT)
         {
-            if (   ((sc.state == SCE_A68K_NUMBER_DEC)        && isdigit(sc.ch))                      // 
Decimal number 
+            if (   ((sc.state == SCE_A68K_NUMBER_DEC)        && isdigit(sc.ch))                      // 
Decimal number
                 || ((sc.state == SCE_A68K_NUMBER_BIN) && IsBin(sc.ch))                                      
// Binary number
                 || ((sc.state == SCE_A68K_NUMBER_HEX) && isxdigit(sc.ch))                                   
// Hexa number
-                || ((sc.state == SCE_A68K_MACRO_ARG)         && isdigit(sc.ch))                      // 
Macro argument 
+                || ((sc.state == SCE_A68K_MACRO_ARG)         && isdigit(sc.ch))                      // 
Macro argument
                 || ((sc.state == SCE_A68K_STRING1)    && (sc.ch != '\''))                                   
// String single-quoted
                 || ((sc.state == SCE_A68K_STRING2)    && (sc.ch != '\"'))                                   
// String double-quoted
-                || ((sc.state == SCE_A68K_MACRO_DECLARATION) && IsIdentifierChar(sc.ch))             // 
Macro declaration (or global label, we don't know at this point) 
-                || ((sc.state == SCE_A68K_IDENTIFIER)        && IsIdentifierChar(sc.ch))             // 
Identifier 
-                || ((sc.state == SCE_A68K_LABEL)             && IsIdentifierChar(sc.ch))             // 
Label (local) 
-                || ((sc.state == SCE_A68K_COMMENT_DOXYGEN)   && IsDoxygenChar(sc.ch))                // 
Doxygen keyword 
-                || ((sc.state == SCE_A68K_COMMENT_SPECIAL)   && isalpha(sc.ch))                      // 
Alert 
-                || ((sc.state == SCE_A68K_COMMENT)           && !isalpha(sc.ch) && (sc.ch != '\\'))) // 
Normal comment 
+                || ((sc.state == SCE_A68K_MACRO_DECLARATION) && IsIdentifierChar(sc.ch))             // 
Macro declaration (or global label, we don't know at this point)
+                || ((sc.state == SCE_A68K_IDENTIFIER)        && IsIdentifierChar(sc.ch))             // 
Identifier
+                || ((sc.state == SCE_A68K_LABEL)             && IsIdentifierChar(sc.ch))             // 
Label (local)
+                || ((sc.state == SCE_A68K_COMMENT_DOXYGEN)   && IsDoxygenChar(sc.ch))                // 
Doxygen keyword
+                || ((sc.state == SCE_A68K_COMMENT_SPECIAL)   && isalpha(sc.ch))                      // Alert
+                || ((sc.state == SCE_A68K_COMMENT)           && !isalpha(sc.ch) && (sc.ch != '\\'))) // 
Normal comment
             {
                 continue;
             }
 
-        /************************************************************ 
-        * 
-        *   Check if current state terminates 
-        * 
-        ************************************************************/ 
+        /************************************************************
+        *
+        *   Check if current state terminates
+        *
+        ************************************************************/
 
-            // Strings: include terminal ' or " in the current string by skipping it 
-            if ((sc.state == SCE_A68K_STRING1) || (sc.state == SCE_A68K_STRING2)) { 
-                sc.Forward(); 
+            // Strings: include terminal ' or " in the current string by skipping it
+            if ((sc.state == SCE_A68K_STRING1) || (sc.state == SCE_A68K_STRING2)) {
+                sc.Forward();
                 }
- 
- 
-            // If a macro declaration was terminated with ':', it was a label 
-            else if ((sc.state == SCE_A68K_MACRO_DECLARATION) && (sc.chPrev == ':')) { 
-                sc.ChangeState(SCE_A68K_LABEL); 
+
+
+            // If a macro declaration was terminated with ':', it was a label
+            else if ((sc.state == SCE_A68K_MACRO_DECLARATION) && (sc.chPrev == ':')) {
+                sc.ChangeState(SCE_A68K_LABEL);
             }
 
- 
-            // If it wasn't a Doxygen keyword, change it to normal comment 
-            else if (sc.state == SCE_A68K_COMMENT_DOXYGEN) { 
+
+            // If it wasn't a Doxygen keyword, change it to normal comment
+            else if (sc.state == SCE_A68K_COMMENT_DOXYGEN) {
                 sc.GetCurrent(Buffer, sizeof(Buffer));
-                if (!doxygenKeyword.InList(Buffer)) { 
+                if (!doxygenKeyword.InList(Buffer)) {
                     sc.ChangeState(SCE_A68K_COMMENT);
                 }
                 sc.SetState(SCE_A68K_COMMENT);
                 continue;
             }
 
- 
-            // If it wasn't an Alert, change it to normal comment 
-            else if (sc.state == SCE_A68K_COMMENT_SPECIAL) { 
-                sc.GetCurrent(Buffer, sizeof(Buffer)); 
-                if (!alert.InList(Buffer)) { 
+
+            // If it wasn't an Alert, change it to normal comment
+            else if (sc.state == SCE_A68K_COMMENT_SPECIAL) {
+                sc.GetCurrent(Buffer, sizeof(Buffer));
+                if (!alert.InList(Buffer)) {
                     sc.ChangeState(SCE_A68K_COMMENT);
                 }
-                // Reset style to normal comment, or to Doxygen keyword if it begins with '\'  
-                if (sc.ch == '\\') { 
-                    sc.SetState(SCE_A68K_COMMENT_DOXYGEN); 
-                } 
-                else { 
+                // Reset style to normal comment, or to Doxygen keyword if it begins with '\'
+                if (sc.ch == '\\') {
+                    sc.SetState(SCE_A68K_COMMENT_DOXYGEN);
+                }
+                else {
                 sc.SetState(SCE_A68K_COMMENT);
-                } 
+                }
                 continue;
             }
 
- 
-            // If we are in a comment, it's a Doxygen keyword or an Alert 
-            else if (sc.state == SCE_A68K_COMMENT) { 
-                if (sc.ch == '\\') { 
-                    sc.SetState(SCE_A68K_COMMENT_DOXYGEN); 
-                } 
-                else { 
-                    sc.SetState(SCE_A68K_COMMENT_SPECIAL); 
-                } 
-                continue; 
+
+            // If we are in a comment, it's a Doxygen keyword or an Alert
+            else if (sc.state == SCE_A68K_COMMENT) {
+                if (sc.ch == '\\') {
+                    sc.SetState(SCE_A68K_COMMENT_DOXYGEN);
+                }
+                else {
+                    sc.SetState(SCE_A68K_COMMENT_SPECIAL);
+                }
+                continue;
             }
 
- 
+
             // Check if we are at the end of an identifier
             // In this case, colourise it if was a keyword.
-            else if ((sc.state == SCE_A68K_IDENTIFIER) && !IsIdentifierChar(sc.ch)) { 
+            else if ((sc.state == SCE_A68K_IDENTIFIER) && !IsIdentifierChar(sc.ch)) {
                 sc.GetCurrentLowered(Buffer, sizeof(Buffer));                           // Buffer the string 
of the current context
                 if (cpuInstruction.InList(Buffer)) {                                    // And check if it 
belongs to a keyword list
                     sc.ChangeState(SCE_A68K_CPUINSTRUCTION);
@@ -269,30 +269,30 @@ static void ColouriseA68kDoc (unsigned int startPos, int length, int initStyle,
         *
         ************************************************************/
 
-        // Something which begins at the beginning of a line, and with  
-        // - '\' + an identifier start char, or 
-        // - '\\@' + an identifier start char 
-        // is a local label (second case is used for macro local labels). We set it already as a label, it 
can't be a macro/equ declaration 
-        if (sc.atLineStart && (sc.ch < 0x80) && IsIdentifierStart(sc.chNext) && (sc.ch == '\\')) { 
-            sc.SetState(SCE_A68K_LABEL); 
-        } 
- 
-        if (sc.atLineStart && (sc.ch < 0x80) && (sc.ch == '\\') && (sc.chNext == '\\')) { 
-            sc.Forward(2); 
-            if ((sc.ch == '@') && IsIdentifierStart(sc.chNext)) { 
-                sc.ChangeState(SCE_A68K_LABEL); 
-                sc.SetState(SCE_A68K_LABEL); 
-            } 
-        } 
-         
+        // Something which begins at the beginning of a line, and with
+        // - '\' + an identifier start char, or
+        // - '\\@' + an identifier start char
+        // is a local label (second case is used for macro local labels). We set it already as a label, it 
can't be a macro/equ declaration
+        if (sc.atLineStart && (sc.ch < 0x80) && IsIdentifierStart(sc.chNext) && (sc.ch == '\\')) {
+            sc.SetState(SCE_A68K_LABEL);
+        }
+
+        if (sc.atLineStart && (sc.ch < 0x80) && (sc.ch == '\\') && (sc.chNext == '\\')) {
+            sc.Forward(2);
+            if ((sc.ch == '@') && IsIdentifierStart(sc.chNext)) {
+                sc.ChangeState(SCE_A68K_LABEL);
+                sc.SetState(SCE_A68K_LABEL);
+            }
+        }
+
         // Label and macro identifiers start at the beginning of a line
-        // We set both as a macro id, but if it wasn't one (':' at the end), 
-        // it will be changed as a label. 
+        // We set both as a macro id, but if it wasn't one (':' at the end),
+        // it will be changed as a label.
         if (sc.atLineStart && (sc.ch < 0x80) && IsIdentifierStart(sc.ch)) {
-            sc.SetState(SCE_A68K_MACRO_DECLARATION); 
+            sc.SetState(SCE_A68K_MACRO_DECLARATION);
         }
-        else if ((sc.ch < 0x80) && (sc.ch == ';')) {                            // Default: alert in a 
comment. If it doesn't match 
-            sc.SetState(SCE_A68K_COMMENT);                                      // with an alert, it will be 
toggle to a normal comment 
+        else if ((sc.ch < 0x80) && (sc.ch == ';')) {                            // Default: alert in a 
comment. If it doesn't match
+            sc.SetState(SCE_A68K_COMMENT);                                      // with an alert, it will be 
toggle to a normal comment
         }
         else if ((sc.ch < 0x80) && isdigit(sc.ch)) {                            // Decimal numbers haven't 
prefix
             sc.SetState(SCE_A68K_NUMBER_DEC);
@@ -309,7 +309,7 @@ static void ColouriseA68kDoc (unsigned int startPos, int length, int initStyle,
         else if ((sc.ch < 0x80) && (sc.ch == '\"')) {                           // String (double-quoted)
             sc.SetState(SCE_A68K_STRING2);
         }
-        else if ((sc.ch < 0x80) && (sc.ch == '\\') && (isdigit(sc.chNext))) {   // Replacement symbols in 
macro are prefixed with '\' 
+        else if ((sc.ch < 0x80) && (sc.ch == '\\') && (isdigit(sc.chNext))) {   // Replacement symbols in 
macro are prefixed with '\'
             sc.SetState(SCE_A68K_MACRO_ARG);
         }
         else if ((sc.ch < 0x80) && IsIdentifierStart(sc.ch)) {                  // An identifier: constant, 
label, etc...
diff --git a/plugins/scintilla/scintilla/lexers/LexAPDL.cxx b/plugins/scintilla/scintilla/lexers/LexAPDL.cxx
index 7d65a56..873ec9d 100644
--- a/plugins/scintilla/scintilla/lexers/LexAPDL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAPDL.cxx
@@ -43,7 +43,7 @@ static inline bool IsAnOperator(char ch) {
        return false;
 }
 
-static void ColouriseAPDLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseAPDLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
 
        int stringStart = ' ';
@@ -184,16 +184,16 @@ static int CheckAPDLFoldPoint(char const *token, int &level) {
        return 0;
 }
 
-static void FoldAPDLDoc(unsigned int startPos, int length, int,
+static void FoldAPDLDoc(Sci_PositionU startPos, Sci_Position length, int,
        WordList *[], Accessor &styler) {
 
-       int line = styler.GetLine(startPos);
+       Sci_Position line = styler.GetLine(startPos);
        int level = styler.LevelAt(line);
        int go = 0, done = 0;
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
        char word[256];
        int wordlen = 0;
-       int i;
+       Sci_Position i;
     bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        // Scan for tokens at the start of the line (they may include
        // whitespace, for tokens like "End Function"
diff --git a/plugins/scintilla/scintilla/lexers/LexASY.cxx b/plugins/scintilla/scintilla/lexers/LexASY.cxx
index 9e3470c..b49975e 100644
--- a/plugins/scintilla/scintilla/lexers/LexASY.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexASY.cxx
@@ -23,7 +23,7 @@
 using namespace Scintilla;
 #endif
 
-static void ColouriseAsyDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseAsyDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                WordList *keywordlists[], Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
@@ -152,7 +152,7 @@ static inline bool isASYidentifier(int ch) {
       ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) ;
 }
 
-static int ParseASYWord(unsigned int pos, Accessor &styler, char *word)
+static int ParseASYWord(Sci_PositionU pos, Accessor &styler, char *word)
 {
   int length=0;
   char ch=styler.SafeGetCharAt(pos);
@@ -167,11 +167,11 @@ static int ParseASYWord(unsigned int pos, Accessor &styler, char *word)
   return length;
 }
 
-static bool IsASYDrawingLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
+static bool IsASYDrawingLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
 
-       int startpos = pos;
+       Sci_Position startpos = pos;
        char buffer[100]="";
 
        while (startpos<eol_pos){
@@ -186,14 +186,14 @@ static bool IsASYDrawingLine(int line, Accessor &styler) {
        return false;
 }
 
-static void FoldAsyDoc(unsigned int startPos, int length, int initStyle,
+static void FoldAsyDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                           WordList *[], Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -202,7 +202,7 @@ static void FoldAsyDoc(unsigned int startPos, int length, int initStyle,
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexAU3.cxx b/plugins/scintilla/scintilla/lexers/LexAU3.cxx
index e9ab757..c8ab9d7 100644
--- a/plugins/scintilla/scintilla/lexers/LexAU3.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAU3.cxx
@@ -87,7 +87,7 @@ static inline bool IsAWordStart(const int ch)
 }
 
 static inline bool IsAOperator(char ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/' ||
            ch == '&' || ch == '^' || ch == '=' || ch == '<' || ch == '>' ||
@@ -170,10 +170,10 @@ static int GetSendKey(const char *szLine, char *szKey)
 //
 // Routine to check the last "none comment" character on a line to see if its a continuation
 //
-static bool IsContinuationLine(unsigned int szLine, Accessor &styler)
+static bool IsContinuationLine(Sci_PositionU szLine, Accessor &styler)
 {
-       int nsPos = styler.LineStart(szLine);
-       int nePos = styler.LineStart(szLine+1) - 2;
+       Sci_Position nsPos = styler.LineStart(szLine);
+       Sci_Position nePos = styler.LineStart(szLine+1) - 2;
        //int stylech = styler.StyleAt(nsPos);
        while (nsPos < nePos)
        {
@@ -195,8 +195,8 @@ static bool IsContinuationLine(unsigned int szLine, Accessor &styler)
 
 //
 // syntax highlighting logic
-static void ColouriseAU3Doc(unsigned int startPos,
-                                                       int length, int initStyle,
+static void ColouriseAU3Doc(Sci_PositionU startPos,
+                                                       Sci_Position length, int initStyle,
                                                        WordList *keywordlists[],
                                                        Accessor &styler) {
 
@@ -209,8 +209,8 @@ static void ColouriseAU3Doc(unsigned int startPos,
     WordList &keywords7 = *keywordlists[6];
     WordList &keywords8 = *keywordlists[7];
        // find the first previous line without continuation character at the end
-       int lineCurrent = styler.GetLine(startPos);
-       int s_startPos = startPos;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       Sci_Position s_startPos = startPos;
        // When not inside a Block comment: find First line without _
        if (!(initStyle==SCE_AU3_COMMENTBLOCK)) {
                while ((lineCurrent > 0 && IsContinuationLine(lineCurrent,styler)) ||
@@ -228,7 +228,7 @@ static void ColouriseAU3Doc(unsigned int startPos,
        char si;     // string indicator "=1 '=2
        char ni;     // Numeric indicator error=9 normal=0 normal+dec=1 hex=2 Enot=3
        char ci;     // comment indicator 0=not linecomment(;)
-       char s_save[100];
+       char s_save[100] = "";
        si=0;
        ni=0;
        ci=0;
@@ -447,7 +447,7 @@ static void ColouriseAU3Doc(unsigned int startPos,
                                {
                                        si=0;
                                        // at line end and not found a continuation char then reset to default
-                                       int lineCurrent = styler.GetLine(sc.currentPos);
+                                       Sci_Position lineCurrent = styler.GetLine(sc.currentPos);
                                        if (!IsContinuationLine(lineCurrent,styler))
                                        {
                                                sc.SetState(SCE_AU3_DEFAULT);
@@ -492,7 +492,7 @@ static void ColouriseAU3Doc(unsigned int startPos,
                                else
                                {
                                        // check if the start is a valid SendKey start
-                                       int             nPos    = 0;
+                                       Sci_Position            nPos    = 0;
                                        int             nState  = 1;
                                        char    cTemp;
                                        while (!(nState == 2) && ((cTemp = s[nPos]) != '\0'))
@@ -659,10 +659,10 @@ static bool IsStreamCommentStyle(int style) {
 //
 // Routine to find first none space on the current line and return its Style
 // needed for comment lines not starting on pos 1
-static int GetStyleFirstWord(unsigned int szLine, Accessor &styler)
+static int GetStyleFirstWord(Sci_PositionU szLine, Accessor &styler)
 {
-       int nsPos = styler.LineStart(szLine);
-       int nePos = styler.LineStart(szLine+1) - 1;
+       Sci_Position nsPos = styler.LineStart(szLine);
+       Sci_Position nePos = styler.LineStart(szLine+1) - 1;
        while (isspacechar(styler.SafeGetCharAt(nsPos)) && nsPos < nePos)
        {
                nsPos++; // skip to next char
@@ -674,16 +674,16 @@ static int GetStyleFirstWord(unsigned int szLine, Accessor &styler)
 
 
 //
-static void FoldAU3Doc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldAU3Doc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
        // get settings from the config files for folding comments and preprocessor lines
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldInComment = styler.GetPropertyInt("fold.comment") == 2;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        bool foldpreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
        // Backtrack to previous line in case need to fix its fold status
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0) {
                if (lineCurrent > 0) {
                        lineCurrent--;
@@ -720,7 +720,7 @@ static void FoldAU3Doc(unsigned int startPos, int length, int, WordList *[], Acc
        char chNext = styler.SafeGetCharAt(startPos);
        char chPrev = ' ';
        //
-       for (int i = startPos; i < endPos; i++) {
+       for (Sci_Position i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                if (IsAWordChar(ch)) {
diff --git a/plugins/scintilla/scintilla/lexers/LexAVE.cxx b/plugins/scintilla/scintilla/lexers/LexAVE.cxx
index 373173c..fd99273 100644
--- a/plugins/scintilla/scintilla/lexers/LexAVE.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAVE.cxx
@@ -45,7 +45,7 @@ inline bool IsAWordStart(const int ch) {
 }
 
 inline bool isAveOperator(char ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        // '.' left out as it is used to make up numbers
        if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
@@ -59,8 +59,8 @@ inline bool isAveOperator(char ch) {
 }
 
 static void ColouriseAveDoc(
-       unsigned int startPos,
-       int length,
+       Sci_PositionU startPos,
+       Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler) {
@@ -82,7 +82,7 @@ static void ColouriseAveDoc(
        for (; sc.More(); sc.Forward()) {
                if (sc.atLineEnd) {
                        // Update the line state, so it can be seen by next line
-                       int currentLine = styler.GetLine(sc.currentPos);
+                       Sci_Position currentLine = styler.GetLine(sc.currentPos);
                        styler.SetLineState(currentLine, 0);
                }
                if (sc.atLineStart && (sc.state == SCE_AVE_STRING)) {
@@ -157,19 +157,19 @@ static void ColouriseAveDoc(
        sc.Complete();
 }
 
-static void FoldAveDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
+static void FoldAveDoc(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList *[],
                        Accessor &styler) {
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = static_cast<char>(tolower(styler[startPos]));
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        int styleNext = styler.StyleAt(startPos);
-       char s[10];
+       char s[10] = "";
 
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = static_cast<char>(tolower(chNext));
                chNext = static_cast<char>(tolower(styler.SafeGetCharAt(i + 1)));
                int style = styleNext;
diff --git a/plugins/scintilla/scintilla/lexers/LexAVS.cxx b/plugins/scintilla/scintilla/lexers/LexAVS.cxx
index 82e4345..129c356 100644
--- a/plugins/scintilla/scintilla/lexers/LexAVS.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAVS.cxx
@@ -44,8 +44,8 @@ static inline bool IsANumberChar(int ch) {
 }
 
 static void ColouriseAvsDoc(
-       unsigned int startPos,
-       int length,
+       Sci_PositionU startPos,
+       Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler) {
@@ -57,7 +57,7 @@ static void ColouriseAvsDoc(
        WordList &clipProperties = *keywordlists[4];
        WordList &userDefined = *keywordlists[5];
 
-       int currentLine = styler.GetLine(startPos);
+       Sci_Position currentLine = styler.GetLine(startPos);
        // Initialize the block comment nesting level, if we are inside such a comment.
        int blockCommentLevel = 0;
        if (initStyle == SCE_AVS_COMMENTBLOCK || initStyle == SCE_AVS_COMMENTBLOCKN) {
@@ -83,7 +83,7 @@ static void ColouriseAvsDoc(
                                styler.SetLineState(currentLine, 0);
                        }
                }
-               
+
                // Determine if the current state should terminate.
                if (sc.state == SCE_AVS_OPERATOR) {
                        sc.SetState(SCE_AVS_DEFAULT);
@@ -208,24 +208,24 @@ static void ColouriseAvsDoc(
 }
 
 static void FoldAvsDoc(
-       unsigned int startPos,
-       int length,
+       Sci_PositionU startPos,
+       Sci_Position length,
        int initStyle,
        WordList *[],
        Accessor &styler) {
 
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexAbaqus.cxx 
b/plugins/scintilla/scintilla/lexers/LexAbaqus.cxx
index 1341700..5f265c7 100644
--- a/plugins/scintilla/scintilla/lexers/LexAbaqus.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAbaqus.cxx
@@ -30,10 +30,6 @@
 using namespace Scintilla;
 #endif
 
-static inline bool IsAWordChar(const int ch) {
-       return (ch < 0x80 && (isalnum(ch) || (ch == '_')));
-}
-
 static inline bool IsAKeywordChar(const int ch) {
        return (ch < 0x80 && (isalnum(ch) || (ch == '_') || (ch == ' ')));
 }
@@ -42,18 +38,7 @@ static inline bool IsASetChar(const int ch) {
        return (ch < 0x80 && (isalnum(ch) || (ch == '_') || (ch == '.') || (ch == '-')));
 }
 
-static inline bool IsAnOperator(char ch) {
-       // '.' left out as it is used to make up numbers
-       if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
-               ch == '(' || ch == ')' || ch == '=' || ch == '^' ||
-               ch == '[' || ch == ']' || ch == '<' || ch == '&' ||
-               ch == '>' || ch == ',' || ch == '|' || ch == '~' ||
-               ch == '$' || ch == ':' || ch == '%')
-               return true;
-       return false;
-}
-
-static void ColouriseABAQUSDoc(unsigned int startPos, int length, int initStyle, WordList*[] /* 
*keywordlists[] */,
+static void ColouriseABAQUSDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList*[] /* 
*keywordlists[] */,
                             Accessor &styler) {
        enum localState { KW_LINE_KW, KW_LINE_COMMA, KW_LINE_PAR, KW_LINE_EQ, KW_LINE_VAL, \
                                          DAT_LINE_VAL, DAT_LINE_COMMA,\
@@ -316,10 +301,10 @@ static int LowerCase(int c)
        return c;
 }
 
-static int LineEnd(int line, Accessor &styler)
+static Sci_Position LineEnd(Sci_Position line, Accessor &styler)
 {
-    const int docLines = styler.GetLine(styler.Length() - 1);  // Available last line
-    int eol_pos ;
+    const Sci_Position docLines = styler.GetLine(styler.Length() - 1);  // Available last line
+    Sci_Position eol_pos ;
     // if the line is the last line, the eol_pos is styler.Length()
     // eol will contain a new line, or a virtual new line
     if ( docLines == line )
@@ -329,7 +314,7 @@ static int LineEnd(int line, Accessor &styler)
     return eol_pos ;
 }
 
-static int LineStart(int line, Accessor &styler)
+static Sci_Position LineStart(Sci_Position line, Accessor &styler)
 {
     return styler.LineStart(line) ;
 }
@@ -345,14 +330,14 @@ static int LineStart(int line, Accessor &styler)
 // 6  : block close keyword line
 // 7  : keyword line in error
 // 8  : comment line
-static int LineType(int line, Accessor &styler) {
-    int pos = LineStart(line, styler) ;
-    int eol_pos = LineEnd(line, styler) ;
+static int LineType(Sci_Position line, Accessor &styler) {
+    Sci_Position pos = LineStart(line, styler) ;
+    Sci_Position eol_pos = LineEnd(line, styler) ;
 
     int c ;
     char ch = ' ';
 
-    int i = pos ;
+    Sci_Position i = pos ;
     while ( i < eol_pos ) {
         c = styler.SafeGetCharAt(i);
         ch = static_cast<char>(LowerCase(c));
@@ -433,7 +418,7 @@ static int LineType(int line, Accessor &styler) {
     return 4 ;
 }
 
-static void SafeSetLevel(int line, int level, Accessor &styler)
+static void SafeSetLevel(Sci_Position line, int level, Accessor &styler)
 {
     if ( line < 0 )
         return ;
@@ -447,20 +432,20 @@ static void SafeSetLevel(int line, int level, Accessor &styler)
         styler.SetLevel(line, level) ;
 }
 
-static void FoldABAQUSDoc(unsigned int startPos, int length, int,
+static void FoldABAQUSDoc(Sci_PositionU startPos, Sci_Position length, int,
 WordList *[], Accessor &styler) {
-    int startLine = styler.GetLine(startPos) ;
-    int endLine   = styler.GetLine(startPos+length-1) ;
+    Sci_Position startLine = styler.GetLine(startPos) ;
+    Sci_Position endLine   = styler.GetLine(startPos+length-1) ;
 
     // bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
     // We want to deal with all the cases
     // To know the correct indentlevel, we need to look back to the
     // previous command line indentation level
        // order of formatting keyline datalines commentlines
-    int beginData    = -1 ;
-    int beginComment = -1 ;
-    int prvKeyLine   = startLine ;
-    int prvKeyLineTp =  0 ;
+    Sci_Position beginData    = -1 ;
+    Sci_Position beginComment = -1 ;
+    Sci_Position prvKeyLine   = startLine ;
+    Sci_Position prvKeyLineTp =  0 ;
 
     // Scan until we find the previous keyword line
     // this will give us the level reference that we need
@@ -482,7 +467,7 @@ WordList *[], Accessor &styler) {
     prvKeyLine = -1 ;
 
     // Now start scanning over the lines.
-    for ( int line = startLine; line <= endLine; line++ ) {
+    for ( Sci_Position line = startLine; line <= endLine; line++ ) {
         int lineType = LineType(line, styler) ;
 
         // Check for comment line
@@ -531,7 +516,7 @@ WordList *[], Accessor &styler) {
                                datLevel = level ;
                        }
 
-            for ( int ll = beginData; ll < beginComment; ll++ )
+            for ( Sci_Position ll = beginData; ll < beginComment; ll++ )
                 SafeSetLevel(ll, datLevel, styler) ;
 
             // The keyword we just found is going to be written at another level
@@ -547,7 +532,7 @@ WordList *[], Accessor &styler) {
                                }
             }
 
-            for ( int lll = beginComment; lll < line; lll++ )
+            for ( Sci_Position lll = beginComment; lll < line; lll++ )
                 SafeSetLevel(lll, level, styler) ;
 
             // wrap and reset
@@ -564,10 +549,10 @@ WordList *[], Accessor &styler) {
     } else {
         // We need to find out whether this comment block is followed by
         // a data line or a keyword line
-        const int docLines = styler.GetLine(styler.Length() - 1);
+        const Sci_Position docLines = styler.GetLine(styler.Length() - 1);
 
-        for ( int line = endLine + 1; line <= docLines; line++ ) {
-            int lineType = LineType(line, styler) ;
+        for ( Sci_Position line = endLine + 1; line <= docLines; line++ ) {
+            Sci_Position lineType = LineType(line, styler) ;
 
             if ( lineType != 8 ) {
                                if ( !(lineType & 4) )  {
@@ -593,17 +578,17 @@ WordList *[], Accessor &styler) {
                datLevel = level ;
        }
 
-    for ( int ll = beginData; ll < beginComment; ll++ )
+    for ( Sci_Position ll = beginData; ll < beginComment; ll++ )
         SafeSetLevel(ll, datLevel, styler) ;
 
-       if ( prvKeyLineTp == 5 ) {
-               level += 1 ;
-       }
+    if ( prvKeyLineTp == 5 ) {
+        level += 1 ;
+    }
 
-       if ( prvKeyLineTp == 6 ) {
-               level -= 1 ;
-       }
-       for ( int m = beginComment; m <= endLine; m++ )
+    if ( prvKeyLineTp == 6 ) {
+        level -= 1 ;
+    }
+    for ( Sci_Position m = beginComment; m <= endLine; m++ )
         SafeSetLevel(m, level, styler) ;
 }
 
diff --git a/plugins/scintilla/scintilla/lexers/LexAda.cxx b/plugins/scintilla/scintilla/lexers/LexAda.cxx
index b11c247..df26d75 100644
--- a/plugins/scintilla/scintilla/lexers/LexAda.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAda.cxx
@@ -34,8 +34,8 @@ using namespace Scintilla;
  */
 
 static void ColouriseDocument(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int initStyle,
     WordList *keywordlists[],
     Accessor &styler);
@@ -222,8 +222,8 @@ static void ColouriseWord(StyleContext& sc, WordList& keywords, bool& apostrophe
 //
 
 static void ColouriseDocument(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int initStyle,
     WordList *keywordlists[],
     Accessor &styler) {
@@ -231,7 +231,7 @@ static void ColouriseDocument(
 
        StyleContext sc(startPos, length, initStyle, styler);
 
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        bool apostropheStartsAttribute = (styler.GetLineState(lineCurrent) & 1) != 0;
 
        while (sc.More()) {
@@ -511,5 +511,5 @@ static inline bool IsWordCharacter(int ch) {
 }
 
 static inline bool IsWordStartCharacter(int ch) {
-       return (isascii(ch) && isalpha(ch)) || ch == '_';
+       return (IsASCII(ch) && isalpha(ch)) || ch == '_';
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexAsm.cxx b/plugins/scintilla/scintilla/lexers/LexAsm.cxx
index 78874de..78550bb 100644
--- a/plugins/scintilla/scintilla/lexers/LexAsm.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAsm.cxx
@@ -150,51 +150,57 @@ class LexerAsm : public ILexer {
        WordList directives4foldend;
        OptionsAsm options;
        OptionSetAsm osAsm;
+       int commentChar;
 public:
-       LexerAsm() {
+       LexerAsm(int commentChar_) {
+               commentChar = commentChar_;
        }
        virtual ~LexerAsm() {
        }
-       void SCI_METHOD Release() {
+       void SCI_METHOD Release() override {
                delete this;
        }
-       int SCI_METHOD Version() const {
+       int SCI_METHOD Version() const override {
                return lvOriginal;
        }
-       const char * SCI_METHOD PropertyNames() {
+       const char * SCI_METHOD PropertyNames() override {
                return osAsm.PropertyNames();
        }
-       int SCI_METHOD PropertyType(const char *name) {
+       int SCI_METHOD PropertyType(const char *name) override {
                return osAsm.PropertyType(name);
        }
-       const char * SCI_METHOD DescribeProperty(const char *name) {
+       const char * SCI_METHOD DescribeProperty(const char *name) override {
                return osAsm.DescribeProperty(name);
        }
-       int SCI_METHOD PropertySet(const char *key, const char *val);
-       const char * SCI_METHOD DescribeWordListSets() {
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char * SCI_METHOD DescribeWordListSets() override {
                return osAsm.DescribeWordListSets();
        }
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-       void * SCI_METHOD PrivateCall(int, void *) {
+       void * SCI_METHOD PrivateCall(int, void *) override {
                return 0;
        }
 
        static ILexer *LexerFactoryAsm() {
-               return new LexerAsm();
+               return new LexerAsm(';');
+       }
+
+       static ILexer *LexerFactoryAs() {
+               return new LexerAsm('#');
        }
 };
 
-int SCI_METHOD LexerAsm::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerAsm::PropertySet(const char *key, const char *val) {
        if (osAsm.PropertySet(&options, key, val)) {
                return 0;
        }
        return -1;
 }
 
-int SCI_METHOD LexerAsm::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerAsm::WordListSet(int n, const char *wl) {
        WordList *wordListN = 0;
        switch (n) {
        case 0:
@@ -222,7 +228,7 @@ int SCI_METHOD LexerAsm::WordListSet(int n, const char *wl) {
                wordListN = &directives4foldend;
                break;
        }
-       int firstModification = -1;
+       Sci_Position firstModification = -1;
        if (wordListN) {
                WordList wlNew;
                wlNew.Set(wl);
@@ -234,7 +240,7 @@ int SCI_METHOD LexerAsm::WordListSet(int n, const char *wl) {
        return firstModification;
 }
 
-void SCI_METHOD LexerAsm::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerAsm::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        LexAccessor styler(pAccess);
 
        // Do not leak onto next line
@@ -342,9 +348,9 @@ void SCI_METHOD LexerAsm::Lex(unsigned int startPos, int length, int initStyle,
 
                // Determine if a new state should be entered.
                if (sc.state == SCE_ASM_DEFAULT) {
-                       if (sc.ch == ';'){
+                       if (sc.ch == commentChar){
                                sc.SetState(SCE_ASM_COMMENT);
-                       } else if (isascii(sc.ch) && (isdigit(sc.ch) || (sc.ch == '.' && isascii(sc.chNext) 
&& isdigit(sc.chNext)))) {
+                       } else if (IsASCII(sc.ch) && (isdigit(sc.ch) || (sc.ch == '.' && IsASCII(sc.chNext) 
&& isdigit(sc.chNext)))) {
                                sc.SetState(SCE_ASM_NUMBER);
                        } else if (IsAWordStart(sc.ch)) {
                                sc.SetState(SCE_ASM_IDENTIFIER);
@@ -365,16 +371,16 @@ void SCI_METHOD LexerAsm::Lex(unsigned int startPos, int length, int initStyle,
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "else".
 
-void SCI_METHOD LexerAsm::Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerAsm::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
 
        if (!options.fold)
                return;
 
        LexAccessor styler(pAccess);
 
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -385,7 +391,7 @@ void SCI_METHOD LexerAsm::Fold(unsigned int startPos, int length, int initStyle,
        char word[100];
        int wordlen = 0;
        const bool userDefinedFoldMarkers = !options.foldExplicitStart.empty() && 
!options.foldExplicitEnd.empty();
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -447,7 +453,7 @@ void SCI_METHOD LexerAsm::Fold(unsigned int startPos, int length, int initStyle,
                        }
                        lineCurrent++;
                        levelCurrent = levelNext;
-                       if (atEOL && (i == static_cast<unsigned int>(styler.Length()-1))) {
+                       if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length() - 1))) {
                                // There is an empty line at end of file so give it same level and empty
                                styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | 
SC_FOLDLEVELWHITEFLAG);
                        }
@@ -457,4 +463,5 @@ void SCI_METHOD LexerAsm::Fold(unsigned int startPos, int length, int initStyle,
 }
 
 LexerModule lmAsm(SCLEX_ASM, LexerAsm::LexerFactoryAsm, "asm", asmWordListDesc);
+LexerModule lmAs(SCLEX_AS, LexerAsm::LexerFactoryAs, "as", asmWordListDesc);
 
diff --git a/plugins/scintilla/scintilla/lexers/LexAsn1.cxx b/plugins/scintilla/scintilla/lexers/LexAsn1.cxx
index 120b895..7c5f48e 100644
--- a/plugins/scintilla/scintilla/lexers/LexAsn1.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAsn1.cxx
@@ -47,7 +47,7 @@ static bool isAsn1Char(int ch)
 //     Function determining the color of a given code portion
 //     Based on a "state"
 //
-static void ColouriseAsn1Doc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[], 
Accessor &styler)
+static void ColouriseAsn1Doc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordLists[], Accessor &styler)
 {
        // The keywords
        WordList &Keywords = *keywordLists[0];
@@ -168,7 +168,7 @@ asn1_default:
        sc.Complete();
 }
 
-static void FoldAsn1Doc(unsigned int, int, int, WordList *[], Accessor &styler)
+static void FoldAsn1Doc(Sci_PositionU, Sci_Position, int, WordList *[], Accessor &styler)
 {
        // No folding enabled, no reason to continue...
        if( styler.GetPropertyInt("fold") == 0 )
diff --git a/plugins/scintilla/scintilla/lexers/LexBaan.cxx b/plugins/scintilla/scintilla/lexers/LexBaan.cxx
index 3784f3c..ab96a0d 100644
--- a/plugins/scintilla/scintilla/lexers/LexBaan.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexBaan.cxx
@@ -1,134 +1,720 @@
 // Scintilla source code edit control
 /** @file LexBaan.cxx
- ** Lexer for Baan.
- ** Based heavily on LexCPP.cxx
- **/
+** Lexer for Baan.
+** Based heavily on LexCPP.cxx
+**/
 // Copyright 2001- by Vamsi Potluru <vamsi who net> & Praveen Ambekar <ambekarpraveen yahoo com>
+// Maintainer Email: oirfeodent yahoo co in
 // The License.txt file describes the conditions under which this software may be distributed.
 
+// C standard library
 #include <stdlib.h>
 #include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <ctype.h>
 
+// C++ wrappers of C standard library
+#include <cassert>
+
+// C++ standard library
+#include <string>
+#include <map>
+
+// Scintilla headers
+
+// Non-platform-specific headers
+
+// include
 #include "ILexer.h"
 #include "Scintilla.h"
 #include "SciLexer.h"
 
+// lexlib
 #include "WordList.h"
 #include "LexAccessor.h"
-#include "Accessor.h"
 #include "StyleContext.h"
 #include "CharacterSet.h"
 #include "LexerModule.h"
+#include "OptionSet.h"
 
-#ifdef SCI_NAMESPACE
+# ifdef SCI_NAMESPACE
 using namespace Scintilla;
-#endif
+# endif
+
+namespace {
+// Use an unnamed namespace to protect the functions and classes from name conflicts
+
+// Options used for LexerBaan
+struct OptionsBaan {
+       bool fold;
+       bool foldComment;
+       bool foldPreprocessor;
+       bool foldCompact;
+       bool baanFoldSyntaxBased;
+       bool baanFoldKeywordsBased;
+       bool baanFoldSections;
+       bool baanFoldInnerLevel;
+       bool baanStylingWithinPreprocessor;
+       OptionsBaan() {
+               fold = false;
+               foldComment = false;
+               foldPreprocessor = false;
+               foldCompact = false;
+               baanFoldSyntaxBased = false;
+               baanFoldKeywordsBased = false;
+               baanFoldSections = false;
+               baanFoldInnerLevel = false;
+               baanStylingWithinPreprocessor = false;
+       }
+};
+
+const char *const baanWordLists[] = {
+       "Baan & BaanSQL Reserved Keywords ",
+       "Baan Standard functions",
+       "Baan Functions Abridged",
+       "Baan Main Sections ",
+       "Baan Sub Sections",
+       "PreDefined Variables",
+       "PreDefined Attributes",
+       "Enumerates",
+       0,
+};
+
+struct OptionSetBaan : public OptionSet<OptionsBaan> {
+       OptionSetBaan() {
+               DefineProperty("fold", &OptionsBaan::fold);
+
+               DefineProperty("fold.comment", &OptionsBaan::foldComment);
+
+               DefineProperty("fold.preprocessor", &OptionsBaan::foldPreprocessor);
+
+               DefineProperty("fold.compact", &OptionsBaan::foldCompact);
+
+               DefineProperty("fold.baan.syntax.based", &OptionsBaan::baanFoldSyntaxBased,
+                       "Set this property to 0 to disable syntax based folding, which is folding based on 
'{' & '('.");
+
+               DefineProperty("fold.baan.keywords.based", &OptionsBaan::baanFoldKeywordsBased,
+                       "Set this property to 0 to disable keywords based folding, which is folding based on "
+                       " for, if, on (case), repeat, select, while and fold ends based on endfor, endif, 
endcase, until, endselect, endwhile respectively."
+                       "Also folds declarations which are grouped together.");
+
+               DefineProperty("fold.baan.sections", &OptionsBaan::baanFoldSections,
+                       "Set this property to 0 to disable folding of Main Sections as well as Sub 
Sections.");
+
+               DefineProperty("fold.baan.inner.level", &OptionsBaan::baanFoldInnerLevel,
+                       "Set this property to 1 to enable folding of inner levels of select statements."
+                       "Disabled by default. case and if statements are also eligible" );
+
+               DefineProperty("lexer.baan.styling.within.preprocessor", 
&OptionsBaan::baanStylingWithinPreprocessor,
+                       "For Baan code, determines whether all preprocessor code is styled in the "
+                       "preprocessor style (0, the default) or only from the initial # to the end "
+                       "of the command word(1).");
+
+               DefineWordListSets(baanWordLists);
+       }
+};
 
 static inline bool IsAWordChar(const int  ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$' || ch == ':');
+       return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$');
+}
+
+static inline bool IsAnOperator(int ch) {
+       if (IsAlphaNumeric(ch))
+               return false;
+       if (ch == '#' || ch == '^' || ch == '&' || ch == '*' ||
+               ch == '(' || ch == ')' || ch == '-' || ch == '+' ||
+               ch == '=' || ch == '|' || ch == '{' || ch == '}' ||
+               ch == '[' || ch == ']' || ch == ':' || ch == ';' ||
+               ch == '<' || ch == '>' || ch == ',' || ch == '/' ||
+               ch == '?' || ch == '!' || ch == '"' || ch == '~' ||
+               ch == '\\')
+               return true;
+       return false;
+}
+
+static inline int IsAnyOtherIdentifier(char *s, int sLength) {
+
+       /*      IsAnyOtherIdentifier uses standard templates used in baan.
+       The matching template is shown as comments just above the return condition.
+       ^ - refers to any character [a-z].
+       # - refers to any number [0-9].
+       Other characters shown are compared as is.
+       Tried implementing with Regex... it was too complicated for me.
+       Any other implementation suggestion welcome.
+       */
+       switch (sLength) {
+       case 8:
+               if (isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && isalpha(s[4]) && 
IsADigit(s[5]) && IsADigit(s[6]) && IsADigit(s[7])) {
+                       //^^^^^### 
+                       return(SCE_BAAN_TABLEDEF);
+               }
+               break;
+       case 9:
+               if (s[0] == 't' && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && isalpha(s[4]) && 
isalpha(s[5]) && IsADigit(s[6]) && IsADigit(s[7]) && IsADigit(s[8])) {
+                       //t^^^^^###
+                       return(SCE_BAAN_TABLEDEF);
+               }
+               else if (s[8] == '.' && isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && 
isalpha(s[4]) && IsADigit(s[5]) && IsADigit(s[6]) && IsADigit(s[7])) {
+                       //^^^^^###.
+                       return(SCE_BAAN_TABLESQL);
+               }
+               break;
+       case 13:
+               if (s[8] == '.' && isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && 
isalpha(s[4]) && IsADigit(s[5]) && IsADigit(s[6]) && IsADigit(s[7])) {
+                       //^^^^^###.****
+                       return(SCE_BAAN_TABLESQL);
+               }
+               else if (s[0] == 'r' && s[1] == 'c' && s[2] == 'd' && s[3] == '.' && s[4] == 't' && 
isalpha(s[5]) && isalpha(s[6]) && isalpha(s[7]) && isalpha(s[8]) && isalpha(s[9]) && IsADigit(s[10]) && 
IsADigit(s[11]) && IsADigit(s[12])) {
+                       //rcd.t^^^^^###
+                       return(SCE_BAAN_TABLEDEF);
+               }
+               break;
+       case 14:
+       case 15:
+               if (s[8] == '.' && isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && 
isalpha(s[4]) && IsADigit(s[5]) && IsADigit(s[6]) && IsADigit(s[7])) {
+                       if (s[13] != ':') {
+                               //^^^^^###.******
+                               return(SCE_BAAN_TABLESQL);
+                       }
+               }
+               break;
+       case 16:
+       case 17:
+               if (s[8] == '.' && s[9] == '_' && s[10] == 'i' && s[11] == 'n' && s[12] == 'd' && s[13] == 
'e' && s[14] == 'x' && IsADigit(s[15]) && isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && 
isalpha(s[4]) && IsADigit(s[5]) && IsADigit(s[6]) && IsADigit(s[7])) {
+                       //^^^^^###._index##
+                       return(SCE_BAAN_TABLEDEF);
+               }
+               else if (s[8] == '.' && s[9] == '_' && s[10] == 'c' && s[11] == 'o' && s[12] == 'm' && s[13] 
== 'p' && s[14] == 'n' && s[15] == 'r' && isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && 
isalpha(s[4]) && IsADigit(s[5]) && IsADigit(s[6]) && IsADigit(s[7])) {
+                       //^^^^^###._compnr
+                       return(SCE_BAAN_TABLEDEF);
+               }
+               break;
+       default:
+               break;
+       }
+       if (sLength > 14 && s[5] == '.' && s[6] == 'd' && s[7] == 'l' && s[8] == 'l' && s[13] == '.' && 
isalpha(s[0]) && isalpha(s[1]) && isalpha(s[2]) && isalpha(s[3]) && isalpha(s[4]) && IsADigit(s[9]) && 
IsADigit(s[10]) && IsADigit(s[11]) && IsADigit(s[12])) {
+               //^^^^^.dll####.
+               return(SCE_BAAN_FUNCTION);
+       }
+       else if (sLength > 15 && s[2] == 'i' && s[3] == 'n' && s[4] == 't' && s[5] == '.' && s[6] == 'd' && 
s[7] == 'l' && s[8] == 'l' && isalpha(s[0]) && isalpha(s[1]) && isalpha(s[9]) && isalpha(s[10]) && 
isalpha(s[11]) && isalpha(s[12]) && isalpha(s[13])) {
+               //^^int.dll^^^^^.
+               return(SCE_BAAN_FUNCTION);
+       }
+       else if (sLength > 11 && s[0] == 'i' && s[10] == '.' && isalpha(s[1]) && isalpha(s[2]) && 
isalpha(s[3]) && isalpha(s[4]) && isalpha(s[5]) && IsADigit(s[6]) && IsADigit(s[7]) && IsADigit(s[8]) && 
IsADigit(s[9])) {
+               //i^^^^^####.
+               return(SCE_BAAN_FUNCTION);
+       }
+
+       return(SCE_BAAN_DEFAULT);
+}
+
+static bool IsCommentLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               int style = styler.StyleAt(i);
+               if (ch == '|' && style == SCE_BAAN_COMMENT)
+                       return true;
+               else if (!IsASpaceOrTab(ch))
+                       return false;
+       }
+       return false;
+}
+
+static bool IsPreProcLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               int style = styler.StyleAt(i);
+               if (ch == '#' && style == SCE_BAAN_PREPROCESSOR) {
+                       if (styler.Match(i, "#elif") || styler.Match(i, "#else") || styler.Match(i, "#endif")
+                               || styler.Match(i, "#if") || styler.Match(i, "#ifdef") || styler.Match(i, 
"#ifndef"))
+                               // Above PreProcessors has a seperate fold mechanism.
+                               return false;
+                       else
+                               return true;
+               }
+               else if (ch == '^')
+                       return true;
+               else if (!IsASpaceOrTab(ch))
+                       return false;
+       }
+       return false;
 }
 
-static inline bool IsAWordStart(const int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '_');
+static int mainOrSubSectionLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               int style = styler.StyleAt(i);
+               if (style == SCE_BAAN_WORD5 || style == SCE_BAAN_WORD4)
+                       return style;
+               else if (IsASpaceOrTab(ch))
+                       continue;
+               else
+                       break;
+       }
+       return 0;
+}
+
+static bool priorSectionIsSubSection(Sci_Position line, LexAccessor &styler){
+       while (line > 0) {
+               Sci_Position pos = styler.LineStart(line);
+               Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+               for (Sci_Position i = pos; i < eol_pos; i++) {
+                       char ch = styler[i];
+                       int style = styler.StyleAt(i);
+                       if (style == SCE_BAAN_WORD4)
+                               return true;
+                       else if (style == SCE_BAAN_WORD5)
+                               return false;
+                       else if (IsASpaceOrTab(ch))
+                               continue;
+                       else
+                               break;
+               }
+               line--;
+       }
+       return false;
+}
+
+static bool nextSectionIsSubSection(Sci_Position line, LexAccessor &styler) {
+       while (line > 0) {
+               Sci_Position pos = styler.LineStart(line);
+               Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+               for (Sci_Position i = pos; i < eol_pos; i++) {
+                       char ch = styler[i];
+                       int style = styler.StyleAt(i);
+                       if (style == SCE_BAAN_WORD4)
+                               return true;
+                       else if (style == SCE_BAAN_WORD5)
+                               return false;
+                       else if (IsASpaceOrTab(ch))
+                               continue;
+                       else
+                               break;
+               }
+               line++;
+       }
+       return false;
+}
+
+static bool IsDeclarationLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               int style = styler.StyleAt(i);
+               if (style == SCE_BAAN_WORD) {
+                       if (styler.Match(i, "table") || styler.Match(i, "extern") || styler.Match(i, "long")
+                               || styler.Match(i, "double") || styler.Match(i, "boolean") || styler.Match(i, 
"string")
+                               || styler.Match(i, "domain")) {
+                               for (Sci_Position j = eol_pos; j > pos; j--) {
+                                       int styleFromEnd = styler.StyleAt(j);
+                                       if (styleFromEnd == SCE_BAAN_COMMENT)
+                                               continue;
+                                       else if (IsASpace(styler[j]))
+                                               continue;
+                                       else if (styler[j] != ',')
+                                               //Above conditions ensures, Declaration is not part of any 
function parameters.
+                                               return true;
+                                       else
+                                               return false;
+                               }
+                       }
+                       else
+                               return false;
+               }
+               else if (!IsASpaceOrTab(ch))
+                       return false;
+       }
+       return false;
+}
+
+static bool IsInnerLevelFold(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               int style = styler.StyleAt(i);
+               if (style == SCE_BAAN_WORD && (styler.Match(i, "else" ) || styler.Match(i, "case")
+                       || styler.Match(i, "default") || styler.Match(i, "selectdo") || styler.Match(i, 
"selecteos")
+                       || styler.Match(i, "selectempty") || styler.Match(i, "selecterror")))
+                       return true;
+               else if (IsASpaceOrTab(ch))
+                       continue;
+               else
+                       return false;
+       }
+       return false;
+}
+
+static inline bool wordInArray(const std::string& value, std::string *array, int length)
+{
+       for (int i = 0; i < length; i++)
+       {
+               if (value == array[i])
+               {
+                       return true;
+               }
+       }
+
+       return false;
+}
+
+class WordListAbridged : public WordList {
+public:
+       WordListAbridged() {
+               kwAbridged = false;
+               kwHasSection = false;
+       };
+       ~WordListAbridged() {
+               Clear();
+       };
+       bool kwAbridged;
+       bool kwHasSection;
+       bool Contains(const char *s) {
+               return kwAbridged ? InListAbridged(s, '~') : InList(s);
+       };
+};
+
+}
+
+class LexerBaan : public ILexer {
+       WordListAbridged keywords;
+       WordListAbridged keywords2;
+       WordListAbridged keywords3;
+       WordListAbridged keywords4;
+       WordListAbridged keywords5;
+       WordListAbridged keywords6;
+       WordListAbridged keywords7;
+       WordListAbridged keywords8;
+       WordListAbridged keywords9;
+       OptionsBaan options;
+       OptionSetBaan osBaan;
+public:
+       LexerBaan() {
+       }
+
+       virtual ~LexerBaan() {
+       }
+
+       int SCI_METHOD Version() const override {
+               return lvOriginal;
+       }
+
+       void SCI_METHOD Release() override {
+               delete this;
+       }
+
+       const char * SCI_METHOD PropertyNames() override {
+               return osBaan.PropertyNames();
+       }
+
+       int SCI_METHOD PropertyType(const char * name) override {
+               return osBaan.PropertyType(name);
+       }
+
+       const char * SCI_METHOD DescribeProperty(const char * name) override {
+               return osBaan.DescribeProperty(name);
+       }
+
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+
+       const char * SCI_METHOD DescribeWordListSets() override {
+               return osBaan.DescribeWordListSets();
+       }
+
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+
+       void * SCI_METHOD PrivateCall(int, void *) override {
+               return NULL;
+       }
+
+       static ILexer * LexerFactoryBaan() {
+               return new LexerBaan();
+       }
+};
+
+Sci_Position SCI_METHOD LexerBaan::PropertySet(const char *key, const char *val) {
+       if (osBaan.PropertySet(&options, key, val)) {
+               return 0;
+       }
+       return -1;
 }
 
-static void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
-                            Accessor &styler) {
+Sci_Position SCI_METHOD LexerBaan::WordListSet(int n, const char *wl) {
+       WordListAbridged *WordListAbridgedN = 0;
+       switch (n) {
+       case 0:
+               WordListAbridgedN = &keywords;
+               break;
+       case 1:
+               WordListAbridgedN = &keywords2;
+               break;
+       case 2:
+               WordListAbridgedN = &keywords3;
+               break;
+       case 3:
+               WordListAbridgedN = &keywords4;
+               break;
+       case 4:
+               WordListAbridgedN = &keywords5;
+               break;
+       case 5:
+               WordListAbridgedN = &keywords6;
+               break;
+       case 6:
+               WordListAbridgedN = &keywords7;
+               break;
+       case 7:
+               WordListAbridgedN = &keywords8;
+               break;
+       case 8:
+               WordListAbridgedN = &keywords9;
+               break;
+       }
+       Sci_Position firstModification = -1;
+       if (WordListAbridgedN) {
+               WordListAbridged wlNew;
+               wlNew.Set(wl);
+               if (*WordListAbridgedN != wlNew) {
+                       WordListAbridgedN->Set(wl);
+                       WordListAbridgedN->kwAbridged = strchr(wl, '~') != NULL;
+                       WordListAbridgedN->kwHasSection = strchr(wl, ':') != NULL;
 
-       WordList &keywords = *keywordlists[0];
-       WordList &keywords2 = *keywordlists[1];
-       bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
+                       firstModification = 0;
+               }
+       }
+       return firstModification;
+}
+
+void SCI_METHOD LexerBaan::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
 
        if (initStyle == SCE_BAAN_STRINGEOL)    // Does not leak onto next line
                initStyle = SCE_BAAN_DEFAULT;
 
        int visibleChars = 0;
+       bool lineHasDomain = false;
+       bool lineHasFunction = false;
+       bool lineHasPreProc = false;
+       bool lineIgnoreString = false;
+       bool lineHasDefines = false;
+       bool numberIsHex = false;
+       char word[1000];
+       int wordlen = 0;
 
+       std::string preProcessorTags[11] = { "#define", "#elif", "#else", "#endif",
+               "#ident", "#if", "#ifdef", "#ifndef",
+               "#include", "#pragma", "#undef" };
+       LexAccessor styler(pAccess);
        StyleContext sc(startPos, length, initStyle, styler);
 
        for (; sc.More(); sc.Forward()) {
 
-               if (sc.state == SCE_BAAN_OPERATOR) {
+               // Determine if the current state should terminate.
+               switch (sc.state) {
+               case SCE_BAAN_OPERATOR:
                        sc.SetState(SCE_BAAN_DEFAULT);
-               } else if (sc.state == SCE_BAAN_NUMBER) {
-                       if (!IsAWordChar(sc.ch)) {
+                       break;
+               case SCE_BAAN_NUMBER: 
+                       if (IsASpaceOrTab(sc.ch) || sc.ch == '\r' || sc.ch == '\n') {
                                sc.SetState(SCE_BAAN_DEFAULT);
                        }
-               } else if (sc.state == SCE_BAAN_IDENTIFIER) {
+                       else if ((numberIsHex && !(MakeLowerCase(sc.ch) == 'x' || MakeLowerCase(sc.ch) == 'e' 
||
+                               IsADigit(sc.ch, 16) || sc.ch == '.' || sc.ch == '-' || sc.ch == '+')) ||
+                               (!numberIsHex && !(MakeLowerCase(sc.ch) == 'e' || IsADigit(sc.ch)
+                               || sc.ch == '.' || sc.ch == '-' || sc.ch == '+'))) {
+                                       // check '-' for possible -10e-5. Add '+' as well.
+                                       numberIsHex = false;
+                                       sc.ChangeState(SCE_BAAN_IDENTIFIER);
+                                       sc.SetState(SCE_BAAN_DEFAULT);
+                       }
+                       break;
+               case SCE_BAAN_IDENTIFIER:
                        if (!IsAWordChar(sc.ch)) {
-                               char s[100];
+                               char s[1000];
+                               char s1[1000];
                                sc.GetCurrentLowered(s, sizeof(s));
-                               if (keywords.InList(s)) {
+                               if (sc.ch == ':') {
+                                       memcpy(s1, s, sizeof(s));
+                                       s1[sc.LengthCurrent()] = sc.ch;
+                                       s1[sc.LengthCurrent() + 1] = '\0';
+                               }
+                               if ((keywords.kwHasSection && (sc.ch == ':')) ? keywords.Contains(s1) : 
keywords.Contains(s)) {
                                        sc.ChangeState(SCE_BAAN_WORD);
-                               } else if (keywords2.InList(s)) {
+                                       if (0 == strcmp(s, "domain")) {
+                                               lineHasDomain = true;
+                                       }
+                                       else if (0 == strcmp(s, "function")) {
+                                               lineHasFunction = true;
+                                       }
+                               }
+                               else if (lineHasDomain) {
+                                       sc.ChangeState(SCE_BAAN_DOMDEF);
+                                       lineHasDomain = false;
+                               }
+                               else if (lineHasFunction) {
+                                       sc.ChangeState(SCE_BAAN_FUNCDEF);
+                                       lineHasFunction = false;
+                               }
+                               else if ((keywords2.kwHasSection && (sc.ch == ':')) ? keywords2.Contains(s1) 
: keywords2.Contains(s)) {
                                        sc.ChangeState(SCE_BAAN_WORD2);
                                }
+                               else if ((keywords3.kwHasSection && (sc.ch == ':')) ? keywords3.Contains(s1) 
: keywords3.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD3);
+                               }
+                               else if ((keywords4.kwHasSection && (sc.ch == ':')) ? keywords4.Contains(s1) 
: keywords4.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD4);
+                               }
+                               else if ((keywords5.kwHasSection && (sc.ch == ':')) ? keywords5.Contains(s1) 
: keywords5.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD5);
+                               }
+                               else if ((keywords6.kwHasSection && (sc.ch == ':')) ? keywords6.Contains(s1) 
: keywords6.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD6);
+                               }
+                               else if ((keywords7.kwHasSection && (sc.ch == ':')) ? keywords7.Contains(s1) 
: keywords7.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD7);
+                               }
+                               else if ((keywords8.kwHasSection && (sc.ch == ':')) ? keywords8.Contains(s1) 
: keywords8.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD8);
+                               }
+                               else if ((keywords9.kwHasSection && (sc.ch == ':')) ? keywords9.Contains(s1) 
: keywords9.Contains(s)) {
+                                       sc.ChangeState(SCE_BAAN_WORD9);
+                               }
+                               else if (lineHasPreProc) {
+                                       sc.ChangeState(SCE_BAAN_OBJECTDEF);
+                                       lineHasPreProc = false;
+                               }
+                               else if (lineHasDefines) {
+                                       sc.ChangeState(SCE_BAAN_DEFINEDEF);
+                                       lineHasDefines = false;
+                               }
+                               else {
+                                       int state = IsAnyOtherIdentifier(s, sc.LengthCurrent());
+                                       if (state > 0) {
+                                               sc.ChangeState(state);
+                                       }
+                               }
                                sc.SetState(SCE_BAAN_DEFAULT);
                        }
-               } else if (sc.state == SCE_BAAN_PREPROCESSOR) {
-                       if (stylingWithinPreprocessor) {
-                               if (IsASpace(sc.ch)) {
+                       break;
+               case SCE_BAAN_PREPROCESSOR:
+                       if (options.baanStylingWithinPreprocessor) {
+                               if (IsASpace(sc.ch) || IsAnOperator(sc.ch)) {
                                        sc.SetState(SCE_BAAN_DEFAULT);
                                }
-                       } else {
+                       }
+                       else {
                                if (sc.atLineEnd && (sc.chNext != '^')) {
                                        sc.SetState(SCE_BAAN_DEFAULT);
                                }
                        }
-               } else if (sc.state == SCE_BAAN_COMMENT) {
-                       if (sc.atLineEnd) {
+                       break;
+               case SCE_BAAN_COMMENT:
+                       if (sc.ch == '\r' || sc.ch == '\n') {
                                sc.SetState(SCE_BAAN_DEFAULT);
                        }
-               } else if (sc.state == SCE_BAAN_COMMENTDOC) {
+                       break;
+               case SCE_BAAN_COMMENTDOC:
                        if (sc.MatchIgnoreCase("enddllusage")) {
-                               for (unsigned int i = 0; i < 10; i++){
+                               for (unsigned int i = 0; i < 10; i++) {
+                                       sc.Forward();
+                               }
+                               sc.ForwardSetState(SCE_BAAN_DEFAULT);
+                       }
+                       else if (sc.MatchIgnoreCase("endfunctionusage")) {
+                               for (unsigned int i = 0; i < 15; i++) {
                                        sc.Forward();
                                }
                                sc.ForwardSetState(SCE_BAAN_DEFAULT);
                        }
-               } else if (sc.state == SCE_BAAN_STRING) {
+                       break;
+               case SCE_BAAN_STRING:
                        if (sc.ch == '\"') {
                                sc.ForwardSetState(SCE_BAAN_DEFAULT);
-                       } else if ((sc.atLineEnd) && (sc.chNext != '^')) {
+                       }
+                       else if ((sc.atLineEnd) && (sc.chNext != '^')) {
                                sc.ChangeState(SCE_BAAN_STRINGEOL);
-                               sc.ForwardSetState(SCE_C_DEFAULT);
+                               sc.ForwardSetState(SCE_BAAN_DEFAULT);
                                visibleChars = 0;
                        }
+                       break;
                }
 
+               // Determine if a new state should be entered.
                if (sc.state == SCE_BAAN_DEFAULT) {
-                       if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+                       if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))
+                               || ((sc.ch == '-' || sc.ch == '+') && (IsADigit(sc.chNext) || sc.chNext == 
'.'))
+                               || (MakeLowerCase(sc.ch) == 'e' && (IsADigit(sc.chNext) || sc.chNext == '+' 
|| sc.chNext == '-'))) {
+                               if ((sc.ch == '0' && MakeLowerCase(sc.chNext) == 'x') ||
+                                       ((sc.ch == '-' || sc.ch == '+') && sc.chNext == '0' && 
MakeLowerCase(sc.GetRelativeCharacter(2)) == 'x')){
+                                       numberIsHex = true;
+                               }
                                sc.SetState(SCE_BAAN_NUMBER);
-                       } else if (sc.MatchIgnoreCase("dllusage")){
-                                       sc.SetState(SCE_BAAN_COMMENTDOC);
-                                       do {
-                                               sc.Forward();
-                                       } while ((!sc.atLineEnd) && sc.More());
-                       } else if (IsAWordStart(sc.ch)) {
-                                       sc.SetState(SCE_BAAN_IDENTIFIER);
-                       } else if (sc.Match('|')){
-                                       sc.SetState(SCE_BAAN_COMMENT);
-                       } else if (sc.ch == '\"') {
+                       }
+                       else if (sc.MatchIgnoreCase("dllusage") || sc.MatchIgnoreCase("functionusage")) {
+                               sc.SetState(SCE_BAAN_COMMENTDOC);
+                               do {
+                                       sc.Forward();
+                               } while ((!sc.atLineEnd) && sc.More());
+                       }
+                       else if (iswordstart(sc.ch)) {
+                               sc.SetState(SCE_BAAN_IDENTIFIER);
+                       }
+                       else if (sc.Match('|')) {
+                               sc.SetState(SCE_BAAN_COMMENT);
+                       }
+                       else if (sc.ch == '\"' && !(lineIgnoreString)) {
                                sc.SetState(SCE_BAAN_STRING);
-                       } else if (sc.ch == '#' && visibleChars == 0) {
+                       }
+                       else if (sc.ch == '#' && visibleChars == 0) {
                                // Preprocessor commands are alone on their line
                                sc.SetState(SCE_BAAN_PREPROCESSOR);
-                               // Skip whitespace between # and preprocessor word
-                               do {
+                               word[0] = '\0';
+                               wordlen = 0;
+                               while (sc.More() && !(IsASpace(sc.chNext) || IsAnOperator(sc.chNext))) {
                                        sc.Forward();
-                               } while (IsASpace(sc.ch) && sc.More());
-                       } else if (isoperator(static_cast<char>(sc.ch))) {
+                                       wordlen++;
+                               }
+                               sc.GetCurrentLowered(word, sizeof(word));
+                               if (!sc.atLineEnd) {
+                                       word[wordlen++] = sc.ch;
+                                       word[wordlen++] = '\0';
+                               }
+                               if (!wordInArray(word, preProcessorTags, 11))
+                                       // Colorise only preprocessor built in Baan.
+                                       sc.ChangeState(SCE_BAAN_IDENTIFIER);
+                               if (strcmp(word, "#pragma") == 0 || strcmp(word, "#include") == 0) {
+                                       lineHasPreProc = true;
+                                       lineIgnoreString = true;
+                               }
+                               else if (strcmp(word, "#define") == 0 || strcmp(word, "#undef") == 0 ||
+                                       strcmp(word, "#ifdef") == 0 || strcmp(word, "#if") == 0 || 
strcmp(word, "#ifndef") == 0) {
+                                       lineHasDefines = true;
+                                       lineIgnoreString = false;
+                               }
+                       }
+                       else if (IsAnOperator(static_cast<char>(sc.ch))) {
                                sc.SetState(SCE_BAAN_OPERATOR);
                        }
                }
+
                if (sc.atLineEnd) {
                        // Reset states to begining of colourise so no surprises
                        // if different sets of lines lexed.
                        visibleChars = 0;
+                       lineHasDomain = false;
+                       lineHasFunction = false;
+                       lineHasPreProc = false;
+                       lineIgnoreString = false;
+                       lineHasDefines = false;
+                       numberIsHex = false;
                }
                if (!IsASpace(sc.ch)) {
                        visibleChars++;
@@ -137,44 +723,247 @@ static void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, W
        sc.Complete();
 }
 
-static void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordList *[],
-                            Accessor &styler) {
-       bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
-       bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+void SCI_METHOD LexerBaan::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
+       if (!options.fold)
+               return;
+
+       char word[100];
+       int wordlen = 0;
+       bool foldStart = true;
+       bool foldNextSelect = true;
+       bool afterFunctionSection = false;
+       bool beforeDeclarationSection = false;
+       int currLineStyle = 0;
+       int nextLineStyle = 0;
+
+       std::string startTags[6] = { "for", "if", "on", "repeat", "select", "while" };
+       std::string endTags[6] = { "endcase", "endfor", "endif", "endselect", "endwhile", "until" };
+       std::string selectCloseTags[5] = { "selectdo", "selecteos", "selectempty", "selecterror", "endselect" 
};
+
+       LexAccessor styler(pAccess);
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
-       int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+
+       // Backtrack to previous line in case need to fix its fold status
+       if (startPos > 0) {
+               if (lineCurrent > 0) {
+                       lineCurrent--;
+                       startPos = styler.LineStart(lineCurrent);
+               }
+       }
+
+       int levelPrev = SC_FOLDLEVELBASE;
+       if (lineCurrent > 0)
+               levelPrev = styler.LevelAt(lineCurrent - 1) >> 16;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
-       int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       int styleNext = styler.StyleAt(startPos);
+
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
-               int stylePrev = style;
                style = styleNext;
                styleNext = styler.StyleAt(i + 1);
+               int stylePrev = (i) ? styler.StyleAt(i - 1) : SCE_BAAN_DEFAULT;
                bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
-               if (foldComment &&
-                       (style == SCE_BAAN_COMMENT || style == SCE_BAAN_COMMENTDOC)) {
+
+               // Comment folding
+               if (options.foldComment && style == SCE_BAAN_COMMENTDOC) {
                        if (style != stylePrev) {
                                levelCurrent++;
-                       } else if ((style != styleNext) && !atEOL) {
-                               // Comments don't end at end of line and the next character may be unstyled.
+                       }
+                       else if (style != styleNext) {
+                               levelCurrent--;
+                       }
+               }
+               if (options.foldComment && atEOL && IsCommentLine(lineCurrent, styler)) {
+                       if (!IsCommentLine(lineCurrent - 1, styler)
+                               && IsCommentLine(lineCurrent + 1, styler))
+                               levelCurrent++;
+                       else if (IsCommentLine(lineCurrent - 1, styler)
+                               && !IsCommentLine(lineCurrent + 1, styler))
                                levelCurrent--;
+               }
+               // PreProcessor Folding
+               if (options.foldPreprocessor) {
+                       if (atEOL && IsPreProcLine(lineCurrent, styler)) {
+                               if (!IsPreProcLine(lineCurrent - 1, styler)
+                                       && IsPreProcLine(lineCurrent + 1, styler))
+                                       levelCurrent++;
+                               else if (IsPreProcLine(lineCurrent - 1, styler)
+                                       && !IsPreProcLine(lineCurrent + 1, styler))
+                                       levelCurrent--;
+                       }
+                       else if (style == SCE_BAAN_PREPROCESSOR) {
+                               // folds #ifdef/#if/#ifndef - they are not part of the IsPreProcLine folding.
+                               if (ch == '#') {
+                                       if (styler.Match(i, "#ifdef") || styler.Match(i, "#if") || 
styler.Match(i, "#ifndef"))
+                                               levelCurrent++;
+                                       else if (styler.Match(i, "#endif"))
+                                               levelCurrent--;
+                               }
+                       }
+               }
+               //Syntax Folding
+               if (options.baanFoldSyntaxBased && (style == SCE_BAAN_OPERATOR)) {
+                       if (ch == '{' || ch == '(') {
+                               levelCurrent++;
+                       }
+                       else if (ch == '}' || ch == ')') {
+                               levelCurrent--;
+                       }
+               }
+               //Keywords Folding
+               if (options.baanFoldKeywordsBased) {
+                       if (atEOL && IsDeclarationLine(lineCurrent, styler)) {
+                               if (!IsDeclarationLine(lineCurrent - 1, styler)
+                                       && IsDeclarationLine(lineCurrent + 1, styler))
+                                       levelCurrent++;
+                               else if (IsDeclarationLine(lineCurrent - 1, styler)
+                                       && !IsDeclarationLine(lineCurrent + 1, styler))
+                                       levelCurrent--;
+                       }
+                       else if (style == SCE_BAAN_WORD) {
+                               word[wordlen++] = static_cast<char>(MakeLowerCase(ch));
+                               if (wordlen == 100) {                   // prevent overflow
+                                       word[0] = '\0';
+                                       wordlen = 1;
+                               }
+                               if (styleNext != SCE_BAAN_WORD) {
+                                       word[wordlen] = '\0';
+                                       wordlen = 0;
+                                       if (strcmp(word, "for") == 0) {
+                                               Sci_PositionU j = i + 1;
+                                               while ((j < endPos) && 
IsASpaceOrTab(styler.SafeGetCharAt(j))) {
+                                                       j++;
+                                               }
+                                               if (styler.Match(j, "update")) {
+                                                       // Means this is a "for update" used by Select which 
is already folded.
+                                                       foldStart = false;
+                                               }
+                                       }
+                                       else if (strcmp(word, "on") == 0) {
+                                               Sci_PositionU j = i + 1;
+                                               while ((j < endPos) && 
IsASpaceOrTab(styler.SafeGetCharAt(j))) {
+                                                       j++;
+                                               }
+                                               if (!styler.Match(j, "case")) {
+                                                       // Means this is not a "on Case" statement... could 
be "on" used by index.
+                                                       foldStart = false;
+                                               }
+                                       }
+                                       else if (strcmp(word, "select") == 0) {
+                                               if (foldNextSelect) {
+                                                       // Next Selects are sub-clause till reach of 
selectCloseTags[] array.
+                                                       foldNextSelect = false;
+                                                       foldStart = true;
+                                               }
+                                               else {
+                                                       foldNextSelect = false;
+                                                       foldStart = false;
+                                               }
+                                       }
+                                       else if (wordInArray(word, selectCloseTags, 5)) {
+                                               // select clause ends, next select clause can be folded.
+                                               foldNextSelect = true;
+                                               foldStart = true;
+                                       }
+                                       else {
+                                               foldStart = true;
+                                       }
+                                       if (foldStart) {
+                                               if (wordInArray(word, startTags, 6)) {
+                                                       levelCurrent++;
+                                               }
+                                               else if (wordInArray(word, endTags, 6)) {
+                                                       levelCurrent--;
+                                               }
+                                       }
+                               }
                        }
                }
-               if (style == SCE_BAAN_OPERATOR) {
-                       if (ch == '{') {
+               // Fold inner level of if/select/case statements
+               if (options.baanFoldInnerLevel && atEOL) {
+                       bool currLineInnerLevel = IsInnerLevelFold(lineCurrent, styler);
+                       bool nextLineInnerLevel = IsInnerLevelFold(lineCurrent + 1, styler);
+                       if (currLineInnerLevel && currLineInnerLevel != nextLineInnerLevel) {
                                levelCurrent++;
-                       } else if (ch == '}') {
+                       }
+                       else if (nextLineInnerLevel && nextLineInnerLevel != currLineInnerLevel) {
                                levelCurrent--;
                        }
                }
+               // Section Foldings.
+               // One way of implementing Section Foldings, as there is no END markings of sections.
+               // first section ends on the previous line of next section.
+               // Re-written whole folding to accomodate this.
+               if (options.baanFoldSections && atEOL) {
+                       currLineStyle = mainOrSubSectionLine(lineCurrent, styler);
+                       nextLineStyle = mainOrSubSectionLine(lineCurrent + 1, styler);
+                       if (currLineStyle != 0 && currLineStyle != nextLineStyle) {
+                               if (levelCurrent < levelPrev)
+                                       --levelPrev;
+                               for (Sci_Position j = styler.LineStart(lineCurrent); j < 
styler.LineStart(lineCurrent + 1) - 1; j++) {
+                                       if (IsASpaceOrTab(styler[j]))
+                                               continue;
+                                       else if (styler.StyleAt(j) == SCE_BAAN_WORD5) {
+                                               if (styler.Match(j, "functions:")) {
+                                                       // Means functions: is the end of MainSections.
+                                                       // Nothing to fold after this.
+                                                       afterFunctionSection = true;
+                                                       break;
+                                               }
+                                               else {
+                                                       afterFunctionSection = false;
+                                                       break;
+                                               }
+                                       }
+                                       else {
+                                               afterFunctionSection = false;
+                                               break;
+                                       }
+                               }
+                               if (!afterFunctionSection)
+                                       levelCurrent++;
+                       }
+                       else if (nextLineStyle != 0 && currLineStyle != nextLineStyle
+                               && (priorSectionIsSubSection(lineCurrent -1 ,styler) 
+                                       || !nextSectionIsSubSection(lineCurrent + 1, styler))) {
+                               for (Sci_Position j = styler.LineStart(lineCurrent + 1); j < 
styler.LineStart(lineCurrent + 1 + 1) - 1; j++) {
+                                       if (IsASpaceOrTab(styler[j]))
+                                               continue;
+                                       else if (styler.StyleAt(j) == SCE_BAAN_WORD5) {
+                                               if (styler.Match(j, "declaration:")) {
+                                                       // Means declaration: is the start of MainSections.
+                                                       // Nothing to fold before this.
+                                                       beforeDeclarationSection = true;
+                                                       break;
+                                               }
+                                               else {
+                                                       beforeDeclarationSection = false;
+                                                       break;
+                                               }
+                                       }
+                                       else {
+                                               beforeDeclarationSection = false;
+                                               break;
+                                       }
+                               }
+                               if (!beforeDeclarationSection) {
+                                       levelCurrent--;
+                                       if (nextLineStyle == SCE_BAAN_WORD5 && 
priorSectionIsSubSection(lineCurrent-1, styler))
+                                               // next levelCurrent--; is to unfold previous subsection fold.
+                                               // On reaching the next main section, the previous main as 
well sub section ends.
+                                               levelCurrent--;
+                               }
+                       }
+               }
                if (atEOL) {
                        int lev = levelPrev;
-                       if (visibleChars == 0 && foldCompact)
+                       lev |= levelCurrent << 16;
+                       if (visibleChars == 0 && options.foldCompact)
                                lev |= SC_FOLDLEVELWHITEFLAG;
                        if ((levelCurrent > levelPrev) && (visibleChars > 0))
                                lev |= SC_FOLDLEVELHEADERFLAG;
@@ -188,9 +977,8 @@ static void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordLi
                if (!isspacechar(ch))
                        visibleChars++;
        }
-       // Fill in the real level of the next line, keeping the current flags as they will be filled in later
        int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
        styler.SetLevel(lineCurrent, levelPrev | flagsNext);
 }
 
-LexerModule lmBaan(SCLEX_BAAN, ColouriseBaanDoc, "baan", FoldBaanDoc);
+LexerModule lmBaan(SCLEX_BAAN, LexerBaan::LexerFactoryBaan, "baan", baanWordLists);
diff --git a/plugins/scintilla/scintilla/lexers/LexBash.cxx b/plugins/scintilla/scintilla/lexers/LexBash.cxx
index 2dc8707..9c02c28 100644
--- a/plugins/scintilla/scintilla/lexers/LexBash.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexBash.cxx
@@ -96,7 +96,33 @@ static int opposite(int ch) {
        return ch;
 }
 
-static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
+static int GlobScan(StyleContext &sc) {
+       // forward scan for zsh globs, disambiguate versus bash arrays
+       // complex expressions may still fail, e.g. unbalanced () '' "" etc
+       int c, sLen = 0;
+       int pCount = 0;
+       int hash = 0;
+       while ((c = sc.GetRelativeCharacter(++sLen)) != 0) {
+               if (IsASpace(c)) {
+                       return 0;
+               } else if (c == '\'' || c == '\"') {
+                       if (hash != 2) return 0;
+               } else if (c == '#' && hash == 0) {
+                       hash = (sLen == 1) ? 2:1;
+               } else if (c == '(') {
+                       pCount++;
+               } else if (c == ')') {
+                       if (pCount == 0) {
+                               if (hash) return sLen;
+                               return 0;
+                       }
+                       pCount--;
+               }
+       }
+       return 0;
+}
+
+static void ColouriseBashDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                                         WordList *keywordlists[], Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
@@ -108,12 +134,14 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
        CharacterSet setWordStart(CharacterSet::setAlpha, "_");
        // note that [+-] are often parts of identifiers in shell scripts
        CharacterSet setWord(CharacterSet::setAlphaNum, "._+-");
+       CharacterSet setMetaCharacter(CharacterSet::setNone, "|&;()<> \t\r\n");
+       setMetaCharacter.Add(0);
        CharacterSet setBashOperator(CharacterSet::setNone, "^&%()-+=|{}[]:;>,*/<?!.~@");
        CharacterSet setSingleCharOp(CharacterSet::setNone, "rwxoRWXOezsfdlpSbctugkTBMACahGLNn");
        CharacterSet setParam(CharacterSet::setAlphaNum, "$_");
-       CharacterSet setHereDoc(CharacterSet::setAlpha, "_\\-+!");
-       CharacterSet setHereDoc2(CharacterSet::setAlphaNum, "_-+!");
-       CharacterSet setLeftShift(CharacterSet::setDigits, "=$");
+       CharacterSet setHereDoc(CharacterSet::setAlpha, "_\\-+!%*,./:?@[]^`{}~");
+       CharacterSet setHereDoc2(CharacterSet::setAlphaNum, "_-+!%*,./:=?@[]^`{}~");
+       CharacterSet setLeftShift(CharacterSet::setDigits, "$");
 
        class HereDocCls {      // Class to manage HERE document elements
        public:
@@ -124,14 +152,13 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                bool Quoted;            // true if Quote in ('\'','"','`')
                bool Indent;            // indented delimiter (for <<-)
                int DelimiterLength;    // strlen(Delimiter)
-               char *Delimiter;        // the Delimiter, 256: sizeof PL_tokenbuf
+               char Delimiter[HERE_DELIM_MAX]; // the Delimiter
                HereDocCls() {
                        State = 0;
                        Quote = 0;
                        Quoted = false;
                        Indent = 0;
                        DelimiterLength = 0;
-                       Delimiter = new char[HERE_DELIM_MAX];
                        Delimiter[0] = '\0';
                }
                void Append(int ch) {
@@ -139,7 +166,6 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                        Delimiter[DelimiterLength] = '\0';
                }
                ~HereDocCls() {
-                       delete []Delimiter;
                }
        };
        HereDocCls HereDoc;
@@ -171,18 +197,15 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                int Up, Down;
                int Style;
                int Depth;                      // levels pushed
-               int *CountStack;
-               int *UpStack;
-               int *StyleStack;
+               int CountStack[BASH_DELIM_STACK_MAX];
+               int UpStack   [BASH_DELIM_STACK_MAX];
+               int StyleStack[BASH_DELIM_STACK_MAX];
                QuoteStackCls() {
                        Count = 0;
                        Up    = '\0';
                        Down  = '\0';
                        Style = 0;
                        Depth = 0;
-                       CountStack = new int[BASH_DELIM_STACK_MAX];
-                       UpStack    = new int[BASH_DELIM_STACK_MAX];
-                       StyleStack = new int[BASH_DELIM_STACK_MAX];
                }
                void Start(int u, int s) {
                        Count = 1;
@@ -212,23 +235,20 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                        Down  = opposite(Up);
                }
                ~QuoteStackCls() {
-                       delete []CountStack;
-                       delete []UpStack;
-                       delete []StyleStack;
                }
        };
        QuoteStackCls QuoteStack;
 
        int numBase = 0;
        int digit;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int cmdState = BASH_CMD_START;
        int testExprType = 0;
 
        // Always backtracks to the start of a line that is not a continuation
        // of the previous line (i.e. start of a bash command segment)
-       int ln = styler.GetLine(startPos);
-       if (ln > 0 && startPos == static_cast<unsigned int>(styler.LineStart(ln)))
+       Sci_Position ln = styler.GetLine(startPos);
+       if (ln > 0 && startPos == static_cast<Sci_PositionU>(styler.LineStart(ln)))
                ln--;
        for (;;) {
                startPos = styler.LineStart(ln);
@@ -343,6 +363,8 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                                        sc.ForwardSetState(SCE_SH_DEFAULT);
                                } else if (!setWord.Contains(sc.ch)) {
                                        sc.SetState(SCE_SH_DEFAULT);
+                               } else if (cmdState == BASH_CMD_ARITH && !setWordStart.Contains(sc.ch)) {
+                                       sc.SetState(SCE_SH_DEFAULT);
                                }
                                break;
                        case SCE_SH_NUMBER:
@@ -417,19 +439,18 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                                                sc.Forward();
                                                HereDoc.Quoted = true;
                                                HereDoc.State = 1;
-                                       } else if (!HereDoc.Indent && sc.chNext == '-') {       // <<- indent 
case
-                                               HereDoc.Indent = true;
-                                       } else if (setHereDoc.Contains(sc.chNext)) {
+                                       } else if (setHereDoc.Contains(sc.chNext) ||
+                                                  (sc.chNext == '=' && cmdState != BASH_CMD_ARITH)) {
                                                // an unquoted here-doc delimiter, no special handling
-                                               // TODO check what exactly bash considers part of the delim
                                                HereDoc.State = 1;
                                        } else if (sc.chNext == '<') {  // HERE string <<<
                                                sc.Forward();
                                                sc.ForwardSetState(SCE_SH_DEFAULT);
                                        } else if (IsASpace(sc.chNext)) {
                                                // eat whitespace
-                                       } else if (setLeftShift.Contains(sc.chNext)) {
-                                               // left shift << or <<= operator cases
+                                       } else if (setLeftShift.Contains(sc.chNext) ||
+                                                  (sc.chNext == '=' && cmdState == BASH_CMD_ARITH)) {
+                                               // left shift <<$var or <<= cases
                                                sc.ChangeState(SCE_SH_OPERATOR);
                                                sc.ForwardSetState(SCE_SH_DEFAULT);
                                        } else {
@@ -437,12 +458,22 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                                                HereDoc.State = 1;
                                        }
                                } else if (HereDoc.State == 1) { // collect the delimiter
-                                       if (setHereDoc2.Contains(sc.ch) || sc.chPrev == '\\') {
+                                       // * if single quoted, there's no escape
+                                       // * if double quoted, there are \\ and \" escapes
+                                       if ((HereDoc.Quote == '\'' && sc.ch != HereDoc.Quote) ||
+                                           (HereDoc.Quoted && sc.ch != HereDoc.Quote && sc.ch != '\\') ||
+                                           (HereDoc.Quote != '\'' && sc.chPrev == '\\') ||
+                                           (setHereDoc2.Contains(sc.ch))) {
                                                HereDoc.Append(sc.ch);
                                        } else if (HereDoc.Quoted && sc.ch == HereDoc.Quote) {  // closing 
quote => end of delimiter
                                                sc.ForwardSetState(SCE_SH_DEFAULT);
                                        } else if (sc.ch == '\\') {
-                                               // skip escape prefix
+                                               if (HereDoc.Quoted && sc.chNext != HereDoc.Quote && sc.chNext 
!= '\\') {
+                                                       // in quoted prefixes only \ and the quote eat the 
escape
+                                                       HereDoc.Append(sc.ch);
+                                               } else {
+                                                       // skip escape prefix
+                                               }
                                        } else if (!HereDoc.Quoted) {
                                                sc.SetState(SCE_SH_DEFAULT);
                                        }
@@ -457,7 +488,7 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                                if (sc.atLineStart) {
                                        sc.SetState(SCE_SH_HERE_Q);
                                        int prefixws = 0;
-                                       while (IsASpace(sc.ch) && !sc.atLineEnd) {      // whitespace prefix
+                                       while (sc.ch == '\t' && !sc.atLineEnd) {        // tabulation prefix
                                                sc.Forward();
                                                prefixws++;
                                        }
@@ -469,7 +500,8 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                                        char s[HERE_DELIM_MAX];
                                        sc.GetCurrent(s, sizeof(s));
                                        if (sc.LengthCurrent() == 0) {  // '' or "" delimiters
-                                               if (prefixws == 0 && HereDoc.Quoted && 
HereDoc.DelimiterLength == 0)
+                                               if ((prefixws == 0 || HereDoc.Indent) &&
+                                                       HereDoc.Quoted && HereDoc.DelimiterLength == 0)
                                                        sc.SetState(SCE_SH_DEFAULT);
                                                break;
                                        }
@@ -573,12 +605,14 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                        HereDoc.State = 2;
                        if (HereDoc.Quoted) {
                                if (sc.state == SCE_SH_HERE_DELIM) {
-                                       // Missing quote at end of string! We are stricter than bash.
-                                       // Colour here-doc anyway while marking this bit as an error.
+                                       // Missing quote at end of string! Syntax error in bash 4.3
+                                       // Mark this bit as an error, do not colour any here-doc
                                        sc.ChangeState(SCE_SH_ERROR);
+                                       sc.SetState(SCE_SH_DEFAULT);
+                               } else {
+                                       // HereDoc.Quote always == '\''
+                                       sc.SetState(SCE_SH_HERE_Q);
                                }
-                               // HereDoc.Quote always == '\''
-                               sc.SetState(SCE_SH_HERE_Q);
                        } else if (HereDoc.DelimiterLength == 0) {
                                // no delimiter, illegal (but '' and "" are legal)
                                sc.ChangeState(SCE_SH_ERROR);
@@ -617,7 +651,29 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                        } else if (setWordStart.Contains(sc.ch)) {
                                sc.SetState(SCE_SH_WORD);
                        } else if (sc.ch == '#') {
-                               sc.SetState(SCE_SH_COMMENTLINE);
+                               if (stylePrev != SCE_SH_WORD && stylePrev != SCE_SH_IDENTIFIER &&
+                                       (sc.currentPos == 0 || setMetaCharacter.Contains(sc.chPrev))) {
+                                       sc.SetState(SCE_SH_COMMENTLINE);
+                               } else {
+                                       sc.SetState(SCE_SH_WORD);
+                               }
+                               // handle some zsh features within arithmetic expressions only
+                               if (cmdState == BASH_CMD_ARITH) {
+                                       if (sc.chPrev == '[') { // [#8] [##8] output digit setting
+                                               sc.SetState(SCE_SH_WORD);
+                                               if (sc.chNext == '#') {
+                                                       sc.Forward();
+                                               }
+                                       } else if (sc.Match("##^") && IsUpperCase(sc.GetRelative(3))) { // 
##^A
+                                               sc.SetState(SCE_SH_IDENTIFIER);
+                                               sc.Forward(3);
+                                       } else if (sc.chNext == '#' && !IsASpace(sc.GetRelative(2))) {  // ##a
+                                               sc.SetState(SCE_SH_IDENTIFIER);
+                                               sc.Forward(2);
+                                       } else if (setWordStart.Contains(sc.chNext)) {  // #name
+                                               sc.SetState(SCE_SH_IDENTIFIER);
+                                       }
+                               }
                        } else if (sc.ch == '\"') {
                                sc.SetState(SCE_SH_STRING);
                                QuoteStack.Start(sc.ch, BASH_DELIM_STRING);
@@ -655,7 +711,12 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                        } else if (sc.Match('<', '<')) {
                                sc.SetState(SCE_SH_HERE_DELIM);
                                HereDoc.State = 0;
-                               HereDoc.Indent = false;
+                               if (sc.GetRelative(2) == '-') { // <<- indent case
+                                       HereDoc.Indent = true;
+                                       sc.Forward();
+                               } else {
+                                       HereDoc.Indent = false;
+                               }
                        } else if (sc.ch == '-' &&      // one-char file test operators
                                           setSingleCharOp.Contains(sc.chNext) &&
                                           !setWord.Contains(sc.GetRelative(2)) &&
@@ -666,6 +727,15 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
                                char s[10];
                                bool isCmdDelim = false;
                                sc.SetState(SCE_SH_OPERATOR);
+                               // globs have no whitespace, do not appear in arithmetic expressions
+                               if (cmdState != BASH_CMD_ARITH && sc.ch == '(' && sc.chNext != '(') {
+                                       int i = GlobScan(sc);
+                                       if (i > 1) {
+                                               sc.SetState(SCE_SH_IDENTIFIER);
+                                               sc.Forward(i);
+                                               continue;
+                                       }
+                               }
                                // handle opening delimiters for test/arithmetic expressions - ((,[[,[
                                if (cmdState == BASH_CMD_START
                                 || cmdState == BASH_CMD_BODY) {
@@ -731,10 +801,10 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eol_pos; i++) {
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
                char ch = styler[i];
                if (ch == '#')
                        return true;
@@ -744,18 +814,19 @@ static bool IsCommentLine(int line, Accessor &styler) {
        return false;
 }
 
-static void FoldBashDoc(unsigned int startPos, int length, int, WordList *[],
+static void FoldBashDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
                                                Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       int skipHereCh = 0;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
@@ -781,7 +852,15 @@ static void FoldBashDoc(unsigned int startPos, int length, int, WordList *[],
                // Here Document folding
                if (style == SCE_SH_HERE_DELIM) {
                        if (ch == '<' && chNext == '<') {
-                               levelCurrent++;
+                               if (styler.SafeGetCharAt(i + 2) == '<') {
+                                       skipHereCh = 1;
+                               } else {
+                                       if (skipHereCh == 0) {
+                                               levelCurrent++;
+                                       } else {
+                                               skipHereCh = 0;
+                                       }
+                               }
                        }
                } else if (style == SCE_SH_HERE_Q && styler.StyleAt(i+1) == SCE_SH_DEFAULT) {
                        levelCurrent--;
diff --git a/plugins/scintilla/scintilla/lexers/LexBasic.cxx b/plugins/scintilla/scintilla/lexers/LexBasic.cxx
index bc8fcee..4aa449d 100644
--- a/plugins/scintilla/scintilla/lexers/LexBasic.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexBasic.cxx
@@ -49,17 +49,18 @@ using namespace Scintilla;
  * 8  - decimal digit
  * 16 - hex digit
  * 32 - bin digit
+ * 64 - letter
  */
 static int character_classification[128] =
 {
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  0,  1,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    1,  2,  0,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  10, 2,
-    60, 60, 28, 28, 28, 28, 28, 28, 28, 28, 2,  2,  2,  2,  2,  2,
-    2,  20, 20, 20, 20, 20, 20, 4,  4,  4,  4,  4,  4,  4,  4,  4,
-    4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  2,  2,  2,  2,  4,
-    2,  20, 20, 20, 20, 20, 20, 4,  4,  4,  4,  4,  4,  4,  4,  4,
-    4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  2,  2,  2,  2,  0
+               0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  0,  1,  0,  0,
+               0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+               1,  2,  0,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  10, 2,
+        60, 60, 28, 28, 28, 28, 28, 28, 28, 28,  2,  2,  2,  2,  2,  2,
+               2, 84, 84, 84, 84, 84, 84, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+        68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,  2,  2,  2,  2, 68,
+               2, 84, 84, 84, 84, 84, 84, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+        68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,  2,  2,  2,  2,  0
 };
 
 static bool IsSpace(int c) {
@@ -86,6 +87,10 @@ static bool IsBinDigit(int c) {
        return c < 128 && (character_classification[c] & 32);
 }
 
+static bool IsLetter(int c) {
+       return c < 128 && (character_classification[c] & 64);
+}
+
 static int LowerCase(int c)
 {
        if (c >= 'A' && c <= 'Z')
@@ -126,13 +131,23 @@ static int CheckPureFoldPoint(char const *token, int &level) {
 static int CheckFreeFoldPoint(char const *token, int &level) {
        if (!strcmp(token, "function") ||
                !strcmp(token, "sub") ||
-               !strcmp(token, "type")) {
+               !strcmp(token, "enum") ||
+               !strcmp(token, "type") ||
+               !strcmp(token, "union") ||
+               !strcmp(token, "property") ||
+               !strcmp(token, "destructor") ||
+               !strcmp(token, "constructor")) {
                level |= SC_FOLDLEVELHEADERFLAG;
                return 1;
        }
        if (!strcmp(token, "end function") ||
                !strcmp(token, "end sub") ||
-               !strcmp(token, "end type")) {
+               !strcmp(token, "end enum") ||
+               !strcmp(token, "end type") ||
+               !strcmp(token, "end union") ||
+               !strcmp(token, "end property") ||
+               !strcmp(token, "end destructor") ||
+               !strcmp(token, "end constructor")) {
                return -1;
        }
        return 0;
@@ -219,36 +234,36 @@ class LexerBasic : public ILexer {
        OptionSetBasic osBasic;
 public:
        LexerBasic(char comment_char_, int (*CheckFoldPoint_)(char const *, int &), const char * const 
wordListDescriptions[]) :
-                  comment_char(comment_char_),
-                  CheckFoldPoint(CheckFoldPoint_),
-                  osBasic(wordListDescriptions) {
+                                                comment_char(comment_char_),
+                                                CheckFoldPoint(CheckFoldPoint_),
+                                                osBasic(wordListDescriptions) {
        }
        virtual ~LexerBasic() {
        }
-       void SCI_METHOD Release() {
+       void SCI_METHOD Release() override {
                delete this;
        }
-       int SCI_METHOD Version() const {
+       int SCI_METHOD Version() const override {
                return lvOriginal;
        }
-       const char * SCI_METHOD PropertyNames() {
+       const char * SCI_METHOD PropertyNames() override {
                return osBasic.PropertyNames();
        }
-       int SCI_METHOD PropertyType(const char *name) {
+       int SCI_METHOD PropertyType(const char *name) override {
                return osBasic.PropertyType(name);
        }
-       const char * SCI_METHOD DescribeProperty(const char *name) {
+       const char * SCI_METHOD DescribeProperty(const char *name) override {
                return osBasic.DescribeProperty(name);
        }
-       int SCI_METHOD PropertySet(const char *key, const char *val);
-       const char * SCI_METHOD DescribeWordListSets() {
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char * SCI_METHOD DescribeWordListSets() override {
                return osBasic.DescribeWordListSets();
        }
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-       void * SCI_METHOD PrivateCall(int, void *) {
+       void * SCI_METHOD PrivateCall(int, void *) override {
                return 0;
        }
        static ILexer *LexerFactoryBlitzBasic() {
@@ -262,14 +277,14 @@ public:
        }
 };
 
-int SCI_METHOD LexerBasic::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerBasic::PropertySet(const char *key, const char *val) {
        if (osBasic.PropertySet(&options, key, val)) {
                return 0;
        }
        return -1;
 }
 
-int SCI_METHOD LexerBasic::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerBasic::WordListSet(int n, const char *wl) {
        WordList *wordListN = 0;
        switch (n) {
        case 0:
@@ -285,7 +300,7 @@ int SCI_METHOD LexerBasic::WordListSet(int n, const char *wl) {
                wordListN = &keywordlists[3];
                break;
        }
-       int firstModification = -1;
+       Sci_Position firstModification = -1;
        if (wordListN) {
                WordList wlNew;
                wlNew.Set(wl);
@@ -297,11 +312,12 @@ int SCI_METHOD LexerBasic::WordListSet(int n, const char *wl) {
        return firstModification;
 }
 
-void SCI_METHOD LexerBasic::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerBasic::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        LexAccessor styler(pAccess);
 
        bool wasfirst = true, isfirst = true; // true if first token in a line
        styler.StartAt(startPos);
+       int styleBeforeKeyword = SCE_B_DEFAULT;
 
        StyleContext sc(startPos, length, initStyle, styler);
 
@@ -367,14 +383,44 @@ void SCI_METHOD LexerBasic::Lex(unsigned int startPos, int length, int initStyle
                        if (sc.atLineEnd) {
                                sc.SetState(SCE_B_DEFAULT);
                        }
+               } else if (sc.state == SCE_B_DOCLINE) {
+                       if (sc.atLineEnd) {
+                               sc.SetState(SCE_B_DEFAULT);
+                       } else if (sc.ch == '\\' || sc.ch == '@') {
+                               if (IsLetter(sc.chNext) && sc.chPrev != '\\') {
+                                       styleBeforeKeyword = sc.state;
+                                       sc.SetState(SCE_B_DOCKEYWORD);
+                               };
+                       }
+               } else if (sc.state == SCE_B_DOCKEYWORD) {
+                       if (IsSpace(sc.ch)) {
+                               sc.SetState(styleBeforeKeyword);
+                       }       else if (sc.atLineEnd && styleBeforeKeyword == SCE_B_DOCLINE) {
+                               sc.SetState(SCE_B_DEFAULT);
+                       }
+               } else if (sc.state == SCE_B_COMMENTBLOCK) {
+                       if (sc.Match("\'/")) {
+                               sc.Forward();
+                               sc.ForwardSetState(SCE_B_DEFAULT);
+                       }
+               } else if (sc.state == SCE_B_DOCBLOCK) {
+                       if (sc.Match("\'/")) {
+                               sc.Forward();
+                               sc.ForwardSetState(SCE_B_DEFAULT);
+                       } else if (sc.ch == '\\' || sc.ch == '@') {
+                               if (IsLetter(sc.chNext) && sc.chPrev != '\\') {
+                                       styleBeforeKeyword = sc.state;
+                                       sc.SetState(SCE_B_DOCKEYWORD);
+                               };
+                       }
                }
 
                if (sc.atLineStart)
                        isfirst = true;
 
                if (sc.state == SCE_B_DEFAULT || sc.state == SCE_B_ERROR) {
-                       if (isfirst && sc.Match('.')) {
-                               sc.SetState(SCE_B_LABEL);
+                       if (isfirst && sc.Match('.') && comment_char != '\'') {
+                                       sc.SetState(SCE_B_LABEL);
                        } else if (isfirst && sc.Match('#')) {
                                wasfirst = isfirst;
                                sc.SetState(SCE_B_IDENTIFIER);
@@ -383,15 +429,25 @@ void SCI_METHOD LexerBasic::Lex(unsigned int startPos, int length, int initStyle
                                // up in freebasic with SCE_B_PREPROCESSOR.
                                if (comment_char == '\'' && sc.Match(comment_char, '$'))
                                        sc.SetState(SCE_B_PREPROCESSOR);
-                               else
+                               else if (sc.Match("\'*") || sc.Match("\'!")) {
+                                       sc.SetState(SCE_B_DOCLINE);
+                               } else {
                                        sc.SetState(SCE_B_COMMENT);
+                               }
+                       } else if (sc.Match("/\'")) {
+                               if (sc.Match("/\'*") || sc.Match("/\'!")) {     // Support of gtk-doc/Doxygen 
doc. style
+                                       sc.SetState(SCE_B_DOCBLOCK);
+                               } else {
+                                       sc.SetState(SCE_B_COMMENTBLOCK);
+                               }
+                               sc.Forward();   // Eat the ' so it isn't used for the end of the comment
                        } else if (sc.Match('"')) {
                                sc.SetState(SCE_B_STRING);
                        } else if (IsDigit(sc.ch)) {
                                sc.SetState(SCE_B_NUMBER);
-                       } else if (sc.Match('$')) {
+                       } else if (sc.Match('$') || sc.Match("&h") || sc.Match("&H") || sc.Match("&o") || 
sc.Match("&O")) {
                                sc.SetState(SCE_B_HEXNUMBER);
-                       } else if (sc.Match('%')) {
+                       } else if (sc.Match('%') || sc.Match("&b") || sc.Match("&B")) {
                                sc.SetState(SCE_B_BINNUMBER);
                        } else if (sc.Match('#')) {
                                sc.SetState(SCE_B_CONSTANT);
@@ -415,17 +471,17 @@ void SCI_METHOD LexerBasic::Lex(unsigned int startPos, int length, int initStyle
 }
 
 
-void SCI_METHOD LexerBasic::Fold(unsigned int startPos, int length, int /* initStyle */, IDocument *pAccess) 
{
+void SCI_METHOD LexerBasic::Fold(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, IDocument 
*pAccess) {
 
        if (!options.fold)
                return;
 
        LexAccessor styler(pAccess);
 
-       int line = styler.GetLine(startPos);
+       Sci_Position line = styler.GetLine(startPos);
        int level = styler.LevelAt(line);
        int go = 0, done = 0;
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
        char word[256];
        int wordlen = 0;
        const bool userDefinedFoldMarkers = !options.foldExplicitStart.empty() && 
!options.foldExplicitEnd.empty();
@@ -433,7 +489,7 @@ void SCI_METHOD LexerBasic::Fold(unsigned int startPos, int length, int /* initS
 
        // Scan for tokens at the start of the line (they may include
        // whitespace, for tokens like "End Function"
-       for (int i = startPos; i < endPos; i++) {
+       for (Sci_Position i = startPos; i < endPos; i++) {
                int c = cNext;
                cNext = styler.SafeGetCharAt(i + 1);
                bool atEOL = (c == '\r' && cNext != '\n') || (c == '\n');
diff --git a/plugins/scintilla/scintilla/lexers/LexBatch.cxx b/plugins/scintilla/scintilla/lexers/LexBatch.cxx
new file mode 100644
index 0000000..377b2cb
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexBatch.cxx
@@ -0,0 +1,500 @@
+// Scintilla source code edit control
+/** @file LexBatch.cxx
+ ** Lexer for batch files.
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static bool Is0To9(char ch) {
+       return (ch >= '0') && (ch <= '9');
+}
+
+static bool IsAlphabetic(int ch) {
+       return IsASCII(ch) && isalpha(ch);
+}
+
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
+       return (styler[i] == '\n') ||
+              ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
+}
+
+// Tests for BATCH Operators
+static bool IsBOperator(char ch) {
+       return (ch == '=') || (ch == '+') || (ch == '>') || (ch == '<') ||
+               (ch == '|') || (ch == '?') || (ch == '*');
+}
+
+// Tests for BATCH Separators
+static bool IsBSeparator(char ch) {
+       return (ch == '\\') || (ch == '.') || (ch == ';') ||
+               (ch == '\"') || (ch == '\'') || (ch == '/');
+}
+
+static void ColouriseBatchLine(
+    char *lineBuffer,
+    Sci_PositionU lengthLine,
+    Sci_PositionU startLine,
+    Sci_PositionU endPos,
+    WordList *keywordlists[],
+    Accessor &styler) {
+
+       Sci_PositionU offset = 0;       // Line Buffer Offset
+       Sci_PositionU cmdLoc;           // External Command / Program Location
+       char wordBuffer[81];            // Word Buffer - large to catch long paths
+       Sci_PositionU wbl;              // Word Buffer Length
+       Sci_PositionU wbo;              // Word Buffer Offset - also Special Keyword Buffer Length
+       WordList &keywords = *keywordlists[0];      // Internal Commands
+       WordList &keywords2 = *keywordlists[1];     // External Commands (optional)
+
+       // CHOICE, ECHO, GOTO, PROMPT and SET have Default Text that may contain Regular Keywords
+       //   Toggling Regular Keyword Checking off improves readability
+       // Other Regular Keywords and External Commands / Programs might also benefit from toggling
+       //   Need a more robust algorithm to properly toggle Regular Keyword Checking
+       bool continueProcessing = true; // Used to toggle Regular Keyword Checking
+       // Special Keywords are those that allow certain characters without whitespace after the command
+       // Examples are: cd. cd\ md. rd. dir| dir> echo: echo. path=
+       // Special Keyword Buffer used to determine if the first n characters is a Keyword
+       char sKeywordBuffer[10];        // Special Keyword Buffer
+       bool sKeywordFound;             // Exit Special Keyword for-loop if found
+
+       // Skip initial spaces
+       while ((offset < lengthLine) && (isspacechar(lineBuffer[offset]))) {
+               offset++;
+       }
+       // Colorize Default Text
+       styler.ColourTo(startLine + offset - 1, SCE_BAT_DEFAULT);
+       // Set External Command / Program Location
+       cmdLoc = offset;
+
+       // Check for Fake Label (Comment) or Real Label - return if found
+       if (lineBuffer[offset] == ':') {
+               if (lineBuffer[offset + 1] == ':') {
+                       // Colorize Fake Label (Comment) - :: is similar to REM, see 
http://content.techweb.com/winmag/columns/explorer/2000/21.htm
+                       styler.ColourTo(endPos, SCE_BAT_COMMENT);
+               } else {
+                       // Colorize Real Label
+                       styler.ColourTo(endPos, SCE_BAT_LABEL);
+               }
+               return;
+       // Check for Drive Change (Drive Change is internal command) - return if found
+       } else if ((IsAlphabetic(lineBuffer[offset])) &&
+               (lineBuffer[offset + 1] == ':') &&
+               ((isspacechar(lineBuffer[offset + 2])) ||
+               (((lineBuffer[offset + 2] == '\\')) &&
+               (isspacechar(lineBuffer[offset + 3]))))) {
+               // Colorize Regular Keyword
+               styler.ColourTo(endPos, SCE_BAT_WORD);
+               return;
+       }
+
+       // Check for Hide Command (@ECHO OFF/ON)
+       if (lineBuffer[offset] == '@') {
+               styler.ColourTo(startLine + offset, SCE_BAT_HIDE);
+               offset++;
+       }
+       // Skip next spaces
+       while ((offset < lengthLine) && (isspacechar(lineBuffer[offset]))) {
+               offset++;
+       }
+
+       // Read remainder of line word-at-a-time or remainder-of-word-at-a-time
+       while (offset < lengthLine) {
+               if (offset > startLine) {
+                       // Colorize Default Text
+                       styler.ColourTo(startLine + offset - 1, SCE_BAT_DEFAULT);
+               }
+               // Copy word from Line Buffer into Word Buffer
+               wbl = 0;
+               for (; offset < lengthLine && wbl < 80 &&
+                       !isspacechar(lineBuffer[offset]); wbl++, offset++) {
+                       wordBuffer[wbl] = static_cast<char>(tolower(lineBuffer[offset]));
+               }
+               wordBuffer[wbl] = '\0';
+               wbo = 0;
+
+               // Check for Comment - return if found
+               if (CompareCaseInsensitive(wordBuffer, "rem") == 0) {
+                       styler.ColourTo(endPos, SCE_BAT_COMMENT);
+                       return;
+               }
+               // Check for Separator
+               if (IsBSeparator(wordBuffer[0])) {
+                       // Check for External Command / Program
+                       if ((cmdLoc == offset - wbl) &&
+                               ((wordBuffer[0] == ':') ||
+                               (wordBuffer[0] == '\\') ||
+                               (wordBuffer[0] == '.'))) {
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 1);
+                               // Colorize External Command / Program
+                               if (!keywords2) {
+                                       styler.ColourTo(startLine + offset - 1, SCE_BAT_COMMAND);
+                               } else if (keywords2.InList(wordBuffer)) {
+                                       styler.ColourTo(startLine + offset - 1, SCE_BAT_COMMAND);
+                               } else {
+                                       styler.ColourTo(startLine + offset - 1, SCE_BAT_DEFAULT);
+                               }
+                               // Reset External Command / Program Location
+                               cmdLoc = offset;
+                       } else {
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 1);
+                               // Colorize Default Text
+                               styler.ColourTo(startLine + offset - 1, SCE_BAT_DEFAULT);
+                       }
+               // Check for Regular Keyword in list
+               } else if ((keywords.InList(wordBuffer)) &&
+                       (continueProcessing)) {
+                       // ECHO, GOTO, PROMPT and SET require no further Regular Keyword Checking
+                       if ((CompareCaseInsensitive(wordBuffer, "echo") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "goto") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "prompt") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "set") == 0)) {
+                               continueProcessing = false;
+                       }
+                       // Identify External Command / Program Location for ERRORLEVEL, and EXIST
+                       if ((CompareCaseInsensitive(wordBuffer, "errorlevel") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "exist") == 0)) {
+                               // Reset External Command / Program Location
+                               cmdLoc = offset;
+                               // Skip next spaces
+                               while ((cmdLoc < lengthLine) &&
+                                       (isspacechar(lineBuffer[cmdLoc]))) {
+                                       cmdLoc++;
+                               }
+                               // Skip comparison
+                               while ((cmdLoc < lengthLine) &&
+                                       (!isspacechar(lineBuffer[cmdLoc]))) {
+                                       cmdLoc++;
+                               }
+                               // Skip next spaces
+                               while ((cmdLoc < lengthLine) &&
+                                       (isspacechar(lineBuffer[cmdLoc]))) {
+                                       cmdLoc++;
+                               }
+                       // Identify External Command / Program Location for CALL, DO, LOADHIGH and LH
+                       } else if ((CompareCaseInsensitive(wordBuffer, "call") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "do") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "loadhigh") == 0) ||
+                               (CompareCaseInsensitive(wordBuffer, "lh") == 0)) {
+                               // Reset External Command / Program Location
+                               cmdLoc = offset;
+                               // Skip next spaces
+                               while ((cmdLoc < lengthLine) &&
+                                       (isspacechar(lineBuffer[cmdLoc]))) {
+                                       cmdLoc++;
+                               }
+                       }
+                       // Colorize Regular keyword
+                       styler.ColourTo(startLine + offset - 1, SCE_BAT_WORD);
+                       // No need to Reset Offset
+               // Check for Special Keyword in list, External Command / Program, or Default Text
+               } else if ((wordBuffer[0] != '%') &&
+                                  (wordBuffer[0] != '!') &&
+                       (!IsBOperator(wordBuffer[0])) &&
+                       (continueProcessing)) {
+                       // Check for Special Keyword
+                       //     Affected Commands are in Length range 2-6
+                       //     Good that ERRORLEVEL, EXIST, CALL, DO, LOADHIGH, and LH are unaffected
+                       sKeywordFound = false;
+                       for (Sci_PositionU keywordLength = 2; keywordLength < wbl && keywordLength < 7 && 
!sKeywordFound; keywordLength++) {
+                               wbo = 0;
+                               // Copy Keyword Length from Word Buffer into Special Keyword Buffer
+                               for (; wbo < keywordLength; wbo++) {
+                                       sKeywordBuffer[wbo] = static_cast<char>(wordBuffer[wbo]);
+                               }
+                               sKeywordBuffer[wbo] = '\0';
+                               // Check for Special Keyword in list
+                               if ((keywords.InList(sKeywordBuffer)) &&
+                                       ((IsBOperator(wordBuffer[wbo])) ||
+                                       (IsBSeparator(wordBuffer[wbo])))) {
+                                       sKeywordFound = true;
+                                       // ECHO requires no further Regular Keyword Checking
+                                       if (CompareCaseInsensitive(sKeywordBuffer, "echo") == 0) {
+                                               continueProcessing = false;
+                                       }
+                                       // Colorize Special Keyword as Regular Keyword
+                                       styler.ColourTo(startLine + offset - 1 - (wbl - wbo), SCE_BAT_WORD);
+                                       // Reset Offset to re-process remainder of word
+                                       offset -= (wbl - wbo);
+                               }
+                       }
+                       // Check for External Command / Program or Default Text
+                       if (!sKeywordFound) {
+                               wbo = 0;
+                               // Check for External Command / Program
+                               if (cmdLoc == offset - wbl) {
+                                       // Read up to %, Operator or Separator
+                                       while ((wbo < wbl) &&
+                                               (wordBuffer[wbo] != '%') &&
+                                               (wordBuffer[wbo] != '!') &&
+                                               (!IsBOperator(wordBuffer[wbo])) &&
+                                               (!IsBSeparator(wordBuffer[wbo]))) {
+                                               wbo++;
+                                       }
+                                       // Reset External Command / Program Location
+                                       cmdLoc = offset - (wbl - wbo);
+                                       // Reset Offset to re-process remainder of word
+                                       offset -= (wbl - wbo);
+                                       // CHOICE requires no further Regular Keyword Checking
+                                       if (CompareCaseInsensitive(wordBuffer, "choice") == 0) {
+                                               continueProcessing = false;
+                                       }
+                                       // Check for START (and its switches) - What follows is External 
Command \ Program
+                                       if (CompareCaseInsensitive(wordBuffer, "start") == 0) {
+                                               // Reset External Command / Program Location
+                                               cmdLoc = offset;
+                                               // Skip next spaces
+                                               while ((cmdLoc < lengthLine) &&
+                                                       (isspacechar(lineBuffer[cmdLoc]))) {
+                                                       cmdLoc++;
+                                               }
+                                               // Reset External Command / Program Location if command 
switch detected
+                                               if (lineBuffer[cmdLoc] == '/') {
+                                                       // Skip command switch
+                                                       while ((cmdLoc < lengthLine) &&
+                                                               (!isspacechar(lineBuffer[cmdLoc]))) {
+                                                               cmdLoc++;
+                                                       }
+                                                       // Skip next spaces
+                                                       while ((cmdLoc < lengthLine) &&
+                                                               (isspacechar(lineBuffer[cmdLoc]))) {
+                                                               cmdLoc++;
+                                                       }
+                                               }
+                                       }
+                                       // Colorize External Command / Program
+                                       if (!keywords2) {
+                                               styler.ColourTo(startLine + offset - 1, SCE_BAT_COMMAND);
+                                       } else if (keywords2.InList(wordBuffer)) {
+                                               styler.ColourTo(startLine + offset - 1, SCE_BAT_COMMAND);
+                                       } else {
+                                               styler.ColourTo(startLine + offset - 1, SCE_BAT_DEFAULT);
+                                       }
+                                       // No need to Reset Offset
+                               // Check for Default Text
+                               } else {
+                                       // Read up to %, Operator or Separator
+                                       while ((wbo < wbl) &&
+                                               (wordBuffer[wbo] != '%') &&
+                                               (wordBuffer[wbo] != '!') &&
+                                               (!IsBOperator(wordBuffer[wbo])) &&
+                                               (!IsBSeparator(wordBuffer[wbo]))) {
+                                               wbo++;
+                                       }
+                                       // Colorize Default Text
+                                       styler.ColourTo(startLine + offset - 1 - (wbl - wbo), 
SCE_BAT_DEFAULT);
+                                       // Reset Offset to re-process remainder of word
+                                       offset -= (wbl - wbo);
+                               }
+                       }
+               // Check for Argument  (%n), Environment Variable (%x...%) or Local Variable (%%a)
+               } else if (wordBuffer[0] == '%') {
+                       // Colorize Default Text
+                       styler.ColourTo(startLine + offset - 1 - wbl, SCE_BAT_DEFAULT);
+                       wbo++;
+                       // Search to end of word for second % (can be a long path)
+                       while ((wbo < wbl) &&
+                               (wordBuffer[wbo] != '%') &&
+                               (!IsBOperator(wordBuffer[wbo])) &&
+                               (!IsBSeparator(wordBuffer[wbo]))) {
+                               wbo++;
+                       }
+                       // Check for Argument (%n) or (%*)
+                       if (((Is0To9(wordBuffer[1])) || (wordBuffer[1] == '*')) &&
+                               (wordBuffer[wbo] != '%')) {
+                               // Check for External Command / Program
+                               if (cmdLoc == offset - wbl) {
+                                       cmdLoc = offset - (wbl - 2);
+                               }
+                               // Colorize Argument
+                               styler.ColourTo(startLine + offset - 1 - (wbl - 2), SCE_BAT_IDENTIFIER);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 2);
+                       // Check for Expanded Argument (%~...) / Variable (%%~...)
+                       } else if (((wbl > 1) && (wordBuffer[1] == '~')) ||
+                               ((wbl > 2) && (wordBuffer[1] == '%') && (wordBuffer[2] == '~'))) {
+                               // Check for External Command / Program
+                               if (cmdLoc == offset - wbl) {
+                                       cmdLoc = offset - (wbl - wbo);
+                               }
+                               // Colorize Expanded Argument / Variable
+                               styler.ColourTo(startLine + offset - 1 - (wbl - wbo), SCE_BAT_IDENTIFIER);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - wbo);
+                       // Check for Environment Variable (%x...%)
+                       } else if ((wordBuffer[1] != '%') &&
+                               (wordBuffer[wbo] == '%')) {
+                               wbo++;
+                               // Check for External Command / Program
+                               if (cmdLoc == offset - wbl) {
+                                       cmdLoc = offset - (wbl - wbo);
+                               }
+                               // Colorize Environment Variable
+                               styler.ColourTo(startLine + offset - 1 - (wbl - wbo), SCE_BAT_IDENTIFIER);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - wbo);
+                       // Check for Local Variable (%%a)
+                       } else if (
+                               (wbl > 2) &&
+                               (wordBuffer[1] == '%') &&
+                               (wordBuffer[2] != '%') &&
+                               (!IsBOperator(wordBuffer[2])) &&
+                               (!IsBSeparator(wordBuffer[2]))) {
+                               // Check for External Command / Program
+                               if (cmdLoc == offset - wbl) {
+                                       cmdLoc = offset - (wbl - 3);
+                               }
+                               // Colorize Local Variable
+                               styler.ColourTo(startLine + offset - 1 - (wbl - 3), SCE_BAT_IDENTIFIER);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 3);
+                       }
+               // Check for Environment Variable (!x...!)
+               } else if (wordBuffer[0] == '!') {
+                       // Colorize Default Text
+                       styler.ColourTo(startLine + offset - 1 - wbl, SCE_BAT_DEFAULT);
+                       wbo++;
+                       // Search to end of word for second ! (can be a long path)
+                       while ((wbo < wbl) &&
+                               (wordBuffer[wbo] != '!') &&
+                               (!IsBOperator(wordBuffer[wbo])) &&
+                               (!IsBSeparator(wordBuffer[wbo]))) {
+                               wbo++;
+                       }
+                       if (wordBuffer[wbo] == '!') {
+                               wbo++;
+                               // Check for External Command / Program
+                               if (cmdLoc == offset - wbl) {
+                                       cmdLoc = offset - (wbl - wbo);
+                               }
+                               // Colorize Environment Variable
+                               styler.ColourTo(startLine + offset - 1 - (wbl - wbo), SCE_BAT_IDENTIFIER);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - wbo);
+                       }
+               // Check for Operator
+               } else if (IsBOperator(wordBuffer[0])) {
+                       // Colorize Default Text
+                       styler.ColourTo(startLine + offset - 1 - wbl, SCE_BAT_DEFAULT);
+                       // Check for Comparison Operator
+                       if ((wordBuffer[0] == '=') && (wordBuffer[1] == '=')) {
+                               // Identify External Command / Program Location for IF
+                               cmdLoc = offset;
+                               // Skip next spaces
+                               while ((cmdLoc < lengthLine) &&
+                                       (isspacechar(lineBuffer[cmdLoc]))) {
+                                       cmdLoc++;
+                               }
+                               // Colorize Comparison Operator
+                               styler.ColourTo(startLine + offset - 1 - (wbl - 2), SCE_BAT_OPERATOR);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 2);
+                       // Check for Pipe Operator
+                       } else if (wordBuffer[0] == '|') {
+                               // Reset External Command / Program Location
+                               cmdLoc = offset - wbl + 1;
+                               // Skip next spaces
+                               while ((cmdLoc < lengthLine) &&
+                                       (isspacechar(lineBuffer[cmdLoc]))) {
+                                       cmdLoc++;
+                               }
+                               // Colorize Pipe Operator
+                               styler.ColourTo(startLine + offset - 1 - (wbl - 1), SCE_BAT_OPERATOR);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 1);
+                       // Check for Other Operator
+                       } else {
+                               // Check for > Operator
+                               if (wordBuffer[0] == '>') {
+                                       // Turn Keyword and External Command / Program checking back on
+                                       continueProcessing = true;
+                               }
+                               // Colorize Other Operator
+                               styler.ColourTo(startLine + offset - 1 - (wbl - 1), SCE_BAT_OPERATOR);
+                               // Reset Offset to re-process remainder of word
+                               offset -= (wbl - 1);
+                       }
+               // Check for Default Text
+               } else {
+                       // Read up to %, Operator or Separator
+                       while ((wbo < wbl) &&
+                               (wordBuffer[wbo] != '%') &&
+                               (wordBuffer[wbo] != '!') &&
+                               (!IsBOperator(wordBuffer[wbo])) &&
+                               (!IsBSeparator(wordBuffer[wbo]))) {
+                               wbo++;
+                       }
+                       // Colorize Default Text
+                       styler.ColourTo(startLine + offset - 1 - (wbl - wbo), SCE_BAT_DEFAULT);
+                       // Reset Offset to re-process remainder of word
+                       offset -= (wbl - wbo);
+               }
+               // Skip next spaces - nothing happens if Offset was Reset
+               while ((offset < lengthLine) && (isspacechar(lineBuffer[offset]))) {
+                       offset++;
+               }
+       }
+       // Colorize Default Text for remainder of line - currently not lexed
+       styler.ColourTo(endPos, SCE_BAT_DEFAULT);
+}
+
+static void ColouriseBatchDoc(
+    Sci_PositionU startPos,
+    Sci_Position length,
+    int /*initStyle*/,
+    WordList *keywordlists[],
+    Accessor &styler) {
+
+       char lineBuffer[1024];
+
+       styler.StartAt(startPos);
+       styler.StartSegment(startPos);
+       Sci_PositionU linePos = 0;
+       Sci_PositionU startLine = startPos;
+       for (Sci_PositionU i = startPos; i < startPos + length; i++) {
+               lineBuffer[linePos++] = styler[i];
+               if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
+                       // End of line (or of line buffer) met, colourise it
+                       lineBuffer[linePos] = '\0';
+                       ColouriseBatchLine(lineBuffer, linePos, startLine, i, keywordlists, styler);
+                       linePos = 0;
+                       startLine = i + 1;
+               }
+       }
+       if (linePos > 0) {      // Last line does not have ending characters
+               lineBuffer[linePos] = '\0';
+               ColouriseBatchLine(lineBuffer, linePos, startLine, startPos + length - 1,
+                                  keywordlists, styler);
+       }
+}
+
+static const char *const batchWordListDesc[] = {
+       "Internal Commands",
+       "External Commands",
+       0
+};
+
+LexerModule lmBatch(SCLEX_BATCH, ColouriseBatchDoc, "batch", 0, batchWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexBibTeX.cxx 
b/plugins/scintilla/scintilla/lexers/LexBibTeX.cxx
new file mode 100644
index 0000000..fef58a9
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexBibTeX.cxx
@@ -0,0 +1,310 @@
+// Copyright 2008-2010 Sergiu Dotenco. The License.txt file describes the
+// conditions under which this software may be distributed.
+
+/**
+ * @file LexBibTeX.cxx
+ * @brief General BibTeX coloring scheme.
+ * @author Sergiu Dotenco
+ * @date April 18, 2009
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <cassert>
+#include <cctype>
+
+#include <string>
+#include <algorithm>
+#include <functional>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "PropSetSimple.h"
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+namespace {
+       bool IsAlphabetic(unsigned int ch)
+       {
+               return IsASCII(ch) && std::isalpha(ch) != 0;
+       }
+       bool IsAlphaNumeric(char ch)
+       {
+           return IsASCII(ch) && std::isalnum(ch);
+       }
+
+       bool EqualCaseInsensitive(const char* a, const char* b)
+       {
+               return CompareCaseInsensitive(a, b) == 0;
+       }
+
+       bool EntryWithoutKey(const char* name)
+       {
+               return EqualCaseInsensitive(name,"string");
+       }
+
+       char GetClosingBrace(char openbrace)
+       {
+               char result = openbrace;
+
+               switch (openbrace) {
+                       case '(': result = ')'; break;
+                       case '{': result = '}'; break;
+               }
+
+               return result;
+       }
+
+       bool IsEntryStart(char prev, char ch)
+       {
+               return prev != '\\' && ch == '@';
+       }
+
+       bool IsEntryStart(const StyleContext& sc)
+       {
+               return IsEntryStart(sc.chPrev, sc.ch);
+       }
+
+       void ColorizeBibTeX(Sci_PositionU start_pos, Sci_Position length, int /*init_style*/, WordList* 
keywordlists[], Accessor& styler)
+       {
+           WordList &EntryNames = *keywordlists[0];
+               bool fold_compact = styler.GetPropertyInt("fold.compact", 1) != 0;
+
+               std::string buffer;
+               buffer.reserve(25);
+
+               // We always colorize a section from the beginning, so let's
+               // search for the @ character which isn't escaped, i.e. \@
+               while (start_pos > 0 && !IsEntryStart(styler.SafeGetCharAt(start_pos - 1),
+                       styler.SafeGetCharAt(start_pos))) {
+                       --start_pos; ++length;
+               }
+
+               styler.StartAt(start_pos);
+               styler.StartSegment(start_pos);
+
+               Sci_Position current_line = styler.GetLine(start_pos);
+               int prev_level = styler.LevelAt(current_line) & SC_FOLDLEVELNUMBERMASK;
+               int current_level = prev_level;
+               int visible_chars = 0;
+
+               bool in_comment = false ;
+               StyleContext sc(start_pos, length, SCE_BIBTEX_DEFAULT, styler);
+
+               bool going = sc.More(); // needed because of a fuzzy end of file state
+               char closing_brace = 0;
+               bool collect_entry_name = false;
+
+               for (; going; sc.Forward()) {
+                       if (!sc.More())
+                               going = false; // we need to go one behind the end of text
+
+                       if (in_comment) {
+                               if (sc.atLineEnd) {
+                                       sc.SetState(SCE_BIBTEX_DEFAULT);
+                                       in_comment = false;
+                               }
+                       }
+                       else {
+                               // Found @entry
+                               if (IsEntryStart(sc)) {
+                                       sc.SetState(SCE_BIBTEX_UNKNOWN_ENTRY);
+                                       sc.Forward();
+                                       ++current_level;
+
+                                       buffer.clear();
+                                       collect_entry_name = true;
+                               }
+                               else if ((sc.state == SCE_BIBTEX_ENTRY || sc.state == 
SCE_BIBTEX_UNKNOWN_ENTRY)
+                                       && (sc.ch == '{' || sc.ch == '(')) {
+                                       // Entry name colorization done
+                                       // Found either a { or a ( after entry's name, e.g. @entry(...) 
@entry{...}
+                                       // Closing counterpart needs to be stored.
+                                       closing_brace = GetClosingBrace(sc.ch);
+
+                                       sc.SetState(SCE_BIBTEX_DEFAULT); // Don't colorize { (
+
+                                       // @string doesn't have any key
+                                       if (EntryWithoutKey(buffer.c_str()))
+                                               sc.ForwardSetState(SCE_BIBTEX_PARAMETER);
+                                       else
+                                               sc.ForwardSetState(SCE_BIBTEX_KEY); // Key/label colorization
+                               }
+
+                               // Need to handle the case where entry's key is empty
+                               // e.g. @book{,...}
+                               if (sc.state == SCE_BIBTEX_KEY && sc.ch == ',') {
+                                       // Key/label colorization done
+                                       sc.SetState(SCE_BIBTEX_DEFAULT); // Don't colorize the ,
+                                       sc.ForwardSetState(SCE_BIBTEX_PARAMETER); // Parameter colorization
+                               }
+                               else if (sc.state == SCE_BIBTEX_PARAMETER && sc.ch == '=') {
+                                       sc.SetState(SCE_BIBTEX_DEFAULT); // Don't colorize the =
+                                       sc.ForwardSetState(SCE_BIBTEX_VALUE); // Parameter value colorization
+
+                                       Sci_Position start = sc.currentPos;
+
+                                       // We need to handle multiple situations:
+                                       // 1. name"one two {three}"
+                                       // 2. name={one {one two {two}} three}
+                                       // 3. year=2005
+
+                                       // Skip ", { until we encounter the first alphanumerical character
+                                       while (sc.More() && !(IsAlphaNumeric(sc.ch) || sc.ch == '"' || sc.ch 
== '{'))
+                                               sc.Forward();
+
+                                       if (sc.More()) {
+                                               // Store " or {
+                                               char ch = sc.ch;
+
+                                               // Not interested in alphanumerical characters
+                                               if (IsAlphaNumeric(ch))
+                                                       ch = 0;
+
+                                               int skipped = 0;
+
+                                               if (ch) {
+                                                       // Skip preceding " or { such as in name={{test}}.
+                                                       // Remember how many characters have been skipped
+                                                       // Make sure that empty values, i.e. "" are also 
handled correctly
+                                                       while (sc.More() && (sc.ch == ch && (ch != '"' || 
skipped < 1))) {
+                                                               sc.Forward();
+                                                               ++skipped;
+                                                       }
+                                               }
+
+                                               // Closing counterpart for " is the same character
+                                               if (ch == '{')
+                                                       ch = '}';
+
+                                               // We have reached the parameter value
+                                               // In case the open character was a alnum char, skip until , 
is found
+                                               // otherwise until skipped == 0
+                                               while (sc.More() && (skipped > 0 || (!ch && !(sc.ch == ',' || 
sc.ch == closing_brace)))) {
+                                                       // Make sure the character isn't escaped
+                                                       if (sc.chPrev != '\\') {
+                                                               // Parameter value contains a { which is the 
2nd case described above
+                                                               if (sc.ch == '{')
+                                                                       ++skipped; // Remember it
+                                                               else if (sc.ch == '}')
+                                                                       --skipped;
+                                                               else if (skipped == 1 && sc.ch == ch && ch == 
'"') // Don't ignore cases like {"o}
+                                                                       skipped = 0;
+                                                       }
+
+                                                       sc.Forward();
+                                               }
+                                       }
+
+                                       // Don't colorize the ,
+                                       sc.SetState(SCE_BIBTEX_DEFAULT);
+
+                                       // Skip until the , or entry's closing closing_brace is found
+                                       // since this parameter might be the last one
+                                       while (sc.More() && !(sc.ch == ',' || sc.ch == closing_brace))
+                                               sc.Forward();
+
+                                       int state = SCE_BIBTEX_PARAMETER; // The might be more parameters
+
+                                       // We've reached the closing closing_brace for the bib entry
+                                       // in case no " or {} has been used to enclose the value,
+                                       // as in 3rd case described above
+                                       if (sc.ch == closing_brace) {
+                                               --current_level;
+                                               // Make sure the text between entries is not colored
+                                               // using parameter's style
+                                               state = SCE_BIBTEX_DEFAULT;
+                                       }
+
+                                       Sci_Position end = sc.currentPos;
+                                       current_line = styler.GetLine(end);
+
+                                       // We have possibly skipped some lines, so the folding levels
+                                       // have to be adjusted separately
+                                       for (Sci_Position i = styler.GetLine(start); i <= 
styler.GetLine(end); ++i)
+                                               styler.SetLevel(i, prev_level);
+
+                                       sc.ForwardSetState(state);
+                               }
+
+                               if (sc.state == SCE_BIBTEX_PARAMETER && sc.ch == closing_brace) {
+                                       sc.SetState(SCE_BIBTEX_DEFAULT);
+                                       --current_level;
+                               }
+
+                               // Non escaped % found which represents a comment until the end of the line
+                               if (sc.chPrev != '\\' && sc.ch == '%') {
+                                       in_comment = true;
+                                       sc.SetState(SCE_BIBTEX_COMMENT);
+                               }
+                       }
+
+                       if (sc.state == SCE_BIBTEX_UNKNOWN_ENTRY || sc.state == SCE_BIBTEX_ENTRY) {
+                               if (!IsAlphabetic(sc.ch) && collect_entry_name)
+                                       collect_entry_name = false;
+
+                               if (collect_entry_name) {
+                                       buffer += static_cast<char>(tolower(sc.ch));
+                    if (EntryNames.InList(buffer.c_str()))
+                        sc.ChangeState(SCE_BIBTEX_ENTRY);
+                    else
+                        sc.ChangeState(SCE_BIBTEX_UNKNOWN_ENTRY);
+                               }
+                       }
+
+                       if (sc.atLineEnd) {
+                               int level = prev_level;
+
+                               if (visible_chars == 0 && fold_compact)
+                                       level |= SC_FOLDLEVELWHITEFLAG;
+
+                               if ((current_level > prev_level))
+                                       level |= SC_FOLDLEVELHEADERFLAG;
+                               // else if (current_level < prev_level)
+                               //      level |= SC_FOLDLEVELBOXFOOTERFLAG; // Deprecated
+
+                               if (level != styler.LevelAt(current_line)) {
+                                       styler.SetLevel(current_line, level);
+                               }
+
+                               ++current_line;
+                               prev_level = current_level;
+                               visible_chars = 0;
+                       }
+
+                       if (!isspacechar(sc.ch))
+                               ++visible_chars;
+               }
+
+               sc.Complete();
+
+               // Fill in the real level of the next line, keeping the current flags as they will be filled 
in later
+               int flagsNext = styler.LevelAt(current_line) & ~SC_FOLDLEVELNUMBERMASK;
+               styler.SetLevel(current_line, prev_level | flagsNext);
+       }
+}
+static const char * const BibTeXWordLists[] = {
+            "Entry Names",
+            0,
+};
+
+
+LexerModule lmBibTeX(SCLEX_BIBTEX, ColorizeBibTeX, "bib", 0, BibTeXWordLists);
+
+// Entry Names
+//    article, book, booklet, conference, inbook,
+//    incollection, inproceedings, manual, mastersthesis,
+//    misc, phdthesis, proceedings, techreport, unpublished,
+//    string, url
+
diff --git a/plugins/scintilla/scintilla/lexers/LexBullant.cxx 
b/plugins/scintilla/scintilla/lexers/LexBullant.cxx
index bb5c9c4..4041887 100644
--- a/plugins/scintilla/scintilla/lexers/LexBullant.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexBullant.cxx
@@ -23,10 +23,10 @@
 using namespace Scintilla;
 #endif
 
-static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
+static int classifyWordBullant(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler) 
{
        char s[100];
        s[0] = '\0';
-       for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
+       for (Sci_PositionU i = 0; i < end - start + 1 && i < 30; i++) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                s[i + 1] = '\0';
        }
@@ -58,14 +58,14 @@ static int classifyWordBullant(unsigned int start, unsigned int end, WordList &k
        return lev;
 }
 
-static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseBullantDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
        Accessor &styler) {
        WordList &keywords = *keywordlists[0];
 
        styler.StartAt(startPos);
 
        bool fold = styler.GetPropertyInt("fold") != 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
 
@@ -74,11 +74,11 @@ static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle
                state = SCE_C_DEFAULT;
        char chPrev = ' ';
        char chNext = styler[startPos];
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
        styler.StartSegment(startPos);
        int endFoundThisLine = 0;
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -116,7 +116,7 @@ static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle
                        }
                        blockChange=0;
 */             }
-               if (!(isascii(ch) && isspace(ch)))
+               if (!(IsASCII(ch) && isspace(ch)))
                        visibleChars++;
 
                if (styler.IsLeadByte(ch)) {
diff --git a/plugins/scintilla/scintilla/lexers/LexCLW.cxx b/plugins/scintilla/scintilla/lexers/LexCLW.cxx
index c1dea60..af2ca15 100644
--- a/plugins/scintilla/scintilla/lexers/LexCLW.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCLW.cxx
@@ -142,12 +142,12 @@ inline bool SetNumericConstantState(StyleContext &scDoc) {
 }
 
 // Get the next word in uppercase from the current position (keyword lookahead)
-inline bool GetNextWordUpper(Accessor &styler, unsigned int uiStartPos, int iLength, char *cWord) {
+inline bool GetNextWordUpper(Accessor &styler, Sci_PositionU uiStartPos, Sci_Position iLength, char *cWord) {
 
-       unsigned int iIndex = 0;                // Buffer Index
+       Sci_PositionU iIndex = 0;               // Buffer Index
 
        // Loop through the remaining string from the current position
-       for (int iOffset = uiStartPos; iOffset < iLength; iOffset++) {
+       for (Sci_Position iOffset = uiStartPos; iOffset < iLength; iOffset++) {
                // Get the character from the buffer using the offset
                char cCharacter = styler[iOffset];
                if (IsEOL(cCharacter)) {
@@ -174,7 +174,7 @@ inline bool GetNextWordUpper(Accessor &styler, unsigned int uiStartPos, int iLen
 }
 
 // Clarion Language Colouring Procedure
-static void ColouriseClarionDoc(unsigned int uiStartPos, int iLength, int iInitStyle, WordList 
*wlKeywords[], Accessor &accStyler, bool bCaseSensitive) {
+static void ColouriseClarionDoc(Sci_PositionU uiStartPos, Sci_Position iLength, int iInitStyle, WordList 
*wlKeywords[], Accessor &accStyler, bool bCaseSensitive) {
 
        int iParenthesesLevel = 0;              // Parenthese Level
        int iColumn1Label = false;              // Label starts in Column 1
@@ -521,22 +521,22 @@ static void ColouriseClarionDoc(unsigned int uiStartPos, int iLength, int iInitS
 }
 
 // Clarion Language Case Sensitive Colouring Procedure
-static void ColouriseClarionDocSensitive(unsigned int uiStartPos, int iLength, int iInitStyle, WordList 
*wlKeywords[], Accessor &accStyler) {
+static void ColouriseClarionDocSensitive(Sci_PositionU uiStartPos, Sci_Position iLength, int iInitStyle, 
WordList *wlKeywords[], Accessor &accStyler) {
 
        ColouriseClarionDoc(uiStartPos, iLength, iInitStyle, wlKeywords, accStyler, true);
 }
 
 // Clarion Language Case Insensitive Colouring Procedure
-static void ColouriseClarionDocInsensitive(unsigned int uiStartPos, int iLength, int iInitStyle, WordList 
*wlKeywords[], Accessor &accStyler) {
+static void ColouriseClarionDocInsensitive(Sci_PositionU uiStartPos, Sci_Position iLength, int iInitStyle, 
WordList *wlKeywords[], Accessor &accStyler) {
 
        ColouriseClarionDoc(uiStartPos, iLength, iInitStyle, wlKeywords, accStyler, false);
 }
 
 // Fill Buffer
 
-static void FillBuffer(unsigned int uiStart, unsigned int uiEnd, Accessor &accStyler, char *szBuffer, 
unsigned int uiLength) {
+static void FillBuffer(Sci_PositionU uiStart, Sci_PositionU uiEnd, Accessor &accStyler, char *szBuffer, 
Sci_PositionU uiLength) {
 
-       unsigned int uiPos = 0;
+       Sci_PositionU uiPos = 0;
 
        while ((uiPos < uiEnd - uiStart + 1) && (uiPos < uiLength-1)) {
                szBuffer[uiPos] = static_cast<char>(toupper(accStyler[uiStart + uiPos]));
@@ -599,19 +599,19 @@ static int ClassifyClarionFoldPoint(int iLevel, const char* szString) {
 }
 
 // Clarion Language Folding Procedure
-static void FoldClarionDoc(unsigned int uiStartPos, int iLength, int iInitStyle, WordList *[], Accessor 
&accStyler) {
+static void FoldClarionDoc(Sci_PositionU uiStartPos, Sci_Position iLength, int iInitStyle, WordList *[], 
Accessor &accStyler) {
 
-       unsigned int uiEndPos = uiStartPos + iLength;
-       int iLineCurrent = accStyler.GetLine(uiStartPos);
+       Sci_PositionU uiEndPos = uiStartPos + iLength;
+       Sci_Position iLineCurrent = accStyler.GetLine(uiStartPos);
        int iLevelPrev = accStyler.LevelAt(iLineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int iLevelCurrent = iLevelPrev;
        char chNext = accStyler[uiStartPos];
        int iStyle = iInitStyle;
        int iStyleNext = accStyler.StyleAt(uiStartPos);
        int iVisibleChars = 0;
-       int iLastStart = 0;
+       Sci_Position iLastStart = 0;
 
-       for (unsigned int uiPos = uiStartPos; uiPos < uiEndPos; uiPos++) {
+       for (Sci_PositionU uiPos = uiStartPos; uiPos < uiEndPos; uiPos++) {
 
                char chChar = chNext;
                chNext = accStyler.SafeGetCharAt(uiPos + 1);
diff --git a/plugins/scintilla/scintilla/lexers/LexCOBOL.cxx b/plugins/scintilla/scintilla/lexers/LexCOBOL.cxx
index b3bc011..3150e33 100644
--- a/plugins/scintilla/scintilla/lexers/LexCOBOL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCOBOL.cxx
@@ -44,13 +44,13 @@ inline bool isCOBOLoperator(char ch)
 
 inline bool isCOBOLwordchar(char ch)
     {
-    return isascii(ch) && (isalnum(ch) || ch == '-');
+    return IsASCII(ch) && (isalnum(ch) || ch == '-');
 
     }
 
 inline bool isCOBOLwordstart(char ch)
     {
-    return isascii(ch) && isalnum(ch);
+    return IsASCII(ch) && isalnum(ch);
     }
 
 static int CountBits(int nBits)
@@ -64,12 +64,12 @@ static int CountBits(int nBits)
        return count;
        }
 
-static void getRange(unsigned int start,
-        unsigned int end,
+static void getRange(Sci_PositionU start,
+        Sci_PositionU end,
         Accessor &styler,
         char *s,
-        unsigned int len) {
-    unsigned int i = 0;
+        Sci_PositionU len) {
+    Sci_PositionU i = 0;
     while ((i < end - start + 1) && (i < len-1)) {
         s[i] = static_cast<char>(tolower(styler[start + i]));
         i++;
@@ -77,12 +77,12 @@ static void getRange(unsigned int start,
     s[i] = '\0';
 }
 
-static void ColourTo(Accessor &styler, unsigned int end, unsigned int attr) {
+static void ColourTo(Accessor &styler, Sci_PositionU end, unsigned int attr) {
     styler.ColourTo(end, attr);
 }
 
 
-static int classifyWordCOBOL(unsigned int start, unsigned int end, /*WordList &keywords*/WordList 
*keywordlists[], Accessor &styler, int nContainment, bool *bAarea) {
+static int classifyWordCOBOL(Sci_PositionU start, Sci_PositionU end, /*WordList &keywords*/WordList 
*keywordlists[], Accessor &styler, int nContainment, bool *bAarea) {
     int ret = 0;
 
     WordList& a_keywords = *keywordlists[0];
@@ -90,6 +90,8 @@ static int classifyWordCOBOL(unsigned int start, unsigned int end, /*WordList &k
     WordList& c_keywords = *keywordlists[2];
 
     char s[100];
+    s[0] = '\0';
+    s[1] = '\0';
     getRange(start, end, styler, s, sizeof(s));
 
     char chAttr = SCE_C_IDENTIFIER;
@@ -140,7 +142,7 @@ static int classifyWordCOBOL(unsigned int start, unsigned int end, /*WordList &k
     return ret;
 }
 
-static void ColouriseCOBOLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseCOBOLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
     Accessor &styler) {
 
     styler.StartAt(startPos);
@@ -150,11 +152,11 @@ static void ColouriseCOBOLDoc(unsigned int startPos, int length, int initStyle,
         state = SCE_C_DEFAULT;
     char chPrev = ' ';
     char chNext = styler[startPos];
-    unsigned int lengthDoc = startPos + length;
+    Sci_PositionU lengthDoc = startPos + length;
 
     int nContainment;
 
-    int currentLine = styler.GetLine(startPos);
+    Sci_Position currentLine = styler.GetLine(startPos);
     if (currentLine > 0) {
         styler.SetLineState(currentLine, styler.GetLineState(currentLine-1));
         nContainment = styler.GetLineState(currentLine);
@@ -168,7 +170,7 @@ static void ColouriseCOBOLDoc(unsigned int startPos, int length, int initStyle,
     bool bNewLine = true;
     bool bAarea = !isspacechar(chNext);
        int column = 0;
-    for (unsigned int i = startPos; i < lengthDoc; i++) {
+    for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
         char ch = chNext;
 
         chNext = styler.SafeGetCharAt(i + 1);
@@ -205,7 +207,7 @@ static void ColouriseCOBOLDoc(unsigned int startPos, int length, int initStyle,
         }
 
         if (state == SCE_C_DEFAULT) {
-            if (isCOBOLwordstart(ch) || (ch == '$' && isascii(chNext) && isalpha(chNext))) {
+            if (isCOBOLwordstart(ch) || (ch == '$' && IsASCII(chNext) && isalpha(chNext))) {
                 ColourTo(styler, i-1, state);
                 state = SCE_C_IDENTIFIER;
             } else if (column == 6 && ch == '*') {
@@ -275,7 +277,7 @@ static void ColouriseCOBOLDoc(unsigned int startPos, int length, int initStyle,
                 if (ch == '\r' || ch == '\n') {
                     if (((i > styler.GetStartSegment() + 2) || (
                         (initStyle == SCE_C_COMMENTDOC) &&
-                        (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
+                        (styler.GetStartSegment() == static_cast<Sci_PositionU>(startPos))))) {
                             ColourTo(styler, i, state);
                             state = SCE_C_DEFAULT;
                     }
@@ -307,12 +309,12 @@ static void ColouriseCOBOLDoc(unsigned int startPos, int length, int initStyle,
     ColourTo(styler, lengthDoc - 1, state);
 }
 
-static void FoldCOBOLDoc(unsigned int startPos, int length, int, WordList *[],
+static void FoldCOBOLDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
                             Accessor &styler) {
     bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-    unsigned int endPos = startPos + length;
+    Sci_PositionU endPos = startPos + length;
     int visibleChars = 0;
-    int lineCurrent = styler.GetLine(startPos);
+    Sci_Position lineCurrent = styler.GetLine(startPos);
     int levelPrev = lineCurrent > 0 ? styler.LevelAt(lineCurrent - 1) & SC_FOLDLEVELNUMBERMASK : 0xFFF;
     char chNext = styler[startPos];
 
@@ -320,7 +322,7 @@ static void FoldCOBOLDoc(unsigned int startPos, int length, int, WordList *[],
     bool bAarea = !isspacechar(chNext);
        int column = 0;
        bool bComment = false;
-    for (unsigned int i = startPos; i < endPos; i++) {
+    for (Sci_PositionU i = startPos; i < endPos; i++) {
         char ch = chNext;
         chNext = styler.SafeGetCharAt(i + 1);
                ++column;
diff --git a/plugins/scintilla/scintilla/lexers/LexCPP.cxx b/plugins/scintilla/scintilla/lexers/LexCPP.cxx
index b3c9346..238856b 100644
--- a/plugins/scintilla/scintilla/lexers/LexCPP.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCPP.cxx
@@ -8,10 +8,10 @@
 
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h>
 #include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <ctype.h>
 
 #include <string>
 #include <vector>
@@ -36,7 +36,10 @@
 using namespace Scintilla;
 #endif
 
-static bool IsSpaceEquiv(int state) {
+namespace {
+       // Use an unnamed namespace to protect the functions and classes from name conflicts
+
+bool IsSpaceEquiv(int state) {
        return (state <= SCE_C_COMMENTDOC) ||
                // including SCE_C_DEFAULT, SCE_C_COMMENT, SCE_C_COMMENTLINE
                (state == SCE_C_COMMENTLINEDOC) || (state == SCE_C_COMMENTDOCKEYWORD) ||
@@ -50,10 +53,10 @@ static bool IsSpaceEquiv(int state) {
 // a = b+++/ptn/...
 // Putting a space between the '++' post-inc operator and the '+' binary op
 // fixes this, and is highly recommended for readability anyway.
-static bool FollowsPostfixOperator(StyleContext &sc, LexAccessor &styler) {
-       int pos = (int) sc.currentPos;
+bool FollowsPostfixOperator(StyleContext &sc, LexAccessor &styler) {
+       Sci_Position pos = static_cast<Sci_Position>(sc.currentPos);
        while (--pos > 0) {
-               char ch = styler[pos];
+               const char ch = styler[pos];
                if (ch == '+' || ch == '-') {
                        return styler[pos - 1] == ch;
                }
@@ -61,13 +64,13 @@ static bool FollowsPostfixOperator(StyleContext &sc, LexAccessor &styler) {
        return false;
 }
 
-static bool followsReturnKeyword(StyleContext &sc, LexAccessor &styler) {
+bool followsReturnKeyword(StyleContext &sc, LexAccessor &styler) {
        // Don't look at styles, so no need to flush.
-       int pos = (int) sc.currentPos;
-       int currentLine = styler.GetLine(pos);
-       int lineStartPos = styler.LineStart(currentLine);
+       Sci_Position pos = static_cast<Sci_Position>(sc.currentPos);
+       Sci_Position currentLine = styler.GetLine(pos);
+       const Sci_Position lineStartPos = styler.LineStart(currentLine);
        while (--pos > lineStartPos) {
-               char ch = styler.SafeGetCharAt(pos);
+               const char ch = styler.SafeGetCharAt(pos);
                if (ch != ' ' && ch != '\t') {
                        break;
                }
@@ -83,13 +86,126 @@ static bool followsReturnKeyword(StyleContext &sc, LexAccessor &styler) {
        return !*s;
 }
 
-static std::string GetRestOfLine(LexAccessor &styler, int start, bool allowSpace) {
+bool IsSpaceOrTab(int ch) {
+       return ch == ' ' || ch == '\t';
+}
+
+bool OnlySpaceOrTab(const std::string &s) {
+       for (const char ch : s) {
+               if (!IsSpaceOrTab(ch))
+                       return false;
+       }
+       return true;
+}
+
+std::vector<std::string> StringSplit(const std::string &text, int separator) {
+       std::vector<std::string> vs(text.empty() ? 0 : 1);
+       for (const char ch : text) {
+               if (ch == separator) {
+                       vs.push_back(std::string());
+               } else {
+                       vs.back() += ch;
+               }
+       }
+       return vs;
+}
+
+struct BracketPair {
+       std::vector<std::string>::iterator itBracket;
+       std::vector<std::string>::iterator itEndBracket;
+};
+
+BracketPair FindBracketPair(std::vector<std::string> &tokens) {
+       BracketPair bp;
+       std::vector<std::string>::iterator itTok = std::find(tokens.begin(), tokens.end(), "(");
+       bp.itBracket = tokens.end();
+       bp.itEndBracket = tokens.end();
+       if (itTok != tokens.end()) {
+               bp.itBracket = itTok;
+               size_t nest = 0;
+               while (itTok != tokens.end()) {
+                       if (*itTok == "(") {
+                               nest++;
+                       } else if (*itTok == ")") {
+                               nest--;
+                               if (nest == 0) {
+                                       bp.itEndBracket = itTok;
+                                       return bp;
+                               }
+                       }
+                       ++itTok;
+               }
+       }
+       bp.itBracket = tokens.end();
+       return bp;
+}
+
+void highlightTaskMarker(StyleContext &sc, LexAccessor &styler,
+               int activity, const WordList &markerList, bool caseSensitive){
+       if ((isoperator(sc.chPrev) || IsASpace(sc.chPrev)) && markerList.Length()) {
+               const int lengthMarker = 50;
+               char marker[lengthMarker+1];
+               Sci_Position currPos = static_cast<Sci_Position>(sc.currentPos);
+               int i = 0;
+               while (i < lengthMarker) {
+                       const char ch = styler.SafeGetCharAt(currPos + i);
+                       if (IsASpace(ch) || isoperator(ch)) {
+                               break;
+                       }
+                       if (caseSensitive)
+                               marker[i] = ch;
+                       else
+                               marker[i] = static_cast<char>(tolower(ch));
+                       i++;
+               }
+               marker[i] = '\0';
+               if (markerList.InList(marker)) {
+                       sc.SetState(SCE_C_TASKMARKER|activity);
+               }
+       }
+}
+
+struct EscapeSequence {
+       int digitsLeft;
+       CharacterSet setHexDigits;
+       CharacterSet setOctDigits;
+       CharacterSet setNoneNumeric;
+       CharacterSet *escapeSetValid;
+       EscapeSequence() {
+               digitsLeft = 0;
+               escapeSetValid = 0;
+               setHexDigits = CharacterSet(CharacterSet::setDigits, "ABCDEFabcdef");
+               setOctDigits = CharacterSet(CharacterSet::setNone, "01234567");
+       }
+       void resetEscapeState(int nextChar) {
+               digitsLeft = 0;
+               escapeSetValid = &setNoneNumeric;
+               if (nextChar == 'U') {
+                       digitsLeft = 9;
+                       escapeSetValid = &setHexDigits;
+               } else if (nextChar == 'u') {
+                       digitsLeft = 5;
+                       escapeSetValid = &setHexDigits;
+               } else if (nextChar == 'x') {
+                       digitsLeft = 5;
+                       escapeSetValid = &setHexDigits;
+               } else if (setOctDigits.Contains(nextChar)) {
+                       digitsLeft = 3;
+                       escapeSetValid = &setOctDigits;
+               }
+       }
+       bool atEscapeEnd(int currChar) const {
+               return (digitsLeft <= 0) || !escapeSetValid->Contains(currChar);
+       }
+};
+
+std::string GetRestOfLine(LexAccessor &styler, Sci_Position start, bool allowSpace) {
        std::string restOfLine;
-       int i =0;
+       Sci_Position i =0;
        char ch = styler.SafeGetCharAt(start, '\n');
-       int endLine = styler.LineEnd(styler.GetLine(start));
+       const Sci_Position endLine = styler.LineEnd(styler.GetLine(start));
        while (((start+i) < endLine) && (ch != '\r')) {
-               char chNext = styler.SafeGetCharAt(start + i + 1, '\n');
+               const char chNext = styler.SafeGetCharAt(start + i + 1, '\n');
                if (ch == '/' && (chNext == '/' || chNext == '*'))
                        break;
                if (allowSpace || (ch != ' '))
@@ -100,40 +216,21 @@ static std::string GetRestOfLine(LexAccessor &styler, int start, bool allowSpace
        return restOfLine;
 }
 
-static bool IsStreamCommentStyle(int style) {
+bool IsStreamCommentStyle(int style) {
        return style == SCE_C_COMMENT ||
                style == SCE_C_COMMENTDOC ||
                style == SCE_C_COMMENTDOCKEYWORD ||
                style == SCE_C_COMMENTDOCKEYWORDERROR;
 }
 
-static std::vector<std::string> Tokenize(const std::string &s) {
-       // Break into space separated tokens
-       std::string word;
-       std::vector<std::string> tokens;
-       for (const char *cp = s.c_str(); *cp; cp++) {
-               if ((*cp == ' ') || (*cp == '\t')) {
-                       if (!word.empty()) {
-                               tokens.push_back(word);
-                               word = "";
-                       }
-               } else {
-                       word += *cp;
-               }
-       }
-       if (!word.empty()) {
-               tokens.push_back(word);
-       }
-       return tokens;
-}
-
 struct PPDefinition {
-       int line;
+       Sci_Position line;
        std::string key;
        std::string value;
        bool isUndef;
-       PPDefinition(int line_, const std::string &key_, const std::string &value_, bool isUndef_ = false) :
-               line(line_), key(key_), value(value_), isUndef(isUndef_) {
+       std::string arguments;
+       PPDefinition(Sci_Position line_, const std::string &key_, const std::string &value_, bool isUndef_ = 
false, const std::string &arguments_="") :
+               line(line_), key(key_), value(value_), isUndef(isUndef_), arguments(arguments_) {
        }
 };
 
@@ -188,14 +285,14 @@ public:
 class PPStates {
        std::vector<LinePPState> vlls;
 public:
-       LinePPState ForLine(int line) const {
+       LinePPState ForLine(Sci_Position line) const {
                if ((line > 0) && (vlls.size() > static_cast<size_t>(line))) {
                        return vlls[line];
                } else {
                        return LinePPState();
                }
        }
-       void Add(int line, LinePPState lls) {
+       void Add(Sci_Position line, LinePPState lls) {
                vlls.resize(line+1);
                vlls[line] = lls;
        }
@@ -209,8 +306,11 @@ struct OptionsCPP {
        bool identifiersAllowDollars;
        bool trackPreprocessor;
        bool updatePreprocessor;
+       bool verbatimStringsAllowEscapes;
        bool triplequotedStrings;
        bool hashquotedStrings;
+       bool backQuotedStrings;
+       bool escapeSequence;
        bool fold;
        bool foldSyntaxBased;
        bool foldComment;
@@ -220,6 +320,7 @@ struct OptionsCPP {
        std::string foldExplicitEnd;
        bool foldExplicitAnywhere;
        bool foldPreprocessor;
+       bool foldPreprocessorAtElse;
        bool foldCompact;
        bool foldAtElse;
        OptionsCPP() {
@@ -227,8 +328,11 @@ struct OptionsCPP {
                identifiersAllowDollars = true;
                trackPreprocessor = true;
                updatePreprocessor = true;
+               verbatimStringsAllowEscapes = false;
                triplequotedStrings = false;
                hashquotedStrings = false;
+               backQuotedStrings = false;
+               escapeSequence = false;
                fold = false;
                foldSyntaxBased = true;
                foldComment = false;
@@ -238,17 +342,19 @@ struct OptionsCPP {
                foldExplicitEnd = "";
                foldExplicitAnywhere = false;
                foldPreprocessor = false;
+               foldPreprocessorAtElse = false;
                foldCompact = false;
                foldAtElse = false;
        }
 };
 
-static const char *const cppWordLists[] = {
+const char *const cppWordLists[] = {
             "Primary keywords and identifiers",
             "Secondary keywords and identifiers",
             "Documentation comment keywords",
             "Global classes and typedefs",
             "Preprocessor definitions",
+            "Task marker and error marker keywords",
             0,
 };
 
@@ -268,12 +374,21 @@ struct OptionSetCPP : public OptionSet<OptionsCPP> {
                DefineProperty("lexer.cpp.update.preprocessor", &OptionsCPP::updatePreprocessor,
                        "Set to 1 to update preprocessor definitions when #define found.");
 
+               DefineProperty("lexer.cpp.verbatim.strings.allow.escapes", 
&OptionsCPP::verbatimStringsAllowEscapes,
+                       "Set to 1 to allow verbatim strings to contain escape sequences.");
+
                DefineProperty("lexer.cpp.triplequoted.strings", &OptionsCPP::triplequotedStrings,
                        "Set to 1 to enable highlighting of triple-quoted strings.");
 
                DefineProperty("lexer.cpp.hashquoted.strings", &OptionsCPP::hashquotedStrings,
                        "Set to 1 to enable highlighting of hash-quoted strings.");
 
+               DefineProperty("lexer.cpp.backquoted.strings", &OptionsCPP::backQuotedStrings,
+                       "Set to 1 to enable highlighting of back-quoted raw strings .");
+
+               DefineProperty("lexer.cpp.escape.sequence", &OptionsCPP::escapeSequence,
+                       "Set to 1 to enable highlighting of escape sequences in strings");
+
                DefineProperty("fold", &OptionsCPP::fold);
 
                DefineProperty("fold.cpp.syntax.based", &OptionsCPP::foldSyntaxBased,
@@ -298,6 +413,9 @@ struct OptionSetCPP : public OptionSet<OptionsCPP> {
 
                DefineProperty("fold.cpp.explicit.anywhere", &OptionsCPP::foldExplicitAnywhere,
                        "Set this property to 1 to enable explicit fold points anywhere, not just in line 
comments.");
+               
+               DefineProperty("fold.cpp.preprocessor.at.else", &OptionsCPP::foldPreprocessorAtElse,
+                       "This option enables folding on a preprocessor #else or #endif line of an #if 
statement.");
 
                DefineProperty("fold.preprocessor", &OptionsCPP::foldPreprocessor,
                        "This option enables folding preprocessor directives when using the C++ lexer. "
@@ -312,7 +430,9 @@ struct OptionSetCPP : public OptionSet<OptionsCPP> {
        }
 };
 
-static const char styleSubable[] = {SCE_C_IDENTIFIER, SCE_C_COMMENTDOCKEYWORD, 0};
+const char styleSubable[] = {SCE_C_IDENTIFIER, SCE_C_COMMENTDOCKEYWORD, 0};
+
+}
 
 class LexerCPP : public ILexerWithSubStyles {
        bool caseSensitive;
@@ -321,6 +441,7 @@ class LexerCPP : public ILexerWithSubStyles {
        CharacterSet setArithmethicOp;
        CharacterSet setRelOp;
        CharacterSet setLogicalOp;
+       CharacterSet setWordStart;
        PPStates vlls;
        std::vector<PPDefinition> ppDefineHistory;
        WordList keywords;
@@ -328,15 +449,32 @@ class LexerCPP : public ILexerWithSubStyles {
        WordList keywords3;
        WordList keywords4;
        WordList ppDefinitions;
-       std::map<std::string, std::string> preprocessorDefinitionsStart;
+       WordList markerList;
+       struct SymbolValue {
+               std::string value;
+               std::string arguments;
+               SymbolValue(const std::string &value_="", const std::string &arguments_="") : value(value_), 
arguments(arguments_) {
+               }
+               SymbolValue &operator = (const std::string &value_) {
+                       value = value_;
+                       arguments.clear();
+                       return *this;
+               }
+               bool IsMacro() const {
+                       return !arguments.empty();
+               }
+       };
+       typedef std::map<std::string, SymbolValue> SymbolTable;
+       SymbolTable preprocessorDefinitionsStart;
        OptionsCPP options;
        OptionSetCPP osCPP;
+       EscapeSequence escapeSeq;
        SparseState<std::string> rawStringTerminators;
        enum { activeFlag = 0x40 };
        enum { ssIdentifier, ssDocKeyword };
        SubStyles subStyles;
 public:
-       LexerCPP(bool caseSensitive_) :
+       explicit LexerCPP(bool caseSensitive_) :
                caseSensitive(caseSensitive_),
                setWord(CharacterSet::setAlphaNum, "._", 0x80, true),
                setNegationOp(CharacterSet::setNone, "!"),
@@ -347,56 +485,64 @@ public:
        }
        virtual ~LexerCPP() {
        }
-       void SCI_METHOD Release() {
+       void SCI_METHOD Release() override {
                delete this;
        }
-       int SCI_METHOD Version() const {
+       int SCI_METHOD Version() const override {
                return lvSubStyles;
        }
-       const char * SCI_METHOD PropertyNames() {
+       const char * SCI_METHOD PropertyNames() override {
                return osCPP.PropertyNames();
        }
-       int SCI_METHOD PropertyType(const char *name) {
+       int SCI_METHOD PropertyType(const char *name) override {
                return osCPP.PropertyType(name);
        }
-       const char * SCI_METHOD DescribeProperty(const char *name) {
+       const char * SCI_METHOD DescribeProperty(const char *name) override {
                return osCPP.DescribeProperty(name);
        }
-       int SCI_METHOD PropertySet(const char *key, const char *val);
-       const char * SCI_METHOD DescribeWordListSets() {
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char * SCI_METHOD DescribeWordListSets() override {
                return osCPP.DescribeWordListSets();
        }
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-       void * SCI_METHOD PrivateCall(int, void *) {
+       void * SCI_METHOD PrivateCall(int, void *) override {
                return 0;
        }
 
-       int SCI_METHOD LineEndTypesSupported() {
+       int SCI_METHOD LineEndTypesSupported() override {
                return SC_LINE_END_TYPE_UNICODE;
-       };
+       }
 
-       int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) {
+       int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override {
                return subStyles.Allocate(styleBase, numberStyles);
        }
-       int SCI_METHOD SubStylesStart(int styleBase) {
+       int SCI_METHOD SubStylesStart(int styleBase) override {
                return subStyles.Start(styleBase);
        }
-       int SCI_METHOD SubStylesLength(int styleBase) {
+       int SCI_METHOD SubStylesLength(int styleBase) override {
                return subStyles.Length(styleBase);
        }
-       void SCI_METHOD FreeSubStyles() {
+       int SCI_METHOD StyleFromSubStyle(int subStyle) override {
+               const int styleBase = subStyles.BaseStyle(MaskActive(subStyle));
+               const int active = subStyle & activeFlag;
+               return styleBase | active;
+       }
+       int SCI_METHOD PrimaryStyleFromStyle(int style) override {
+               return MaskActive(style);
+       }
+       void SCI_METHOD FreeSubStyles() override {
                subStyles.Free();
        }
-       void SCI_METHOD SetIdentifiers(int style, const char *identifiers) {
+       void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override {
                subStyles.SetIdentifiers(style, identifiers);
        }
-       int SCI_METHOD DistanceToSecondaryStyles() {
+       int SCI_METHOD DistanceToSecondaryStyles() override {
                return activeFlag;
        }
-       const char * SCI_METHOD GetSubStyleBases() {
+       const char * SCI_METHOD GetSubStyleBases() override {
                return styleSubable;
        }
 
@@ -409,11 +555,12 @@ public:
        static int MaskActive(int style) {
                return style & ~activeFlag;
        }
-       void EvaluateTokens(std::vector<std::string> &tokens);
-       bool EvaluateExpression(const std::string &expr, const std::map<std::string, std::string> 
&preprocessorDefinitions);
+       void EvaluateTokens(std::vector<std::string> &tokens, const SymbolTable &preprocessorDefinitions);
+       std::vector<std::string> Tokenize(const std::string &expr) const;
+       bool EvaluateExpression(const std::string &expr, const SymbolTable &preprocessorDefinitions);
 };
 
-int SCI_METHOD LexerCPP::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerCPP::PropertySet(const char *key, const char *val) {
        if (osCPP.PropertySet(&options, key, val)) {
                if (strcmp(key, "lexer.cpp.allow.dollars") == 0) {
                        setWord = CharacterSet(CharacterSet::setAlphaNum, "._", 0x80, true);
@@ -426,7 +573,7 @@ int SCI_METHOD LexerCPP::PropertySet(const char *key, const char *val) {
        return -1;
 }
 
-int SCI_METHOD LexerCPP::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerCPP::WordListSet(int n, const char *wl) {
        WordList *wordListN = 0;
        switch (n) {
        case 0:
@@ -444,8 +591,11 @@ int SCI_METHOD LexerCPP::WordListSet(int n, const char *wl) {
        case 4:
                wordListN = &ppDefinitions;
                break;
+       case 5:
+               wordListN = &markerList;
+               break;
        }
-       int firstModification = -1;
+       Sci_Position firstModification = -1;
        if (wordListN) {
                WordList wlNew;
                wlNew.Set(wl);
@@ -461,7 +611,16 @@ int SCI_METHOD LexerCPP::WordListSet(int n, const char *wl) {
                                        if (cpEquals) {
                                                std::string name(cpDefinition, cpEquals - cpDefinition);
                                                std::string val(cpEquals+1);
-                                               preprocessorDefinitionsStart[name] = val;
+                                               size_t bracket = name.find('(');
+                                               size_t bracketEnd = name.find(')');
+                                               if ((bracket != std::string::npos) && (bracketEnd != 
std::string::npos)) {
+                                                       // Macro
+                                                       std::string args = name.substr(bracket + 1, 
bracketEnd - bracket - 1);
+                                                       name = name.substr(0, bracket);
+                                                       preprocessorDefinitionsStart[name] = SymbolValue(val, 
args);
+                                               } else {
+                                                       preprocessorDefinitionsStart[name] = val;
+                                               }
                                        } else {
                                                std::string name(cpDefinition);
                                                std::string val("1");
@@ -476,14 +635,14 @@ int SCI_METHOD LexerCPP::WordListSet(int n, const char *wl) {
 
 // Functor used to truncate history
 struct After {
-       int line;
-       After(int line_) : line(line_) {}
-       bool operator()(PPDefinition &p) const {
+       Sci_Position line;
+       explicit After(Sci_Position line_) : line(line_) {}
+       bool operator()(const PPDefinition &p) const {
                return p.line > line;
        }
 };
 
-void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerCPP::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        LexAccessor styler(pAccess);
 
        CharacterSet setOKBeforeRE(CharacterSet::setNone, "([{=,:;!%^&*|?~+-");
@@ -491,7 +650,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 
        CharacterSet setDoxygen(CharacterSet::setAlpha, "$@\\&<>#{}[]");
 
-       CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
+       setWordStart = CharacterSet(CharacterSet::setAlpha, "_", 0x80, true);
 
        CharacterSet setInvalidRawFirst(CharacterSet::setNone, " )\\\t\v\f\n");
 
@@ -503,18 +662,20 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
        int visibleChars = 0;
        bool lastWordWasUUID = false;
        int styleBeforeDCKeyword = SCE_C_DEFAULT;
+       int styleBeforeTaskMarker = SCE_C_DEFAULT;
        bool continuationLine = false;
        bool isIncludePreprocessor = false;
        bool isStringInPreprocessor = false;
        bool inRERange = false;
+       bool seenDocKeyBrace = false;
 
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if ((MaskActive(initStyle) == SCE_C_PREPROCESSOR) ||
       (MaskActive(initStyle) == SCE_C_COMMENTLINE) ||
       (MaskActive(initStyle) == SCE_C_COMMENTLINEDOC)) {
                // Set continuationLine if last character of previous line is '\'
                if (lineCurrent > 0) {
-                       int endLinePrevious = styler.LineEnd(lineCurrent - 1);
+                       Sci_Position endLinePrevious = styler.LineEnd(lineCurrent - 1);
                        if (endLinePrevious > 0) {
                                continuationLine = styler.SafeGetCharAt(endLinePrevious-1) == '\\';
                        }
@@ -523,7 +684,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 
        // look back to set chPrevNonWhite properly for better regex colouring
        if (startPos > 0) {
-               int back = startPos;
+               Sci_Position back = startPos;
                while (--back && IsSpaceEquiv(MaskActive(styler.StyleAt(back))))
                        ;
                if (MaskActive(styler.StyleAt(back)) == SCE_C_OPERATOR) {
@@ -531,7 +692,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                }
        }
 
-       StyleContext sc(startPos, length, initStyle, styler, static_cast<char>(0xff));
+       StyleContext sc(startPos, length, initStyle, styler);
        LinePPState preproc = vlls.ForLine(lineCurrent);
 
        bool definitionsChanged = false;
@@ -547,12 +708,12 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                definitionsChanged = true;
        }
 
-       std::map<std::string, std::string> preprocessorDefinitions = preprocessorDefinitionsStart;
-       for (std::vector<PPDefinition>::iterator itDef = ppDefineHistory.begin(); itDef != 
ppDefineHistory.end(); ++itDef) {
-               if (itDef->isUndef)
-                       preprocessorDefinitions.erase(itDef->key);
+       SymbolTable preprocessorDefinitions = preprocessorDefinitionsStart;
+       for (const PPDefinition &ppDef : ppDefineHistory) {
+               if (ppDef.isUndef)
+                       preprocessorDefinitions.erase(ppDef.key);
                else
-                       preprocessorDefinitions[itDef->key] = itDef->value;
+                       preprocessorDefinitions[ppDef.key] = SymbolValue(ppDef.value, ppDef.arguments);
        }
 
        std::string rawStringTerminator = rawStringTerminators.ValueAt(lineCurrent-1);
@@ -563,7 +724,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
        const WordClassifier &classifierIdentifiers = subStyles.Classifier(SCE_C_IDENTIFIER);
        const WordClassifier &classifierDocKeyWords = subStyles.Classifier(SCE_C_COMMENTDOCKEYWORD);
 
-       int lineEndNext = styler.LineEnd(lineCurrent);
+       Sci_Position lineEndNext = styler.LineEnd(lineCurrent);
 
        for (; sc.More();) {
 
@@ -572,13 +733,13 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                        // Inside inactive preprocessor declaration, state will be reset anyway at the end of 
this block.
                        if ((sc.state == SCE_C_STRING) || (sc.state == SCE_C_CHARACTER)) {
                                // Prevent SCE_C_STRINGEOL from leaking back to previous line which
-                               // ends with a line continuation by locking in the state upto this position.
+                               // ends with a line continuation by locking in the state up to this position.
                                sc.SetState(sc.state);
                        }
                        if ((MaskActive(sc.state) == SCE_C_PREPROCESSOR) && (!continuationLine)) {
                                sc.SetState(SCE_C_DEFAULT|activitySet);
                        }
-                       // Reset states to begining of colourise so no surprises
+                       // Reset states to beginning of colourise so no surprises
                        // if different sets of lines lexed.
                        visibleChars = 0;
                        lastWordWasUUID = false;
@@ -601,10 +762,13 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 
                // Handle line continuation generically.
                if (sc.ch == '\\') {
-                       if (static_cast<int>((sc.currentPos+1)) >= lineEndNext) {
+                       if (static_cast<Sci_Position>((sc.currentPos+1)) >= lineEndNext) {
                                lineCurrent++;
                                lineEndNext = styler.LineEnd(lineCurrent);
                                vlls.Add(lineCurrent, preproc);
+                               if (rawStringTerminator != "") {
+                                       rawSTNew.Set(lineCurrent-1, rawStringTerminator);
+                               }
                                sc.Forward();
                                if (sc.ch == '\r' && sc.chNext == '\n') {
                                        // Even in UTF-8, \r and \n are separate
@@ -625,12 +789,19 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                break;
                        case SCE_C_NUMBER:
                                // We accept almost anything because of hex. and number suffixes
-                               if (!(setWord.Contains(sc.ch)
+                               if (sc.ch == '_') {
+                                       sc.ChangeState(SCE_C_USERLITERAL|activitySet);
+                               } else if (!(setWord.Contains(sc.ch)
+                                  || (sc.ch == '\'')
                                   || ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 
'E' ||
                                                                          sc.chPrev == 'p' || sc.chPrev == 
'P')))) {
                                        sc.SetState(SCE_C_DEFAULT|activitySet);
                                }
                                break;
+                       case SCE_C_USERLITERAL:
+                               if (!(setWord.Contains(sc.ch)))
+                                       sc.SetState(SCE_C_DEFAULT|activitySet);
+                               break;
                        case SCE_C_IDENTIFIER:
                                if (sc.atLineStart || sc.atLineEnd || !setWord.Contains(sc.ch) || (sc.ch == 
'.')) {
                                        char s[1000];
@@ -658,18 +829,29 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                                const bool raw = literalString && sc.chPrev == 'R' && 
!setInvalidRawFirst.Contains(sc.chNext);
                                                if (raw)
                                                        s[lenS--] = '\0';
-                                               bool valid =
+                                               const bool valid =
                                                        (lenS == 0) ||
                                                        ((lenS == 1) && ((s[0] == 'L') || (s[0] == 'u') || 
(s[0] == 'U'))) ||
                                                        ((lenS == 2) && literalString && (s[0] == 'u') && 
(s[1] == '8'));
                                                if (valid) {
-                                                       if (literalString)
-                                                               sc.ChangeState((raw ? SCE_C_STRINGRAW : 
SCE_C_STRING)|activitySet);
-                                                       else
+                                                       if (literalString) {
+                                                               if (raw) {
+                                                                       // Set the style of the string prefix 
to SCE_C_STRINGRAW but then change to
+                                                                       // SCE_C_DEFAULT as that allows the 
raw string start code to run.
+                                                                       
sc.ChangeState(SCE_C_STRINGRAW|activitySet);
+                                                                       
sc.SetState(SCE_C_DEFAULT|activitySet);
+                                                               } else {
+                                                                       
sc.ChangeState(SCE_C_STRING|activitySet);
+                                                               }
+                                                       } else {
                                                                sc.ChangeState(SCE_C_CHARACTER|activitySet);
+                                                       }
+                                               } else {
+                                                       sc.SetState(SCE_C_DEFAULT | activitySet);
                                                }
+                                       } else {
+                                               sc.SetState(SCE_C_DEFAULT|activitySet);
                                        }
-                                       sc.SetState(SCE_C_DEFAULT|activitySet);
                                }
                                break;
                        case SCE_C_PREPROCESSOR:
@@ -677,7 +859,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                        if (IsASpace(sc.ch)) {
                                                sc.SetState(SCE_C_DEFAULT|activitySet);
                                        }
-                               } else if (isStringInPreprocessor && (sc.Match('>') || sc.Match('\"'))) {
+                               } else if (isStringInPreprocessor && (sc.Match('>') || sc.Match('\"') || 
sc.atLineEnd)) {
                                        isStringInPreprocessor = false;
                                } else if (!isStringInPreprocessor) {
                                        if ((isIncludePreprocessor && sc.Match('<')) || sc.Match('\"')) {
@@ -706,6 +888,9 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                if (sc.Match('*', '/')) {
                                        sc.Forward();
                                        sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
+                               } else {
+                                       styleBeforeTaskMarker = SCE_C_COMMENT;
+                                       highlightTaskMarker(sc, styler, activitySet, markerList, 
caseSensitive);
                                }
                                break;
                        case SCE_C_COMMENTDOC:
@@ -723,6 +908,9 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                        case SCE_C_COMMENTLINE:
                                if (sc.atLineStart && !continuationLine) {
                                        sc.SetState(SCE_C_DEFAULT|activitySet);
+                               } else {
+                                       styleBeforeTaskMarker = SCE_C_COMMENTLINE;
+                                       highlightTaskMarker(sc, styler, activitySet, markerList, 
caseSensitive);
                                }
                                break;
                        case SCE_C_COMMENTLINEDOC:
@@ -741,14 +929,18 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                        sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
                                        sc.Forward();
                                        sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
-                               } else if (!setDoxygen.Contains(sc.ch)) {
+                                       seenDocKeyBrace = false;
+                               } else if (sc.ch == '[' || sc.ch == '{') {
+                                       seenDocKeyBrace = true;
+                               } else if (!setDoxygen.Contains(sc.ch)
+                                          && !(seenDocKeyBrace && (sc.ch == ',' || sc.ch == '.'))) {
                                        char s[100];
                                        if (caseSensitive) {
                                                sc.GetCurrent(s, sizeof(s));
                                        } else {
                                                sc.GetCurrentLowered(s, sizeof(s));
                                        }
-                                       if (!IsASpace(sc.ch)) {
+                                       if (!(IsASpace(sc.ch) || (sc.ch == 0))) {
                                                sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR|activitySet);
                                        } else if (!keywords3.InList(s + 1)) {
                                                int subStyleCDKW = classifierDocKeyWords.ValueFor(s+1);
@@ -759,6 +951,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                                }
                                        }
                                        sc.SetState(styleBeforeDCKeyword|activitySet);
+                                       seenDocKeyBrace = false;
                                }
                                break;
                        case SCE_C_STRING:
@@ -770,11 +963,35 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                                isIncludePreprocessor = false;
                                        }
                                } else if (sc.ch == '\\') {
-                                       if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
-                                               sc.Forward();
+                                       if (options.escapeSequence) {
+                                               sc.SetState(SCE_C_ESCAPESEQUENCE|activitySet);
+                                               escapeSeq.resetEscapeState(sc.chNext);
                                        }
+                                       sc.Forward(); // Skip all characters after the backslash
                                } else if (sc.ch == '\"') {
+                                       if (sc.chNext == '_') {
+                                               sc.ChangeState(SCE_C_USERLITERAL|activitySet);
+                                       } else {
+                                               sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
+                                       }
+                               }
+                               break;
+                       case SCE_C_ESCAPESEQUENCE:
+                               escapeSeq.digitsLeft--;
+                               if (!escapeSeq.atEscapeEnd(sc.ch)) {
+                                       break;
+                               }
+                               if (sc.ch == '"') {
+                                       sc.SetState(SCE_C_STRING|activitySet);
                                        sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
+                               } else if (sc.ch == '\\') {
+                                       escapeSeq.resetEscapeState(sc.chNext);
+                                       sc.Forward();
+                               } else {
+                                       sc.SetState(SCE_C_STRING|activitySet);
+                                       if (sc.atLineEnd) {
+                                               sc.ChangeState(SCE_C_STRINGEOL|activitySet);
+                                       }
                                }
                                break;
                        case SCE_C_HASHQUOTEDSTRING:
@@ -802,7 +1019,11 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                                sc.Forward();
                                        }
                                } else if (sc.ch == '\'') {
-                                       sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
+                                       if (sc.chNext == '_') {
+                                               sc.ChangeState(SCE_C_USERLITERAL|activitySet);
+                                       } else {
+                                               sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
+                                       }
                                }
                                break;
                        case SCE_C_REGEX:
@@ -813,7 +1034,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                        while ((sc.ch < 0x80) && islower(sc.ch))
                                                sc.Forward();    // gobble regex flags
                                        sc.SetState(SCE_C_DEFAULT|activitySet);
-                               } else if (sc.ch == '\\' && (static_cast<int>(sc.currentPos+1) < 
lineEndNext)) {
+                               } else if (sc.ch == '\\' && (static_cast<Sci_Position>(sc.currentPos+1) < 
lineEndNext)) {
                                        // Gobble up the escaped character
                                        sc.Forward();
                                } else if (sc.ch == '[') {
@@ -828,7 +1049,9 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                }
                                break;
                        case SCE_C_VERBATIM:
-                               if (sc.ch == '\"') {
+                               if (options.verbatimStringsAllowEscapes && (sc.ch == '\\')) {
+                                       sc.Forward(); // Skip all characters after the backslash
+                               } else if (sc.ch == '\"') {
                                        if (sc.chNext == '\"') {
                                                sc.Forward();
                                        } else {
@@ -848,6 +1071,12 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                if (sc.atLineEnd || sc.ch == ')') {
                                        sc.SetState(SCE_C_DEFAULT|activitySet);
                                }
+                               break;
+                       case SCE_C_TASKMARKER:
+                               if (isoperator(sc.ch) || IsASpace(sc.ch)) {
+                                       sc.SetState(styleBeforeTaskMarker|activitySet);
+                                       styleBeforeTaskMarker = SCE_C_DEFAULT;
+                               }
                }
 
                if (sc.atLineEnd && !atLineEndBeforeSwitch) {
@@ -868,6 +1097,9 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                        } else if (options.hashquotedStrings && sc.Match('#', '\"')) {
                                sc.SetState(SCE_C_HASHQUOTEDSTRING|activitySet);
                                sc.Forward();
+                       } else if (options.backQuotedStrings && sc.Match('`')) {
+                               sc.SetState(SCE_C_STRINGRAW|activitySet);
+                               rawStringTerminator = "`";
                        } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
                                if (lastWordWasUUID) {
                                        sc.SetState(SCE_C_UUID|activitySet);
@@ -908,7 +1140,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                        if (MaskActive(styler.StyleAt(sc.currentPos - 1)) == SCE_C_STRINGRAW) 
{
                                                sc.SetState(SCE_C_STRINGRAW|activitySet);
                                                rawStringTerminator = ")";
-                                               for (int termPos = sc.currentPos + 1;; termPos++) {
+                                               for (Sci_Position termPos = sc.currentPos + 1;; termPos++) {
                                                        char chTerminator = styler.SafeGetCharAt(termPos, 
'(');
                                                        if (chTerminator == '(')
                                                                break;
@@ -966,7 +1198,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                                        if (!preproc.CurrentIfTaken()) {
                                                                // Similar to #if
                                                                std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 2, true);
-                                                               bool ifGood = EvaluateExpression(restOfLine, 
preprocessorDefinitions);
+                                                               const bool ifGood = 
EvaluateExpression(restOfLine, preprocessorDefinitions);
                                                                if (ifGood) {
                                                                        preproc.InvertCurrentLevel();
                                                                        activitySet = preproc.IsInactive() ? 
activeFlag : 0;
@@ -986,28 +1218,45 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
                                                } else if (sc.Match("define")) {
                                                        if (options.updatePreprocessor && 
!preproc.IsInactive()) {
                                                                std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 6, true);
-                                                               if (restOfLine.find(")") == 
std::string::npos) {        // Don't handle macros with arguments
-                                                                       std::vector<std::string> tokens = 
Tokenize(restOfLine);
-                                                                       std::string key;
-                                                                       std::string value("1");
-                                                                       if (tokens.size() >= 1) {
-                                                                               key = tokens[0];
-                                                                               if (tokens.size() >= 2) {
-                                                                                       value = tokens[1];
-                                                                               }
-                                                                               preprocessorDefinitions[key] 
= value;
-                                                                               
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, value));
-                                                                               definitionsChanged = true;
-                                                                       }
+                                                               size_t startName = 0;
+                                                               while ((startName < restOfLine.length()) && 
IsSpaceOrTab(restOfLine[startName]))
+                                                                       startName++;
+                                                               size_t endName = startName;
+                                                               while ((endName < restOfLine.length()) && 
setWord.Contains(static_cast<unsigned char>(restOfLine[endName])))
+                                                                       endName++;
+                                                               std::string key = 
restOfLine.substr(startName, endName-startName);
+                                                               if ((endName < restOfLine.length()) && 
(restOfLine.at(endName) == '(')) {
+                                                                       // Macro
+                                                                       size_t endArgs = endName;
+                                                                       while ((endArgs < 
restOfLine.length()) && (restOfLine[endArgs] != ')'))
+                                                                               endArgs++;
+                                                                       std::string args = 
restOfLine.substr(endName + 1, endArgs - endName - 1);
+                                                                       size_t startValue = endArgs+1;
+                                                                       while ((startValue < 
restOfLine.length()) && IsSpaceOrTab(restOfLine[startValue]))
+                                                                               startValue++;
+                                                                       std::string value;
+                                                                       if (startValue < restOfLine.length())
+                                                                               value = 
restOfLine.substr(startValue);
+                                                                       preprocessorDefinitions[key] = 
SymbolValue(value, args);
+                                                                       
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, value, false, args));
+                                                                       definitionsChanged = true;
+                                                               } else {
+                                                                       // Value
+                                                                       size_t startValue = endName;
+                                                                       while ((startValue < 
restOfLine.length()) && IsSpaceOrTab(restOfLine[startValue]))
+                                                                               startValue++;
+                                                                       std::string value = 
restOfLine.substr(startValue);
+                                                                       preprocessorDefinitions[key] = value;
+                                                                       
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, value));
+                                                                       definitionsChanged = true;
                                                                }
                                                        }
                                                } else if (sc.Match("undef")) {
                                                        if (options.updatePreprocessor && 
!preproc.IsInactive()) {
-                                                               std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 5, true);
+                                                               const std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 5, false);
                                                                std::vector<std::string> tokens = 
Tokenize(restOfLine);
-                                                               std::string key;
                                                                if (tokens.size() >= 1) {
-                                                                       key = tokens[0];
+                                                                       const std::string key = tokens[0];
                                                                        preprocessorDefinitions.erase(key);
                                                                        
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, "", true));
                                                                        definitionsChanged = true;
@@ -1038,34 +1287,34 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
 
-void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerCPP::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
 
        if (!options.fold)
                return;
 
        LexAccessor styler(pAccess);
 
-       unsigned int endPos = startPos + length;
+       const Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
        bool inLineComment = false;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
-       unsigned int lineStartNext = styler.LineStart(lineCurrent+1);
+       Sci_PositionU lineStartNext = styler.LineStart(lineCurrent+1);
        int levelMinCurrent = levelCurrent;
        int levelNext = levelCurrent;
        char chNext = styler[startPos];
        int styleNext = MaskActive(styler.StyleAt(startPos));
        int style = MaskActive(initStyle);
        const bool userDefinedFoldMarkers = !options.foldExplicitStart.empty() && 
!options.foldExplicitEnd.empty();
-       for (unsigned int i = startPos; i < endPos; i++) {
-               char ch = chNext;
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
+               const char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
-               int stylePrev = style;
+               const int stylePrev = style;
                style = styleNext;
                styleNext = MaskActive(styler.StyleAt(i + 1));
-               bool atEOL = i == (lineStartNext-1);
+               const bool atEOL = i == (lineStartNext-1);
                if ((style == SCE_C_COMMENTLINE) || (style == SCE_C_COMMENTLINEDOC))
                        inLineComment = true;
                if (options.foldComment && options.foldCommentMultiline && IsStreamCommentStyle(style) && 
!inLineComment) {
@@ -1085,7 +1334,7 @@ void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle,
                                }
                        } else {
                                if ((ch == '/') && (chNext == '/')) {
-                                       char chNext2 = styler.SafeGetCharAt(i + 2);
+                                       const char chNext2 = styler.SafeGetCharAt(i + 2);
                                        if (chNext2 == '{') {
                                                levelNext++;
                                        } else if (chNext2 == '}') {
@@ -1096,7 +1345,7 @@ void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle,
                }
                if (options.foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
                        if (ch == '#') {
-                               unsigned int j = i + 1;
+                               Sci_PositionU j = i + 1;
                                while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                        j++;
                                }
@@ -1105,17 +1354,21 @@ void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle,
                                } else if (styler.Match(j, "end")) {
                                        levelNext--;
                                }
+                               
+                               if (options.foldPreprocessorAtElse && (styler.Match(j, "else") || 
styler.Match(j, "elif"))) {
+                                       levelMinCurrent--;
+                               }
                        }
                }
                if (options.foldSyntaxBased && (style == SCE_C_OPERATOR)) {
-                       if (ch == '{') {
+                       if (ch == '{' || ch == '[' || ch == '(') {
                                // Measure the minimum before a '{' to allow
                                // folding on "} else {"
-                               if (levelMinCurrent > levelNext) {
+                               if (options.foldAtElse && levelMinCurrent > levelNext) {
                                        levelMinCurrent = levelNext;
                                }
                                levelNext++;
-                       } else if (ch == '}') {
+                       } else if (ch == '}' || ch == ']' || ch == ')') {
                                levelNext--;
                        }
                }
@@ -1123,7 +1376,9 @@ void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle,
                        visibleChars++;
                if (atEOL || (i == endPos-1)) {
                        int levelUse = levelCurrent;
-                       if (options.foldSyntaxBased && options.foldAtElse) {
+                       if ((options.foldSyntaxBased && options.foldAtElse) ||
+                               (options.foldPreprocessor && options.foldPreprocessorAtElse)
+                       ) {
                                levelUse = levelMinCurrent;
                        }
                        int lev = levelUse | levelNext << 16;
@@ -1138,7 +1393,7 @@ void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle,
                        lineStartNext = styler.LineStart(lineCurrent+1);
                        levelCurrent = levelNext;
                        levelMinCurrent = levelCurrent;
-                       if (atEOL && (i == static_cast<unsigned int>(styler.Length()-1))) {
+                       if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length()-1))) {
                                // There is an empty line at end of file so give it same level and empty
                                styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | 
SC_FOLDLEVELWHITEFLAG);
                        }
@@ -1148,19 +1403,36 @@ void SCI_METHOD LexerCPP::Fold(unsigned int startPos, int length, int initStyle,
        }
 }
 
-void LexerCPP::EvaluateTokens(std::vector<std::string> &tokens) {
+void LexerCPP::EvaluateTokens(std::vector<std::string> &tokens, const SymbolTable &preprocessorDefinitions) {
+
+       // Remove whitespace tokens
+       tokens.erase(std::remove_if(tokens.begin(), tokens.end(), OnlySpaceOrTab), tokens.end());
 
-       // Evaluate defined() statements to either 0 or 1
-       for (size_t i=0; (i+2)<tokens.size();) {
-               if ((tokens[i] == "defined") && (tokens[i+1] == "(")) {
+       // Evaluate defined statements to either 0 or 1
+       for (size_t i=0; (i+1)<tokens.size();) {
+               if (tokens[i] == "defined") {
                        const char *val = "0";
-                       if (tokens[i+2] == ")") {
-                               // defined()
-                               tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 3);
-                       } else if (((i+3)<tokens.size()) && (tokens[i+3] == ")")) {
-                               // defined(<int>)
-                               tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 4);
-                               val = "1";
+                       if (tokens[i+1] == "(") {
+                               if (((i + 2)<tokens.size()) && (tokens[i + 2] == ")")) {
+                                       // defined()
+                                       tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 3);
+                               } else if (((i+3)<tokens.size()) && (tokens[i+3] == ")")) {
+                                       // defined(<identifier>)
+                                       SymbolTable::const_iterator it = 
preprocessorDefinitions.find(tokens[i+2]);
+                                       if (it != preprocessorDefinitions.end()) {
+                                               val = "1";
+                                       }
+                                       tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 4);
+                               } else {
+                                       // Spurious '(' so erase as more likely to result in false
+                                       tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 2);
+                               }
+                       } else {
+                               // defined <identifier>
+                               SymbolTable::const_iterator it = preprocessorDefinitions.find(tokens[i+1]);
+                               if (it != preprocessorDefinitions.end()) {
+                                       val = "1";
+                               }
                        }
                        tokens[i] = val;
                } else {
@@ -1168,21 +1440,82 @@ void LexerCPP::EvaluateTokens(std::vector<std::string> &tokens) {
                }
        }
 
+       // Evaluate identifiers
+       const size_t maxIterations = 100;
+       size_t iterations = 0;  // Limit number of iterations in case there is a recursive macro.
+       for (size_t i = 0; (i<tokens.size()) && (iterations < maxIterations);) {
+               iterations++;
+               if (setWordStart.Contains(static_cast<unsigned char>(tokens[i][0]))) {
+                       SymbolTable::const_iterator it = preprocessorDefinitions.find(tokens[i]);
+                       if (it != preprocessorDefinitions.end()) {
+                               // Tokenize value
+                               std::vector<std::string> macroTokens = Tokenize(it->second.value);
+                               if (it->second.IsMacro()) {
+                                       if ((i + 1 < tokens.size()) && (tokens.at(i + 1) == "(")) {
+                                               // Create map of argument name to value
+                                               std::vector<std::string> argumentNames = 
StringSplit(it->second.arguments, ',');
+                                               std::map<std::string, std::string> arguments;
+                                               size_t arg = 0;
+                                               size_t tok = i+2;
+                                               while ((tok < tokens.size()) && (arg < argumentNames.size()) 
&& (tokens.at(tok) != ")")) {
+                                                       if (tokens.at(tok) != ",") {
+                                                               arguments[argumentNames.at(arg)] = 
tokens.at(tok);
+                                                               arg++;
+                                                       }
+                                                       tok++;
+                                               }
+
+                                               // Remove invocation
+                                               tokens.erase(tokens.begin() + i, tokens.begin() + tok + 1);
+
+                                               // Substitute values into macro
+                                               macroTokens.erase(std::remove_if(macroTokens.begin(), 
macroTokens.end(), OnlySpaceOrTab), macroTokens.end());
+
+                                               for (size_t iMacro = 0; iMacro < macroTokens.size();) {
+                                                       if (setWordStart.Contains(static_cast<unsigned 
char>(macroTokens[iMacro][0]))) {
+                                                               std::map<std::string, 
std::string>::const_iterator itFind = arguments.find(macroTokens[iMacro]);
+                                                               if (itFind != arguments.end()) {
+                                                                       // TODO: Possible that value will be 
expression so should insert tokenized form
+                                                                       macroTokens[iMacro] = itFind->second;
+                                                               }
+                                                       }
+                                                       iMacro++;
+                                               }
+
+                                               // Insert results back into tokens
+                                               tokens.insert(tokens.begin() + i, macroTokens.begin(), 
macroTokens.end());
+
+                                       } else {
+                                               i++;
+                                       }
+                               } else {
+                                       // Remove invocation
+                                       tokens.erase(tokens.begin() + i);
+                                       // Insert results back into tokens
+                                       tokens.insert(tokens.begin() + i, macroTokens.begin(), 
macroTokens.end());
+                               }
+                       } else {
+                               // Identifier not found
+                               tokens.erase(tokens.begin() + i);
+                       }
+               } else {
+                       i++;
+               }
+       }
+
        // Find bracketed subexpressions and recurse on them
-       std::vector<std::string>::iterator itBracket = std::find(tokens.begin(), tokens.end(), "(");
-       std::vector<std::string>::iterator itEndBracket = std::find(tokens.begin(), tokens.end(), ")");
-       while ((itBracket != tokens.end()) && (itEndBracket != tokens.end()) && (itEndBracket > itBracket)) {
-               std::vector<std::string> inBracket(itBracket + 1, itEndBracket);
-               EvaluateTokens(inBracket);
+       BracketPair bracketPair = FindBracketPair(tokens);
+       while (bracketPair.itBracket != tokens.end()) {
+               std::vector<std::string> inBracket(bracketPair.itBracket + 1, bracketPair.itEndBracket);
+               EvaluateTokens(inBracket, preprocessorDefinitions);
 
                // The insertion is done before the removal because there were failures with the opposite 
approach
-               tokens.insert(itBracket, inBracket.begin(), inBracket.end());
-               itBracket = std::find(tokens.begin(), tokens.end(), "(");
-               itEndBracket = std::find(tokens.begin(), tokens.end(), ")");
-               tokens.erase(itBracket, itEndBracket + 1);
+               tokens.insert(bracketPair.itBracket, inBracket.begin(), inBracket.end());
 
-               itBracket = std::find(tokens.begin(), tokens.end(), "(");
-               itEndBracket = std::find(tokens.begin(), tokens.end(), ")");
+               bracketPair = FindBracketPair(tokens);
+               tokens.erase(bracketPair.itBracket, bracketPair.itEndBracket + 1);
+
+               bracketPair = FindBracketPair(tokens);
        }
 
        // Evaluate logical negations
@@ -1204,14 +1537,14 @@ void LexerCPP::EvaluateTokens(std::vector<std::string> &tokens) {
        for (int prec=precArithmetic; prec <= precLogical; prec++) {
                // Looking at 3 tokens at a time so end at 2 before end
                for (size_t k=0; (k+2)<tokens.size();) {
-                       char chOp = tokens[k+1][0];
+                       const char chOp = tokens[k+1][0];
                        if (
                                ((prec==precArithmetic) && setArithmethicOp.Contains(chOp)) ||
                                ((prec==precRelative) && setRelOp.Contains(chOp)) ||
                                ((prec==precLogical) && setLogicalOp.Contains(chOp))
                                ) {
-                               int valA = atoi(tokens[k].c_str());
-                               int valB = atoi(tokens[k+2].c_str());
+                               const int valA = atoi(tokens[k].c_str());
+                               const int valB = atoi(tokens[k+2].c_str());
                                int result = 0;
                                if (tokens[k+1] == "+")
                                        result = valA + valB;
@@ -1251,48 +1584,54 @@ void LexerCPP::EvaluateTokens(std::vector<std::string> &tokens) {
        }
 }
 
-bool LexerCPP::EvaluateExpression(const std::string &expr, const std::map<std::string, std::string> 
&preprocessorDefinitions) {
-       // Break into tokens, replacing with definitions
-       std::string word;
+std::vector<std::string> LexerCPP::Tokenize(const std::string &expr) const {
+       // Break into tokens
        std::vector<std::string> tokens;
        const char *cp = expr.c_str();
-       for (;;) {
+       while (*cp) {
+               std::string word;
                if (setWord.Contains(static_cast<unsigned char>(*cp))) {
-                       word += *cp;
-               } else {
-                       std::map<std::string, std::string>::const_iterator it = 
preprocessorDefinitions.find(word);
-                       if (it != preprocessorDefinitions.end()) {
-                               tokens.push_back(it->second);
-                       } else if (!word.empty() && ((word[0] >= '0' && word[0] <= '9') || (word == 
"defined"))) {
-                               tokens.push_back(word);
+                       // Identifiers and numbers
+                       while (setWord.Contains(static_cast<unsigned char>(*cp))) {
+                               word += *cp;
+                               cp++;
                        }
-                       word = "";
-                       if (!*cp) {
-                               break;
+               } else if (IsSpaceOrTab(*cp)) {
+                       while (IsSpaceOrTab(*cp)) {
+                               word += *cp;
+                               cp++;
                        }
-                       if ((*cp != ' ') && (*cp != '\t')) {
-                               std::string op(cp, 1);
-                               if (setRelOp.Contains(static_cast<unsigned char>(*cp))) {
-                                       if (setRelOp.Contains(static_cast<unsigned char>(cp[1]))) {
-                                               op += cp[1];
-                                               cp++;
-                                       }
-                               } else if (setLogicalOp.Contains(static_cast<unsigned char>(*cp))) {
-                                       if (setLogicalOp.Contains(static_cast<unsigned char>(cp[1]))) {
-                                               op += cp[1];
-                                               cp++;
-                                       }
-                               }
-                               tokens.push_back(op);
+               } else if (setRelOp.Contains(static_cast<unsigned char>(*cp))) {
+                       word += *cp;
+                       cp++;
+                       if (setRelOp.Contains(static_cast<unsigned char>(*cp))) {
+                               word += *cp;
+                               cp++;
                        }
+               } else if (setLogicalOp.Contains(static_cast<unsigned char>(*cp))) {
+                       word += *cp;
+                       cp++;
+                       if (setLogicalOp.Contains(static_cast<unsigned char>(*cp))) {
+                               word += *cp;
+                               cp++;
+                       }
+               } else {
+                       // Should handle strings, characters, and comments here
+                       word += *cp;
+                       cp++;
                }
-               cp++;
+               tokens.push_back(word);
        }
+       return tokens;
+}
+
+bool LexerCPP::EvaluateExpression(const std::string &expr, const SymbolTable &preprocessorDefinitions) {
+       std::vector<std::string> tokens = Tokenize(expr);
 
-       EvaluateTokens(tokens);
+       EvaluateTokens(tokens, preprocessorDefinitions);
 
        // "0" or "" -> false else true
-       bool isFalse = tokens.empty() ||
+       const bool isFalse = tokens.empty() ||
                ((tokens.size() == 1) && ((tokens[0] == "") || tokens[0] == "0"));
        return !isFalse;
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexCSS.cxx b/plugins/scintilla/scintilla/lexers/LexCSS.cxx
index 036bb2e..19345af 100644
--- a/plugins/scintilla/scintilla/lexers/LexCSS.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCSS.cxx
@@ -58,11 +58,11 @@ inline bool IsCssOperator(const int ch) {
 }
 
 // look behind (from start of document to our start position) to determine current nesting level
-inline int NestingLevelLookBehind(unsigned int startPos, Accessor &styler) {
+inline int NestingLevelLookBehind(Sci_PositionU startPos, Accessor &styler) {
        int ch;
        int nestingLevel = 0;
 
-       for (unsigned int i = 0; i < startPos; i++) {
+       for (Sci_PositionU i = 0; i < startPos; i++) {
                ch = styler.SafeGetCharAt(i);
                if (ch == '{')
                        nestingLevel++;
@@ -73,7 +73,7 @@ inline int NestingLevelLookBehind(unsigned int startPos, Accessor &styler) {
        return nestingLevel;
 }
 
-static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], 
Accessor &styler) {
+static void ColouriseCssDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[], Accessor &styler) {
        WordList &css1Props = *keywordlists[0];
        WordList &pseudoClasses = *keywordlists[1];
        WordList &css2Props = *keywordlists[2];
@@ -131,7 +131,7 @@ static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, Wo
                        if (lastStateC == -1) {
                                // backtrack to get last state:
                                // comments are like whitespace, so we must return to the previous state
-                               unsigned int i = startPos;
+                               Sci_PositionU i = startPos;
                                for (; i > 0; i--) {
                                        if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
                                                if (lastStateC == SCE_CSS_OPERATOR) {
@@ -165,7 +165,7 @@ static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, Wo
                if (sc.state == SCE_CSS_DOUBLESTRING || sc.state == SCE_CSS_SINGLESTRING) {
                        if (sc.ch != (sc.state == SCE_CSS_DOUBLESTRING ? '\"' : '\''))
                                continue;
-                       unsigned int i = sc.currentPos;
+                       Sci_PositionU i = sc.currentPos;
                        while (i && styler[i-1] == '\\')
                                i--;
                        if ((sc.currentPos - i) % 2 == 1)
@@ -175,7 +175,7 @@ static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, Wo
 
                if (sc.state == SCE_CSS_OPERATOR) {
                        if (op == ' ') {
-                               unsigned int i = startPos;
+                               Sci_PositionU i = startPos;
                                op = styler.SafeGetCharAt(i-1);
                                opPrev = styler.SafeGetCharAt(i-2);
                                while (--i) {
@@ -380,10 +380,10 @@ static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, Wo
                        // check for nested rule selector
                        if (sc.state == SCE_CSS_IDENTIFIER && (IsAWordChar(sc.ch) || sc.ch == ':' || sc.ch == 
'.' || sc.ch == '#')) {
                                // look ahead to see whether { comes before next ; and }
-                               unsigned int endPos = startPos + length;
+                               Sci_PositionU endPos = startPos + length;
                                int ch;
 
-                               for (unsigned int i = sc.currentPos; i < endPos; i++) {
+                               for (Sci_PositionU i = sc.currentPos; i < endPos; i++) {
                                        ch = styler.SafeGetCharAt(i);
                                        if (ch == ';' || ch == '}')
                                                break;
@@ -502,17 +502,17 @@ static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, Wo
        sc.Complete();
 }
 
-static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
+static void FoldCSSDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styler.StyleAt(i);
diff --git a/plugins/scintilla/scintilla/lexers/LexCaml.cxx b/plugins/scintilla/scintilla/lexers/LexCaml.cxx
index f576e3e..df87815 100644
--- a/plugins/scintilla/scintilla/lexers/LexCaml.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCaml.cxx
@@ -66,18 +66,18 @@ using namespace Scintilla;
 #endif
 
 static void ColouriseCamlDoc(
-       unsigned int startPos, int length,
+       Sci_PositionU startPos, Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler);
 
 static void FoldCamlDoc(
-       unsigned int startPos, int length,
+       Sci_PositionU startPos, Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler);
 
-static void InternalLexOrFold(int lexOrFold, unsigned int startPos, int length,
+static void InternalLexOrFold(int lexOrFold, Sci_PositionU startPos, Sci_Position length,
        int initStyle, char *words[], WindowID window, char *props);
 
 static const char* LexerName = "caml";
@@ -109,7 +109,7 @@ long Platform::SendScintillaPointer(WindowID w, unsigned int msg, unsigned long
                reinterpret_cast<LPARAM>(lParam));
 }
 
-void EXT_LEXER_DECL Fold(unsigned int lexer, unsigned int startPos, int length,
+void EXT_LEXER_DECL Fold(unsigned int lexer, Sci_PositionU startPos, Sci_Position length,
        int initStyle, char *words[], WindowID window, char *props)
 {
        // below useless evaluation(s) to supress "not used" warnings
@@ -138,7 +138,7 @@ void EXT_LEXER_DECL GetLexerName(unsigned int Index, char *name, int buflength)
        }
 }
 
-void EXT_LEXER_DECL Lex(unsigned int lexer, unsigned int startPos, int length,
+void EXT_LEXER_DECL Lex(unsigned int lexer, Sci_PositionU startPos, Sci_Position length,
        int initStyle, char *words[], WindowID window, char *props)
 {
        // below useless evaluation(s) to supress "not used" warnings
@@ -147,7 +147,7 @@ void EXT_LEXER_DECL Lex(unsigned int lexer, unsigned int startPos, int length,
        InternalLexOrFold(0, startPos, length, initStyle, words, window, props);
 }
 
-static void InternalLexOrFold(int foldOrLex, unsigned int startPos, int length,
+static void InternalLexOrFold(int foldOrLex, Sci_PositionU startPos, Sci_Position length,
        int initStyle, char *words[], WindowID window, char *props)
 {
        // create and initialize a WindowAccessor (including contained PropSet)
@@ -180,7 +180,7 @@ static
 #endif /* BUILD_AS_EXTERNAL_LEXER */
 
 void ColouriseCamlDoc(
-       unsigned int startPos, int length,
+       Sci_PositionU startPos, Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler)
@@ -188,7 +188,8 @@ void ColouriseCamlDoc(
        // initialize styler
        StyleContext sc(startPos, length, initStyle, styler);
 
-       int chBase = 0, chToken = 0, chLit = 0;
+       Sci_PositionU chToken = 0;
+       int chBase = 0, chLit = 0;
        WordList& keywords  = *keywordlists[0];
        WordList& keywords2 = *keywordlists[1];
        WordList& keywords3 = *keywordlists[2];
@@ -206,7 +207,7 @@ void ColouriseCamlDoc(
        while (sc.More()) {
                // set up [per-char] state info
                int state2 = -1;                                // (ASSUME no state change)
-               int chColor = sc.currentPos - 1;// (ASSUME standard coloring range)
+               Sci_Position chColor = sc.currentPos - 1;// (ASSUME standard coloring range)
                bool advance = true;                    // (ASSUME scanner "eats" 1 char)
 
                // step state machine
@@ -254,11 +255,11 @@ void ColouriseCamlDoc(
                case SCE_CAML_IDENTIFIER:
                        // [try to] interpret as [additional] identifier char
                        if (!(iscaml(sc.ch) || sc.Match('\''))) {
-                               const int n = sc.currentPos - chToken;
+                               const Sci_Position n = sc.currentPos - chToken;
                                if (n < 24) {
                                        // length is believable as keyword, [re-]construct token
                                        char t[24];
-                                       for (int i = -n; i < 0; i++)
+                                       for (Sci_Position i = -n; i < 0; i++)
                                                t[n + i] = static_cast<char>(sc.GetRelative(i));
                                        t[n] = '\0';
                                        // special-case "_" token as KEYWORD
@@ -390,7 +391,7 @@ void ColouriseCamlDoc(
                                state2 = SCE_CAML_STRING, sc.ch = ' ' /* (...\") */, chColor++,
                                        styler.ColourTo(chColor, SCE_CAML_WHITE), styler.Flush();
                                // ... then backtrack to determine original SML literal type
-                               int p = chColor - 2;
+                               Sci_Position p = chColor - 2;
                                for (; p >= 0 && styler.StyleAt(p) == SCE_CAML_WHITE; p--) ;
                                if (p >= 0)
                                        state2 = static_cast<int>(styler.StyleAt(p));
@@ -437,7 +438,7 @@ void ColouriseCamlDoc(
 static
 #endif /* BUILD_AS_EXTERNAL_LEXER */
 void FoldCamlDoc(
-       unsigned int, int,
+       Sci_PositionU, Sci_Position,
        int,
        WordList *[],
        Accessor &)
diff --git a/plugins/scintilla/scintilla/lexers/LexCmake.cxx b/plugins/scintilla/scintilla/lexers/LexCmake.cxx
index 70e9dee..1cbca36 100644
--- a/plugins/scintilla/scintilla/lexers/LexCmake.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCmake.cxx
@@ -43,10 +43,10 @@ static bool isCmakeLetter(char ch)
     return(ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
 }
 
-static bool CmakeNextLineHasElse(unsigned int start, unsigned int end, Accessor &styler)
+static bool CmakeNextLineHasElse(Sci_PositionU start, Sci_PositionU end, Accessor &styler)
 {
-    int nNextLine = -1;
-    for ( unsigned int i = start; i < end; i++ ) {
+    Sci_Position nNextLine = -1;
+    for ( Sci_PositionU i = start; i < end; i++ ) {
         char cNext = styler.SafeGetCharAt( i );
         if ( cNext == '\n' ) {
             nNextLine = i+1;
@@ -57,7 +57,7 @@ static bool CmakeNextLineHasElse(unsigned int start, unsigned int end, Accessor
     if ( nNextLine == -1 ) // We never foudn the next line...
         return false;
 
-    for ( unsigned int firstChar = nNextLine; firstChar < end; firstChar++ ) {
+    for ( Sci_PositionU firstChar = nNextLine; firstChar < end; firstChar++ ) {
         char cNext = styler.SafeGetCharAt( firstChar );
         if ( cNext == ' ' )
             continue;
@@ -71,7 +71,7 @@ static bool CmakeNextLineHasElse(unsigned int start, unsigned int end, Accessor
     return false;
 }
 
-static int calculateFoldCmake(unsigned int start, unsigned int end, int foldlevel, Accessor &styler, bool 
bElse)
+static int calculateFoldCmake(Sci_PositionU start, Sci_PositionU end, int foldlevel, Accessor &styler, bool 
bElse)
 {
     // If the word is too long, it is not what we are looking for
     if ( end - start > 20 )
@@ -100,7 +100,7 @@ static int calculateFoldCmake(unsigned int start, unsigned int end, int foldleve
     return newFoldlevel;
 }
 
-static int classifyWordCmake(unsigned int start, unsigned int end, WordList *keywordLists[], Accessor 
&styler )
+static int classifyWordCmake(Sci_PositionU start, Sci_PositionU end, WordList *keywordLists[], Accessor 
&styler )
 {
     char word[100] = {0};
     char lowercaseWord[100] = {0};
@@ -109,7 +109,7 @@ static int classifyWordCmake(unsigned int start, unsigned int end, WordList *key
     WordList &Parameters = *keywordLists[1];
     WordList &UserDefined = *keywordLists[2];
 
-    for (unsigned int i = 0; i < end - start + 1 && i < 99; i++) {
+    for (Sci_PositionU i = 0; i < end - start + 1 && i < 99; i++) {
         word[i] = static_cast<char>( styler[ start + i ] );
         lowercaseWord[i] = static_cast<char>(tolower(word[i]));
     }
@@ -162,7 +162,7 @@ static int classifyWordCmake(unsigned int start, unsigned int end, WordList *key
     return SCE_CMAKE_DEFAULT;
 }
 
-static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor 
&styler)
+static void ColouriseCmakeDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], 
Accessor &styler)
 {
     int state = SCE_CMAKE_DEFAULT;
     if ( startPos > 0 )
@@ -171,14 +171,14 @@ static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *
     styler.StartAt( startPos );
     styler.GetLine( startPos );
 
-    unsigned int nLengthDoc = startPos + length;
+    Sci_PositionU nLengthDoc = startPos + length;
     styler.StartSegment( startPos );
 
     char cCurrChar;
     bool bVarInString = false;
     bool bClassicVarInString = false;
 
-    unsigned int i;
+    Sci_PositionU i;
     for ( i = startPos; i < nLengthDoc; i++ ) {
         cCurrChar = styler.SafeGetCharAt( i );
         char cNextChar = styler.SafeGetCharAt(i+1);
@@ -226,14 +226,13 @@ static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *
 
             break;
         case SCE_CMAKE_COMMENT:
-            if ( cNextChar == '\n' || cNextChar == '\r' ) {
-                // Special case:
-                if ( cCurrChar == '\\' ) {
+            if ( cCurrChar == '\n' || cCurrChar == '\r' ) {
+                if ( styler.SafeGetCharAt(i-1) == '\\' ) {
                     styler.ColourTo(i-2,state);
-                    styler.ColourTo(i,SCE_CMAKE_DEFAULT);
+                    styler.ColourTo(i-1,SCE_CMAKE_DEFAULT);
                 }
                 else {
-                    styler.ColourTo(i,state);
+                    styler.ColourTo(i-1,state);
                     state = SCE_CMAKE_DEFAULT;
                 }
             }
@@ -264,8 +263,8 @@ static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *
             }
 
             if ( cNextChar == '\r' || cNextChar == '\n' ) {
-                int nCurLine = styler.GetLine(i+1);
-                int nBack = i;
+                Sci_Position nCurLine = styler.GetLine(i+1);
+                Sci_Position nBack = i;
                 // We need to check if the previous line has a \ in it...
                 bool bNextLine = false;
 
@@ -335,10 +334,7 @@ static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *
             break;
         }
 
-        if ( state == SCE_CMAKE_COMMENT) {
-            styler.ColourTo(i,state);
-        }
-        else if ( state == SCE_CMAKE_STRINGDQ || state == SCE_CMAKE_STRINGLQ || state == SCE_CMAKE_STRINGRQ 
) {
+        if ( state == SCE_CMAKE_STRINGDQ || state == SCE_CMAKE_STRINGLQ || state == SCE_CMAKE_STRINGRQ ) {
             bool bIngoreNextDollarSign = false;
 
             if ( bVarInString && cCurrChar == '$' ) {
@@ -381,7 +377,7 @@ static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *
     styler.ColourTo(nLengthDoc-1,state);
 }
 
-static void FoldCmakeDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldCmakeDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
     // No folding enabled, no reason to continue...
     if ( styler.GetPropertyInt("fold") == 0 )
@@ -389,18 +385,18 @@ static void FoldCmakeDoc(unsigned int startPos, int length, int, WordList *[], A
 
     bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) == 1;
 
-    int lineCurrent = styler.GetLine(startPos);
-    unsigned int safeStartPos = styler.LineStart( lineCurrent );
+    Sci_Position lineCurrent = styler.GetLine(startPos);
+    Sci_PositionU safeStartPos = styler.LineStart( lineCurrent );
 
     bool bArg1 = true;
-    int nWordStart = -1;
+    Sci_Position nWordStart = -1;
 
     int levelCurrent = SC_FOLDLEVELBASE;
     if (lineCurrent > 0)
         levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
     int levelNext = levelCurrent;
 
-    for (unsigned int i = safeStartPos; i < startPos + length; i++) {
+    for (Sci_PositionU i = safeStartPos; i < startPos + length; i++) {
         char chCurr = styler.SafeGetCharAt(i);
 
         if ( bArg1 ) {
diff --git a/plugins/scintilla/scintilla/lexers/LexCoffeeScript.cxx 
b/plugins/scintilla/scintilla/lexers/LexCoffeeScript.cxx
index d6e0ea2..63ee172 100644
--- a/plugins/scintilla/scintilla/lexers/LexCoffeeScript.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCoffeeScript.cxx
@@ -31,16 +31,43 @@ using namespace Scintilla;
 #endif
 
 static bool IsSpaceEquiv(int state) {
-       return (state <= SCE_C_COMMENTDOC
-           // including SCE_C_DEFAULT, SCE_C_COMMENT, SCE_C_COMMENTLINE
-           || state == SCE_C_COMMENTLINEDOC
-           || state == SCE_C_COMMENTDOCKEYWORD
-           || state == SCE_C_COMMENTDOCKEYWORDERROR
+       return (state == SCE_COFFEESCRIPT_DEFAULT
+           || state == SCE_COFFEESCRIPT_COMMENTLINE
            || state == SCE_COFFEESCRIPT_COMMENTBLOCK
            || state == SCE_COFFEESCRIPT_VERBOSE_REGEX
            || state == SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT
-           || state == SCE_C_WORD
-           || state == SCE_C_REGEX);
+           || state == SCE_COFFEESCRIPT_WORD
+           || state == SCE_COFFEESCRIPT_REGEX);
+}
+
+// Store the current lexer state and brace count prior to starting a new
+// `#{}` interpolation level.
+// Based on LexRuby.cxx.
+static void enterInnerExpression(int  *p_inner_string_types,
+                                 int  *p_inner_expn_brace_counts,
+                                 int&  inner_string_count,
+                                 int   state,
+                                 int&  brace_counts
+                                 ) {
+       p_inner_string_types[inner_string_count] = state;
+       p_inner_expn_brace_counts[inner_string_count] = brace_counts;
+       brace_counts = 0;
+       ++inner_string_count;
+}
+
+// Restore the lexer state and brace count for the previous `#{}` interpolation
+// level upon returning to it.
+// Note the previous lexer state is the return value and needs to be restored
+// manually by the StyleContext.
+// Based on LexRuby.cxx.
+static int exitInnerExpression(int  *p_inner_string_types,
+                               int  *p_inner_expn_brace_counts,
+                               int&  inner_string_count,
+                               int&  brace_counts
+                              ) {
+       --inner_string_count;
+       brace_counts = p_inner_expn_brace_counts[inner_string_count];
+       return p_inner_string_types[inner_string_count];
 }
 
 // Preconditions: sc.currentPos points to a character after '+' or '-'.
@@ -51,7 +78,7 @@ static bool IsSpaceEquiv(int state) {
 // Putting a space between the '++' post-inc operator and the '+' binary op
 // fixes this, and is highly recommended for readability anyway.
 static bool FollowsPostfixOperator(StyleContext &sc, Accessor &styler) {
-       int pos = (int) sc.currentPos;
+       Sci_Position pos = (Sci_Position) sc.currentPos;
        while (--pos > 0) {
                char ch = styler[pos];
                if (ch == '+' || ch == '-') {
@@ -61,94 +88,71 @@ static bool FollowsPostfixOperator(StyleContext &sc, Accessor &styler) {
        return false;
 }
 
-static bool followsReturnKeyword(StyleContext &sc, Accessor &styler) {
-    // Don't look at styles, so no need to flush.
-       int pos = (int) sc.currentPos;
-       int currentLine = styler.GetLine(pos);
-       int lineStartPos = styler.LineStart(currentLine);
-       char ch;
+static bool followsKeyword(StyleContext &sc, Accessor &styler) {
+       Sci_Position pos = (Sci_Position) sc.currentPos;
+       Sci_Position currentLine = styler.GetLine(pos);
+       Sci_Position lineStartPos = styler.LineStart(currentLine);
        while (--pos > lineStartPos) {
-               ch = styler.SafeGetCharAt(pos);
+               char ch = styler.SafeGetCharAt(pos);
                if (ch != ' ' && ch != '\t') {
                        break;
                }
        }
-       const char *retBack = "nruter";
-       const char *s = retBack;
-       while (*s
-              && pos >= lineStartPos
-              && styler.SafeGetCharAt(pos) == *s) {
-               s++;
-               pos--;
-       }
-       return !*s;
+       styler.Flush();
+       return styler.StyleAt(pos) == SCE_COFFEESCRIPT_WORD;
 }
 
-static void ColouriseCoffeeScriptDoc(unsigned int startPos, int length, int initStyle, WordList 
*keywordlists[],
+static void ColouriseCoffeeScriptDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
        WordList &keywords2 = *keywordlists[1];
-       WordList &keywords3 = *keywordlists[2];
        WordList &keywords4 = *keywordlists[3];
 
-       // property styling.within.preprocessor
-       //      For C++ code, determines whether all preprocessor code is styled in the preprocessor style 
(0, the default)
-       //      or only from the initial # to the end of the command word(1).
-       bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
-
        CharacterSet setOKBeforeRE(CharacterSet::setNone, "([{=,:;!%^&*|?~+-");
        CharacterSet setCouldBePostOp(CharacterSet::setNone, "+-");
 
-       CharacterSet setDoxygen(CharacterSet::setAlpha, "$@\\&<>#{}[]");
-
-       CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
-       CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);
-
-       // property lexer.cpp.allow.dollars
-       //      Set to 0 to disallow the '$' character in identifiers with the cpp lexer.
-       if (styler.GetPropertyInt("lexer.cpp.allow.dollars", 1) != 0) {
-               setWordStart.Add('$');
-               setWord.Add('$');
-       }
+       CharacterSet setWordStart(CharacterSet::setAlpha, "_$@", 0x80, true);
+       CharacterSet setWord(CharacterSet::setAlphaNum, "._$", 0x80, true);
 
        int chPrevNonWhite = ' ';
        int visibleChars = 0;
-       bool lastWordWasUUID = false;
-       int styleBeforeDCKeyword = SCE_C_DEFAULT;
-       bool continuationLine = false;
-       bool isIncludePreprocessor = false;
-
-       if (initStyle == SCE_C_PREPROCESSOR) {
-               // Set continuationLine if last character of previous line is '\'
-               int lineCurrent = styler.GetLine(startPos);
-               if (lineCurrent > 0) {
-                       int chBack = styler.SafeGetCharAt(startPos-1, 0);
-                       int chBack2 = styler.SafeGetCharAt(startPos-2, 0);
-                       int lineEndChar = '!';
-                       if (chBack2 == '\r' && chBack == '\n') {
-                               lineEndChar = styler.SafeGetCharAt(startPos-3, 0);
-                       } else if (chBack == '\n' || chBack == '\r') {
-                               lineEndChar = chBack2;
-                       }
-                       continuationLine = lineEndChar == '\\';
-               }
+
+       // String/Regex interpolation variables, based on LexRuby.cxx.
+       // In most cases a value of 2 should be ample for the code the user is
+       // likely to enter. For example,
+       //   "Filling the #{container} with #{liquid}..."
+       // from the CoffeeScript homepage nests to a level of 2
+       // If the user actually hits a 6th occurrence of '#{' in a double-quoted
+       // string (including regexes), it will stay as a string.  The problem with
+       // this is that quotes might flip, a 7th '#{' will look like a comment,
+       // and code-folding might be wrong.
+#define INNER_STRINGS_MAX_COUNT 5
+       // These vars track our instances of "...#{,,,'..#{,,,}...',,,}..."
+       int inner_string_types[INNER_STRINGS_MAX_COUNT];
+       // Track # braces when we push a new #{ thing
+       int inner_expn_brace_counts[INNER_STRINGS_MAX_COUNT];
+       int inner_string_count = 0;
+       int brace_counts = 0;   // Number of #{ ... } things within an expression
+       for (int i = 0; i < INNER_STRINGS_MAX_COUNT; i++) {
+               inner_string_types[i] = 0;
+               inner_expn_brace_counts[i] = 0;
        }
 
        // look back to set chPrevNonWhite properly for better regex colouring
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
         if (startPos > 0 && IsSpaceEquiv(initStyle)) {
-               unsigned int back = startPos;
+               Sci_PositionU back = startPos;
                styler.Flush();
                while (back > 0 && IsSpaceEquiv(styler.StyleAt(--back)))
                        ;
-               if (styler.StyleAt(back) == SCE_C_OPERATOR) {
+               if (styler.StyleAt(back) == SCE_COFFEESCRIPT_OPERATOR) {
                        chPrevNonWhite = styler.SafeGetCharAt(back);
                }
                if (startPos != back) {
                        initStyle = styler.StyleAt(back);
                        if (IsSpaceEquiv(initStyle)) {
-                               initStyle = SCE_C_DEFAULT;
+                               initStyle = SCE_COFFEESCRIPT_DEFAULT;
                        }
                }
                startPos = back;
@@ -156,146 +160,89 @@ static void ColouriseCoffeeScriptDoc(unsigned int startPos, int length, int init
 
        StyleContext sc(startPos, endPos - startPos, initStyle, styler);
 
-       for (; sc.More(); sc.Forward()) {
+       for (; sc.More();) {
 
                if (sc.atLineStart) {
-                       // Reset states to begining of colourise so no surprises
+                       // Reset states to beginning of colourise so no surprises
                        // if different sets of lines lexed.
                        visibleChars = 0;
-                       lastWordWasUUID = false;
-                       isIncludePreprocessor = false;
-               }
-
-               // Handle line continuation generically.
-               if (sc.ch == '\\') {
-                       if (sc.chNext == '\n' || sc.chNext == '\r') {
-                               sc.Forward();
-                               if (sc.ch == '\r' && sc.chNext == '\n') {
-                                       sc.Forward();
-                               }
-                               continuationLine = true;
-                               continue;
-                       }
                }
 
                // Determine if the current state should terminate.
                switch (sc.state) {
-                       case SCE_C_OPERATOR:
-                               sc.SetState(SCE_C_DEFAULT);
+                       case SCE_COFFEESCRIPT_OPERATOR:
+                               sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                break;
-                       case SCE_C_NUMBER:
+                       case SCE_COFFEESCRIPT_NUMBER:
                                // We accept almost anything because of hex. and number suffixes
-                               if (!setWord.Contains(sc.ch)) {
-                                       sc.SetState(SCE_C_DEFAULT);
+                               if (!setWord.Contains(sc.ch) || sc.Match('.', '.')) {
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
-                       case SCE_C_IDENTIFIER:
+                       case SCE_COFFEESCRIPT_IDENTIFIER:
                                if (!setWord.Contains(sc.ch) || (sc.ch == '.') || (sc.ch == '$')) {
                                        char s[1000];
                                        sc.GetCurrent(s, sizeof(s));
                                        if (keywords.InList(s)) {
-                                               lastWordWasUUID = strcmp(s, "uuid") == 0;
-                                               sc.ChangeState(SCE_C_WORD);
+                                               sc.ChangeState(SCE_COFFEESCRIPT_WORD);
                                        } else if (keywords2.InList(s)) {
-                                               sc.ChangeState(SCE_C_WORD2);
+                                               sc.ChangeState(SCE_COFFEESCRIPT_WORD2);
                                        } else if (keywords4.InList(s)) {
-                                               sc.ChangeState(SCE_C_GLOBALCLASS);
-                                       }
-                                       sc.SetState(SCE_C_DEFAULT);
-                               }
-                               break;
-                       case SCE_C_PREPROCESSOR:
-                               if (sc.atLineStart && !continuationLine) {
-                                       sc.SetState(SCE_C_DEFAULT);
-                               } else if (stylingWithinPreprocessor) {
-                                       if (IsASpace(sc.ch)) {
-                                               sc.SetState(SCE_C_DEFAULT);
-                                       }
-                               } else {
-                                       if (sc.Match('/', '*') || sc.Match('/', '/')) {
-                                               sc.SetState(SCE_C_DEFAULT);
+                                               sc.ChangeState(SCE_COFFEESCRIPT_GLOBALCLASS);
+                                       } else if (sc.LengthCurrent() > 0 && s[0] == '@') {
+                                               sc.ChangeState(SCE_COFFEESCRIPT_INSTANCEPROPERTY);
                                        }
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
-                       case SCE_C_COMMENT:
-                               if (sc.Match('*', '/')) {
-                                       sc.Forward();
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
-                               }
-                               break;
-                       case SCE_C_COMMENTDOC:
-                               if (sc.Match('*', '/')) {
-                                       sc.Forward();
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
-                               } else if (sc.ch == '@' || sc.ch == '\\') { // JavaDoc and Doxygen support
-                                       // Verify that we have the conditions to mark a comment-doc-keyword
-                                       if ((IsASpace(sc.chPrev) || sc.chPrev == '*') && 
(!IsASpace(sc.chNext))) {
-                                               styleBeforeDCKeyword = SCE_C_COMMENTDOC;
-                                               sc.SetState(SCE_C_COMMENTDOCKEYWORD);
-                                       }
-                               }
-                               break;
-                       case SCE_C_COMMENTLINE:
-                               if (sc.atLineStart) {
-                                       sc.SetState(SCE_C_DEFAULT);
+                       case SCE_COFFEESCRIPT_WORD:
+                       case SCE_COFFEESCRIPT_WORD2:
+                       case SCE_COFFEESCRIPT_GLOBALCLASS:
+                       case SCE_COFFEESCRIPT_INSTANCEPROPERTY:
+                               if (!setWord.Contains(sc.ch)) {
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
-                       case SCE_C_COMMENTLINEDOC:
+                       case SCE_COFFEESCRIPT_COMMENTLINE:
                                if (sc.atLineStart) {
-                                       sc.SetState(SCE_C_DEFAULT);
-                               } else if (sc.ch == '@' || sc.ch == '\\') { // JavaDoc and Doxygen support
-                                       // Verify that we have the conditions to mark a comment-doc-keyword
-                                       if ((IsASpace(sc.chPrev) || sc.chPrev == '/' || sc.chPrev == '!') && 
(!IsASpace(sc.chNext))) {
-                                               styleBeforeDCKeyword = SCE_C_COMMENTLINEDOC;
-                                               sc.SetState(SCE_C_COMMENTDOCKEYWORD);
-                                       }
-                               }
-                               break;
-                       case SCE_C_COMMENTDOCKEYWORD:
-                               if ((styleBeforeDCKeyword == SCE_C_COMMENTDOC) && sc.Match('*', '/')) {
-                                       sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
-                                       sc.Forward();
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
-                               } else if (!setDoxygen.Contains(sc.ch)) {
-                                       char s[100];
-                                       sc.GetCurrent(s, sizeof(s));
-                                       if (!IsASpace(sc.ch) || !keywords3.InList(s + 1)) {
-                                               sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
-                                       }
-                                       sc.SetState(styleBeforeDCKeyword);
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
-                       case SCE_C_STRING:
-                               if (isIncludePreprocessor) {
-                                       if (sc.ch == '>') {
-                                               sc.ForwardSetState(SCE_C_DEFAULT);
-                                               isIncludePreprocessor = false;
-                                       }
-                               } else if (sc.ch == '\\') {
+                       case SCE_COFFEESCRIPT_STRING:
+                               if (sc.ch == '\\') {
                                        if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
                                                sc.Forward();
                                        }
                                } else if (sc.ch == '\"') {
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
+                                       sc.ForwardSetState(SCE_COFFEESCRIPT_DEFAULT);
+                               } else if (sc.ch == '#' && sc.chNext == '{' && inner_string_count < 
INNER_STRINGS_MAX_COUNT) {
+                                       // process interpolated code #{ ... }
+                                       enterInnerExpression(inner_string_types,
+                                                            inner_expn_brace_counts,
+                                                            inner_string_count,
+                                                            sc.state,
+                                                            brace_counts);
+                                       sc.SetState(SCE_COFFEESCRIPT_OPERATOR);
+                                       sc.ForwardSetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
-                       case SCE_C_CHARACTER:
+                       case SCE_COFFEESCRIPT_CHARACTER:
                                if (sc.ch == '\\') {
                                        if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
                                                sc.Forward();
                                        }
                                } else if (sc.ch == '\'') {
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
+                                       sc.ForwardSetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
-                       case SCE_C_REGEX:
+                       case SCE_COFFEESCRIPT_REGEX:
                                if (sc.atLineStart) {
-                                       sc.SetState(SCE_C_DEFAULT);
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                } else if (sc.ch == '/') {
                                        sc.Forward();
                                        while ((sc.ch < 0x80) && islower(sc.ch))
                                                sc.Forward();    // gobble regex flags
-                                       sc.SetState(SCE_C_DEFAULT);
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                } else if (sc.ch == '\\') {
                                        // Gobble up the quoted character
                                        if (sc.chNext == '\\' || sc.chNext == '/') {
@@ -303,30 +250,16 @@ static void ColouriseCoffeeScriptDoc(unsigned int startPos, int length, int init
                                        }
                                }
                                break;
-                       case SCE_C_STRINGEOL:
+                       case SCE_COFFEESCRIPT_STRINGEOL:
                                if (sc.atLineStart) {
-                                       sc.SetState(SCE_C_DEFAULT);
-                               }
-                               break;
-                       case SCE_C_VERBATIM:
-                               if (sc.ch == '\"') {
-                                       if (sc.chNext == '\"') {
-                                               sc.Forward();
-                                       } else {
-                                               sc.ForwardSetState(SCE_C_DEFAULT);
-                                       }
-                               }
-                               break;
-                       case SCE_C_UUID:
-                               if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
-                                       sc.SetState(SCE_C_DEFAULT);
+                                       sc.SetState(SCE_COFFEESCRIPT_DEFAULT);
                                }
                                break;
                        case SCE_COFFEESCRIPT_COMMENTBLOCK:
                                if (sc.Match("###")) {
                                        sc.Forward();
                                        sc.Forward();
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
+                                       sc.ForwardSetState(SCE_COFFEESCRIPT_DEFAULT);
                                } else if (sc.ch == '\\') {
                                        sc.Forward();
                                }
@@ -335,7 +268,7 @@ static void ColouriseCoffeeScriptDoc(unsigned int startPos, int length, int init
                                if (sc.Match("///")) {
                                        sc.Forward();
                                        sc.Forward();
-                                       sc.ForwardSetState(SCE_C_DEFAULT);
+                                       sc.ForwardSetState(SCE_COFFEESCRIPT_DEFAULT);
                                } else if (sc.Match('#')) {
                                        sc.SetState(SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT);
                                } else if (sc.ch == '\\') {
@@ -350,59 +283,48 @@ static void ColouriseCoffeeScriptDoc(unsigned int startPos, int length, int init
                }
 
                // Determine if a new state should be entered.
-               if (sc.state == SCE_C_DEFAULT) {
-                       if (sc.Match('@', '\"')) {
-                               sc.SetState(SCE_C_VERBATIM);
-                               sc.Forward();
-                       } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
-                               if (lastWordWasUUID) {
-                                       sc.SetState(SCE_C_UUID);
-                                       lastWordWasUUID = false;
-                               } else {
-                                       sc.SetState(SCE_C_NUMBER);
-                               }
-                       } else if (setWordStart.Contains(sc.ch) || (sc.ch == '@') || (sc.ch == '$')) {
-                               if (lastWordWasUUID) {
-                                       sc.SetState(SCE_C_UUID);
-                                       lastWordWasUUID = false;
-                               } else {
-                                       sc.SetState(SCE_C_IDENTIFIER);
-                               }
-                       } else if (sc.Match('/', '*')) {
-                               if (sc.Match("/**") || sc.Match("/*!")) {       // Support of Qt/Doxygen doc. 
style
-                                       sc.SetState(SCE_C_COMMENTDOC);
-                               } else {
-                                       sc.SetState(SCE_C_COMMENT);
-                               }
-                               sc.Forward();   // Eat the * so it isn't used for the end of the comment
+               if (sc.state == SCE_COFFEESCRIPT_DEFAULT) {
+                       if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+                               sc.SetState(SCE_COFFEESCRIPT_NUMBER);
+                       } else if (setWordStart.Contains(sc.ch)) {
+                               sc.SetState(SCE_COFFEESCRIPT_IDENTIFIER);
                        } else if (sc.Match("///")) {
                                sc.SetState(SCE_COFFEESCRIPT_VERBOSE_REGEX);
                                sc.Forward();
                                sc.Forward();
                        } else if (sc.ch == '/'
                                   && (setOKBeforeRE.Contains(chPrevNonWhite)
-                                      || followsReturnKeyword(sc, styler))
+                                      || followsKeyword(sc, styler))
                                   && (!setCouldBePostOp.Contains(chPrevNonWhite)
                                       || !FollowsPostfixOperator(sc, styler))) {
-                               sc.SetState(SCE_C_REGEX);       // JavaScript's RegEx
+                               sc.SetState(SCE_COFFEESCRIPT_REGEX);    // JavaScript's RegEx
                        } else if (sc.ch == '\"') {
-                               sc.SetState(SCE_C_STRING);
-                               isIncludePreprocessor = false;  // ensure that '>' won't end the string
-                       } else if (isIncludePreprocessor && sc.ch == '<') {
-                               sc.SetState(SCE_C_STRING);
+                               sc.SetState(SCE_COFFEESCRIPT_STRING);
                        } else if (sc.ch == '\'') {
-                               sc.SetState(SCE_C_CHARACTER);
+                               sc.SetState(SCE_COFFEESCRIPT_CHARACTER);
                        } else if (sc.ch == '#') {
                                if (sc.Match("###")) {
                                        sc.SetState(SCE_COFFEESCRIPT_COMMENTBLOCK);
                                        sc.Forward();
                                        sc.Forward();
-                                       
                                } else {
-                                       sc.SetState(SCE_C_COMMENTLINE);
+                                       sc.SetState(SCE_COFFEESCRIPT_COMMENTLINE);
                                }
                        } else if (isoperator(static_cast<char>(sc.ch))) {
-                               sc.SetState(SCE_C_OPERATOR);
+                               sc.SetState(SCE_COFFEESCRIPT_OPERATOR);
+                               // Handle '..' and '...' operators correctly.
+                               if (sc.ch == '.') {
+                                       for (int i = 0; i < 2 && sc.chNext == '.'; i++, sc.Forward()) ;
+                               } else if (sc.ch == '{') {
+                                       ++brace_counts;
+                               } else if (sc.ch == '}' && --brace_counts <= 0 && inner_string_count > 0) {
+                                       // Return to previous state before #{ ... }
+                                       sc.ForwardSetState(exitInnerExpression(inner_string_types,
+                                                                              inner_expn_brace_counts,
+                                                                              inner_string_count,
+                                                                              brace_counts));
+                                       continue; // skip sc.Forward() at loop end
+                               }
                        }
                }
 
@@ -410,34 +332,30 @@ static void ColouriseCoffeeScriptDoc(unsigned int startPos, int length, int init
                        chPrevNonWhite = sc.ch;
                        visibleChars++;
                }
-               continuationLine = false;
+               sc.Forward();
        }
        sc.Complete();
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eol_pos; i++) {
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
                char ch = styler[i];
                if (ch == '#')
                        return true;
-        else if (ch == '/'
-                 && i < eol_pos - 1
-                 && styler[i + 1] == '*')
-                       return true;
                else if (ch != ' ' && ch != '\t')
                        return false;
        }
        return false;
 }
 
-static void FoldCoffeeScriptDoc(unsigned int startPos, int length, int,
+static void FoldCoffeeScriptDoc(Sci_PositionU startPos, Sci_Position length, int,
                                WordList *[], Accessor &styler) {
        // A simplified version of FoldPyDoc
-       const int maxPos = startPos + length;
-       const int maxLines = styler.GetLine(maxPos - 1);             // Requested last line
-       const int docLines = styler.GetLine(styler.Length() - 1);  // Available last line
+       const Sci_Position maxPos = startPos + length;
+       const Sci_Position maxLines = styler.GetLine(maxPos - 1);             // Requested last line
+       const Sci_Position docLines = styler.GetLine(styler.Length() - 1);  // Available last line
 
        // property fold.coffeescript.comment
        const bool foldComment = styler.GetPropertyInt("fold.coffeescript.comment") != 0;
@@ -449,7 +367,7 @@ static void FoldCoffeeScriptDoc(unsigned int startPos, int length, int,
        // and so we can fix any preceding fold level (which is why we go back
        // at least one line in all cases)
        int spaceFlags = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
        while (lineCurrent > 0) {
                lineCurrent--;
@@ -472,7 +390,7 @@ static void FoldCoffeeScriptDoc(unsigned int startPos, int length, int,
 
                // Gather info
                int lev = indentCurrent;
-               int lineNext = lineCurrent + 1;
+               Sci_Position lineNext = lineCurrent + 1;
                int indentNext = indentCurrent;
                if (lineNext <= docLines) {
                        // Information about next line is only available if not at end of document
@@ -516,7 +434,7 @@ static void FoldCoffeeScriptDoc(unsigned int startPos, int length, int,
                // which is indented more than the line after the end of
                // the comment-block, use the level of the block before
 
-               int skipLine = lineNext;
+               Sci_Position skipLine = lineNext;
                int skipLevel = levelAfterComments;
 
                while (--skipLine > lineCurrent) {
@@ -557,6 +475,9 @@ static void FoldCoffeeScriptDoc(unsigned int startPos, int length, int,
 
 static const char *const csWordLists[] = {
             "Keywords",
+            "Secondary keywords",
+            "Unused",
+            "Global classes",
             0,
 };
 
diff --git a/plugins/scintilla/scintilla/lexers/LexConf.cxx b/plugins/scintilla/scintilla/lexers/LexConf.cxx
index 23ed5a6..2eed51b 100644
--- a/plugins/scintilla/scintilla/lexers/LexConf.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexConf.cxx
@@ -31,14 +31,14 @@
 using namespace Scintilla;
 #endif
 
-static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor 
&styler)
+static void ColouriseConfDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], 
Accessor &styler)
 {
        int state = SCE_CONF_DEFAULT;
        char chNext = styler[startPos];
-       int lengthDoc = startPos + length;
+       Sci_Position lengthDoc = startPos + length;
        // create a buffer large enough to take the largest chunk...
-       char *buffer = new char[length];
-       int bufferCount = 0;
+       char *buffer = new char[length+1];
+       Sci_Position bufferCount = 0;
 
        // this assumes that we have 2 keyword list in conf.properties
        WordList &directives = *keywordLists[0];
@@ -48,7 +48,7 @@ static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *k
        // using the hand-written state machine shown below
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
-       for (int i = startPos; i < lengthDoc; i++) {
+       for (Sci_Position i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -74,17 +74,17 @@ static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *k
                                } else if( ch == '"') {
                                        state = SCE_CONF_STRING;
                                        styler.ColourTo(i,SCE_CONF_STRING);
-                               } else if( isascii(ch) && ispunct(ch) ) {
+                               } else if( IsASCII(ch) && ispunct(ch) ) {
                                        // signals an operator...
                                        // no state jump necessary for this
                                        // simple case...
                                        styler.ColourTo(i,SCE_CONF_OPERATOR);
-                               } else if( isascii(ch) && isalpha(ch) ) {
+                               } else if( IsASCII(ch) && isalpha(ch) ) {
                                        // signals the start of an identifier
                                        bufferCount = 0;
                                        buffer[bufferCount++] = static_cast<char>(tolower(ch));
                                        state = SCE_CONF_IDENTIFIER;
-                               } else if( isascii(ch) && isdigit(ch) ) {
+                               } else if( IsASCII(ch) && isdigit(ch) ) {
                                        // signals the start of a number
                                        bufferCount = 0;
                                        buffer[bufferCount++] = ch;
@@ -111,7 +111,7 @@ static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *k
                                // if we find a non-alphanumeric char,
                                // we simply go to default state
                                // else we're still dealing with an extension...
-                               if( (isascii(ch) && isalnum(ch)) || (ch == '_') ||
+                               if( (IsASCII(ch) && isalnum(ch)) || (ch == '_') ||
                                        (ch == '-') || (ch == '$') ||
                                        (ch == '/') || (ch == '.') || (ch == '*') )
                                {
@@ -133,7 +133,7 @@ static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *k
 
                        case SCE_CONF_IDENTIFIER:
                                // stay  in CONF_IDENTIFIER state until we find a non-alphanumeric
-                               if( (isascii(ch) && isalnum(ch)) || (ch == '_') || (ch == '-') || (ch == '/') 
|| (ch == '$') || (ch == '.') || (ch == '*')) {
+                               if( (IsASCII(ch) && isalnum(ch)) || (ch == '_') || (ch == '-') || (ch == '/') 
|| (ch == '$') || (ch == '.') || (ch == '*')) {
                                        buffer[bufferCount++] = static_cast<char>(tolower(ch));
                                } else {
                                        state = SCE_CONF_DEFAULT;
@@ -158,7 +158,7 @@ static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *k
 
                        case SCE_CONF_NUMBER:
                                // stay  in CONF_NUMBER state until we find a non-numeric
-                               if( (isascii(ch) && isdigit(ch)) || ch == '.') {
+                               if( (IsASCII(ch) && isdigit(ch)) || ch == '.') {
                                        buffer[bufferCount++] = ch;
                                } else {
                                        state = SCE_CONF_DEFAULT;
diff --git a/plugins/scintilla/scintilla/lexers/LexCrontab.cxx 
b/plugins/scintilla/scintilla/lexers/LexCrontab.cxx
index 08abc71..b500d2d 100644
--- a/plugins/scintilla/scintilla/lexers/LexCrontab.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCrontab.cxx
@@ -29,15 +29,15 @@
 using namespace Scintilla;
 #endif
 
-static void ColouriseNncrontabDoc(unsigned int startPos, int length, int, WordList
+static void ColouriseNncrontabDoc(Sci_PositionU startPos, Sci_Position length, int, WordList
 *keywordLists[], Accessor &styler)
 {
        int state = SCE_NNCRONTAB_DEFAULT;
        char chNext = styler[startPos];
-       int lengthDoc = startPos + length;
+       Sci_Position lengthDoc = startPos + length;
        // create a buffer large enough to take the largest chunk...
-       char *buffer = new char[length];
-       int bufferCount = 0;
+       char *buffer = new char[length+1];
+       Sci_Position bufferCount = 0;
        // used when highliting environment variables inside quoted string:
        bool insideString = false;
 
@@ -50,7 +50,7 @@ static void ColouriseNncrontabDoc(unsigned int startPos, int length, int, WordLi
        // using the hand-written state machine shown below
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
-       for (int i = startPos; i < lengthDoc; i++) {
+       for (Sci_Position i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -98,12 +98,12 @@ static void ColouriseNncrontabDoc(unsigned int startPos, int length, int, WordLi
                                        // signals an asterisk
                                        // no state jump necessary for this simple case...
                                        styler.ColourTo(i,SCE_NNCRONTAB_ASTERISK);
-                               } else if( (isascii(ch) && isalpha(ch)) || ch == '<' ) {
+                               } else if( (IsASCII(ch) && isalpha(ch)) || ch == '<' ) {
                                        // signals the start of an identifier
                                        bufferCount = 0;
                                        buffer[bufferCount++] = ch;
                                        state = SCE_NNCRONTAB_IDENTIFIER;
-                               } else if( isascii(ch) && isdigit(ch) ) {
+                               } else if( IsASCII(ch) && isdigit(ch) ) {
                                        // signals the start of a number
                                        bufferCount = 0;
                                        buffer[bufferCount++] = ch;
@@ -171,7 +171,7 @@ static void ColouriseNncrontabDoc(unsigned int startPos, int length, int, WordLi
 
                        case SCE_NNCRONTAB_IDENTIFIER:
                                // stay  in CONF_IDENTIFIER state until we find a non-alphanumeric
-                               if( (isascii(ch) && isalnum(ch)) || (ch == '_') || (ch == '-') || (ch == '/') 
||
+                               if( (IsASCII(ch) && isalnum(ch)) || (ch == '_') || (ch == '-') || (ch == '/') 
||
                                        (ch == '$') || (ch == '.') || (ch == '<') || (ch == '>') ||
                                        (ch == '@') ) {
                                        buffer[bufferCount++] = ch;
@@ -200,7 +200,7 @@ static void ColouriseNncrontabDoc(unsigned int startPos, int length, int, WordLi
 
                        case SCE_NNCRONTAB_NUMBER:
                                // stay  in CONF_NUMBER state until we find a non-numeric
-                               if( isascii(ch) && isdigit(ch) /* || ch == '.' */ ) {
+                               if( IsASCII(ch) && isdigit(ch) /* || ch == '.' */ ) {
                                        buffer[bufferCount++] = ch;
                                } else {
                                        state = SCE_NNCRONTAB_DEFAULT;
diff --git a/plugins/scintilla/scintilla/lexers/LexCsound.cxx 
b/plugins/scintilla/scintilla/lexers/LexCsound.cxx
index 8e5880c..6d065c8 100644
--- a/plugins/scintilla/scintilla/lexers/LexCsound.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCsound.cxx
@@ -39,7 +39,7 @@ static inline bool IsAWordStart(const int ch) {
 }
 
 static inline bool IsCsoundOperator(char ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        // '.' left out as it is used to make up numbers
        if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
@@ -51,7 +51,7 @@ static inline bool IsCsoundOperator(char ch) {
        return false;
 }
 
-static void ColouriseCsoundDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseCsoundDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                                Accessor &styler) {
 
        WordList &opcode = *keywordlists[0];
@@ -150,17 +150,17 @@ static void ColouriseCsoundDoc(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-static void FoldCsoundInstruments(unsigned int startPos, int length, int /* initStyle */, WordList *[],
+static void FoldCsoundInstruments(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList 
*[],
                Accessor &styler) {
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int stylePrev = 0;
        int styleNext = styler.StyleAt(startPos);
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
diff --git a/plugins/scintilla/scintilla/lexers/LexD.cxx b/plugins/scintilla/scintilla/lexers/LexD.cxx
index 32e3c86..ededccd 100644
--- a/plugins/scintilla/scintilla/lexers/LexD.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexD.cxx
@@ -41,15 +41,15 @@ using namespace Scintilla;
 // Underscore, letter, digit and universal alphas from C99 Appendix D.
 
 static bool IsWordStart(int ch) {
-       return (isascii(ch) && (isalpha(ch) || ch == '_')) || !isascii(ch);
+       return (IsASCII(ch) && (isalpha(ch) || ch == '_')) || !IsASCII(ch);
 }
 
 static bool IsWord(int ch) {
-       return (isascii(ch) && (isalnum(ch) || ch == '_')) || !isascii(ch);
+       return (IsASCII(ch) && (isalnum(ch) || ch == '_')) || !IsASCII(ch);
 }
 
 static bool IsDoxygen(int ch) {
-       if (isascii(ch) && islower(ch))
+       if (IsASCII(ch) && islower(ch))
                return true;
        if (ch == '$' || ch == '@' || ch == '\\' ||
                ch == '&' || ch == '#' || ch == '<' || ch == '>' ||
@@ -162,30 +162,30 @@ public:
        }
        virtual ~LexerD() {
        }
-       void SCI_METHOD Release() {
+       void SCI_METHOD Release() override {
                delete this;
        }
-       int SCI_METHOD Version() const {
+       int SCI_METHOD Version() const override {
                return lvOriginal;
        }
-       const char * SCI_METHOD PropertyNames() {
+       const char * SCI_METHOD PropertyNames() override {
                return osD.PropertyNames();
        }
-       int SCI_METHOD PropertyType(const char *name) {
+       int SCI_METHOD PropertyType(const char *name) override {
                return osD.PropertyType(name);
        }
-       const char * SCI_METHOD DescribeProperty(const char *name) {
+       const char * SCI_METHOD DescribeProperty(const char *name) override {
                return osD.DescribeProperty(name);
        }
-       int SCI_METHOD PropertySet(const char *key, const char *val);
-       const char * SCI_METHOD DescribeWordListSets() {
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char * SCI_METHOD DescribeWordListSets() override {
                return osD.DescribeWordListSets();
        }
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-       void * SCI_METHOD PrivateCall(int, void *) {
+       void * SCI_METHOD PrivateCall(int, void *) override {
                return 0;
        }
 
@@ -197,14 +197,14 @@ public:
        }
 };
 
-int SCI_METHOD LexerD::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerD::PropertySet(const char *key, const char *val) {
        if (osD.PropertySet(&options, key, val)) {
                return 0;
        }
        return -1;
 }
 
-int SCI_METHOD LexerD::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerD::WordListSet(int n, const char *wl) {
        WordList *wordListN = 0;
        switch (n) {
        case 0:
@@ -229,7 +229,7 @@ int SCI_METHOD LexerD::WordListSet(int n, const char *wl) {
                wordListN = &keywords7;
                break;
        }
-       int firstModification = -1;
+       Sci_Position firstModification = -1;
        if (wordListN) {
                WordList wlNew;
                wlNew.Set(wl);
@@ -241,14 +241,14 @@ int SCI_METHOD LexerD::WordListSet(int n, const char *wl) {
        return firstModification;
 }
 
-void SCI_METHOD LexerD::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerD::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) {
        LexAccessor styler(pAccess);
 
        int styleBeforeDCKeyword = SCE_D_DEFAULT;
 
        StyleContext sc(startPos, length, initStyle, styler);
 
-       int curLine = styler.GetLine(startPos);
+       Sci_Position curLine = styler.GetLine(startPos);
        int curNcLevel = curLine > 0? styler.GetLineState(curLine-1): 0;
        bool numFloat = false; // Float literals have '+' and '-' signs
        bool numHex = false;
@@ -267,7 +267,7 @@ void SCI_METHOD LexerD::Lex(unsigned int startPos, int length, int initStyle, ID
                                break;
                        case SCE_D_NUMBER:
                                // We accept almost anything because of hex. and number suffixes
-                               if (isascii(sc.ch) && (isalnum(sc.ch) || sc.ch == '_')) {
+                               if (IsASCII(sc.ch) && (isalnum(sc.ch) || sc.ch == '_')) {
                                        continue;
                                } else if (sc.ch == '.' && sc.chNext != '.' && !numFloat) {
                                        // Don't parse 0..2 as number.
@@ -471,16 +471,16 @@ void SCI_METHOD LexerD::Lex(unsigned int startPos, int length, int initStyle, ID
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
 
-void SCI_METHOD LexerD::Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerD::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
{
 
        if (!options.fold)
                return;
 
        LexAccessor styler(pAccess);
 
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -491,7 +491,7 @@ void SCI_METHOD LexerD::Fold(unsigned int startPos, int length, int initStyle, I
        int style = initStyle;
        bool foldAtElse = options.foldAtElseInt >= 0 ? options.foldAtElseInt != 0 : options.foldAtElse;
        const bool userDefinedFoldMarkers = !options.foldExplicitStart.empty() && 
!options.foldExplicitEnd.empty();
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexDMAP.cxx b/plugins/scintilla/scintilla/lexers/LexDMAP.cxx
new file mode 100644
index 0000000..eb43cde
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexDMAP.cxx
@@ -0,0 +1,228 @@
+// Scintilla source code edit control
+/** @file LexDMAP.cxx
+ ** Lexer for MSC Nastran DMAP.
+ ** Written by Mark Robinson, based on the Fortran lexer by Chuan-jian Shen, Last changed Aug. 2013
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+/***************************************/
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+/***************************************/
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+/***************************************/
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+/***********************************************/
+static inline bool IsAWordChar(const int ch) {
+    return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '%');
+}
+/**********************************************/
+static inline bool IsAWordStart(const int ch) {
+    return (ch < 0x80) && (isalnum(ch));
+}
+/***************************************/
+static void ColouriseDMAPDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+            WordList *keywordlists[], Accessor &styler) {
+    WordList &keywords = *keywordlists[0];
+    WordList &keywords2 = *keywordlists[1];
+    WordList &keywords3 = *keywordlists[2];
+    /***************************************/
+    Sci_Position posLineStart = 0, numNonBlank = 0;
+    Sci_Position endPos = startPos + length;
+    /***************************************/
+    // backtrack to the nearest keyword
+    while ((startPos > 1) && (styler.StyleAt(startPos) != SCE_DMAP_WORD)) {
+        startPos--;
+    }
+    startPos = styler.LineStart(styler.GetLine(startPos));
+    initStyle = styler.StyleAt(startPos - 1);
+    StyleContext sc(startPos, endPos-startPos, initStyle, styler);
+    /***************************************/
+    for (; sc.More(); sc.Forward()) {
+        // remember the start position of the line
+        if (sc.atLineStart) {
+            posLineStart = sc.currentPos;
+            numNonBlank = 0;
+            sc.SetState(SCE_DMAP_DEFAULT);
+        }
+        if (!IsASpaceOrTab(sc.ch)) numNonBlank ++;
+        /***********************************************/
+        // Handle data appearing after column 72; it is ignored
+        Sci_Position toLineStart = sc.currentPos - posLineStart;
+        if (toLineStart >= 72 || sc.ch == '$') {
+            sc.SetState(SCE_DMAP_COMMENT);
+            while (!sc.atLineEnd && sc.More()) sc.Forward(); // Until line end
+            continue;
+        }
+        /***************************************/
+        // Determine if the current state should terminate.
+        if (sc.state == SCE_DMAP_OPERATOR) {
+            sc.SetState(SCE_DMAP_DEFAULT);
+        } else if (sc.state == SCE_DMAP_NUMBER) {
+            if (!(IsAWordChar(sc.ch) || sc.ch=='\'' || sc.ch=='\"' || sc.ch=='.')) {
+                sc.SetState(SCE_DMAP_DEFAULT);
+            }
+        } else if (sc.state == SCE_DMAP_IDENTIFIER) {
+            if (!IsAWordChar(sc.ch) || (sc.ch == '%')) {
+                char s[100];
+                sc.GetCurrentLowered(s, sizeof(s));
+                if (keywords.InList(s)) {
+                    sc.ChangeState(SCE_DMAP_WORD);
+                } else if (keywords2.InList(s)) {
+                    sc.ChangeState(SCE_DMAP_WORD2);
+                } else if (keywords3.InList(s)) {
+                    sc.ChangeState(SCE_DMAP_WORD3);
+                }
+                sc.SetState(SCE_DMAP_DEFAULT);
+            }
+        } else if (sc.state == SCE_DMAP_COMMENT) {
+            if (sc.ch == '\r' || sc.ch == '\n') {
+                sc.SetState(SCE_DMAP_DEFAULT);
+            }
+        } else if (sc.state == SCE_DMAP_STRING1) {
+            if (sc.ch == '\'') {
+                if (sc.chNext == '\'') {
+                    sc.Forward();
+                } else {
+                    sc.ForwardSetState(SCE_DMAP_DEFAULT);
+                }
+            } else if (sc.atLineEnd) {
+                sc.ChangeState(SCE_DMAP_STRINGEOL);
+                sc.ForwardSetState(SCE_DMAP_DEFAULT);
+            }
+        } else if (sc.state == SCE_DMAP_STRING2) {
+            if (sc.atLineEnd) {
+                sc.ChangeState(SCE_DMAP_STRINGEOL);
+                sc.ForwardSetState(SCE_DMAP_DEFAULT);
+            } else if (sc.ch == '\"') {
+                if (sc.chNext == '\"') {
+                    sc.Forward();
+                } else {
+                    sc.ForwardSetState(SCE_DMAP_DEFAULT);
+                }
+            }
+        }
+        /***************************************/
+        // Determine if a new state should be entered.
+        if (sc.state == SCE_DMAP_DEFAULT) {
+            if (sc.ch == '$') {
+                sc.SetState(SCE_DMAP_COMMENT);
+            } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext)) || (sc.ch == '-' && 
IsADigit(sc.chNext))) {
+                sc.SetState(SCE_F_NUMBER);
+            } else if (IsAWordStart(sc.ch)) {
+                sc.SetState(SCE_DMAP_IDENTIFIER);
+            } else if (sc.ch == '\"') {
+                sc.SetState(SCE_DMAP_STRING2);
+            } else if (sc.ch == '\'') {
+                sc.SetState(SCE_DMAP_STRING1);
+            } else if (isoperator(static_cast<char>(sc.ch))) {
+                sc.SetState(SCE_DMAP_OPERATOR);
+            }
+        }
+    }
+    sc.Complete();
+}
+/***************************************/
+// To determine the folding level depending on keywords
+static int classifyFoldPointDMAP(const char* s, const char* prevWord) {
+    int lev = 0;
+    if ((strcmp(prevWord, "else") == 0 && strcmp(s, "if") == 0) || strcmp(s, "enddo") == 0 || strcmp(s, 
"endif") == 0) {
+        lev = -1;
+    } else if ((strcmp(prevWord, "do") == 0 && strcmp(s, "while") == 0) || strcmp(s, "then") == 0) {
+        lev = 1;
+    }
+    return lev;
+}
+// Folding the code
+static void FoldDMAPDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+                           WordList *[], Accessor &styler) {
+    //
+    // bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
+    // Do not know how to fold the comment at the moment.
+    //
+    bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
+    Sci_PositionU endPos = startPos + length;
+    int visibleChars = 0;
+    Sci_Position lineCurrent = styler.GetLine(startPos);
+    int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
+    int levelCurrent = levelPrev;
+    char chNext = styler[startPos];
+    int styleNext = styler.StyleAt(startPos);
+    int style = initStyle;
+    /***************************************/
+    Sci_Position lastStart = 0;
+    char prevWord[32] = "";
+    /***************************************/
+    for (Sci_PositionU i = startPos; i < endPos; i++) {
+        char ch = chNext;
+        chNext = styler.SafeGetCharAt(i + 1);
+        int stylePrev = style;
+        style = styleNext;
+        styleNext = styler.StyleAt(i + 1);
+        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+        //
+        if ((stylePrev == SCE_DMAP_DEFAULT || stylePrev == SCE_DMAP_OPERATOR || stylePrev == 
SCE_DMAP_COMMENT) && (style == SCE_DMAP_WORD)) {
+            // Store last word and label start point.
+            lastStart = i;
+        }
+        /***************************************/
+        if (style == SCE_DMAP_WORD) {
+            if(iswordchar(ch) && !iswordchar(chNext)) {
+                char s[32];
+                Sci_PositionU k;
+                for(k=0; (k<31 ) && (k<i-lastStart+1 ); k++) {
+                    s[k] = static_cast<char>(tolower(styler[lastStart+k]));
+                }
+                s[k] = '\0';
+                levelCurrent += classifyFoldPointDMAP(s, prevWord);
+                strcpy(prevWord, s);
+            }
+        }
+        if (atEOL) {
+            int lev = levelPrev;
+            if (visibleChars == 0 && foldCompact)
+                lev |= SC_FOLDLEVELWHITEFLAG;
+            if ((levelCurrent > levelPrev) && (visibleChars > 0))
+                lev |= SC_FOLDLEVELHEADERFLAG;
+            if (lev != styler.LevelAt(lineCurrent)) {
+                styler.SetLevel(lineCurrent, lev);
+            }
+            lineCurrent++;
+            levelPrev = levelCurrent;
+            visibleChars = 0;
+            strcpy(prevWord, "");
+        }
+        /***************************************/
+        if (!isspacechar(ch)) visibleChars++;
+    }
+    /***************************************/
+    // Fill in the real level of the next line, keeping the current flags as they will be filled in later
+    int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
+    styler.SetLevel(lineCurrent, levelPrev | flagsNext);
+}
+/***************************************/
+static const char * const DMAPWordLists[] = {
+    "Primary keywords and identifiers",
+    "Intrinsic functions",
+    "Extended and user defined functions",
+    0,
+};
+/***************************************/
+LexerModule lmDMAP(SCLEX_DMAP, ColouriseDMAPDoc, "DMAP", FoldDMAPDoc, DMAPWordLists);
diff --git a/plugins/scintilla/scintilla/lexers/LexDMIS.cxx b/plugins/scintilla/scintilla/lexers/LexDMIS.cxx
new file mode 100644
index 0000000..8700d53
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexDMIS.cxx
@@ -0,0 +1,355 @@
+// Scintilla source code edit control
+/** @file LexDMIS.cxx
+ ** Lexer for DMIS.
+  **/
+// Copyright 1998-2005 by Neil Hodgson <neilh scintilla org>
+// Copyright 2013-2014 by Andreas Tscharner <andy vis ethz ch>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cctype>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+
+static const char *const DMISWordListDesc[] = {
+       "DMIS Major Words",
+       "DMIS Minor Words",
+       "Unsupported DMIS Major Words",
+       "Unsupported DMIS Minor Words",
+       "Keywords for code folding start",
+       "Corresponding keywords for code folding end",
+       0
+};
+
+
+class LexerDMIS : public ILexer
+{
+       private:
+               char *m_wordListSets;
+               WordList m_majorWords;
+               WordList m_minorWords;
+               WordList m_unsupportedMajor;
+               WordList m_unsupportedMinor;
+               WordList m_codeFoldingStart;
+               WordList m_codeFoldingEnd;
+
+               char * SCI_METHOD UpperCase(char *item);
+               void SCI_METHOD InitWordListSets(void);
+
+       public:
+               LexerDMIS(void);
+               virtual ~LexerDMIS(void);
+
+               int SCI_METHOD Version() const override {
+                       return lvOriginal;
+               }
+
+               void SCI_METHOD Release() override {
+                       delete this;
+               }
+
+               const char * SCI_METHOD PropertyNames() override {
+                       return NULL;
+               }
+
+               int SCI_METHOD PropertyType(const char *) override {
+                       return -1;
+               }
+
+               const char * SCI_METHOD DescribeProperty(const char *) override {
+                       return NULL;
+               }
+
+               Sci_Position SCI_METHOD PropertySet(const char *, const char *) override {
+                       return -1;
+               }
+
+               Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+
+               void * SCI_METHOD PrivateCall(int, void *) override {
+                       return NULL;
+               }
+
+               static ILexer *LexerFactoryDMIS() {
+                       return new LexerDMIS;
+               }
+
+               const char * SCI_METHOD DescribeWordListSets() override;
+               void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) override;
+               void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) override;
+};
+
+
+char * SCI_METHOD LexerDMIS::UpperCase(char *item)
+{
+       char *itemStart;
+
+
+       itemStart = item;
+       while (item && *item) {
+               *item = toupper(*item);
+               item++;
+       };
+       return itemStart;
+}
+
+void SCI_METHOD LexerDMIS::InitWordListSets(void)
+{
+       size_t totalLen = 0;
+
+
+       for (int i=0; DMISWordListDesc[i]; i++) {
+               totalLen += strlen(DMISWordListDesc[i]);
+               totalLen++;
+       };
+
+       totalLen++;
+       this->m_wordListSets = new char[totalLen];
+       memset(this->m_wordListSets, 0, totalLen);
+
+       for (int i=0; DMISWordListDesc[i]; i++) {
+               strcat(this->m_wordListSets, DMISWordListDesc[i]);
+               strcat(this->m_wordListSets, "\n");
+       };
+}
+
+
+LexerDMIS::LexerDMIS(void) {
+       this->InitWordListSets();
+
+       this->m_majorWords.Clear();
+       this->m_minorWords.Clear();
+       this->m_unsupportedMajor.Clear();
+       this->m_unsupportedMinor.Clear();
+       this->m_codeFoldingStart.Clear();
+       this->m_codeFoldingEnd.Clear();
+}
+
+LexerDMIS::~LexerDMIS(void) {
+       delete[] this->m_wordListSets;
+}
+
+Sci_Position SCI_METHOD LexerDMIS::WordListSet(int n, const char *wl)
+{
+       switch (n) {
+               case 0:
+                       this->m_majorWords.Clear();
+                       this->m_majorWords.Set(wl);
+                       break;
+               case 1:
+                       this->m_minorWords.Clear();
+                       this->m_minorWords.Set(wl);
+                       break;
+               case 2:
+                       this->m_unsupportedMajor.Clear();
+                       this->m_unsupportedMajor.Set(wl);
+                       break;
+               case 3:
+                       this->m_unsupportedMinor.Clear();
+                       this->m_unsupportedMinor.Set(wl);
+                       break;
+               case 4:
+                       this->m_codeFoldingStart.Clear();
+                       this->m_codeFoldingStart.Set(wl);
+                       break;
+               case 5:
+                       this->m_codeFoldingEnd.Clear();
+                       this->m_codeFoldingEnd.Set(wl);
+                       break;
+               default:
+                       return -1;
+                       break;
+       }
+
+       return 0;
+}
+
+const char * SCI_METHOD LexerDMIS::DescribeWordListSets()
+{
+       return this->m_wordListSets;
+}
+
+void SCI_METHOD LexerDMIS::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess)
+{
+       const Sci_PositionU MAX_STR_LEN = 100;
+
+       LexAccessor styler(pAccess);
+       StyleContext scCTX(startPos, lengthDoc, initStyle, styler);
+       CharacterSet setDMISNumber(CharacterSet::setDigits, ".-+eE");
+       CharacterSet setDMISWordStart(CharacterSet::setAlpha, "-234", 0x80, true);
+       CharacterSet setDMISWord(CharacterSet::setAlpha);
+
+
+       bool isIFLine = false;
+
+       for (; scCTX.More(); scCTX.Forward()) {
+               if (scCTX.atLineEnd) {
+                       isIFLine = false;
+               };
+
+               switch (scCTX.state) {
+                       case SCE_DMIS_DEFAULT:
+                               if (scCTX.Match('$', '$')) {
+                                       scCTX.SetState(SCE_DMIS_COMMENT);
+                                       scCTX.Forward();
+                               };
+                               if (scCTX.Match('\'')) {
+                                       scCTX.SetState(SCE_DMIS_STRING);
+                               };
+                               if (IsADigit(scCTX.ch) || ((scCTX.Match('-') || scCTX.Match('+')) && 
IsADigit(scCTX.chNext))) {
+                                       scCTX.SetState(SCE_DMIS_NUMBER);
+                                       break;
+                               };
+                               if (setDMISWordStart.Contains(scCTX.ch)) {
+                                       scCTX.SetState(SCE_DMIS_KEYWORD);
+                               };
+                               if (scCTX.Match('(') && (!isIFLine)) {
+                                       scCTX.SetState(SCE_DMIS_LABEL);
+                               };
+                               break;
+
+                       case SCE_DMIS_COMMENT:
+                               if (scCTX.atLineEnd) {
+                                       scCTX.SetState(SCE_DMIS_DEFAULT);
+                               };
+                               break;
+
+                       case SCE_DMIS_STRING:
+                               if (scCTX.Match('\'')) {
+                                       scCTX.SetState(SCE_DMIS_DEFAULT);
+                               };
+                               break;
+
+                       case SCE_DMIS_NUMBER:
+                               if (!setDMISNumber.Contains(scCTX.ch)) {
+                                       scCTX.SetState(SCE_DMIS_DEFAULT);
+                               };
+                               break;
+
+                       case SCE_DMIS_KEYWORD:
+                               if (!setDMISWord.Contains(scCTX.ch)) {
+                                       char tmpStr[MAX_STR_LEN];
+                                       memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
+                                       scCTX.GetCurrent(tmpStr, (MAX_STR_LEN-1));
+                                       strncpy(tmpStr, this->UpperCase(tmpStr), (MAX_STR_LEN-1));
+
+                                       if (this->m_minorWords.InList(tmpStr)) {
+                                               scCTX.ChangeState(SCE_DMIS_MINORWORD);
+                                       };
+                                       if (this->m_majorWords.InList(tmpStr)) {
+                                               isIFLine = (strcmp(tmpStr, "IF") == 0);
+                                               scCTX.ChangeState(SCE_DMIS_MAJORWORD);
+                                       };
+                                       if (this->m_unsupportedMajor.InList(tmpStr)) {
+                                               scCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MAJOR);
+                                       };
+                                       if (this->m_unsupportedMinor.InList(tmpStr)) {
+                                               scCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MINOR);
+                                       };
+
+                                       if (scCTX.Match('(') && (!isIFLine)) {
+                                               scCTX.SetState(SCE_DMIS_LABEL);
+                                       } else {
+                                               scCTX.SetState(SCE_DMIS_DEFAULT);
+                                       };
+                               };
+                               break;
+
+                       case SCE_DMIS_LABEL:
+                               if (scCTX.Match(')')) {
+                                       scCTX.SetState(SCE_DMIS_DEFAULT);
+                               };
+                               break;
+               };
+       };
+       scCTX.Complete();
+}
+
+void SCI_METHOD LexerDMIS::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int, IDocument *pAccess)
+{
+       const int MAX_STR_LEN = 100;
+
+       LexAccessor styler(pAccess);
+       Sci_PositionU endPos = startPos + lengthDoc;
+       char chNext = styler[startPos];
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
+       int levelCurrent = levelPrev;
+       int strPos = 0;
+       bool foldWordPossible = false;
+       CharacterSet setDMISFoldWord(CharacterSet::setAlpha);
+       char *tmpStr;
+
+
+       tmpStr = new char[MAX_STR_LEN];
+       memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
+
+       for (Sci_PositionU i=startPos; i<endPos; i++) {
+               char ch = chNext;
+               chNext = styler.SafeGetCharAt(i+1);
+
+               bool atEOL = ((ch == '\r' && chNext != '\n') || (ch == '\n'));
+
+               if (strPos >= (MAX_STR_LEN-1)) {
+                       strPos = MAX_STR_LEN-1;
+               };
+
+               int style = styler.StyleAt(i);
+               bool noFoldPos = ((style == SCE_DMIS_COMMENT) || (style == SCE_DMIS_STRING));
+
+               if (foldWordPossible) {
+                       if (setDMISFoldWord.Contains(ch)) {
+                               tmpStr[strPos++] = ch;
+                       } else {
+                               tmpStr = this->UpperCase(tmpStr);
+                               if (this->m_codeFoldingStart.InList(tmpStr) && (!noFoldPos)) {
+                                       levelCurrent++;
+                               };
+                               if (this->m_codeFoldingEnd.InList(tmpStr) && (!noFoldPos)) {
+                                       levelCurrent--;
+                               };
+                               memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
+                               strPos = 0;
+                               foldWordPossible = false;
+                       };
+               } else {
+                       if (setDMISFoldWord.Contains(ch)) {
+                               tmpStr[strPos++] = ch;
+                               foldWordPossible = true;
+                       };
+               };
+
+               if (atEOL || (i == (endPos-1))) {
+                       int lev = levelPrev;
+
+                       if (levelCurrent > levelPrev) {
+                               lev |= SC_FOLDLEVELHEADERFLAG;
+                       };
+                       if (lev != styler.LevelAt(lineCurrent)) {
+                               styler.SetLevel(lineCurrent, lev);
+                       };
+                       lineCurrent++;
+                       levelPrev = levelCurrent;
+               };
+       };
+       delete[] tmpStr;
+}
+
+
+LexerModule lmDMIS(SCLEX_DMIS, LexerDMIS::LexerFactoryDMIS, "DMIS", DMISWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexDiff.cxx b/plugins/scintilla/scintilla/lexers/LexDiff.cxx
new file mode 100644
index 0000000..9512550
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexDiff.cxx
@@ -0,0 +1,155 @@
+// Scintilla source code edit control
+/** @file LexDiff.cxx
+ ** Lexer for diff results.
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
+       return (styler[i] == '\n') ||
+              ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
+}
+
+#define DIFF_BUFFER_START_SIZE 16
+// Note that ColouriseDiffLine analyzes only the first DIFF_BUFFER_START_SIZE
+// characters of each line to classify the line.
+
+static void ColouriseDiffLine(char *lineBuffer, Sci_Position endLine, Accessor &styler) {
+       // It is needed to remember the current state to recognize starting
+       // comment lines before the first "diff " or "--- ". If a real
+       // difference starts then each line starting with ' ' is a whitespace
+       // otherwise it is considered a comment (Only in..., Binary file...)
+       if (0 == strncmp(lineBuffer, "diff ", 5)) {
+               styler.ColourTo(endLine, SCE_DIFF_COMMAND);
+       } else if (0 == strncmp(lineBuffer, "Index: ", 7)) {  // For subversion's diff
+               styler.ColourTo(endLine, SCE_DIFF_COMMAND);
+       } else if (0 == strncmp(lineBuffer, "---", 3) && lineBuffer[3] != '-') {
+               // In a context diff, --- appears in both the header and the position markers
+               if (lineBuffer[3] == ' ' && atoi(lineBuffer + 4) && !strchr(lineBuffer, '/'))
+                       styler.ColourTo(endLine, SCE_DIFF_POSITION);
+               else if (lineBuffer[3] == '\r' || lineBuffer[3] == '\n')
+                       styler.ColourTo(endLine, SCE_DIFF_POSITION);
+               else if (lineBuffer[3] == ' ')
+                       styler.ColourTo(endLine, SCE_DIFF_HEADER);
+               else
+                       styler.ColourTo(endLine, SCE_DIFF_DELETED);
+       } else if (0 == strncmp(lineBuffer, "+++ ", 4)) {
+               // I don't know of any diff where "+++ " is a position marker, but for
+               // consistency, do the same as with "--- " and "*** ".
+               if (atoi(lineBuffer+4) && !strchr(lineBuffer, '/'))
+                       styler.ColourTo(endLine, SCE_DIFF_POSITION);
+               else
+                       styler.ColourTo(endLine, SCE_DIFF_HEADER);
+       } else if (0 == strncmp(lineBuffer, "====", 4)) {  // For p4's diff
+               styler.ColourTo(endLine, SCE_DIFF_HEADER);
+       } else if (0 == strncmp(lineBuffer, "***", 3)) {
+               // In a context diff, *** appears in both the header and the position markers.
+               // Also ******** is a chunk header, but here it's treated as part of the
+               // position marker since there is no separate style for a chunk header.
+               if (lineBuffer[3] == ' ' && atoi(lineBuffer+4) && !strchr(lineBuffer, '/'))
+                       styler.ColourTo(endLine, SCE_DIFF_POSITION);
+               else if (lineBuffer[3] == '*')
+                       styler.ColourTo(endLine, SCE_DIFF_POSITION);
+               else
+                       styler.ColourTo(endLine, SCE_DIFF_HEADER);
+       } else if (0 == strncmp(lineBuffer, "? ", 2)) {    // For difflib
+               styler.ColourTo(endLine, SCE_DIFF_HEADER);
+       } else if (lineBuffer[0] == '@') {
+               styler.ColourTo(endLine, SCE_DIFF_POSITION);
+       } else if (lineBuffer[0] >= '0' && lineBuffer[0] <= '9') {
+               styler.ColourTo(endLine, SCE_DIFF_POSITION);
+       } else if (lineBuffer[0] == '-' || lineBuffer[0] == '<') {
+               styler.ColourTo(endLine, SCE_DIFF_DELETED);
+       } else if (lineBuffer[0] == '+' || lineBuffer[0] == '>') {
+               styler.ColourTo(endLine, SCE_DIFF_ADDED);
+       } else if (lineBuffer[0] == '!') {
+               styler.ColourTo(endLine, SCE_DIFF_CHANGED);
+       } else if (lineBuffer[0] != ' ') {
+               styler.ColourTo(endLine, SCE_DIFF_COMMENT);
+       } else {
+               styler.ColourTo(endLine, SCE_DIFF_DEFAULT);
+       }
+}
+
+static void ColouriseDiffDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor 
&styler) {
+       char lineBuffer[DIFF_BUFFER_START_SIZE] = "";
+       styler.StartAt(startPos);
+       styler.StartSegment(startPos);
+       Sci_PositionU linePos = 0;
+       for (Sci_PositionU i = startPos; i < startPos + length; i++) {
+               if (AtEOL(styler, i)) {
+                       if (linePos < DIFF_BUFFER_START_SIZE) {
+                               lineBuffer[linePos] = 0;
+                       }
+                       ColouriseDiffLine(lineBuffer, i, styler);
+                       linePos = 0;
+               } else if (linePos < DIFF_BUFFER_START_SIZE - 1) {
+                       lineBuffer[linePos++] = styler[i];
+               } else if (linePos == DIFF_BUFFER_START_SIZE - 1) {
+                       lineBuffer[linePos++] = 0;
+               }
+       }
+       if (linePos > 0) {      // Last line does not have ending characters
+               if (linePos < DIFF_BUFFER_START_SIZE) {
+                       lineBuffer[linePos] = 0;
+               }
+               ColouriseDiffLine(lineBuffer, startPos + length - 1, styler);
+       }
+}
+
+static void FoldDiffDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
+       Sci_Position curLine = styler.GetLine(startPos);
+       Sci_Position curLineStart = styler.LineStart(curLine);
+       int prevLevel = curLine > 0 ? styler.LevelAt(curLine - 1) : SC_FOLDLEVELBASE;
+       int nextLevel;
+
+       do {
+               const int lineType = styler.StyleAt(curLineStart);
+               if (lineType == SCE_DIFF_COMMAND)
+                       nextLevel = SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG;
+               else if (lineType == SCE_DIFF_HEADER)
+                       nextLevel = (SC_FOLDLEVELBASE + 1) | SC_FOLDLEVELHEADERFLAG;
+               else if (lineType == SCE_DIFF_POSITION && styler[curLineStart] != '-')
+                       nextLevel = (SC_FOLDLEVELBASE + 2) | SC_FOLDLEVELHEADERFLAG;
+               else if (prevLevel & SC_FOLDLEVELHEADERFLAG)
+                       nextLevel = (prevLevel & SC_FOLDLEVELNUMBERMASK) + 1;
+               else
+                       nextLevel = prevLevel;
+
+               if ((nextLevel & SC_FOLDLEVELHEADERFLAG) && (nextLevel == prevLevel))
+                       styler.SetLevel(curLine-1, prevLevel & ~SC_FOLDLEVELHEADERFLAG);
+
+               styler.SetLevel(curLine, nextLevel);
+               prevLevel = nextLevel;
+
+               curLineStart = styler.LineStart(++curLine);
+       } while (static_cast<Sci_Position>(startPos)+length > curLineStart);
+}
+
+static const char *const emptyWordListDesc[] = {
+       0
+};
+
+LexerModule lmDiff(SCLEX_DIFF, ColouriseDiffDoc, "diff", FoldDiffDoc, emptyWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexECL.cxx b/plugins/scintilla/scintilla/lexers/LexECL.cxx
index 6a08d58..2e5433e 100644
--- a/plugins/scintilla/scintilla/lexers/LexECL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexECL.cxx
@@ -7,10 +7,10 @@
 
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h>
 #include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <ctype.h>
 
 #ifdef _MSC_VER
 #pragma warning(disable: 4786)
@@ -62,7 +62,7 @@ static bool IsSpaceEquiv(int state) {
        }
 }
 
-static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseEclDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
        WordList &keywords0 = *keywordlists[0];
        WordList &keywords1 = *keywordlists[1];
@@ -90,7 +90,7 @@ static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, Wo
 
        if (initStyle == SCE_ECL_PREPROCESSOR) {
                // Set continuationLine if last character of previous line is '\'
-               int lineCurrent = styler.GetLine(startPos);
+               Sci_Position lineCurrent = styler.GetLine(startPos);
                if (lineCurrent > 0) {
                        int chBack = styler.SafeGetCharAt(startPos-1, 0);
                        int chBack2 = styler.SafeGetCharAt(startPos-2, 0);
@@ -106,7 +106,7 @@ static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, Wo
 
        // look back to set chPrevNonWhite properly for better regex colouring
        if (startPos > 0) {
-               int back = startPos;
+               Sci_Position back = startPos;
                while (--back && IsSpaceEquiv(styler.StyleAt(back)))
                        ;
                if (styler.StyleAt(back) == SCE_ECL_OPERATOR) {
@@ -175,7 +175,7 @@ static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, Wo
                                        } else if (keywords5.InList(s)) {
                                                sc.ChangeState(SCE_ECL_WORD5);
                                        }
-                                       else    //Data types are of from KEYWORD## 
+                                       else    //Data types are of from KEYWORD##
                                        {
                                                int i = static_cast<int>(strlen(s)) - 1;
                                                while(i >= 0 && (isdigit(s[i]) || s[i] == '_'))
@@ -186,7 +186,7 @@ static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, Wo
                                                s2[i + 1] = 0;
                                                if (keywords3.InList(s2)) {
                                                        sc.ChangeState(SCE_ECL_WORD3);
-                                               } 
+                                               }
                                        }
                                        sc.SetState(SCE_ECL_DEFAULT);
                                }
@@ -311,7 +311,7 @@ static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, Wo
                }
 
                // Determine if a new state should be entered.
-               int lineCurrent = styler.GetLine(sc.currentPos);
+               Sci_Position lineCurrent = styler.GetLine(sc.currentPos);
                int lineState = styler.GetLineState(lineCurrent);
                if (sc.state == SCE_ECL_DEFAULT) {
                        if (lineState) {
@@ -388,12 +388,12 @@ static bool IsStreamCommentStyle(int style) {
                style == SCE_ECL_COMMENTDOCKEYWORDERROR;
 }
 
-bool MatchNoCase(Accessor & styler, unsigned int & pos, const char *s) {
-       int i=0;
+static bool MatchNoCase(Accessor & styler, Sci_PositionU & pos, const char *s) {
+       Sci_Position i=0;
        for (; *s; i++) {
                char compare_char = tolower(*s);
                char styler_char = tolower(styler.SafeGetCharAt(pos+i));
-               if (compare_char != styler_char) 
+               if (compare_char != styler_char)
                        return false;
                s++;
        }
@@ -405,15 +405,15 @@ bool MatchNoCase(Accessor & styler, unsigned int & pos, const char *s) {
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
-static void FoldEclDoc(unsigned int startPos, int length, int initStyle, 
+static void FoldEclDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                           WordList *[], Accessor &styler) {
        bool foldComment = true;
        bool foldPreprocessor = true;
        bool foldCompact = true;
        bool foldAtElse = true;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -422,7 +422,7 @@ static void FoldEclDoc(unsigned int startPos, int length, int initStyle,
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -449,7 +449,7 @@ static void FoldEclDoc(unsigned int startPos, int length, int initStyle,
                }
                if (foldPreprocessor && (style == SCE_ECL_PREPROCESSOR)) {
                        if (ch == '#') {
-                               unsigned int j = i + 1;
+                               Sci_PositionU j = i + 1;
                                while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                        j++;
                                }
@@ -473,7 +473,7 @@ static void FoldEclDoc(unsigned int startPos, int length, int initStyle,
                        }
                }
                if (style == SCE_ECL_WORD2) {
-                       if (MatchNoCase(styler, i, "record") || MatchNoCase(styler, i, "transform") || 
MatchNoCase(styler, i, "type") || MatchNoCase(styler, i, "function") || 
+                       if (MatchNoCase(styler, i, "record") || MatchNoCase(styler, i, "transform") || 
MatchNoCase(styler, i, "type") || MatchNoCase(styler, i, "function") ||
                                MatchNoCase(styler, i, "module") || MatchNoCase(styler, i, "service") || 
MatchNoCase(styler, i, "interface") || MatchNoCase(styler, i, "ifblock") ||
                                MatchNoCase(styler, i, "macro") || MatchNoCase(styler, i, "beginc++")) {
                                levelNext++;
@@ -497,7 +497,7 @@ static void FoldEclDoc(unsigned int startPos, int length, int initStyle,
                        lineCurrent++;
                        levelCurrent = levelNext;
                        levelMinCurrent = levelCurrent;
-                       if (atEOL && (i == static_cast<unsigned int>(styler.Length()-1))) {
+                       if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length()-1))) {
                                // There is an empty line at end of file so give it same level and empty
                                styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | 
SC_FOLDLEVELWHITEFLAG);
                        }
diff --git a/plugins/scintilla/scintilla/lexers/LexEDIFACT.cxx 
b/plugins/scintilla/scintilla/lexers/LexEDIFACT.cxx
new file mode 100644
index 0000000..f7e55bf
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexEDIFACT.cxx
@@ -0,0 +1,319 @@
+// Scintilla Lexer for EDIFACT
+// Written by Iain Clarke, IMCSoft & Inobiz AB.
+// EDIFACT documented here: https://www.unece.org/cefact/edifact/welcome.html
+// and more readably here: https://en.wikipedia.org/wiki/EDIFACT
+// This code is subject to the same license terms as the rest of the scintilla project:
+// The License.txt file describes the conditions under which this software may be distributed.
+// 
+
+// Header order must match order in scripts/HeaderOrder.txt
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cctype>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "LexAccessor.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+class LexerEDIFACT : public ILexer
+{
+public:
+       LexerEDIFACT();
+       virtual ~LexerEDIFACT() {} // virtual destructor, as we inherit from ILexer
+
+       static ILexer *Factory() {
+               return new LexerEDIFACT;
+       }
+
+       int SCI_METHOD Version() const override
+       {
+               return lvOriginal;
+       }
+       void SCI_METHOD Release() override
+       {
+               delete this;
+       }
+
+       const char * SCI_METHOD PropertyNames() override
+       {
+               return "fold";
+       }
+       int SCI_METHOD PropertyType(const char *) override
+       {
+               return SC_TYPE_BOOLEAN; // Only one property!
+       }
+       const char * SCI_METHOD DescribeProperty(const char *name) override
+       {
+               if (strcmp(name, "fold"))
+                       return NULL;
+               return "Whether to apply folding to document or not";
+       }
+
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override
+       {
+               if (strcmp(key, "fold"))
+                       return -1;
+               m_bFold = strcmp(val, "0") ? true : false;
+               return 0;
+       }
+       const char * SCI_METHOD DescribeWordListSets() override
+       {
+               return NULL;
+       }
+       Sci_Position SCI_METHOD WordListSet(int, const char *) override
+       {
+               return -1;
+       }
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) override;
+       void * SCI_METHOD PrivateCall(int, void *) override
+       {
+               return NULL;
+       }
+
+protected:
+       Sci_Position InitialiseFromUNA(IDocument *pAccess, Sci_PositionU MaxLength);
+       Sci_Position FindPreviousEnd(IDocument *pAccess, Sci_Position startPos) const;
+       Sci_Position ForwardPastWhitespace(IDocument *pAccess, Sci_Position startPos, Sci_Position MaxLength) 
const;
+       int DetectSegmentHeader(char SegmentHeader[3]) const;
+
+       bool m_bFold;
+       char m_chComponent;
+       char m_chData;
+       char m_chDecimal;
+       char m_chRelease;
+       char m_chSegment;
+};
+
+LexerModule lmEDIFACT(SCLEX_EDIFACT, LexerEDIFACT::Factory, "edifact");
+
+///////////////////////////////////////////////////////////////////////////////
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+
+LexerEDIFACT::LexerEDIFACT()
+{
+       m_bFold = false;
+       m_chComponent = ':';
+       m_chData = '+';
+       m_chDecimal = '.';
+       m_chRelease = '?';
+       m_chSegment = '\'';
+}
+
+void LexerEDIFACT::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int, IDocument *pAccess)
+{
+       Sci_PositionU posFinish = startPos + lengthDoc;
+       InitialiseFromUNA(pAccess, posFinish);
+
+       // Look backwards for a ' or a document beginning
+       Sci_PositionU posCurrent = FindPreviousEnd(pAccess, startPos);
+       // And jump past the ' if this was not the beginning of the document
+       if (posCurrent != 0)
+               posCurrent++;
+
+       // Style buffer, so we're not issuing loads of notifications
+       LexAccessor styler (pAccess);
+       pAccess->StartStyling(posCurrent, '\377');
+       styler.StartSegment(posCurrent);
+       Sci_Position posSegmentStart = -1;
+
+       while ((posCurrent < posFinish) && (posSegmentStart == -1))
+       {
+               posCurrent = ForwardPastWhitespace(pAccess, posCurrent, posFinish);
+               // Mark whitespace as default
+               styler.ColourTo(posCurrent - 1, SCE_EDI_DEFAULT);
+               if (posCurrent >= posFinish)
+                       break;
+
+               // Does is start with 3 charaters? ie, UNH
+               char SegmentHeader[4] = { 0 };
+               pAccess->GetCharRange(SegmentHeader, posCurrent, 3);
+
+               int SegmentStyle = DetectSegmentHeader(SegmentHeader);
+               if (SegmentStyle == SCE_EDI_BADSEGMENT)
+                       break;
+               if (SegmentStyle == SCE_EDI_UNA)
+               {
+                       posCurrent += 9;
+                       styler.ColourTo(posCurrent - 1, SCE_EDI_UNA); // UNA   
+                       continue;
+               }
+               posSegmentStart = posCurrent;
+               posCurrent += 3;
+
+               styler.ColourTo(posCurrent - 1, SegmentStyle); // UNH etc
+
+               // Colour in the rest of the segment
+               for (char c; posCurrent < posFinish; posCurrent++)
+               {
+                       pAccess->GetCharRange(&c, posCurrent, 1);
+
+                       if (c == m_chRelease) // ? escape character, check first, in case of ?'
+                               posCurrent++;
+                       else if (c == m_chSegment) // '
+                       {
+                               // Make sure the whole segment is on one line. styler won't let us go back in 
time, so we'll settle for marking the ' as bad.
+                               Sci_Position lineSegmentStart = pAccess->LineFromPosition(posSegmentStart);
+                               Sci_Position lineSegmentEnd = pAccess->LineFromPosition(posCurrent);
+                               if (lineSegmentStart == lineSegmentEnd)
+                                       styler.ColourTo(posCurrent, SCE_EDI_SEGMENTEND);
+                               else
+                                       styler.ColourTo(posCurrent, SCE_EDI_BADSEGMENT);
+                               posSegmentStart = -1;
+                               posCurrent++;
+                               break;
+                       }
+                       else if (c == m_chComponent) // :
+                               styler.ColourTo(posCurrent, SCE_EDI_SEP_COMPOSITE);
+                       else if (c == m_chData) // +
+                               styler.ColourTo(posCurrent, SCE_EDI_SEP_ELEMENT);
+                       else
+                               styler.ColourTo(posCurrent, SCE_EDI_DEFAULT);
+               }
+       }
+       styler.Flush();
+
+       if (posSegmentStart == -1)
+               return;
+
+       pAccess->StartStyling(posSegmentStart, -1);
+       pAccess->SetStyleFor(posFinish - posSegmentStart, SCE_EDI_BADSEGMENT);
+}
+
+void LexerEDIFACT::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int, IDocument *pAccess)
+{
+       if (!m_bFold)
+               return;
+
+       // Fold at UNx lines. ie, UNx segments = 0, other segments = 1.
+       // There's no sub folding, so we can be quite simple.
+       Sci_Position endPos = startPos + lengthDoc;
+       char SegmentHeader[4] = { 0 };
+
+       int iIndentPrevious = 0;
+       Sci_Position lineLast = pAccess->LineFromPosition(endPos);
+
+       for (Sci_Position lineCurrent = pAccess->LineFromPosition(startPos); lineCurrent <= lineLast; 
lineCurrent++)
+       {
+               Sci_Position posLineStart = pAccess->LineStart(lineCurrent);
+               posLineStart = ForwardPastWhitespace(pAccess, posLineStart, endPos);
+               Sci_Position lineDataStart = pAccess->LineFromPosition(posLineStart);
+               // Fill in whitespace lines?
+               for (; lineCurrent < lineDataStart; lineCurrent++)
+                       pAccess->SetLevel(lineCurrent, SC_FOLDLEVELBASE | SC_FOLDLEVELWHITEFLAG | 
iIndentPrevious);
+               pAccess->GetCharRange(SegmentHeader, posLineStart, 3);
+               //if (DetectSegmentHeader(SegmentHeader) == SCE_EDI_BADSEGMENT) // Abort if this is not a 
proper segment header
+
+               int level = 0;
+               if (memcmp(SegmentHeader, "UNH", 3) == 0) // UNH starts blocks
+                       level = SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG;
+               // Check for UNA,B and Z. All others are inside messages
+               else if (!memcmp(SegmentHeader, "UNA", 3) || !memcmp(SegmentHeader, "UNB", 3) || 
!memcmp(SegmentHeader, "UNZ", 3))
+                       level = SC_FOLDLEVELBASE;
+               else
+                       level = SC_FOLDLEVELBASE | 1;
+               pAccess->SetLevel(lineCurrent, level);
+               iIndentPrevious = level & SC_FOLDLEVELNUMBERMASK;
+       }
+}
+
+Sci_Position LexerEDIFACT::InitialiseFromUNA(IDocument *pAccess, Sci_PositionU MaxLength)
+{
+       MaxLength -= 9; // drop 9 chars, to give us room for UNA:+.? '
+
+       Sci_PositionU startPos = 0;
+       startPos += ForwardPastWhitespace(pAccess, 0, MaxLength);
+       if (startPos < MaxLength)
+       {
+               char bufUNA[9];
+               pAccess->GetCharRange(bufUNA, startPos, 9);
+
+               // Check it's UNA segment
+               if (!memcmp(bufUNA, "UNA", 3))
+               {
+                       m_chComponent = bufUNA[3];
+                       m_chData = bufUNA[4];
+                       m_chDecimal = bufUNA[5];
+                       m_chRelease = bufUNA[6];
+                       // bufUNA [7] should be space - reserved.
+                       m_chSegment = bufUNA[8];
+
+                       return 0; // success!
+               }
+       }
+
+       // We failed to find a UNA, so drop to defaults
+       m_chComponent = ':';
+       m_chData = '+';
+       m_chDecimal = '.';
+       m_chRelease = '?';
+       m_chSegment = '\'';
+
+       return -1;
+}
+
+Sci_Position LexerEDIFACT::ForwardPastWhitespace(IDocument *pAccess, Sci_Position startPos, Sci_Position 
MaxLength) const
+{
+       char c;
+
+       while (startPos < MaxLength)
+       {
+               pAccess->GetCharRange(&c, startPos, 1);
+               switch (c)
+               {
+               case '\t':
+               case '\r':
+               case '\n':
+               case ' ':
+                       break;
+               default:
+                       return startPos;
+               }
+
+               startPos++;
+       }
+
+       return MaxLength;
+}
+
+int LexerEDIFACT::DetectSegmentHeader(char SegmentHeader[3]) const
+{
+       if (
+               SegmentHeader[0] < 'A' || SegmentHeader[0] > 'Z' ||
+               SegmentHeader[1] < 'A' || SegmentHeader[1] > 'Z' ||
+               SegmentHeader[2] < 'A' || SegmentHeader[2] > 'Z')
+               return SCE_EDI_BADSEGMENT;
+
+       if (memcmp(SegmentHeader, "UNA", 3) == 0)
+               return SCE_EDI_UNA;
+       if (memcmp(SegmentHeader, "UNH", 3) == 0)
+               return SCE_EDI_UNH;
+
+       return SCE_EDI_SEGMENTSTART;
+}
+
+// Look backwards for a ' or a document beginning
+Sci_Position LexerEDIFACT::FindPreviousEnd(IDocument *pAccess, Sci_Position startPos) const
+{
+       for (char c; startPos > 0; startPos--)
+       {
+               pAccess->GetCharRange(&c, startPos, 1);
+               if (c == m_chSegment)
+                       return startPos;
+       }
+       // We didn't find a ', so just go with the beginning
+       return 0;
+}
+
+
diff --git a/plugins/scintilla/scintilla/lexers/LexEScript.cxx 
b/plugins/scintilla/scintilla/lexers/LexEScript.cxx
index 9a7560e..bc1fb32 100644
--- a/plugins/scintilla/scintilla/lexers/LexEScript.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexEScript.cxx
@@ -6,10 +6,10 @@
 
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h>
 #include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <ctype.h>
 
 #include "ILexer.h"
 #include "Scintilla.h"
@@ -37,7 +37,7 @@ static inline bool IsAWordStart(const int ch) {
 
 
 
-static void ColouriseESCRIPTDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseESCRIPTDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
@@ -176,24 +176,24 @@ static bool IsStreamCommentStyle(int style) {
               style == SCE_ESCRIPT_COMMENTLINE;
 }
 
-static void FoldESCRIPTDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) 
{
+static void FoldESCRIPTDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], 
Accessor &styler) {
        //~ bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        // Do not know how to fold the comment at the moment.
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
         bool foldComment = true;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
 
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
        char prevWord[32] = "";
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -231,7 +231,7 @@ static void FoldESCRIPTDoc(unsigned int startPos, int length, int initStyle, Wor
                if (style == SCE_ESCRIPT_WORD3) {
                        if(iswordchar(ch) && !iswordchar(chNext)) {
                                char s[32];
-                               unsigned int j;
+                               Sci_PositionU j;
                                for(j = 0; ( j < 31 ) && ( j < i-lastStart+1 ); j++) {
                                        s[j] = static_cast<char>(tolower(styler[lastStart + j]));
                                }
diff --git a/plugins/scintilla/scintilla/lexers/LexEiffel.cxx 
b/plugins/scintilla/scintilla/lexers/LexEiffel.cxx
index 067801c..2e2813e 100644
--- a/plugins/scintilla/scintilla/lexers/LexEiffel.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexEiffel.cxx
@@ -46,8 +46,8 @@ static inline bool IsAWordStart(unsigned int ch) {
        return (ch < 0x80) && (isalnum(ch) || ch == '_');
 }
 
-static void ColouriseEiffelDoc(unsigned int startPos,
-                            int length,
+static void ColouriseEiffelDoc(Sci_PositionU startPos,
+                            Sci_Position length,
                             int initStyle,
                             WordList *keywordlists[],
                             Accessor &styler) {
@@ -118,16 +118,16 @@ static void ColouriseEiffelDoc(unsigned int startPos,
        sc.Complete();
 }
 
-static bool IsEiffelComment(Accessor &styler, int pos, int len) {
+static bool IsEiffelComment(Accessor &styler, Sci_Position pos, Sci_Position len) {
        return len>1 && styler[pos]=='-' && styler[pos+1]=='-';
 }
 
-static void FoldEiffelDocIndent(unsigned int startPos, int length, int,
+static void FoldEiffelDocIndent(Sci_PositionU startPos, Sci_Position length, int,
                                                   WordList *[], Accessor &styler) {
-       int lengthDoc = startPos + length;
+       Sci_Position lengthDoc = startPos + length;
 
        // Backtrack to previous line in case need to fix its fold status
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0) {
                if (lineCurrent > 0) {
                        lineCurrent--;
@@ -137,7 +137,7 @@ static void FoldEiffelDocIndent(unsigned int startPos, int length, int,
        int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsEiffelComment);
        char chNext = styler[startPos];
-       for (int i = startPos; i < lengthDoc; i++) {
+       for (Sci_Position i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -164,11 +164,11 @@ static void FoldEiffelDocIndent(unsigned int startPos, int length, int,
        }
 }
 
-static void FoldEiffelDocKeyWords(unsigned int startPos, int length, int /* initStyle */, WordList *[],
+static void FoldEiffelDocKeyWords(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList 
*[],
                        Accessor &styler) {
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
@@ -177,7 +177,7 @@ static void FoldEiffelDocKeyWords(unsigned int startPos, int length, int /* init
        // lastDeferred should be determined by looking back to last keyword in case
        // the "deferred" is on a line before "class"
        bool lastDeferred = false;
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
@@ -185,7 +185,7 @@ static void FoldEiffelDocKeyWords(unsigned int startPos, int length, int /* init
                bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
                if ((stylePrev != SCE_EIFFEL_WORD) && (style == SCE_EIFFEL_WORD)) {
                        char s[20];
-                       unsigned int j = 0;
+                       Sci_PositionU j = 0;
                        while ((j < (sizeof(s) - 1)) && (iswordchar(styler[i + j]))) {
                                s[j] = styler[i + j];
                                j++;
diff --git a/plugins/scintilla/scintilla/lexers/LexErlang.cxx 
b/plugins/scintilla/scintilla/lexers/LexErlang.cxx
index 5f52258..3d3c1e8 100644
--- a/plugins/scintilla/scintilla/lexers/LexErlang.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexErlang.cxx
@@ -75,7 +75,7 @@ static inline bool IsAWordChar(const int ch) {
        return (ch < 0x80) && (ch != ' ') && (isalnum(ch) || ch == '_');
 }
 
-static void ColouriseErlangDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseErlangDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                                                WordList *keywordlists[], Accessor &styler) {
 
        StyleContext sc(startPos, length, initStyle, styler);
@@ -500,7 +500,7 @@ static void ColouriseErlangDoc(unsigned int startPos, int length, int initStyle,
 static int ClassifyErlangFoldPoint(
        Accessor &styler,
        int styleNext,
-       int keyword_start
+       Sci_Position keyword_start
 ) {
        int lev = 0;
        if (styler.Match(keyword_start,"case")
@@ -521,23 +521,23 @@ static int ClassifyErlangFoldPoint(
 }
 
 static void FoldErlangDoc(
-       unsigned int startPos, int length, int initStyle,
+       Sci_PositionU startPos, Sci_Position length, int initStyle,
        WordList** /*keywordlists*/, Accessor &styler
 ) {
-       unsigned int endPos = startPos + length;
-       int currentLine = styler.GetLine(startPos);
+       Sci_PositionU endPos = startPos + length;
+       Sci_Position currentLine = styler.GetLine(startPos);
        int lev;
        int previousLevel = styler.LevelAt(currentLine) & SC_FOLDLEVELNUMBERMASK;
        int currentLevel = previousLevel;
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
        int stylePrev;
-       int keyword_start = 0;
+       Sci_Position keyword_start = 0;
        char ch;
        char chNext = styler.SafeGetCharAt(startPos);
        bool atEOL;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
diff --git a/plugins/scintilla/scintilla/lexers/LexErrorList.cxx 
b/plugins/scintilla/scintilla/lexers/LexErrorList.cxx
new file mode 100644
index 0000000..871902a
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexErrorList.cxx
@@ -0,0 +1,395 @@
+// Scintilla source code edit control
+/** @file LexErrorList.cxx
+ ** Lexer for error lists. Used for the output pane in SciTE.
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static bool strstart(const char *haystack, const char *needle) {
+       return strncmp(haystack, needle, strlen(needle)) == 0;
+}
+
+static bool Is0To9(char ch) {
+       return (ch >= '0') && (ch <= '9');
+}
+
+static bool Is1To9(char ch) {
+       return (ch >= '1') && (ch <= '9');
+}
+
+static bool IsAlphabetic(int ch) {
+       return IsASCII(ch) && isalpha(ch);
+}
+
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
+       return (styler[i] == '\n') ||
+              ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
+}
+
+static int RecogniseErrorListLine(const char *lineBuffer, Sci_PositionU lengthLine, Sci_Position 
&startValue) {
+       if (lineBuffer[0] == '>') {
+               // Command or return status
+               return SCE_ERR_CMD;
+       } else if (lineBuffer[0] == '<') {
+               // Diff removal.
+               return SCE_ERR_DIFF_DELETION;
+       } else if (lineBuffer[0] == '!') {
+               return SCE_ERR_DIFF_CHANGED;
+       } else if (lineBuffer[0] == '+') {
+               if (strstart(lineBuffer, "+++ ")) {
+                       return SCE_ERR_DIFF_MESSAGE;
+               } else {
+                       return SCE_ERR_DIFF_ADDITION;
+               }
+       } else if (lineBuffer[0] == '-') {
+               if (strstart(lineBuffer, "--- ")) {
+                       return SCE_ERR_DIFF_MESSAGE;
+               } else {
+                       return SCE_ERR_DIFF_DELETION;
+               }
+       } else if (strstart(lineBuffer, "cf90-")) {
+               // Absoft Pro Fortran 90/95 v8.2 error and/or warning message
+               return SCE_ERR_ABSF;
+       } else if (strstart(lineBuffer, "fortcom:")) {
+               // Intel Fortran Compiler v8.0 error/warning message
+               return SCE_ERR_IFORT;
+       } else if (strstr(lineBuffer, "File \"") && strstr(lineBuffer, ", line ")) {
+               return SCE_ERR_PYTHON;
+       } else if (strstr(lineBuffer, " in ") && strstr(lineBuffer, " on line ")) {
+               return SCE_ERR_PHP;
+       } else if ((strstart(lineBuffer, "Error ") ||
+                   strstart(lineBuffer, "Warning ")) &&
+                  strstr(lineBuffer, " at (") &&
+                  strstr(lineBuffer, ") : ") &&
+                  (strstr(lineBuffer, " at (") < strstr(lineBuffer, ") : "))) {
+               // Intel Fortran Compiler error/warning message
+               return SCE_ERR_IFC;
+       } else if (strstart(lineBuffer, "Error ")) {
+               // Borland error message
+               return SCE_ERR_BORLAND;
+       } else if (strstart(lineBuffer, "Warning ")) {
+               // Borland warning message
+               return SCE_ERR_BORLAND;
+       } else if (strstr(lineBuffer, "at line ") &&
+               (strstr(lineBuffer, "at line ") < (lineBuffer + lengthLine)) &&
+                  strstr(lineBuffer, "file ") &&
+                  (strstr(lineBuffer, "file ") < (lineBuffer + lengthLine))) {
+               // Lua 4 error message
+               return SCE_ERR_LUA;
+       } else if (strstr(lineBuffer, " at ") &&
+               (strstr(lineBuffer, " at ") < (lineBuffer + lengthLine)) &&
+                  strstr(lineBuffer, " line ") &&
+                  (strstr(lineBuffer, " line ") < (lineBuffer + lengthLine)) &&
+               (strstr(lineBuffer, " at ") + 4 < (strstr(lineBuffer, " line ")))) {
+               // perl error message:
+               // <message> at <file> line <line>
+               return SCE_ERR_PERL;
+       } else if ((lengthLine >= 6) && 
+                  (memcmp(lineBuffer, "   at ", 6) == 0) &&
+                  strstr(lineBuffer, ":line ")) {
+               // A .NET traceback
+               return SCE_ERR_NET;
+       } else if (strstart(lineBuffer, "Line ") &&
+                  strstr(lineBuffer, ", file ")) {
+               // Essential Lahey Fortran error message
+               return SCE_ERR_ELF;
+       } else if (strstart(lineBuffer, "line ") &&
+                  strstr(lineBuffer, " column ")) {
+               // HTML tidy style: line 42 column 1
+               return SCE_ERR_TIDY;
+       } else if (strstart(lineBuffer, "\tat ") &&
+                  strstr(lineBuffer, "(") &&
+                  strstr(lineBuffer, ".java:")) {
+               // Java stack back trace
+               return SCE_ERR_JAVA_STACK;
+       } else if (strstart(lineBuffer, "In file included from ") ||
+                  strstart(lineBuffer, "                 from ")) {
+               // GCC showing include path to following error
+               return SCE_ERR_GCC_INCLUDED_FROM;
+       } else if (strstr(lineBuffer, "warning LNK")) {
+               // Microsoft linker warning:
+               // {<object> : } warning LNK9999
+               return SCE_ERR_MS;
+       } else {
+               // Look for one of the following formats:
+               // GCC: <filename>:<line>:<message>
+               // Microsoft: <filename>(<line>) :<message>
+               // Common: <filename>(<line>): warning|error|note|remark|catastrophic|fatal
+               // Common: <filename>(<line>) warning|error|note|remark|catastrophic|fatal
+               // Microsoft: <filename>(<line>,<column>)<message>
+               // CTags: <identifier>\t<filename>\t<message>
+               // Lua 5 traceback: \t<filename>:<line>:<message>
+               // Lua 5.1: <exe>: <filename>:<line>:<message>
+               const bool initialTab = (lineBuffer[0] == '\t');
+               bool initialColonPart = false;
+               bool canBeCtags = !initialTab;  // For ctags must have an identifier with no spaces then a tab
+               enum { stInitial,
+                       stGccStart, stGccDigit, stGccColumn, stGcc,
+                       stMsStart, stMsDigit, stMsBracket, stMsVc, stMsDigitComma, stMsDotNet,
+                       stCtagsStart, stCtagsFile, stCtagsStartString, stCtagsStringDollar, stCtags,
+                       stUnrecognized
+               } state = stInitial;
+               for (Sci_PositionU i = 0; i < lengthLine; i++) {
+                       const char ch = lineBuffer[i];
+                       char chNext = ' ';
+                       if ((i + 1) < lengthLine)
+                               chNext = lineBuffer[i + 1];
+                       if (state == stInitial) {
+                               if (ch == ':') {
+                                       // May be GCC, or might be Lua 5 (Lua traceback same but with tab 
prefix)
+                                       if ((chNext != '\\') && (chNext != '/') && (chNext != ' ')) {
+                                               // This check is not completely accurate as may be on
+                                               // GTK+ with a file name that includes ':'.
+                                               state = stGccStart;
+                                       } else if (chNext == ' ') { // indicates a Lua 5.1 error message
+                                               initialColonPart = true;
+                                       }
+                               } else if ((ch == '(') && Is1To9(chNext) && (!initialTab)) {
+                                       // May be Microsoft
+                                       // Check against '0' often removes phone numbers
+                                       state = stMsStart;
+                               } else if ((ch == '\t') && canBeCtags) {
+                                       // May be CTags
+                                       state = stCtagsStart;
+                               } else if (ch == ' ') {
+                                       canBeCtags = false;
+                               }
+                       } else if (state == stGccStart) {       // <filename>:
+                               state = Is0To9(ch) ? stGccDigit : stUnrecognized;
+                       } else if (state == stGccDigit) {       // <filename>:<line>
+                               if (ch == ':') {
+                                       state = stGccColumn;    // :9.*: is GCC
+                                       startValue = i + 1;
+                               } else if (!Is0To9(ch)) {
+                                       state = stUnrecognized;
+                               }
+                       } else if (state == stGccColumn) {      // <filename>:<line>:<column>
+                               if (!Is0To9(ch)) {
+                                       state = stGcc;
+                                       if (ch == ':')
+                                               startValue = i + 1;
+                                       break;
+                               }
+                       } else if (state == stMsStart) {        // <filename>(
+                               state = Is0To9(ch) ? stMsDigit : stUnrecognized;
+                       } else if (state == stMsDigit) {        // <filename>(<line>
+                               if (ch == ',') {
+                                       state = stMsDigitComma;
+                               } else if (ch == ')') {
+                                       state = stMsBracket;
+                               } else if ((ch != ' ') && !Is0To9(ch)) {
+                                       state = stUnrecognized;
+                               }
+                       } else if (state == stMsBracket) {      // <filename>(<line>)
+                               if ((ch == ' ') && (chNext == ':')) {
+                                       state = stMsVc;
+                               } else if ((ch == ':' && chNext == ' ') || (ch == ' ')) {
+                                       // Possibly Delphi.. don't test against chNext as it's one of the 
strings below.
+                                       char word[512];
+                                       Sci_PositionU j, chPos;
+                                       unsigned numstep;
+                                       chPos = 0;
+                                       if (ch == ' ')
+                                               numstep = 1; // ch was ' ', handle as if it's a delphi 
errorline, only add 1 to i.
+                                       else
+                                               numstep = 2; // otherwise add 2.
+                                       for (j = i + numstep; j < lengthLine && IsAlphabetic(lineBuffer[j]) 
&& chPos < sizeof(word) - 1; j++)
+                                               word[chPos++] = lineBuffer[j];
+                                       word[chPos] = 0;
+                                       if (!CompareCaseInsensitive(word, "error") || 
!CompareCaseInsensitive(word, "warning") ||
+                                               !CompareCaseInsensitive(word, "fatal") || 
!CompareCaseInsensitive(word, "catastrophic") ||
+                                               !CompareCaseInsensitive(word, "note") || 
!CompareCaseInsensitive(word, "remark")) {
+                                               state = stMsVc;
+                                       } else {
+                                               state = stUnrecognized;
+                                       }
+                               } else {
+                                       state = stUnrecognized;
+                               }
+                       } else if (state == stMsDigitComma) {   // <filename>(<line>,
+                               if (ch == ')') {
+                                       state = stMsDotNet;
+                                       break;
+                               } else if ((ch != ' ') && !Is0To9(ch)) {
+                                       state = stUnrecognized;
+                               }
+                       } else if (state == stCtagsStart) {
+                               if (ch == '\t') {
+                                       state = stCtagsFile;
+                               }
+                       } else if (state == stCtagsFile) {
+                               if ((lineBuffer[i - 1] == '\t') &&
+                                       ((ch == '/' && chNext == '^') || Is0To9(ch))) {
+                                       state = stCtags;
+                                       break;
+                               } else if ((ch == '/') && (chNext == '^')) {
+                                       state = stCtagsStartString;
+                               }
+                       } else if ((state == stCtagsStartString) && ((lineBuffer[i] == '$') && (lineBuffer[i 
+ 1] == '/'))) {
+                               state = stCtagsStringDollar;
+                               break;
+                       }
+               }
+               if (state == stGcc) {
+                       return initialColonPart ? SCE_ERR_LUA : SCE_ERR_GCC;
+               } else if ((state == stMsVc) || (state == stMsDotNet)) {
+                       return SCE_ERR_MS;
+               } else if ((state == stCtagsStringDollar) || (state == stCtags)) {
+                       return SCE_ERR_CTAG;
+               } else if (initialColonPart && strstr(lineBuffer, ": warning C")) {
+                       // Microsoft warning without line number
+                       // <filename>: warning C9999
+                       return SCE_ERR_MS;
+               } else {
+                       return SCE_ERR_DEFAULT;
+               }
+       }
+}
+
+#define CSI "\033["
+
+namespace {
+
+bool SequenceEnd(int ch) {
+       return (ch == 0) || ((ch >= '@') && (ch <= '~'));
+}
+
+int StyleFromSequence(const char *seq) {
+       int bold = 0;
+       int colour = 0;
+       while (!SequenceEnd(*seq)) {
+               if (Is0To9(*seq)) {
+                       int base = *seq - '0';
+                       if (Is0To9(seq[1])) {
+                               base = base * 10;
+                               base += seq[1] - '0';
+                               seq++;
+                       }
+                       if (base == 0) {
+                               colour = 0;
+                               bold = 0;
+                       }
+                       else if (base == 1) {
+                               bold = 1;
+                       }
+                       else if (base >= 30 && base <= 37) {
+                               colour = base - 30;
+                       }
+               }
+               seq++;
+       }
+       return SCE_ERR_ES_BLACK + bold * 8 + colour;
+}
+
+}
+
+static void ColouriseErrorListLine(
+    char *lineBuffer,
+    Sci_PositionU lengthLine,
+    Sci_PositionU endPos,
+    Accessor &styler,
+       bool valueSeparate,
+       bool escapeSequences) {
+       Sci_Position startValue = -1;
+       int style = RecogniseErrorListLine(lineBuffer, lengthLine, startValue);
+       if (escapeSequences && strstr(lineBuffer, CSI)) {
+               const Sci_Position startPos = endPos - lengthLine;
+               const char *linePortion = lineBuffer;
+               Sci_Position startPortion = startPos;
+               int portionStyle = style;
+               while (const char *startSeq = strstr(linePortion, CSI)) {
+                       if (startSeq > linePortion) {
+                               styler.ColourTo(startPortion + static_cast<int>(startSeq - linePortion), 
portionStyle);
+                       }
+                       const char *endSeq = startSeq + 2;
+                       while (!SequenceEnd(*endSeq))
+                               endSeq++;
+                       const Sci_Position endSeqPosition = startPortion + static_cast<Sci_Position>(endSeq - 
linePortion) + 1;
+                       switch (*endSeq) {
+                       case 0:
+                               styler.ColourTo(endPos, SCE_ERR_ESCSEQ_UNKNOWN);
+                               return;
+                       case 'm':       // Colour command
+                               styler.ColourTo(endSeqPosition, SCE_ERR_ESCSEQ);
+                               portionStyle = StyleFromSequence(startSeq+2);
+                               break;
+                       case 'K':       // Erase to end of line -> ignore
+                               styler.ColourTo(endSeqPosition, SCE_ERR_ESCSEQ);
+                               break;
+                       default:
+                               styler.ColourTo(endSeqPosition, SCE_ERR_ESCSEQ_UNKNOWN);
+                               portionStyle = style;
+                       }
+                       startPortion = endSeqPosition;
+                       linePortion = endSeq + 1;
+               }
+               styler.ColourTo(endPos, portionStyle);
+       } else {
+               if (valueSeparate && (startValue >= 0)) {
+                       styler.ColourTo(endPos - (lengthLine - startValue), style);
+                       styler.ColourTo(endPos, SCE_ERR_VALUE);
+               } else {
+                       styler.ColourTo(endPos, style);
+               }
+       }
+}
+
+static void ColouriseErrorListDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor 
&styler) {
+       char lineBuffer[10000];
+       styler.StartAt(startPos);
+       styler.StartSegment(startPos);
+       Sci_PositionU linePos = 0;
+
+       // property lexer.errorlist.value.separate
+       //      For lines in the output pane that are matches from Find in Files or GCC-style
+       //      diagnostics, style the path and line number separately from the rest of the
+       //      line with style 21 used for the rest of the line.
+       //      This allows matched text to be more easily distinguished from its location.
+       const bool valueSeparate = styler.GetPropertyInt("lexer.errorlist.value.separate", 0) != 0;
+
+       // property lexer.errorlist.escape.sequences
+       //      Set to 1 to interpret escape sequences.
+       const bool escapeSequences = styler.GetPropertyInt("lexer.errorlist.escape.sequences") != 0;
+
+       for (Sci_PositionU i = startPos; i < startPos + length; i++) {
+               lineBuffer[linePos++] = styler[i];
+               if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
+                       // End of line (or of line buffer) met, colourise it
+                       lineBuffer[linePos] = '\0';
+                       ColouriseErrorListLine(lineBuffer, linePos, i, styler, valueSeparate, 
escapeSequences);
+                       linePos = 0;
+               }
+       }
+       if (linePos > 0) {      // Last line does not have ending characters
+               lineBuffer[linePos] = '\0';
+               ColouriseErrorListLine(lineBuffer, linePos, startPos + length - 1, styler, valueSeparate, 
escapeSequences);
+       }
+}
+
+static const char *const emptyWordListDesc[] = {
+       0
+};
+
+LexerModule lmErrorList(SCLEX_ERRORLIST, ColouriseErrorListDoc, "errorlist", 0, emptyWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexFlagship.cxx 
b/plugins/scintilla/scintilla/lexers/LexFlagship.cxx
index b8568b0..6f6f4c0 100644
--- a/plugins/scintilla/scintilla/lexers/LexFlagship.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexFlagship.cxx
@@ -37,7 +37,7 @@ static inline bool IsAWordChar(int ch)
                                (isalnum(ch) || ch == '_');
 }
 
-static void ColouriseFlagShipDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseFlagShipDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                  WordList *keywordlists[], Accessor &styler)
 {
 
@@ -271,9 +271,9 @@ static void ColouriseFlagShipDoc(unsigned int startPos, int length, int initStyl
                                        }
                                }
                        } else if (bEnableCode && sc.ch == '{') {
-                               int p = 0;
+                               Sci_Position p = 0;
                                int chSeek;
-                               unsigned int endPos(startPos + length);
+                               Sci_PositionU endPos(startPos + length);
                                do {    // Skip whitespace
                                        chSeek = sc.GetRelative(++p);
                                } while (IsASpaceOrTab(chSeek) && (sc.currentPos + p < endPos));
@@ -302,14 +302,14 @@ static void ColouriseFlagShipDoc(unsigned int startPos, int length, int initStyl
        sc.Complete();
 }
 
-static void FoldFlagShipDoc(unsigned int startPos, int length, int,
+static void FoldFlagShipDoc(Sci_PositionU startPos, Sci_Position length, int,
                                                                        WordList *[], Accessor &styler)
 {
 
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
 
        // Backtrack to previous line in case need to fix its fold status
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0 && lineCurrent > 0) {
                        lineCurrent--;
                        startPos = styler.LineStart(lineCurrent);
@@ -317,7 +317,7 @@ static void FoldFlagShipDoc(unsigned int startPos, int length, int,
        int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
        char chNext = styler[startPos];
-       for (int i = startPos; i < endPos; i++) {
+       for (Sci_Position i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
diff --git a/plugins/scintilla/scintilla/lexers/LexForth.cxx b/plugins/scintilla/scintilla/lexers/LexForth.cxx
index 0e9875c..63d3f4f 100644
--- a/plugins/scintilla/scintilla/lexers/LexForth.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexForth.cxx
@@ -27,15 +27,6 @@
 using namespace Scintilla;
 #endif
 
-static inline bool IsAWordChar(int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
-               ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
-               ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
-               ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
-               ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
-               ch == ')' );
-}
-
 static inline bool IsAWordStart(int ch) {
        return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
 }
@@ -48,7 +39,7 @@ static inline bool IsASpaceChar(int ch) {
        return (ch < 0x80) && isspace(ch);
 }
 
-static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
+static void ColouriseForthDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordLists[],
                             Accessor &styler) {
 
     WordList &control = *keywordLists[0];
@@ -123,29 +114,29 @@ static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle,
                                        (sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
                                        (sc.atLineEnd   || IsASpaceChar(sc.chNext))) {
                                sc.SetState(SCE_FORTH_COMMENT_ML);
-                       } else if (     (sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
+                       } else if (     (sc.ch == '$' && (IsASCII(sc.chNext) && isxdigit(sc.chNext))) ) {
                                // number starting with $ is a hex number
                                sc.SetState(SCE_FORTH_NUMBER);
-                               while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
+                               while(sc.More() && IsASCII(sc.chNext) && isxdigit(sc.chNext))
                                        sc.Forward();
-                       } else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == 
'1'))) ) {
+                       } else if ( (sc.ch == '%' && (IsASCII(sc.chNext) && (sc.chNext == '0' || sc.chNext == 
'1'))) ) {
                                // number starting with % is binary
                                sc.SetState(SCE_FORTH_NUMBER);
-                               while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == 
'1'))
+                               while(sc.More() && IsASCII(sc.chNext) && (sc.chNext == '0' || sc.chNext == 
'1'))
                                        sc.Forward();
-                       } else if (     isascii(sc.ch) &&
-                                               (isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && 
isascii(sc.chNext) && isxdigit(sc.chNext)) )
+                       } else if (     IsASCII(sc.ch) &&
+                                               (isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && 
IsASCII(sc.chNext) && isxdigit(sc.chNext)) )
                                        ){
                                sc.SetState(SCE_FORTH_NUMBER);
                        } else if (IsAWordStart(sc.ch)) {
                                sc.SetState(SCE_FORTH_IDENTIFIER);
                        } else if (sc.ch == '{') {
                                sc.SetState(SCE_FORTH_LOCALE);
-                       } else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
+                       } else if (sc.ch == ':' && IsASCII(sc.chNext) && isspace(sc.chNext)) {
                                // highlight word definitions e.g.  : GCD ( n n -- n ) ..... ;
                                //                                  ^ ^^^
                                sc.SetState(SCE_FORTH_DEFWORD);
-                               while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
+                               while(sc.More() && IsASCII(sc.chNext) && isspace(sc.chNext))
                                        sc.Forward();
                        } else if (sc.ch == ';' &&
                                        (sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
@@ -160,7 +151,7 @@ static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-static void FoldForthDoc(unsigned int, int, int, WordList *[],
+static void FoldForthDoc(Sci_PositionU, Sci_Position, int, WordList *[],
                                                Accessor &) {
 }
 
diff --git a/plugins/scintilla/scintilla/lexers/LexFortran.cxx 
b/plugins/scintilla/scintilla/lexers/LexFortran.cxx
index bfbe301..495b002 100644
--- a/plugins/scintilla/scintilla/lexers/LexFortran.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexFortran.cxx
@@ -1,7 +1,7 @@
 // Scintilla source code edit control
 /** @file LexFortran.cxx
  ** Lexer for Fortran.
- ** Writen by Chuan-jian Shen, Last changed Sep. 2003
+ ** Written by Chuan-jian Shen, Last changed Sep. 2003
  **/
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
@@ -38,15 +38,15 @@ static inline bool IsAWordStart(const int ch) {
        return (ch < 0x80) && (isalnum(ch));
 }
 /***************************************/
-inline bool IsABlank(unsigned int ch) {
-    return (ch == ' ') || (ch == 0x09) || (ch == 0x0b) ;
+static inline bool IsABlank(unsigned int ch) {
+       return (ch == ' ') || (ch == 0x09) || (ch == 0x0b) ;
 }
 /***************************************/
-inline bool IsALineEnd(char ch) {
-    return ((ch == '\n') || (ch == '\r')) ;
+static inline bool IsALineEnd(char ch) {
+       return ((ch == '\n') || (ch == '\r')) ;
 }
 /***************************************/
-unsigned int GetContinuedPos(unsigned int pos, Accessor &styler) {
+static Sci_PositionU GetContinuedPos(Sci_PositionU pos, Accessor &styler) {
        while (!IsALineEnd(styler.SafeGetCharAt(pos++))) continue;
        if (styler.SafeGetCharAt(pos) == '\n') pos++;
        while (IsABlank(styler.SafeGetCharAt(pos++))) continue;
@@ -59,14 +59,15 @@ unsigned int GetContinuedPos(unsigned int pos, Accessor &styler) {
        }
 }
 /***************************************/
-static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle,
-                       WordList *keywordlists[], Accessor &styler, bool isFixFormat) {
+static void ColouriseFortranDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+        WordList *keywordlists[], Accessor &styler, bool isFixFormat) {
        WordList &keywords = *keywordlists[0];
        WordList &keywords2 = *keywordlists[1];
        WordList &keywords3 = *keywordlists[2];
        /***************************************/
-       int posLineStart = 0, numNonBlank = 0, prevState = 0;
-       int endPos = startPos + length;
+       Sci_Position posLineStart = 0;
+       int numNonBlank = 0, prevState = 0;
+       Sci_Position endPos = startPos + length;
        /***************************************/
        // backtrack to the nearest keyword
        while ((startPos > 1) && (styler.StyleAt(startPos) != SCE_F_WORD)) {
@@ -86,14 +87,14 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
                if (!IsASpaceOrTab(sc.ch)) numNonBlank ++;
                /***********************************************/
                // Handle the fix format generically
-               int toLineStart = sc.currentPos - posLineStart;
+               Sci_Position toLineStart = sc.currentPos - posLineStart;
                if (isFixFormat && (toLineStart < 6 || toLineStart >= 72)) {
                        if ((toLineStart == 0 && (tolower(sc.ch) == 'c' || sc.ch == '*')) || sc.ch == '!') {
-                if (sc.MatchIgnoreCase("cdec$") || sc.MatchIgnoreCase("*dec$") || 
sc.MatchIgnoreCase("!dec$") ||
-                    sc.MatchIgnoreCase("cdir$") || sc.MatchIgnoreCase("*dir$") || 
sc.MatchIgnoreCase("!dir$") ||
-                    sc.MatchIgnoreCase("cms$")  || sc.MatchIgnoreCase("*ms$")  || sc.MatchIgnoreCase("!ms$") 
 ||
-                    sc.chNext == '$') {
-                    sc.SetState(SCE_F_PREPROCESSOR);
+                               if (sc.MatchIgnoreCase("cdec$") || sc.MatchIgnoreCase("*dec$") || 
sc.MatchIgnoreCase("!dec$") ||
+                                       sc.MatchIgnoreCase("cdir$") || sc.MatchIgnoreCase("*dir$") || 
sc.MatchIgnoreCase("!dir$") ||
+                                       sc.MatchIgnoreCase("cms$")  || sc.MatchIgnoreCase("*ms$")  || 
sc.MatchIgnoreCase("!ms$")  ||
+                                       sc.chNext == '$') {
+                                       sc.SetState(SCE_F_PREPROCESSOR);
                                } else {
                                        sc.SetState(SCE_F_COMMENT);
                                }
@@ -111,26 +112,18 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
                                //if (!IsASpace(sc.ch) && sc.ch != '0') {
                                if (sc.ch != '\r' && sc.ch != '\n') {
                                        sc.SetState(SCE_F_CONTINUATION);
-                    if (!IsASpace(sc.ch) && sc.ch != '0')
-                        sc.ForwardSetState(prevState);
+                                       if (!IsASpace(sc.ch) && sc.ch != '0')
+                                               sc.ForwardSetState(prevState);
                                } else
                                        sc.SetState(SCE_F_DEFAULT);
                        }
                        continue;
                }
                /***************************************/
-               // Hanndle preprocessor directives
-               if (sc.ch == '#' && numNonBlank == 1)
-               {
-            sc.SetState(SCE_F_PREPROCESSOR);
-            while (!sc.atLineEnd && sc.More())
-                sc.Forward(); // Until line end
-               }
-               /***************************************/
                // Handle line continuation generically.
                if (!isFixFormat && sc.ch == '&' && sc.state != SCE_F_COMMENT) {
                        char chTemp = ' ';
-                       int j = 1;
+                       Sci_Position j = 1;
                        while (IsABlank(chTemp) && j<132) {
                                chTemp = static_cast<char>(sc.GetRelative(j));
                                j++;
@@ -142,7 +135,11 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
                                int currentState = sc.state;
                                sc.SetState(SCE_F_CONTINUATION);
                                sc.ForwardSetState(SCE_F_DEFAULT);
-                               while (IsASpace(sc.ch) && sc.More()) sc.Forward();
+                               while (IsASpace(sc.ch) && sc.More()) {
+                                       sc.Forward();
+                                       if (sc.atLineStart) numNonBlank = 0;
+                                       if (!IsASpaceOrTab(sc.ch)) numNonBlank ++;
+                               }
                                if (sc.ch == '&') {
                                        sc.SetState(SCE_F_CONTINUATION);
                                        sc.Forward();
@@ -151,6 +148,14 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
                        }
                }
                /***************************************/
+               // Hanndle preprocessor directives
+               if (sc.ch == '#' && numNonBlank == 1)
+               {
+                       sc.SetState(SCE_F_PREPROCESSOR);
+                       while (!sc.atLineEnd && sc.More())
+                               sc.Forward(); // Until line end
+               }
+               /***************************************/
                // Determine if the current state should terminate.
                if (sc.state == SCE_F_OPERATOR) {
                        sc.SetState(SCE_F_DEFAULT);
@@ -221,8 +226,8 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
                // Determine if a new state should be entered.
                if (sc.state == SCE_F_DEFAULT) {
                        if (sc.ch == '!') {
-                if (sc.MatchIgnoreCase("!dec$") || sc.MatchIgnoreCase("!dir$") ||
-                    sc.MatchIgnoreCase("!ms$") || sc.chNext == '$') {
+                               if (sc.MatchIgnoreCase("!dec$") || sc.MatchIgnoreCase("!dir$") ||
+                                       sc.MatchIgnoreCase("!ms$") || sc.chNext == '$') {
                                        sc.SetState(SCE_F_PREPROCESSOR);
                                } else {
                                        sc.SetState(SCE_F_COMMENT);
@@ -232,7 +237,7 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
                        } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
                                sc.SetState(SCE_F_NUMBER);
                        } else if ((tolower(sc.ch) == 'b' || tolower(sc.ch) == 'o' ||
-                                           tolower(sc.ch) == 'z') && (sc.chNext == '\"' || sc.chNext == 
'\'')) {
+                               tolower(sc.ch) == 'z') && (sc.chNext == '\"' || sc.chNext == '\'')) {
                                sc.SetState(SCE_F_NUMBER);
                                sc.Forward();
                        } else if (sc.ch == '.' && isalpha(sc.chNext)) {
@@ -251,81 +256,297 @@ static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle
        sc.Complete();
 }
 /***************************************/
+static void CheckLevelCommentLine(const unsigned int nComL,
+                                 int nComColB[], int nComColF[], int &nComCur,
+                                 bool comLineB[], bool comLineF[], bool &comLineCur,
+                                 int &levelDeltaNext) {
+       levelDeltaNext = 0;
+       if (!comLineCur) {
+               return;
+       }
+
+       if (!comLineF[0] || nComColF[0] != nComCur) {
+               unsigned int i=0;
+               for (; i<nComL; i++) {
+                       if (!comLineB[i] || nComColB[i] != nComCur) {
+                               break;
+                       }
+               }
+               if (i == nComL) {
+                       levelDeltaNext = -1;
+               }
+       }
+       else if (!comLineB[0] || nComColB[0] != nComCur) {
+               unsigned int i=0;
+               for (; i<nComL; i++) {
+                       if (!comLineF[i] || nComColF[i] != nComCur) {
+                               break;
+                       }
+               }
+               if (i == nComL) {
+                       levelDeltaNext = 1;
+               }
+       }
+}
+/***************************************/
+static void GetIfLineComment(Accessor &styler, bool isFixFormat, const Sci_Position line, bool &isComLine, 
Sci_Position &comCol) {
+       Sci_Position col = 0;
+       isComLine = false;
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position len = styler.Length();
+       while(pos<len) {
+               char ch = styler.SafeGetCharAt(pos);
+               if (ch == '!' || (isFixFormat && col == 0 && (tolower(ch) == 'c' || ch == '*'))) {
+                       isComLine = true;
+                       comCol = col;
+                       break;
+               }
+               else if (!IsABlank(ch) || IsALineEnd(ch)) {
+                       break;
+               }
+               pos++;
+               col++;
+       }
+}
+/***************************************/
+static void StepCommentLine(Accessor &styler, bool isFixFormat, Sci_Position lineCurrent, const unsigned int 
nComL,
+                                 Sci_Position nComColB[], Sci_Position nComColF[], Sci_Position &nComCur,
+                                 bool comLineB[], bool comLineF[], bool &comLineCur) {
+       Sci_Position nLineTotal = styler.GetLine(styler.Length()-1) + 1;
+       if (lineCurrent >= nLineTotal) {
+               return;
+       }
+
+       for (int i=nComL-2; i>=0; i--) {
+               nComColB[i+1] = nComColB[i];
+               comLineB[i+1] = comLineB[i];
+       }
+       nComColB[0] = nComCur;
+       comLineB[0] = comLineCur;
+       nComCur = nComColF[0];
+       comLineCur = comLineF[0];
+       for (unsigned int i=0; i+1<nComL; i++) {
+               nComColF[i] = nComColF[i+1];
+               comLineF[i] = comLineF[i+1];
+       }
+       Sci_Position chL = lineCurrent + nComL;
+       if (chL < nLineTotal) {
+               GetIfLineComment(styler, isFixFormat, chL, comLineF[nComL-1], nComColF[nComL-1]);
+       }
+       else {
+               comLineF[nComL-1] = false;
+       }
+}
+/***************************************/
+static void CheckBackComLines(Accessor &styler, bool isFixFormat, Sci_Position lineCurrent, const unsigned 
int nComL,
+                                 Sci_Position nComColB[], Sci_Position nComColF[], Sci_Position nComCur,
+                                 bool comLineB[], bool comLineF[], bool &comLineCur) {
+       unsigned int nLines = nComL + nComL + 1;
+       bool* comL = new bool[nLines];
+       Sci_Position* nComCol = new Sci_Position[nLines];
+       bool comL0;
+       Sci_Position nComCol0;
+       GetIfLineComment(styler, isFixFormat, lineCurrent-nComL-1, comL0, nComCol0);
+       for (unsigned int i=0; i<nComL; i++) {
+               unsigned copyTo = nComL - i - 1;
+               comL[copyTo]    = comLineB[i];
+               nComCol[copyTo] = nComColB[i];
+       }
+       assert(nComL < nLines);
+       comL[nComL] = comLineCur;
+       nComCol[nComL] = nComCur;
+       for (unsigned int i=0; i<nComL; i++) {
+               unsigned copyTo = i + nComL + 1;
+               comL[copyTo]    = comLineF[i];
+               nComCol[copyTo] = nComColF[i];
+       }
+       
+       Sci_Position lineC = lineCurrent - nComL + 1;
+       unsigned int iStart;
+       if (lineC <= 0) {
+               lineC = 0;
+               iStart = nComL - lineCurrent;
+       }
+       else {
+               iStart = 1;
+       }
+       bool levChanged = false;
+       int lev = styler.LevelAt(lineC) & SC_FOLDLEVELNUMBERMASK;
+       
+       for (unsigned int i=iStart; i<=nComL; i++) {
+               if (comL[i] && (!comL[i-1] || nComCol[i] != nComCol[i-1])) {
+                       bool increase = true;
+                       unsigned int until = i + nComL;
+                       for (unsigned int j=i+1; j<=until; j++) {
+                               if (!comL[j] || nComCol[j] != nComCol[i]) {
+                                       increase = false;
+                                       break;
+                               }
+                       }
+                       lev = styler.LevelAt(lineC) & SC_FOLDLEVELNUMBERMASK;
+                       if (increase) {
+                               int levH = lev | SC_FOLDLEVELHEADERFLAG;
+                               lev += 1;
+                               if (levH != styler.LevelAt(lineC)) {
+                                       styler.SetLevel(lineC, levH);
+                               }
+                               for (Sci_Position j=lineC+1; j<=lineCurrent; j++) {
+                                       if (lev != styler.LevelAt(j)) {
+                                               styler.SetLevel(j, lev);
+                                       }
+                               }
+                               break;
+                       }
+                       else {
+                               if (lev != styler.LevelAt(lineC)) {
+                                       styler.SetLevel(lineC, lev);
+                               }
+                       }
+                       levChanged = true;
+               }
+               else if (levChanged && comL[i]) {
+                       if (lev != styler.LevelAt(lineC)) {
+                               styler.SetLevel(lineC, lev);
+                       }
+               }
+               lineC++;
+       }
+       delete[] comL;
+       delete[] nComCol;
+}
+/***************************************/
 // To determine the folding level depending on keywords
 static int classifyFoldPointFortran(const char* s, const char* prevWord, const char chNextNonBlank) {
        int lev = 0;
-       if ((strcmp(prevWord, "else") == 0 && strcmp(s, "if") == 0) || strcmp(s, "elseif") == 0)
-               return -1;
-       if (strcmp(s, "associate") == 0 || strcmp(s, "block") == 0
-           || strcmp(s, "blockdata") == 0 || strcmp(s, "select") == 0
-           || strcmp(s, "do") == 0 || strcmp(s, "enum") ==0
-           || strcmp(s, "function") == 0 || strcmp(s, "interface") == 0
-               || strcmp(s, "module") == 0 || strcmp(s, "program") == 0
-               || strcmp(s, "subroutine") == 0 || strcmp(s, "then") == 0
-               || (strcmp(s, "type") == 0 && chNextNonBlank != '(')
-        || strcmp(s, "critical") == 0){
-                       if (strcmp(prevWord, "end") == 0)
-                               lev = 0;
-                       else
-                               lev = 1;
+
+       if ((strcmp(prevWord, "module") == 0 && strcmp(s, "subroutine") == 0)
+               || (strcmp(prevWord, "module") == 0 && strcmp(s, "function") == 0)) {
+               lev = 0;
+       } else if (strcmp(s, "associate") == 0 || strcmp(s, "block") == 0
+               || strcmp(s, "blockdata") == 0 || strcmp(s, "select") == 0
+               || strcmp(s, "selecttype") == 0 || strcmp(s, "selectcase") == 0
+               || strcmp(s, "do") == 0 || strcmp(s, "enum") ==0
+               || strcmp(s, "function") == 0 || strcmp(s, "interface") == 0
+               || strcmp(s, "module") == 0 || strcmp(s, "program") == 0
+               || strcmp(s, "subroutine") == 0 || strcmp(s, "then") == 0
+               || (strcmp(s, "type") == 0 && chNextNonBlank != '(')
+               || strcmp(s, "critical") == 0 || strcmp(s, "submodule") == 0){
+               if (strcmp(prevWord, "end") == 0)
+                       lev = 0;
+               else
+                       lev = 1;
        } else if ((strcmp(s, "end") == 0 && chNextNonBlank != '=')
-               || strcmp(s, "endassociate") == 0 || strcmp(s, "endblock") == 0
-               || strcmp(s, "endblockdata") == 0 || strcmp(s, "endselect") == 0
-               || strcmp(s, "enddo") == 0 || strcmp(s, "endenum") ==0
-               || strcmp(s, "endif") == 0 || strcmp(s, "endforall") == 0
-               || strcmp(s, "endfunction") == 0 || strcmp(s, "endinterface") == 0
-               || strcmp(s, "endmodule") == 0 || strcmp(s, "endprogram") == 0
-               || strcmp(s, "endsubroutine") == 0 || strcmp(s, "endtype") == 0
-               || strcmp(s, "endwhere") == 0 || strcmp(s, "endcritical") == 0
-               || (strcmp(s, "procedure") == 0 && strcmp(prevWord, "module") == 0) ) { // Take care of the 
"module procedure" statement
-                       lev = -1;
+               || strcmp(s, "endassociate") == 0 || strcmp(s, "endblock") == 0
+               || strcmp(s, "endblockdata") == 0 || strcmp(s, "endselect") == 0
+               || strcmp(s, "enddo") == 0 || strcmp(s, "endenum") ==0
+               || strcmp(s, "endif") == 0 || strcmp(s, "endforall") == 0
+               || strcmp(s, "endfunction") == 0 || strcmp(s, "endinterface") == 0
+               || strcmp(s, "endmodule") == 0 || strcmp(s, "endprogram") == 0
+               || strcmp(s, "endsubroutine") == 0 || strcmp(s, "endtype") == 0
+               || strcmp(s, "endwhere") == 0 || strcmp(s, "endcritical") == 0
+               || (strcmp(prevWord, "module") == 0 && strcmp(s, "procedure") == 0)  // Take care of the 
"module procedure" statement
+               || strcmp(s, "endsubmodule") == 0) {
+               lev = -1;
        } else if (strcmp(prevWord, "end") == 0 && strcmp(s, "if") == 0){ // end if
-                       lev = 0;
+               lev = 0;
        } else if (strcmp(prevWord, "type") == 0 && strcmp(s, "is") == 0){ // type is
-                        lev = -1;
-        }
+               lev = -1;
+       } else if ((strcmp(prevWord, "end") == 0 && strcmp(s, "procedure") == 0)
+                          || strcmp(s, "endprocedure") == 0) {
+                       lev = 1; // level back to 0, because no folding support for "module procedure" in 
submodule
+       }
        return lev;
 }
+/***************************************/
 // Folding the code
-static void FoldFortranDoc(unsigned int startPos, int length, int initStyle,
-                                                  Accessor &styler, bool isFixFormat) {
-       //
-       // bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
-       // Do not know how to fold the comment at the moment.
-       //
+static void FoldFortranDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+        Accessor &styler, bool isFixFormat) {
+
+       bool foldComment = styler.GetPropertyInt("fold.comment", 1) != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
-       int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
-       int levelCurrent = levelPrev;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       bool isPrevLine;
+       if (lineCurrent > 0) {
+               lineCurrent--;
+               startPos = styler.LineStart(lineCurrent);
+               isPrevLine = true;
+       } else {
+               isPrevLine = false;
+       }
        char chNext = styler[startPos];
-       char chNextNonBlank;
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
+       int levelDeltaNext = 0;
+
+       const unsigned int nComL = 3; // defines how many comment lines should be before they are folded
+       Sci_Position nComColB[nComL];
+       Sci_Position nComColF[nComL] = {};
+       Sci_Position nComCur;
+       bool comLineB[nComL];
+       bool comLineF[nComL];
+       bool comLineCur;
+       Sci_Position nLineTotal = styler.GetLine(styler.Length()-1) + 1;
+       if (foldComment) {
+               for (unsigned int i=0; i<nComL; i++) {
+                       Sci_Position chL = lineCurrent-(i+1);
+                       if (chL < 0) {
+                               comLineB[i] = false;
+                               break;
+                       }
+                       GetIfLineComment(styler, isFixFormat, chL, comLineB[i], nComColB[i]);
+                       if (!comLineB[i]) {
+                               for (unsigned int j=i+1; j<nComL; j++) {
+                                       comLineB[j] = false;
+                               }
+                               break;
+                       }
+               }
+               for (unsigned int i=0; i<nComL; i++) {
+                       Sci_Position chL = lineCurrent+i+1;
+                       if (chL >= nLineTotal) {
+                               comLineF[i] = false;
+                               break;
+                       }
+                       GetIfLineComment(styler, isFixFormat, chL, comLineF[i], nComColF[i]);
+               }
+               GetIfLineComment(styler, isFixFormat, lineCurrent, comLineCur, nComCur);
+               CheckBackComLines(styler, isFixFormat, lineCurrent, nComL, nComColB, nComColF, nComCur, 
+                               comLineB, comLineF, comLineCur);
+       }
+       int levelCurrent = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
+
        /***************************************/
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
        char prevWord[32] = "";
-       char Label[6] = "";
-       // Variables for do label folding.
-       static int doLabels[100];
-       static int posLabel=-1;
        /***************************************/
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
-               chNextNonBlank = chNext;
-               unsigned int j=i+1;
+               char chNextNonBlank = chNext;
+               bool nextEOL = false;
+               if (IsALineEnd(chNextNonBlank)) {
+                       nextEOL = true;
+               }
+               Sci_PositionU j=i+1;
                while(IsABlank(chNextNonBlank) && j<endPos) {
                        j ++ ;
                        chNextNonBlank = styler.SafeGetCharAt(j);
+                       if (IsALineEnd(chNextNonBlank)) {
+                               nextEOL = true;
+                       }
+               }
+               if (!nextEOL && j == endPos) {
+                       nextEOL = true;
                }
                int stylePrev = style;
                style = styleNext;
                styleNext = styler.StyleAt(i + 1);
                bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
                //
-               if (((isFixFormat && stylePrev == SCE_F_CONTINUATION) || stylePrev == SCE_F_DEFAULT || 
stylePrev == SCE_F_OPERATOR) && (style == SCE_F_WORD || style == SCE_F_LABEL)) {
+               if (((isFixFormat && stylePrev == SCE_F_CONTINUATION) || stylePrev == SCE_F_DEFAULT
+                       || stylePrev == SCE_F_OPERATOR) && (style == SCE_F_WORD || style == SCE_F_LABEL)) {
                        // Store last word and label start point.
                        lastStart = i;
                }
@@ -333,13 +554,13 @@ static void FoldFortranDoc(unsigned int startPos, int length, int initStyle,
                if (style == SCE_F_WORD) {
                        if(iswordchar(ch) && !iswordchar(chNext)) {
                                char s[32];
-                               unsigned int k;
+                               Sci_PositionU k;
                                for(k=0; (k<31 ) && (k<i-lastStart+1 ); k++) {
                                        s[k] = static_cast<char>(tolower(styler[lastStart+k]));
                                }
                                s[k] = '\0';
                                // Handle the forall and where statement and structure.
-                               if (strcmp(s, "forall") == 0 || strcmp(s, "where") == 0) {
+                               if (strcmp(s, "forall") == 0 || (strcmp(s, "where") == 0 && strcmp(prevWord, 
"else") != 0)) {
                                        if (strcmp(prevWord, "end") != 0) {
                                                j = i + 1;
                                                char chBrace = '(', chSeek = ')', ch1 = 
styler.SafeGetCharAt(j);
@@ -362,22 +583,25 @@ static void FoldFortranDoc(unsigned int startPos, int length, int initStyle,
                                                                if (depth == 0) break;
                                                        }
                                                }
+                                               Sci_Position tmpLineCurrent = lineCurrent;
                                                while (j<endPos) {
                                                        j++;
                                                        chAtPos = styler.SafeGetCharAt(j);
                                                        styAtPos = styler.StyleAt(j);
-                                                       if (styAtPos == SCE_F_COMMENT || IsABlank(chAtPos)) 
continue;
+                                                       if (!IsALineEnd(chAtPos) && (styAtPos == 
SCE_F_COMMENT || IsABlank(chAtPos))) continue;
                                                        if (isFixFormat) {
                                                                if (!IsALineEnd(chAtPos)) {
                                                                        break;
                                                                } else {
-                                                                       if (lineCurrent < 
styler.GetLine(styler.Length()-1)) {
-                                                                               j = 
styler.LineStart(lineCurrent+1);
-                                                                               if (styler.StyleAt(j+5) == 
SCE_F_CONTINUATION) {
+                                                                       if (tmpLineCurrent < 
styler.GetLine(styler.Length()-1)) {
+                                                                               tmpLineCurrent++;
+                                                                               j = 
styler.LineStart(tmpLineCurrent);
+                                                                               if (styler.StyleAt(j+5) == 
SCE_F_CONTINUATION
+                                                                                       && 
!IsABlank(styler.SafeGetCharAt(j+5)) && styler.SafeGetCharAt(j+5) != '0') {
                                                                                        j += 5;
                                                                                        continue;
                                                                                } else {
-                                                                                       levelCurrent++;
+                                                                                       levelDeltaNext++;
                                                                                        break;
                                                                                }
                                                                        }
@@ -387,7 +611,7 @@ static void FoldFortranDoc(unsigned int startPos, int length, int initStyle,
                                                                        j = GetContinuedPos(j+1, styler);
                                                                        continue;
                                                                } else if (IsALineEnd(chAtPos)) {
-                                                                       levelCurrent ++;
+                                                                       levelDeltaNext++;
                                                                        break;
                                                                } else {
                                                                        break;
@@ -396,61 +620,74 @@ static void FoldFortranDoc(unsigned int startPos, int length, int initStyle,
                                                }
                                        }
                                } else {
-                                       levelCurrent += classifyFoldPointFortran(s, prevWord, chNextNonBlank);
-                                       // Store the do Labels into array
-                                       if (strcmp(s, "do") == 0 && IsADigit(chNextNonBlank)) {
-                                               unsigned int k = 0;
-                                               for (i=j; (i<j+5 && i<endPos); i++) {
-                                                       ch = styler.SafeGetCharAt(i);
-                                                       if (IsADigit(ch))
-                                                               Label[k++] = ch;
-                                                       else
-                                                               break;
+                                       int wordLevelDelta = classifyFoldPointFortran(s, prevWord, 
chNextNonBlank);
+                                       levelDeltaNext += wordLevelDelta;
+                                       if (((strcmp(s, "else") == 0) && (nextEOL || chNextNonBlank == '!')) 
||
+                                               (strcmp(prevWord, "else") == 0 && strcmp(s, "where") == 0) || 
strcmp(s, "elsewhere") == 0) {
+                                               if (!isPrevLine) {
+                                                       levelCurrent--;
+                                               }
+                                               levelDeltaNext++;
+                                       } else if ((strcmp(prevWord, "else") == 0 && strcmp(s, "if") == 0) || 
strcmp(s, "elseif") == 0) {
+                                               if (!isPrevLine) {
+                                                       levelCurrent--;
+                                               }
+                                       } else if ((strcmp(prevWord, "select") == 0 && strcmp(s, "case") == 
0) || strcmp(s, "selectcase") == 0 ||
+                                                          (strcmp(prevWord, "select") == 0 && strcmp(s, 
"type") == 0) || strcmp(s, "selecttype") == 0) {
+                                               levelDeltaNext += 2;
+                                       } else if ((strcmp(s, "case") == 0 && chNextNonBlank == '(') || 
(strcmp(prevWord, "case") == 0 && strcmp(s, "default") == 0) ||
+                                                          (strcmp(prevWord, "type") == 0 && strcmp(s, "is") 
== 0) ||
+                                                          (strcmp(prevWord, "class") == 0 && strcmp(s, "is") 
== 0) ||
+                                                          (strcmp(prevWord, "class") == 0 && strcmp(s, 
"default") == 0) ) {
+                                               if (!isPrevLine) {
+                                                       levelCurrent--;
                                                }
-                                               Label[k] = '\0';
-                                               posLabel ++;
-                                               doLabels[posLabel] = atoi(Label);
+                                               levelDeltaNext++;
+                                       } else if ((strcmp(prevWord, "end") == 0 && strcmp(s, "select") == 0) 
|| strcmp(s, "endselect") == 0) {
+                                               levelDeltaNext -= 2;
+                                       }
+
+                                       // There are multiple forms of "do" loop. The older form with a label 
"do 100 i=1,10" would require matching
+                                       // labels to ensure the folding level does not decrease too far when 
labels are used for other purposes.
+                                       // Since this is difficult, do-label constructs are not folded.
+                                       if (strcmp(s, "do") == 0 && IsADigit(chNextNonBlank)) {
+                                               // Remove delta for do-label
+                                               levelDeltaNext -= wordLevelDelta;
                                        }
                                }
                                strcpy(prevWord, s);
                        }
-               } else if (style == SCE_F_LABEL) {
-                       if(IsADigit(ch) && !IsADigit(chNext)) {
-                               for(j = 0; ( j < 5 ) && ( j < i-lastStart+1 ); j++) {
-                                       ch = styler.SafeGetCharAt(lastStart + j);
-                                       if (IsADigit(ch) && styler.StyleAt(lastStart+j) == SCE_F_LABEL)
-                                               Label[j] = ch;
-                                       else
-                                               break;
-                               }
-                               Label[j] = '\0';
-                               while (doLabels[posLabel] == atoi(Label) && posLabel > -1) {
-                                       levelCurrent--;
-                                       posLabel--;
-                               }
-                       }
                }
                if (atEOL) {
-                       int lev = levelPrev;
+                       if (foldComment) {
+                               int ldNext;
+                               CheckLevelCommentLine(nComL, nComColB, nComColF, nComCur, comLineB, comLineF, 
comLineCur, ldNext);
+                               levelDeltaNext += ldNext;
+                       }
+                       int lev = levelCurrent;
                        if (visibleChars == 0 && foldCompact)
                                lev |= SC_FOLDLEVELWHITEFLAG;
-                       if ((levelCurrent > levelPrev) && (visibleChars > 0))
+                       if ((levelDeltaNext > 0) && (visibleChars > 0))
                                lev |= SC_FOLDLEVELHEADERFLAG;
-                       if (lev != styler.LevelAt(lineCurrent)) {
+                       if (lev != styler.LevelAt(lineCurrent))
                                styler.SetLevel(lineCurrent, lev);
-                       }
+
                        lineCurrent++;
-                       levelPrev = levelCurrent;
+                       levelCurrent += levelDeltaNext;
+                       levelDeltaNext = 0;
                        visibleChars = 0;
                        strcpy(prevWord, "");
+                       isPrevLine = false;
+
+                       if (foldComment) {
+                               StepCommentLine(styler, isFixFormat, lineCurrent, nComL, nComColB, nComColF, 
nComCur,
+                                               comLineB, comLineF, comLineCur);
+                       }
                }
                /***************************************/
                if (!isspacechar(ch)) visibleChars++;
        }
        /***************************************/
-       // Fill in the real level of the next line, keeping the current flags as they will be filled in later
-       int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
-       styler.SetLevel(lineCurrent, levelPrev | flagsNext);
 }
 /***************************************/
 static const char * const FortranWordLists[] = {
@@ -460,23 +697,23 @@ static const char * const FortranWordLists[] = {
        0,
 };
 /***************************************/
-static void ColouriseFortranDocFreeFormat(unsigned int startPos, int length, int initStyle, WordList 
*keywordlists[],
-                            Accessor &styler) {
+static void ColouriseFortranDocFreeFormat(Sci_PositionU startPos, Sci_Position length, int initStyle, 
WordList *keywordlists[],
+        Accessor &styler) {
        ColouriseFortranDoc(startPos, length, initStyle, keywordlists, styler, false);
 }
 /***************************************/
-static void ColouriseFortranDocFixFormat(unsigned int startPos, int length, int initStyle, WordList 
*keywordlists[],
-                            Accessor &styler) {
+static void ColouriseFortranDocFixFormat(Sci_PositionU startPos, Sci_Position length, int initStyle, 
WordList *keywordlists[],
+        Accessor &styler) {
        ColouriseFortranDoc(startPos, length, initStyle, keywordlists, styler, true);
 }
 /***************************************/
-static void FoldFortranDocFreeFormat(unsigned int startPos, int length, int initStyle,
-               WordList *[], Accessor &styler) {
+static void FoldFortranDocFreeFormat(Sci_PositionU startPos, Sci_Position length, int initStyle,
+        WordList *[], Accessor &styler) {
        FoldFortranDoc(startPos, length, initStyle,styler, false);
 }
 /***************************************/
-static void FoldFortranDocFixFormat(unsigned int startPos, int length, int initStyle,
-               WordList *[], Accessor &styler) {
+static void FoldFortranDocFixFormat(Sci_PositionU startPos, Sci_Position length, int initStyle,
+        WordList *[], Accessor &styler) {
        FoldFortranDoc(startPos, length, initStyle,styler, true);
 }
 /***************************************/
diff --git a/plugins/scintilla/scintilla/lexers/LexGAP.cxx b/plugins/scintilla/scintilla/lexers/LexGAP.cxx
index fb30660..ee0a7ad 100644
--- a/plugins/scintilla/scintilla/lexers/LexGAP.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexGAP.cxx
@@ -29,7 +29,7 @@ using namespace Scintilla;
 #endif
 
 static inline bool IsGAPOperator(char ch) {
-       if (isascii(ch) && isalnum(ch)) return false;
+       if (IsASCII(ch) && isalnum(ch)) return false;
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/' ||
                ch == '^' || ch == ',' || ch == '!' || ch == '.' ||
                ch == '=' || ch == '<' || ch == '>' || ch == '(' ||
@@ -39,8 +39,8 @@ static inline bool IsGAPOperator(char ch) {
        return false;
 }
 
-static void GetRange(unsigned int start, unsigned int end, Accessor &styler, char *s, unsigned int len) {
-       unsigned int i = 0;
+static void GetRange(Sci_PositionU start, Sci_PositionU end, Accessor &styler, char *s, Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(styler[start + i]);
                i++;
@@ -48,7 +48,7 @@ static void GetRange(unsigned int start, unsigned int end, Accessor &styler, cha
        s[i] = '\0';
 }
 
-static void ColouriseGAPDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], 
Accessor &styler) {
+static void ColouriseGAPDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[], Accessor &styler) {
 
        WordList &keywords1 = *keywordlists[0];
        WordList &keywords2 = *keywordlists[1];
@@ -197,19 +197,19 @@ static int ClassifyFoldPointGAP(const char* s) {
        return level;
 }
 
-static void FoldGAPDoc( unsigned int startPos, int length, int initStyle,   WordList** , Accessor &styler) {
-       unsigned int endPos = startPos + length;
+static void FoldGAPDoc( Sci_PositionU startPos, Sci_Position length, int initStyle,   WordList** , Accessor 
&styler) {
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
 
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexGui4Cli.cxx 
b/plugins/scintilla/scintilla/lexers/LexGui4Cli.cxx
index 13cf9ea..c162516 100644
--- a/plugins/scintilla/scintilla/lexers/LexGui4Cli.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexGui4Cli.cxx
@@ -6,8 +6,8 @@ This is the Lexer for Gui4Cli, included in SciLexer.dll
 
 To add to SciLexer.dll:
 1. Add the values below to INCLUDE\Scintilla.iface
-2. Run the include/HFacer.py script
-3. Run the src/lexGen.py script
+2. Run the scripts/HFacer.py script
+3. Run the scripts/LexGen.py script
 
 val SCE_GC_DEFAULT=0
 val SCE_GC_COMMENTLINE=1
@@ -49,10 +49,6 @@ static inline bool IsAWordChar(const int ch) {
        return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch =='\\');
 }
 
-static inline bool IsAWordStart(const int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
-}
-
 inline bool isGCOperator(int ch)
 {      if (isalnum(ch))
                return false;
@@ -72,9 +68,9 @@ inline bool isGCOperator(int ch)
 #define isFoldPoint(x)  ((styler.LevelAt(x) & SC_FOLDLEVELNUMBERMASK) == 1024)
 
 static void colorFirstWord(WordList *keywordlists[], Accessor &styler,
-                                                                       StyleContext *sc, char *buff, int 
length, int)
+                                                                       StyleContext *sc, char *buff, 
Sci_Position length, int)
 {
-       int c = 0;
+       Sci_Position c = 0;
        while (sc->More() && isSpaceOrNL(sc->ch))
        {       sc->Forward();
        }
@@ -123,12 +119,13 @@ static void colorFirstWord(WordList *keywordlists[], Accessor &styler,
 
 // Main colorizing function called by Scintilla
 static void
-ColouriseGui4CliDoc(unsigned int startPos, int length, int initStyle,
+ColouriseGui4CliDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                     WordList *keywordlists[], Accessor &styler)
 {
        styler.StartAt(startPos);
 
-       int quotestart = 0, oldstate, currentline = styler.GetLine(startPos);
+       Sci_Position currentline = styler.GetLine(startPos);
+       int quotestart = 0, oldstate;
        styler.StartSegment(startPos);
        bool noforward;
        char buff[BUFFSIZE+1];  // buffer for command name
@@ -247,20 +244,20 @@ ColouriseGui4CliDoc(unsigned int startPos, int length, int initStyle,
 }
 
 // Main folding function called by Scintilla - (based on props (.ini) files function)
-static void FoldGui4Cli(unsigned int startPos, int length, int,
+static void FoldGui4Cli(Sci_PositionU startPos, Sci_Position length, int,
                                                                WordList *[], Accessor &styler)
 {
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
 
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
 
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        bool headerPoint = false;
 
-       for (unsigned int i = startPos; i < endPos; i++)
+       for (Sci_PositionU i = startPos; i < endPos; i++)
        {
                char ch = chNext;
                chNext = styler[i+1];
diff --git a/plugins/scintilla/scintilla/lexers/LexHTML.cxx b/plugins/scintilla/scintilla/lexers/LexHTML.cxx
index ebfd730..028c5ec 100644
--- a/plugins/scintilla/scintilla/lexers/LexHTML.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexHTML.cxx
@@ -16,6 +16,7 @@
 #include "Scintilla.h"
 #include "SciLexer.h"
 
+#include "StringCopy.h"
 #include "WordList.h"
 #include "LexAccessor.h"
 #include "Accessor.h"
@@ -43,7 +44,7 @@ static inline bool IsAWordStart(const int ch) {
 }
 
 inline bool IsOperator(int ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        // '.' left out as it is used to make up numbers
        if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
@@ -56,17 +57,17 @@ inline bool IsOperator(int ch) {
        return false;
 }
 
-static void GetTextSegment(Accessor &styler, unsigned int start, unsigned int end, char *s, size_t len) {
-       unsigned int i = 0;
+static void GetTextSegment(Accessor &styler, Sci_PositionU start, Sci_PositionU end, char *s, size_t len) {
+       Sci_PositionU i = 0;
        for (; (i < end - start + 1) && (i < len-1); i++) {
                s[i] = static_cast<char>(MakeLowerCase(styler[start + i]));
        }
        s[i] = '\0';
 }
 
-static const char *GetNextWord(Accessor &styler, unsigned int start, char *s, size_t sLen) {
+static const char *GetNextWord(Accessor &styler, Sci_PositionU start, char *s, size_t sLen) {
 
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        for (; i < sLen-1; i++) {
                char ch = static_cast<char>(styler.SafeGetCharAt(start + i));
                if ((i == 0) && !IsAWordStart(ch))
@@ -80,7 +81,7 @@ static const char *GetNextWord(Accessor &styler, unsigned int start, char *s, si
        return s;
 }
 
-static script_type segIsScriptingIndicator(Accessor &styler, unsigned int start, unsigned int end, 
script_type prevValue) {
+static script_type segIsScriptingIndicator(Accessor &styler, Sci_PositionU start, Sci_PositionU end, 
script_type prevValue) {
        char s[100];
        GetTextSegment(styler, start, end, s, sizeof(s));
        //Platform::DebugPrintf("Scripting indicator [%s]\n", s);
@@ -109,7 +110,7 @@ static script_type segIsScriptingIndicator(Accessor &styler, unsigned int start,
        return prevValue;
 }
 
-static int PrintScriptingIndicatorOffset(Accessor &styler, unsigned int start, unsigned int end) {
+static int PrintScriptingIndicatorOffset(Accessor &styler, Sci_PositionU start, Sci_PositionU end) {
        int iResult = 0;
        char s[100];
        GetTextSegment(styler, start, end, s, sizeof(s));
@@ -170,7 +171,7 @@ static int stateForPrintState(int StateToPrint) {
        return state;
 }
 
-static inline bool IsNumber(unsigned int start, Accessor &styler) {
+static inline bool IsNumber(Sci_PositionU start, Accessor &styler) {
        return IsADigit(styler[start]) || (styler[start] == '.') ||
               (styler[start] == '-') || (styler[start] == '#');
 }
@@ -241,7 +242,7 @@ static inline bool isCommentASPState(int state) {
        return bResult;
 }
 
-static void classifyAttribHTML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
+static void classifyAttribHTML(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler) 
{
        bool wordIsNumber = IsNumber(start, styler);
        char chAttr = SCE_H_ATTRIBUTEUNKNOWN;
        if (wordIsNumber) {
@@ -258,14 +259,14 @@ static void classifyAttribHTML(unsigned int start, unsigned int end, WordList &k
        styler.ColourTo(end, chAttr);
 }
 
-static int classifyTagHTML(unsigned int start, unsigned int end,
+static int classifyTagHTML(Sci_PositionU start, Sci_PositionU end,
                            WordList &keywords, Accessor &styler, bool &tagDontFold,
                           bool caseSensitive, bool isXml, bool allowScripts) {
        char withSpace[30 + 2] = " ";
        const char *s = withSpace + 1;
        // Copy after the '<'
-       unsigned int i = 1;
-       for (unsigned int cPos = start; cPos <= end && i < 30; cPos++) {
+       Sci_PositionU i = 1;
+       for (Sci_PositionU cPos = start; cPos <= end && i < 30; cPos++) {
                char ch = styler[cPos];
                if ((ch != '<') && (ch != '/')) {
                        withSpace[i++] = caseSensitive ? ch : static_cast<char>(MakeLowerCase(ch));
@@ -297,7 +298,7 @@ static int classifyTagHTML(unsigned int start, unsigned int end,
                if (allowScripts && 0 == strcmp(s, "script")) {
                        // check to see if this is a self-closing tag by sniffing ahead
                        bool isSelfClose = false;
-                       for (unsigned int cPos = end; cPos <= end + 200; cPos++) {
+                       for (Sci_PositionU cPos = end; cPos <= end + 200; cPos++) {
                                char ch = styler.SafeGetCharAt(cPos, '\0');
                                if (ch == '\0' || ch == '>')
                                        break;
@@ -317,10 +318,10 @@ static int classifyTagHTML(unsigned int start, unsigned int end,
        return chAttr;
 }
 
-static void classifyWordHTJS(unsigned int start, unsigned int end,
+static void classifyWordHTJS(Sci_PositionU start, Sci_PositionU end,
                              WordList &keywords, Accessor &styler, script_mode inScriptType) {
        char s[30 + 1];
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        for (; i < end - start + 1 && i < 30; i++) {
                s[i] = styler[start + i];
        }
@@ -336,12 +337,12 @@ static void classifyWordHTJS(unsigned int start, unsigned int end,
        styler.ColourTo(end, statePrintForState(chAttr, inScriptType));
 }
 
-static int classifyWordHTVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, 
script_mode inScriptType) {
+static int classifyWordHTVB(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler, 
script_mode inScriptType) {
        char chAttr = SCE_HB_IDENTIFIER;
        bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.');
-       if (wordIsNumber)
+       if (wordIsNumber) {
                chAttr = SCE_HB_NUMBER;
-       else {
+       } else {
                char s[100];
                GetTextSegment(styler, start, end, s, sizeof(s));
                if (keywords.InList(s)) {
@@ -357,10 +358,10 @@ static int classifyWordHTVB(unsigned int start, unsigned int end, WordList &keyw
                return SCE_HB_DEFAULT;
 }
 
-static void classifyWordHTPy(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, 
char *prevWord, script_mode inScriptType, bool isMako) {
+static void classifyWordHTPy(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler, 
char *prevWord, script_mode inScriptType, bool isMako) {
        bool wordIsNumber = IsADigit(styler[start]);
        char s[30 + 1];
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        for (; i < end - start + 1 && i < 30; i++) {
                s[i] = styler[start + i];
        }
@@ -382,12 +383,12 @@ static void classifyWordHTPy(unsigned int start, unsigned int end, WordList &key
 
 // Update the word colour to default or keyword
 // Called when in a PHP word
-static void classifyWordHTPHP(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
+static void classifyWordHTPHP(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler) {
        char chAttr = SCE_HPHP_DEFAULT;
        bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.' && start+1 <= end && 
IsADigit(styler[start+1]));
-       if (wordIsNumber)
+       if (wordIsNumber) {
                chAttr = SCE_HPHP_NUMBER;
-       else {
+       } else {
                char s[100];
                GetTextSegment(styler, start, end, s, sizeof(s));
                if (keywords.InList(s))
@@ -396,9 +397,9 @@ static void classifyWordHTPHP(unsigned int start, unsigned int end, WordList &ke
        styler.ColourTo(end, chAttr);
 }
 
-static bool isWordHSGML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
+static bool isWordHSGML(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler) {
        char s[30 + 1];
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        for (; i < end - start + 1 && i < 30; i++) {
                s[i] = styler[start + i];
        }
@@ -406,9 +407,9 @@ static bool isWordHSGML(unsigned int start, unsigned int end, WordList &keywords
        return keywords.InList(s);
 }
 
-static bool isWordCdata(unsigned int start, unsigned int end, Accessor &styler) {
+static bool isWordCdata(Sci_PositionU start, Sci_PositionU end, Accessor &styler) {
        char s[30 + 1];
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        for (; i < end - start + 1 && i < 30; i++) {
                s[i] = styler[start + i];
        }
@@ -446,12 +447,12 @@ static int StateForScript(script_type scriptLanguage) {
 }
 
 static inline bool issgmlwordchar(int ch) {
-       return !isascii(ch) ||
+       return !IsASCII(ch) ||
                (isalnum(ch) || ch == '.' || ch == '_' || ch == ':' || ch == '!' || ch == '#' || ch == '[');
 }
 
 static inline bool IsPhpWordStart(int ch) {
-       return (isascii(ch) && (isalpha(ch) || (ch == '_'))) || (ch >= 0x7f);
+       return (IsASCII(ch) && (isalpha(ch) || (ch == '_'))) || (ch >= 0x7f);
 }
 
 static inline bool IsPhpWordChar(int ch) {
@@ -489,9 +490,9 @@ static bool isMakoBlockEnd(const int ch, const int chNext, const char *blockType
                return ((ch == '/') && (chNext == '>'));
        } else if (0 == strcmp(blockType, "%")) {
                if (ch == '/' && isLineEnd(chNext))
-                       return 1;
+                       return true;
                else
-                   return isLineEnd(ch);
+                       return isLineEnd(ch);
        } else if (0 == strcmp(blockType, "{")) {
                return ch == '}';
        } else {
@@ -501,13 +502,13 @@ static bool isMakoBlockEnd(const int ch, const int chNext, const char *blockType
 
 static bool isDjangoBlockEnd(const int ch, const int chNext, const char *blockType) {
        if (strlen(blockType) == 0) {
-               return 0;
+               return false;
        } else if (0 == strcmp(blockType, "%")) {
                return ((ch == '%') && (chNext == '}'));
        } else if (0 == strcmp(blockType, "{")) {
                return ((ch == '}') && (chNext == '}'));
        } else {
-               return 0;
+               return false;
        }
 }
 
@@ -519,9 +520,9 @@ static bool isPHPStringState(int state) {
            (state == SCE_HPHP_COMPLEX_VARIABLE);
 }
 
-static int FindPhpStringDelimiter(char *phpStringDelimiter, const int phpStringDelimiterSize, int i, const 
int lengthDoc, Accessor &styler, bool &isSimpleString) {
-       int j;
-       const int beginning = i - 1;
+static Sci_Position FindPhpStringDelimiter(char *phpStringDelimiter, const int phpStringDelimiterSize, 
Sci_Position i, const Sci_Position lengthDoc, Accessor &styler, bool &isSimpleString) {
+       Sci_Position j;
+       const Sci_Position beginning = i - 1;
        bool isValidSimpleString = false;
 
        while (i < lengthDoc && (styler[i] == ' ' || styler[i] == '\t'))
@@ -566,7 +567,7 @@ static int FindPhpStringDelimiter(char *phpStringDelimiter, const int phpStringD
        return j - 1;
 }
 
-static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseHyperTextDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                                   Accessor &styler, bool isXml) {
        WordList &keywords = *keywordlists[0];
        WordList &keywords2 = *keywordlists[1];
@@ -575,8 +576,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
        WordList &keywords5 = *keywordlists[4];
        WordList &keywords6 = *keywordlists[5]; // SGML (DTD) keywords
 
-       // Lexer for HTML requires more lexical states (8 bits worth) than most lexers
-       styler.StartAt(startPos, static_cast<char>(STYLE_MAX));
+       styler.StartAt(startPos);
        char prevWord[200];
        prevWord[0] = '\0';
        char phpStringDelimiter[200]; // PHP is not limited in length, we are
@@ -592,7 +592,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
        // If inside a tag, it may be a script tag, so reread from the start of line starting tag to ensure 
any language tags are seen
        if (InTagState(state)) {
                while ((startPos > 0) && (InTagState(styler.StyleAt(startPos - 1)))) {
-                       int backLineStart = styler.LineStart(styler.GetLine(startPos-1));
+                       Sci_Position backLineStart = styler.LineStart(styler.GetLine(startPos-1));
                        length += startPos - backLineStart;
                        startPos = backLineStart;
                }
@@ -608,9 +608,20 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                if (startPos == 0)
                        state = SCE_H_DEFAULT;
        }
-       styler.StartAt(startPos, static_cast<char>(STYLE_MAX));
+       styler.StartAt(startPos);
+
+       /* Nothing handles getting out of these, so we need not start in any of them.
+        * As we're at line start and they can't span lines, we'll re-detect them anyway */
+       switch (state) {
+               case SCE_H_QUESTION:
+               case SCE_H_XMLSTART:
+               case SCE_H_XMLEND:
+               case SCE_H_ASP:
+                       state = SCE_H_DEFAULT;
+                       break;
+       }
 
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int lineState;
        if (lineCurrent > 0) {
                lineState = styler.GetLineState(lineCurrent-1);
@@ -695,7 +706,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
        int chPrevNonWhite = ' ';
        // look back to set chPrevNonWhite properly for better regex colouring
        if (scriptLanguage == eScriptJS && startPos > 0) {
-               int back = startPos;
+               Sci_Position back = startPos;
                int style = 0;
                while (--back) {
                        style = styler.StyleAt(back);
@@ -709,8 +720,8 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
        }
 
        styler.StartSegment(startPos);
-       const int lengthDoc = startPos + length;
-       for (int i = startPos; i < lengthDoc; i++) {
+       const Sci_Position lengthDoc = startPos + length;
+       for (Sci_Position i = startPos; i < lengthDoc; i++) {
                const int chPrev2 = chPrev;
                chPrev = ch;
                if (!IsASpace(ch) && state != SCE_HJ_COMMENT &&
@@ -746,7 +757,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                //Platform::DebugPrintf("state=%d, StateToPrint=%d, initStyle=%d\n", state, 
StateToPrint, initStyle);
                                //if ((state == SCE_HPHP_OPERATOR) || (state == SCE_HPHP_DEFAULT) || (state 
== SCE_HJ_SYMBOLS) || (state == SCE_HJ_START) || (state == SCE_HJ_DEFAULT)) {
                                        if (ch == '#') {
-                                               int j = i + 1;
+                                               Sci_Position j = i + 1;
                                                while ((j < lengthDoc) && 
IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                                        j++;
                                                }
@@ -769,7 +780,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                        } else if ((ch == '\n') && !((chNext == '\r') && (chNext2 == '\n')) 
&& (chNext != '\n')) {
                                                // check if the number of tabs is lower than the level
                                                int Findlevel = (levelCurrent & ~SC_FOLDLEVELBASE) * 8;
-                                               for (int j = 0; Findlevel > 0; j++) {
+                                               for (Sci_Position j = 0; Findlevel > 0; j++) {
                                                        char chTmp = styler.SafeGetCharAt(i + j + 1);
                                                        if (chTmp == '\t') {
                                                                Findlevel -= 8;
@@ -810,8 +821,8 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                        }
                        styler.SetLineState(lineCurrent,
                                            ((inScriptType & 0x03) << 0) |
-                                           ((tagOpened & 0x01) << 2) |
-                                           ((tagClosing & 0x01) << 3) |
+                                           ((tagOpened ? 1 : 0) << 2) |
+                                           ((tagClosing ? 1 : 0) << 3) |
                                            ((aspScript & 0x0F) << 4) |
                                            ((clientScript & 0x0F) << 8) |
                                            ((beforePreProc & 0xFF) << 12));
@@ -822,19 +833,27 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                // handle start of Mako comment line
                if (isMako && ch == '#' && chNext == '#') {
                        makoComment = 1;
+                       state = SCE_HP_COMMENTLINE;
                }
-               
+
                // handle end of Mako comment line
                else if (isMako && makoComment && (ch == '\r' || ch == '\n')) {
                        makoComment = 0;
-                       styler.ColourTo(i, SCE_HP_COMMENTLINE);
-                       state = SCE_HP_DEFAULT;
+                       styler.ColourTo(i - 1, StateToPrint);
+                       if (scriptLanguage == eScriptPython) {
+                               state = SCE_HP_DEFAULT;
+                       } else {
+                               state = SCE_H_DEFAULT;
+                       }
                }
-               
+
                // Allow falling through to mako handling code if newline is going to end a block
                if (((ch == '\r' && chNext != '\n') || (ch == '\n')) &&
                        (!isMako || (0 != strcmp(makoBlockType, "%")))) {
                }
+               // Ignore everything in mako comment until the line ends
+               else if (isMako && makoComment) {
+               }
 
                // generic end of script processing
                else if ((inScriptType == eNonHtmlScript) && (ch == '<') && (chNext == '/')) {
@@ -867,7 +886,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                if (const char *tag =
                                                state == SCE_HJ_COMMENTLINE || isXml ? "script" :
                                                state == SCE_H_COMMENT ? "comment" : 0) {
-                                       int j = i + 2;
+                                       Sci_Position j = i + 2;
                                        int chr;
                                        do {
                                                chr = static_cast<int>(*tag++);
@@ -890,7 +909,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                /////////////////////////////////////
                // handle the start of PHP pre-processor = Non-HTML
                else if ((state != SCE_H_ASPAT) &&
-                        !isPHPStringState(state) &&
+                        !isStringState(state) &&
                         (state != SCE_HPHP_COMMENT) &&
                         (state != SCE_HPHP_COMMENTLINE) &&
                         (ch == '<') &&
@@ -929,9 +948,9 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                                                                                              
           (ch == '$' && chNext == '{') ||
                                                                                                              
           (ch == '<' && chNext == '/' && chNext2 == '%'))) {
                        if (ch == '%' || ch == '/')
-                               strcpy(makoBlockType, "%");
+                               StringCopy(makoBlockType, "%");
                        else if (ch == '$')
-                               strcpy(makoBlockType, "{");
+                               StringCopy(makoBlockType, "{");
                        else if (chNext == '/')
                                GetNextWord(styler, i+3, makoBlockType, sizeof(makoBlockType));
                        else
@@ -1000,9 +1019,9 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                // handle the start Django template code
                else if (isDjango && scriptLanguage != eScriptPython && (ch == '{' && (chNext == '%' ||  
chNext == '{'))) {
                        if (chNext == '%')
-                               strcpy(djangoBlockType, "%");
+                               StringCopy(djangoBlockType, "%");
                        else
-                               strcpy(djangoBlockType, "{");
+                               StringCopy(djangoBlockType, "{");
                        styler.ColourTo(i - 1, StateToPrint);
                        beforePreProc = state;
                        if (inScriptType == eNonHtmlScript)
@@ -1229,11 +1248,11 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                styler.ColourTo(i - 1, StateToPrint);
                                state = SCE_H_SGML_SIMPLESTRING;
                        } else if ((ch == '-') && (chPrev == '-')) {
-                               if (static_cast<int>(styler.GetStartSegment()) <= (i - 2)) {
+                               if (static_cast<Sci_Position>(styler.GetStartSegment()) <= (i - 2)) {
                                        styler.ColourTo(i - 2, StateToPrint);
                                }
                                state = SCE_H_SGML_COMMENT;
-                       } else if (isascii(ch) && isalpha(ch) && (chPrev == '%')) {
+                       } else if (IsASCII(ch) && isalpha(ch) && (chPrev == '%')) {
                                styler.ColourTo(i - 2, StateToPrint);
                                state = SCE_H_SGML_ENTITY;
                        } else if (ch == '#') {
@@ -1312,6 +1331,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                styler.ColourTo(i - 2, StateToPrint);
                                state = SCE_H_SGML_COMMENT;
                        }
+                       break;
                case SCE_H_SGML_DOUBLESTRING:
                        if (ch == '\"') {
                                styler.ColourTo(i, StateToPrint);
@@ -1351,7 +1371,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                        }
                        break;
                case SCE_H_SGML_SPECIAL:
-                       if (!(isascii(ch) && isupper(ch))) {
+                       if (!(IsASCII(ch) && isupper(ch))) {
                                styler.ColourTo(i - 1, StateToPrint);
                                if (isalnum(ch)) {
                                        state = SCE_H_SGML_ERROR;
@@ -1364,7 +1384,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                        if (ch == ';') {
                                styler.ColourTo(i, StateToPrint);
                                state = SCE_H_SGML_DEFAULT;
-                       } else if (!(isascii(ch) && isalnum(ch)) && ch != '-' && ch != '.') {
+                       } else if (!(IsASCII(ch) && isalnum(ch)) && ch != '-' && ch != '.') {
                                styler.ColourTo(i, SCE_H_SGML_ERROR);
                                state = SCE_H_SGML_DEFAULT;
                        }
@@ -1374,9 +1394,9 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                styler.ColourTo(i, StateToPrint);
                                state = SCE_H_DEFAULT;
                        }
-                       if (ch != '#' && !(isascii(ch) && isalnum(ch))  // Should check that '#' follows '&', 
but it is unlikely anyway...
+                       if (ch != '#' && !(IsASCII(ch) && isalnum(ch))  // Should check that '#' follows '&', 
but it is unlikely anyway...
                                && ch != '.' && ch != '-' && ch != '_' && ch != ':') { // valid in XML
-                               if (!isascii(ch))       // Possibly start of a multibyte character so don't 
allow this byte to be in entity style
+                               if (!IsASCII(ch))       // Possibly start of a multibyte character so don't 
allow this byte to be in entity style
                                        styler.ColourTo(i-1, SCE_H_TAGUNKNOWN);
                                else
                                        styler.ColourTo(i, SCE_H_TAGUNKNOWN);
@@ -1702,7 +1722,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                case SCE_HJ_REGEX:
                        if (ch == '\r' || ch == '\n' || ch == '/') {
                                if (ch == '/') {
-                                       while (isascii(chNext) && islower(chNext)) {   // gobble regex flags
+                                       while (IsASCII(chNext) && islower(chNext)) {   // gobble regex flags
                                                i++;
                                                ch = chNext;
                                                chNext = static_cast<unsigned char>(styler.SafeGetCharAt(i + 
1));
@@ -1916,7 +1936,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                        state = SCE_HPHP_COMMENTLINE;
                                } else if (ch == '\"') {
                                        state = SCE_HPHP_HSTRING;
-                                       strcpy(phpStringDelimiter, "\"");
+                                       StringCopy(phpStringDelimiter, "\"");
                                } else if (styler.Match(i, "<<<")) {
                                        bool isSimpleString = false;
                                        i = FindPhpStringDelimiter(phpStringDelimiter, 
sizeof(phpStringDelimiter), i + 3, lengthDoc, styler, isSimpleString);
@@ -1926,7 +1946,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                        }
                                } else if (ch == '\'') {
                                        state = SCE_HPHP_SIMPLESTRING;
-                                       strcpy(phpStringDelimiter, "\'");
+                                       StringCopy(phpStringDelimiter, "\'");
                                } else if (ch == '$' && IsPhpWordStart(chNext)) {
                                        state = SCE_HPHP_VARIABLE;
                                } else if (IsOperator(ch)) {
@@ -2046,7 +2066,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                state = SCE_HPHP_COMMENTLINE;
                        } else if (ch == '\"') {
                                state = SCE_HPHP_HSTRING;
-                               strcpy(phpStringDelimiter, "\"");
+                               StringCopy(phpStringDelimiter, "\"");
                        } else if (styler.Match(i, "<<<")) {
                                bool isSimpleString = false;
                                i = FindPhpStringDelimiter(phpStringDelimiter, sizeof(phpStringDelimiter), i 
+ 3, lengthDoc, styler, isSimpleString);
@@ -2056,7 +2076,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                                }
                        } else if (ch == '\'') {
                                state = SCE_HPHP_SIMPLESTRING;
-                               strcpy(phpStringDelimiter, "\'");
+                               StringCopy(phpStringDelimiter, "\'");
                        } else if (ch == '$' && IsPhpWordStart(chNext)) {
                                state = SCE_HPHP_VARIABLE;
                        } else if (IsOperator(ch)) {
@@ -2071,7 +2091,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                // Some of the above terminated their lexeme but since the same character starts
                // the same class again, only reenter if non empty segment.
 
-               bool nonEmptySegment = i >= static_cast<int>(styler.GetStartSegment());
+               bool nonEmptySegment = i >= static_cast<Sci_Position>(styler.GetStartSegment());
                if (state == SCE_HB_DEFAULT) {    // One of the above succeeded
                        if ((ch == '\"') && (nonEmptySegment)) {
                                state = SCE_HB_STRING;
@@ -2127,7 +2147,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
                break;
        default:
                StateToPrint = statePrintForState(state, inScriptType);
-               if (static_cast<int>(styler.GetStartSegment()) < lengthDoc)
+               if (static_cast<Sci_Position>(styler.GetStartSegment()) < lengthDoc)
                        styler.ColourTo(lengthDoc - 1, StateToPrint);
                break;
        }
@@ -2139,19 +2159,19 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
        }
 }
 
-static void ColouriseXMLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseXMLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                                   Accessor &styler) {
        // Passing in true because we're lexing XML
        ColouriseHyperTextDoc(startPos, length, initStyle, keywordlists, styler, true);
 }
 
-static void ColouriseHTMLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseHTMLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                                   Accessor &styler) {
        // Passing in false because we're notlexing XML
        ColouriseHyperTextDoc(startPos, length, initStyle, keywordlists, styler, false);
 }
 
-static void ColourisePHPScriptDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColourisePHPScriptDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
         Accessor &styler) {
        if (startPos == 0)
                initStyle = SCE_HPHP_DEFAULT;
@@ -2178,6 +2198,6 @@ static const char * const phpscriptWordListDesc[] = {
        0,
 };
 
-LexerModule lmHTML(SCLEX_HTML, ColouriseHTMLDoc, "hypertext", 0, htmlWordListDesc, 8);
-LexerModule lmXML(SCLEX_XML, ColouriseXMLDoc, "xml", 0, htmlWordListDesc, 8);
-LexerModule lmPHPSCRIPT(SCLEX_PHPSCRIPT, ColourisePHPScriptDoc, "phpscript", 0, phpscriptWordListDesc, 8);
+LexerModule lmHTML(SCLEX_HTML, ColouriseHTMLDoc, "hypertext", 0, htmlWordListDesc);
+LexerModule lmXML(SCLEX_XML, ColouriseXMLDoc, "xml", 0, htmlWordListDesc);
+LexerModule lmPHPSCRIPT(SCLEX_PHPSCRIPT, ColourisePHPScriptDoc, "phpscript", 0, phpscriptWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexHaskell.cxx 
b/plugins/scintilla/scintilla/lexers/LexHaskell.cxx
index e10cb8c..2665783 100644
--- a/plugins/scintilla/scintilla/lexers/LexHaskell.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexHaskell.cxx
@@ -38,9 +38,9 @@
 #include "Accessor.h"
 #include "StyleContext.h"
 #include "CharacterSet.h"
+#include "CharacterCategory.h"
 #include "LexerModule.h"
 #include "OptionSet.h"
-#include "CharacterCategory.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
@@ -143,13 +143,13 @@ static inline int CommentBlockStyleFromNestLevel(const unsigned int nestLevel) {
 // Mangled version of lexlib/Accessor.cxx IndentAmount.
 // Modified to treat comment blocks as whitespace
 // plus special case for commentline/preprocessor.
-static int HaskellIndentAmount(Accessor &styler, const int line) {
+static int HaskellIndentAmount(Accessor &styler, const Sci_Position line) {
 
    // Determines the indentation level of the current line
    // Comment blocks are treated as whitespace
 
-   int pos = styler.LineStart(line);
-   int eol_pos = styler.LineStart(line + 1) - 1;
+   Sci_Position pos = styler.LineStart(line);
+   Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
 
    char ch = styler[pos];
    int style = styler.StyleAt(pos);
@@ -157,7 +157,7 @@ static int HaskellIndentAmount(Accessor &styler, const int line) {
    int indent = 0;
    bool inPrevPrefix = line > 0;
 
-   int posPrev = inPrevPrefix ? styler.LineStart(line-1) : 0;
+   Sci_Position posPrev = inPrevPrefix ? styler.LineStart(line-1) : 0;
 
    while ((  ch == ' ' || ch == '\t'
           || IsCommentBlockStyle(style)
@@ -271,7 +271,7 @@ struct OptionSetHaskell : public OptionSet<OptionsHaskell> {
 
 class LexerHaskell : public ILexer {
    bool literate;
-   int firstImportLine;
+   Sci_Position firstImportLine;
    int firstImportIndent;
    WordList keywords;
    WordList ffi;
@@ -347,12 +347,12 @@ class LexerHaskell : public ILexer {
       }
    }
 
-   bool LineContainsImport(const int line, Accessor &styler) const {
+   bool LineContainsImport(const Sci_Position line, Accessor &styler) const {
       if (options.foldImports) {
-         int currentPos = styler.LineStart(line);
+         Sci_Position currentPos = styler.LineStart(line);
          int style = styler.StyleAt(currentPos);
 
-         int eol_pos = styler.LineStart(line + 1) - 1;
+         Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
 
          while (currentPos < eol_pos) {
             int ch = styler[currentPos];
@@ -374,7 +374,7 @@ class LexerHaskell : public ILexer {
       }
    }
 
-   inline int IndentAmountWithOffset(Accessor &styler, const int line) const {
+   inline int IndentAmountWithOffset(Accessor &styler, const Sci_Position line) const {
       const int indent = HaskellIndentAmount(styler, line);
       const int indentLevel = indent & SC_FOLDLEVELNUMBERMASK;
       return indentLevel <= ((firstImportIndent - 1) + SC_FOLDLEVELBASE)
@@ -396,39 +396,39 @@ public:
       {}
    virtual ~LexerHaskell() {}
 
-   void SCI_METHOD Release() {
+   void SCI_METHOD Release() override {
       delete this;
    }
 
-   int SCI_METHOD Version() const {
+   int SCI_METHOD Version() const override {
       return lvOriginal;
    }
 
-   const char * SCI_METHOD PropertyNames() {
+   const char * SCI_METHOD PropertyNames() override {
       return osHaskell.PropertyNames();
    }
 
-   int SCI_METHOD PropertyType(const char *name) {
+   int SCI_METHOD PropertyType(const char *name) override {
       return osHaskell.PropertyType(name);
    }
 
-   const char * SCI_METHOD DescribeProperty(const char *name) {
+   const char * SCI_METHOD DescribeProperty(const char *name) override {
       return osHaskell.DescribeProperty(name);
    }
 
-   int SCI_METHOD PropertySet(const char *key, const char *val);
+   Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
 
-   const char * SCI_METHOD DescribeWordListSets() {
+   const char * SCI_METHOD DescribeWordListSets() override {
       return osHaskell.DescribeWordListSets();
    }
 
-   int SCI_METHOD WordListSet(int n, const char *wl);
+   Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
 
-   void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+   void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-   void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+   void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-   void * SCI_METHOD PrivateCall(int, void *) {
+   void * SCI_METHOD PrivateCall(int, void *) override {
       return 0;
    }
 
@@ -441,14 +441,14 @@ public:
    }
 };
 
-int SCI_METHOD LexerHaskell::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerHaskell::PropertySet(const char *key, const char *val) {
    if (osHaskell.PropertySet(&options, key, val)) {
       return 0;
    }
    return -1;
 }
 
-int SCI_METHOD LexerHaskell::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerHaskell::WordListSet(int n, const char *wl) {
    WordList *wordListN = 0;
    switch (n) {
    case 0:
@@ -461,7 +461,7 @@ int SCI_METHOD LexerHaskell::WordListSet(int n, const char *wl) {
       wordListN = &reserved_operators;
       break;
    }
-   int firstModification = -1;
+   Sci_Position firstModification = -1;
    if (wordListN) {
       WordList wlNew;
       wlNew.Set(wl);
@@ -473,11 +473,11 @@ int SCI_METHOD LexerHaskell::WordListSet(int n, const char *wl) {
    return firstModification;
 }
 
-void SCI_METHOD LexerHaskell::Lex(unsigned int startPos, int length, int initStyle
+void SCI_METHOD LexerHaskell::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle
                                  ,IDocument *pAccess) {
    LexAccessor styler(pAccess);
 
-   int lineCurrent = styler.GetLine(startPos);
+   Sci_Position lineCurrent = styler.GetLine(startPos);
 
    HaskellLineInfo hs = HaskellLineInfo(lineCurrent ? styler.GetLineState(lineCurrent-1) : 0);
 
@@ -961,26 +961,26 @@ void SCI_METHOD LexerHaskell::Lex(unsigned int startPos, int length, int initSty
    sc.Complete();
 }
 
-void SCI_METHOD LexerHaskell::Fold(unsigned int startPos, int length, int // initStyle
+void SCI_METHOD LexerHaskell::Fold(Sci_PositionU startPos, Sci_Position length, int // initStyle
                                   ,IDocument *pAccess) {
    if (!options.fold)
       return;
 
    Accessor styler(pAccess, NULL);
 
-   int lineCurrent = styler.GetLine(startPos);
+   Sci_Position lineCurrent = styler.GetLine(startPos);
 
    if (lineCurrent <= firstImportLine) {
       firstImportLine = -1; // readjust first import position
       firstImportIndent = 0;
    }
 
-   const int maxPos = startPos + length;
-   const int maxLines =
+   const Sci_Position maxPos = startPos + length;
+   const Sci_Position maxLines =
       maxPos == styler.Length()
          ? styler.GetLine(maxPos)
          : styler.GetLine(maxPos - 1);  // Requested last line
-   const int docLines = styler.GetLine(styler.Length()); // Available last line
+   const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line
 
    // Backtrack to previous non-blank line so we can determine indent level
    // for any white space lines
@@ -1018,7 +1018,7 @@ void SCI_METHOD LexerHaskell::Fold(unsigned int startPos, int length, int // ini
    while (lineCurrent <= docLines && lineCurrent <= maxLines) {
 
       // Gather info
-      int lineNext = lineCurrent + 1;
+      Sci_Position lineNext = lineCurrent + 1;
       importHere = false;
       int indentNext = indentCurrent;
 
@@ -1063,7 +1063,7 @@ void SCI_METHOD LexerHaskell::Fold(unsigned int startPos, int length, int // ini
       // which is indented more than the line after the end of
       // the comment-block, use the level of the block before
 
-      int skipLine = lineNext;
+      Sci_Position skipLine = lineNext;
       int skipLevel = indentNextLevel;
 
       while (--skipLine > lineCurrent) {
diff --git a/plugins/scintilla/scintilla/lexers/LexHex.cxx b/plugins/scintilla/scintilla/lexers/LexHex.cxx
new file mode 100644
index 0000000..d549881
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexHex.cxx
@@ -0,0 +1,1045 @@
+// Scintilla source code edit control
+/** @file LexHex.cxx
+ ** Lexers for Motorola S-Record, Intel HEX and Tektronix extended HEX.
+ **
+ ** Written by Markus Heidelberg
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+/*
+ *  Motorola S-Record
+ * ===============================
+ *
+ * Each record (line) is built as follows:
+ *
+ *    field       digits          states
+ *
+ *  +----------+
+ *  | start    |  1 ('S')         SCE_HEX_RECSTART
+ *  +----------+
+ *  | type     |  1               SCE_HEX_RECTYPE, (SCE_HEX_RECTYPE_UNKNOWN)
+ *  +----------+
+ *  | count    |  2               SCE_HEX_BYTECOUNT, SCE_HEX_BYTECOUNT_WRONG
+ *  +----------+
+ *  | address  |  4/6/8           SCE_HEX_NOADDRESS, SCE_HEX_DATAADDRESS, SCE_HEX_RECCOUNT, 
SCE_HEX_STARTADDRESS, (SCE_HEX_ADDRESSFIELD_UNKNOWN)
+ *  +----------+
+ *  | data     |  0..504/502/500  SCE_HEX_DATA_ODD, SCE_HEX_DATA_EVEN, SCE_HEX_DATA_EMPTY, 
(SCE_HEX_DATA_UNKNOWN)
+ *  +----------+
+ *  | checksum |  2               SCE_HEX_CHECKSUM, SCE_HEX_CHECKSUM_WRONG
+ *  +----------+
+ *
+ *
+ *  Intel HEX
+ * ===============================
+ *
+ * Each record (line) is built as follows:
+ *
+ *    field       digits          states
+ *
+ *  +----------+
+ *  | start    |  1 (':')         SCE_HEX_RECSTART
+ *  +----------+
+ *  | count    |  2               SCE_HEX_BYTECOUNT, SCE_HEX_BYTECOUNT_WRONG
+ *  +----------+
+ *  | address  |  4               SCE_HEX_NOADDRESS, SCE_HEX_DATAADDRESS, (SCE_HEX_ADDRESSFIELD_UNKNOWN)
+ *  +----------+
+ *  | type     |  2               SCE_HEX_RECTYPE, (SCE_HEX_RECTYPE_UNKNOWN)
+ *  +----------+
+ *  | data     |  0..510          SCE_HEX_DATA_ODD, SCE_HEX_DATA_EVEN, SCE_HEX_DATA_EMPTY, 
SCE_HEX_EXTENDEDADDRESS, SCE_HEX_STARTADDRESS, (SCE_HEX_DATA_UNKNOWN)
+ *  +----------+
+ *  | checksum |  2               SCE_HEX_CHECKSUM, SCE_HEX_CHECKSUM_WRONG
+ *  +----------+
+ *
+ *
+ * Folding:
+ *
+ *   Data records (type 0x00), which follow an extended address record (type
+ *   0x02 or 0x04), can be folded. The extended address record is the fold
+ *   point at fold level 0, the corresponding data records are set to level 1.
+ *
+ *   Any record, which is not a data record, sets the fold level back to 0.
+ *   Any line, which is not a record (blank lines and lines starting with a
+ *   character other than ':'), leaves the fold level unchanged.
+ *
+ *
+ *  Tektronix extended HEX
+ * ===============================
+ *
+ * Each record (line) is built as follows:
+ *
+ *    field       digits          states
+ *
+ *  +----------+
+ *  | start    |  1 ('%')         SCE_HEX_RECSTART
+ *  +----------+
+ *  | length   |  2               SCE_HEX_BYTECOUNT, SCE_HEX_BYTECOUNT_WRONG
+ *  +----------+
+ *  | type     |  1               SCE_HEX_RECTYPE, (SCE_HEX_RECTYPE_UNKNOWN)
+ *  +----------+
+ *  | checksum |  2               SCE_HEX_CHECKSUM, SCE_HEX_CHECKSUM_WRONG
+ *  +----------+
+ *  | address  |  9               SCE_HEX_DATAADDRESS, SCE_HEX_STARTADDRESS, (SCE_HEX_ADDRESSFIELD_UNKNOWN)
+ *  +----------+
+ *  | data     |  0..241          SCE_HEX_DATA_ODD, SCE_HEX_DATA_EVEN
+ *  +----------+
+ *
+ *
+ *  General notes for all lexers
+ * ===============================
+ *
+ * - Depending on where the helper functions are invoked, some of them have to
+ *   read beyond the current position. In case of malformed data (record too
+ *   short), it has to be ensured that this either does not have bad influence
+ *   or will be captured deliberately.
+ *
+ * - States in parentheses in the upper format descriptions indicate that they
+ *   should not appear in a valid hex file.
+ *
+ * - State SCE_HEX_GARBAGE means garbage data after the intended end of the
+ *   record, the line is too long then. This state is used in all lexers.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+// prototypes for general helper functions
+static inline bool IsNewline(const int ch);
+static int GetHexaNibble(char hd);
+static int GetHexaChar(char hd1, char hd2);
+static int GetHexaChar(Sci_PositionU pos, Accessor &styler);
+static bool ForwardWithinLine(StyleContext &sc, Sci_Position nb = 1);
+static bool PosInSameRecord(Sci_PositionU pos1, Sci_PositionU pos2, Accessor &styler);
+static Sci_Position CountByteCount(Sci_PositionU startPos, Sci_Position uncountedDigits, Accessor &styler);
+static int CalcChecksum(Sci_PositionU startPos, Sci_Position cnt, bool twosCompl, Accessor &styler);
+
+// prototypes for file format specific helper functions
+static Sci_PositionU GetSrecRecStartPosition(Sci_PositionU pos, Accessor &styler);
+static int GetSrecByteCount(Sci_PositionU recStartPos, Accessor &styler);
+static Sci_Position CountSrecByteCount(Sci_PositionU recStartPos, Accessor &styler);
+static int GetSrecAddressFieldSize(Sci_PositionU recStartPos, Accessor &styler);
+static int GetSrecAddressFieldType(Sci_PositionU recStartPos, Accessor &styler);
+static int GetSrecDataFieldType(Sci_PositionU recStartPos, Accessor &styler);
+static Sci_Position GetSrecRequiredDataFieldSize(Sci_PositionU recStartPos, Accessor &styler);
+static int GetSrecChecksum(Sci_PositionU recStartPos, Accessor &styler);
+static int CalcSrecChecksum(Sci_PositionU recStartPos, Accessor &styler);
+
+static Sci_PositionU GetIHexRecStartPosition(Sci_PositionU pos, Accessor &styler);
+static int GetIHexByteCount(Sci_PositionU recStartPos, Accessor &styler);
+static Sci_Position CountIHexByteCount(Sci_PositionU recStartPos, Accessor &styler);
+static int GetIHexAddressFieldType(Sci_PositionU recStartPos, Accessor &styler);
+static int GetIHexDataFieldType(Sci_PositionU recStartPos, Accessor &styler);
+static int GetIHexRequiredDataFieldSize(Sci_PositionU recStartPos, Accessor &styler);
+static int GetIHexChecksum(Sci_PositionU recStartPos, Accessor &styler);
+static int CalcIHexChecksum(Sci_PositionU recStartPos, Accessor &styler);
+
+static int GetTEHexDigitCount(Sci_PositionU recStartPos, Accessor &styler);
+static Sci_Position CountTEHexDigitCount(Sci_PositionU recStartPos, Accessor &styler);
+static int GetTEHexAddressFieldType(Sci_PositionU recStartPos, Accessor &styler);
+static int GetTEHexChecksum(Sci_PositionU recStartPos, Accessor &styler);
+static int CalcTEHexChecksum(Sci_PositionU recStartPos, Accessor &styler);
+
+static inline bool IsNewline(const int ch)
+{
+    return (ch == '\n' || ch == '\r');
+}
+
+static int GetHexaNibble(char hd)
+{
+       int hexValue = 0;
+
+       if (hd >= '0' && hd <= '9') {
+               hexValue += hd - '0';
+       } else if (hd >= 'A' && hd <= 'F') {
+               hexValue += hd - 'A' + 10;
+       } else if (hd >= 'a' && hd <= 'f') {
+               hexValue += hd - 'a' + 10;
+       } else {
+               return -1;
+       }
+
+       return hexValue;
+}
+
+static int GetHexaChar(char hd1, char hd2)
+{
+       int hexValue = 0;
+
+       if (hd1 >= '0' && hd1 <= '9') {
+               hexValue += 16 * (hd1 - '0');
+       } else if (hd1 >= 'A' && hd1 <= 'F') {
+               hexValue += 16 * (hd1 - 'A' + 10);
+       } else if (hd1 >= 'a' && hd1 <= 'f') {
+               hexValue += 16 * (hd1 - 'a' + 10);
+       } else {
+               return -1;
+       }
+
+       if (hd2 >= '0' && hd2 <= '9') {
+               hexValue += hd2 - '0';
+       } else if (hd2 >= 'A' && hd2 <= 'F') {
+               hexValue += hd2 - 'A' + 10;
+       } else if (hd2 >= 'a' && hd2 <= 'f') {
+               hexValue += hd2 - 'a' + 10;
+       } else {
+               return -1;
+       }
+
+       return hexValue;
+}
+
+static int GetHexaChar(Sci_PositionU pos, Accessor &styler)
+{
+       char highNibble, lowNibble;
+
+       highNibble = styler.SafeGetCharAt(pos);
+       lowNibble = styler.SafeGetCharAt(pos + 1);
+
+       return GetHexaChar(highNibble, lowNibble);
+}
+
+// Forward <nb> characters, but abort (and return false) if hitting the line
+// end. Return true if forwarding within the line was possible.
+// Avoids influence on highlighting of the subsequent line if the current line
+// is malformed (too short).
+static bool ForwardWithinLine(StyleContext &sc, Sci_Position nb)
+{
+       for (Sci_Position i = 0; i < nb; i++) {
+               if (sc.atLineEnd) {
+                       // line is too short
+                       sc.SetState(SCE_HEX_DEFAULT);
+                       sc.Forward();
+                       return false;
+               } else {
+                       sc.Forward();
+               }
+       }
+
+       return true;
+}
+
+// Checks whether the given positions are in the same record.
+static bool PosInSameRecord(Sci_PositionU pos1, Sci_PositionU pos2, Accessor &styler)
+{
+       return styler.GetLine(pos1) == styler.GetLine(pos2);
+}
+
+// Count the number of digit pairs from <startPos> till end of record, ignoring
+// <uncountedDigits> digits.
+// If the record is too short, a negative count may be returned.
+static Sci_Position CountByteCount(Sci_PositionU startPos, Sci_Position uncountedDigits, Accessor &styler)
+{
+       Sci_Position cnt;
+       Sci_PositionU pos;
+
+       pos = startPos;
+
+       while (!IsNewline(styler.SafeGetCharAt(pos, '\n'))) {
+               pos++;
+       }
+
+       // number of digits in this line minus number of digits of uncounted fields
+       cnt = static_cast<Sci_Position>(pos - startPos) - uncountedDigits;
+
+       // Prepare round up if odd (digit pair incomplete), this way the byte
+       // count is considered to be valid if the checksum is incomplete.
+       if (cnt >= 0) {
+               cnt++;
+       }
+
+       // digit pairs
+       cnt /= 2;
+
+       return cnt;
+}
+
+// Calculate the checksum of the record.
+// <startPos> is the position of the first character of the starting digit
+// pair, <cnt> is the number of digit pairs.
+static int CalcChecksum(Sci_PositionU startPos, Sci_Position cnt, bool twosCompl, Accessor &styler)
+{
+       int cs = 0;
+
+       for (Sci_PositionU pos = startPos; pos < startPos + cnt; pos += 2) {
+               int val = GetHexaChar(pos, styler);
+
+               if (val < 0) {
+                       return val;
+               }
+
+               // overflow does not matter
+               cs += val;
+       }
+
+       if (twosCompl) {
+               // low byte of two's complement
+               return -cs & 0xFF;
+       } else {
+               // low byte of one's complement
+               return ~cs & 0xFF;
+       }
+}
+
+// Get the position of the record "start" field (first character in line) in
+// the record around position <pos>.
+static Sci_PositionU GetSrecRecStartPosition(Sci_PositionU pos, Accessor &styler)
+{
+       while (styler.SafeGetCharAt(pos) != 'S') {
+               pos--;
+       }
+
+       return pos;
+}
+
+// Get the value of the "byte count" field, it counts the number of bytes in
+// the subsequent fields ("address", "data" and "checksum" fields).
+static int GetSrecByteCount(Sci_PositionU recStartPos, Accessor &styler)
+{
+       int val;
+
+       val = GetHexaChar(recStartPos + 2, styler);
+       if (val < 0) {
+              val = 0;
+       }
+
+       return val;
+}
+
+// Count the number of digit pairs for the "address", "data" and "checksum"
+// fields in this record. Has to be equal to the "byte count" field value.
+// If the record is too short, a negative count may be returned.
+static Sci_Position CountSrecByteCount(Sci_PositionU recStartPos, Accessor &styler)
+{
+       return CountByteCount(recStartPos, 4, styler);
+}
+
+// Get the size of the "address" field.
+static int GetSrecAddressFieldSize(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (styler.SafeGetCharAt(recStartPos + 1)) {
+               case '0':
+               case '1':
+               case '5':
+               case '9':
+                       return 2; // 16 bit
+
+               case '2':
+               case '6':
+               case '8':
+                       return 3; // 24 bit
+
+               case '3':
+               case '7':
+                       return 4; // 32 bit
+
+               default:
+                       return 0;
+       }
+}
+
+// Get the type of the "address" field content.
+static int GetSrecAddressFieldType(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (styler.SafeGetCharAt(recStartPos + 1)) {
+               case '0':
+                       return SCE_HEX_NOADDRESS;
+
+               case '1':
+               case '2':
+               case '3':
+                       return SCE_HEX_DATAADDRESS;
+
+               case '5':
+               case '6':
+                       return SCE_HEX_RECCOUNT;
+
+               case '7':
+               case '8':
+               case '9':
+                       return SCE_HEX_STARTADDRESS;
+
+               default: // handle possible format extension in the future
+                       return SCE_HEX_ADDRESSFIELD_UNKNOWN;
+       }
+}
+
+// Get the type of the "data" field content.
+static int GetSrecDataFieldType(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (styler.SafeGetCharAt(recStartPos + 1)) {
+               case '0':
+               case '1':
+               case '2':
+               case '3':
+                       return SCE_HEX_DATA_ODD;
+
+               case '5':
+               case '6':
+               case '7':
+               case '8':
+               case '9':
+                       return SCE_HEX_DATA_EMPTY;
+
+               default: // handle possible format extension in the future
+                       return SCE_HEX_DATA_UNKNOWN;
+       }
+}
+
+// Get the required size of the "data" field. Useless for block header and
+// ordinary data records (type S0, S1, S2, S3), return the value calculated
+// from the "byte count" and "address field" size in this case.
+static Sci_Position GetSrecRequiredDataFieldSize(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (styler.SafeGetCharAt(recStartPos + 1)) {
+               case '5':
+               case '6':
+               case '7':
+               case '8':
+               case '9':
+                       return 0;
+
+               default:
+                       return GetSrecByteCount(recStartPos, styler)
+                               - GetSrecAddressFieldSize(recStartPos, styler)
+                               - 1; // -1 for checksum field
+       }
+}
+
+// Get the value of the "checksum" field.
+static int GetSrecChecksum(Sci_PositionU recStartPos, Accessor &styler)
+{
+       int byteCount;
+
+       byteCount = GetSrecByteCount(recStartPos, styler);
+
+       return GetHexaChar(recStartPos + 2 + byteCount * 2, styler);
+}
+
+// Calculate the checksum of the record.
+static int CalcSrecChecksum(Sci_PositionU recStartPos, Accessor &styler)
+{
+       Sci_Position byteCount;
+
+       byteCount = GetSrecByteCount(recStartPos, styler);
+
+       // sum over "byte count", "address" and "data" fields (6..510 digits)
+       return CalcChecksum(recStartPos + 2, byteCount * 2, false, styler);
+}
+
+// Get the position of the record "start" field (first character in line) in
+// the record around position <pos>.
+static Sci_PositionU GetIHexRecStartPosition(Sci_PositionU pos, Accessor &styler)
+{
+       while (styler.SafeGetCharAt(pos) != ':') {
+               pos--;
+       }
+
+       return pos;
+}
+
+// Get the value of the "byte count" field, it counts the number of bytes in
+// the "data" field.
+static int GetIHexByteCount(Sci_PositionU recStartPos, Accessor &styler)
+{
+       int val;
+
+       val = GetHexaChar(recStartPos + 1, styler);
+       if (val < 0) {
+              val = 0;
+       }
+
+       return val;
+}
+
+// Count the number of digit pairs for the "data" field in this record. Has to
+// be equal to the "byte count" field value.
+// If the record is too short, a negative count may be returned.
+static Sci_Position CountIHexByteCount(Sci_PositionU recStartPos, Accessor &styler)
+{
+       return CountByteCount(recStartPos, 11, styler);
+}
+
+// Get the type of the "address" field content.
+static int GetIHexAddressFieldType(Sci_PositionU recStartPos, Accessor &styler)
+{
+       if (!PosInSameRecord(recStartPos, recStartPos + 7, styler)) {
+               // malformed (record too short)
+               // type cannot be determined
+               return SCE_HEX_ADDRESSFIELD_UNKNOWN;
+       }
+
+       switch (GetHexaChar(recStartPos + 7, styler)) {
+               case 0x00:
+                       return SCE_HEX_DATAADDRESS;
+
+               case 0x01:
+               case 0x02:
+               case 0x03:
+               case 0x04:
+               case 0x05:
+                       return SCE_HEX_NOADDRESS;
+
+               default: // handle possible format extension in the future
+                       return SCE_HEX_ADDRESSFIELD_UNKNOWN;
+       }
+}
+
+// Get the type of the "data" field content.
+static int GetIHexDataFieldType(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (GetHexaChar(recStartPos + 7, styler)) {
+               case 0x00:
+                       return SCE_HEX_DATA_ODD;
+
+               case 0x01:
+                       return SCE_HEX_DATA_EMPTY;
+
+               case 0x02:
+               case 0x04:
+                       return SCE_HEX_EXTENDEDADDRESS;
+
+               case 0x03:
+               case 0x05:
+                       return SCE_HEX_STARTADDRESS;
+
+               default: // handle possible format extension in the future
+                       return SCE_HEX_DATA_UNKNOWN;
+       }
+}
+
+// Get the required size of the "data" field. Useless for an ordinary data
+// record (type 00), return the "byte count" in this case.
+static int GetIHexRequiredDataFieldSize(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (GetHexaChar(recStartPos + 7, styler)) {
+               case 0x01:
+                       return 0;
+
+               case 0x02:
+               case 0x04:
+                       return 2;
+
+               case 0x03:
+               case 0x05:
+                       return 4;
+
+               default:
+                       return GetIHexByteCount(recStartPos, styler);
+       }
+}
+
+// Get the value of the "checksum" field.
+static int GetIHexChecksum(Sci_PositionU recStartPos, Accessor &styler)
+{
+       int byteCount;
+
+       byteCount = GetIHexByteCount(recStartPos, styler);
+
+       return GetHexaChar(recStartPos + 9 + byteCount * 2, styler);
+}
+
+// Calculate the checksum of the record.
+static int CalcIHexChecksum(Sci_PositionU recStartPos, Accessor &styler)
+{
+       int byteCount;
+
+       byteCount = GetIHexByteCount(recStartPos, styler);
+
+       // sum over "byte count", "address", "type" and "data" fields (8..518 digits)
+       return CalcChecksum(recStartPos + 1, 8 + byteCount * 2, true, styler);
+}
+
+
+// Get the value of the "record length" field, it counts the number of digits in
+// the record excluding the percent.
+static int GetTEHexDigitCount(Sci_PositionU recStartPos, Accessor &styler)
+{
+       int val = GetHexaChar(recStartPos + 1, styler);
+       if (val < 0)
+              val = 0;
+
+       return val;
+}
+
+// Count the number of digits in this record. Has to
+// be equal to the "record length" field value.
+static Sci_Position CountTEHexDigitCount(Sci_PositionU recStartPos, Accessor &styler)
+{
+       Sci_PositionU pos;
+
+       pos = recStartPos+1;
+
+       while (!IsNewline(styler.SafeGetCharAt(pos, '\n'))) {
+               pos++;
+       }
+
+       return static_cast<Sci_Position>(pos - (recStartPos+1));
+}
+
+// Get the type of the "address" field content.
+static int GetTEHexAddressFieldType(Sci_PositionU recStartPos, Accessor &styler)
+{
+       switch (styler.SafeGetCharAt(recStartPos + 3)) {
+               case '6':
+                       return SCE_HEX_DATAADDRESS;
+
+               case '8':
+                       return SCE_HEX_STARTADDRESS;
+
+               default: // handle possible format extension in the future
+                       return SCE_HEX_ADDRESSFIELD_UNKNOWN;
+       }
+}
+
+// Get the value of the "checksum" field.
+static int GetTEHexChecksum(Sci_PositionU recStartPos, Accessor &styler)
+{
+       return GetHexaChar(recStartPos+4, styler);
+}
+
+// Calculate the checksum of the record (excluding the checksum field).
+static int CalcTEHexChecksum(Sci_PositionU recStartPos, Accessor &styler)
+{
+       Sci_PositionU pos = recStartPos +1;
+       Sci_PositionU length = GetTEHexDigitCount(recStartPos, styler);
+
+       int cs = GetHexaNibble(styler.SafeGetCharAt(pos++));//length
+       cs += GetHexaNibble(styler.SafeGetCharAt(pos++));//length
+
+       cs += GetHexaNibble(styler.SafeGetCharAt(pos++));//type
+
+       pos += 2;// jump over CS field
+
+       for (; pos <= recStartPos + length; ++pos) {
+               int val = GetHexaNibble(styler.SafeGetCharAt(pos));
+
+               if (val < 0) {
+                       return val;
+               }
+
+               // overflow does not matter
+               cs += val;
+       }
+
+       // low byte
+       return cs & 0xFF;
+
+}
+
+static void ColouriseSrecDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], 
Accessor &styler)
+{
+       StyleContext sc(startPos, length, initStyle, styler);
+
+       while (sc.More()) {
+               Sci_PositionU recStartPos;
+               int byteCount, reqByteCount, addrFieldSize, addrFieldType, dataFieldSize, dataFieldType;
+               int cs1, cs2;
+
+               switch (sc.state) {
+                       case SCE_HEX_DEFAULT:
+                               if (sc.atLineStart && sc.Match('S')) {
+                                       sc.SetState(SCE_HEX_RECSTART);
+                               }
+                               ForwardWithinLine(sc);
+                               break;
+
+                       case SCE_HEX_RECSTART:
+                               recStartPos = sc.currentPos - 1;
+                               addrFieldType = GetSrecAddressFieldType(recStartPos, styler);
+
+                               if (addrFieldType == SCE_HEX_ADDRESSFIELD_UNKNOWN) {
+                                       sc.SetState(SCE_HEX_RECTYPE_UNKNOWN);
+                               } else {
+                                       sc.SetState(SCE_HEX_RECTYPE);
+                               }
+
+                               ForwardWithinLine(sc);
+                               break;
+
+                       case SCE_HEX_RECTYPE:
+                       case SCE_HEX_RECTYPE_UNKNOWN:
+                               recStartPos = sc.currentPos - 2;
+                               byteCount = GetSrecByteCount(recStartPos, styler);
+                               reqByteCount = GetSrecAddressFieldSize(recStartPos, styler)
+                                               + GetSrecRequiredDataFieldSize(recStartPos, styler)
+                                               + 1; // +1 for checksum field
+
+                               if (byteCount == CountSrecByteCount(recStartPos, styler)
+                                               && byteCount == reqByteCount) {
+                                       sc.SetState(SCE_HEX_BYTECOUNT);
+                               } else {
+                                       sc.SetState(SCE_HEX_BYTECOUNT_WRONG);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+                       case SCE_HEX_BYTECOUNT:
+                       case SCE_HEX_BYTECOUNT_WRONG:
+                               recStartPos = sc.currentPos - 4;
+                               addrFieldSize = GetSrecAddressFieldSize(recStartPos, styler);
+                               addrFieldType = GetSrecAddressFieldType(recStartPos, styler);
+
+                               sc.SetState(addrFieldType);
+                               ForwardWithinLine(sc, addrFieldSize * 2);
+                               break;
+
+                       case SCE_HEX_NOADDRESS:
+                       case SCE_HEX_DATAADDRESS:
+                       case SCE_HEX_RECCOUNT:
+                       case SCE_HEX_STARTADDRESS:
+                       case SCE_HEX_ADDRESSFIELD_UNKNOWN:
+                               recStartPos = GetSrecRecStartPosition(sc.currentPos, styler);
+                               dataFieldType = GetSrecDataFieldType(recStartPos, styler);
+
+                               // Using the required size here if possible has the effect that the
+                               // checksum is highlighted at a fixed position after this field for
+                               // specific record types, independent on the "byte count" value.
+                               dataFieldSize = GetSrecRequiredDataFieldSize(recStartPos, styler);
+
+                               sc.SetState(dataFieldType);
+
+                               if (dataFieldType == SCE_HEX_DATA_ODD) {
+                                       for (int i = 0; i < dataFieldSize * 2; i++) {
+                                               if ((i & 0x3) == 0) {
+                                                       sc.SetState(SCE_HEX_DATA_ODD);
+                                               } else if ((i & 0x3) == 2) {
+                                                       sc.SetState(SCE_HEX_DATA_EVEN);
+                                               }
+
+                                               if (!ForwardWithinLine(sc)) {
+                                                       break;
+                                               }
+                                       }
+                               } else {
+                                       ForwardWithinLine(sc, dataFieldSize * 2);
+                               }
+                               break;
+
+                       case SCE_HEX_DATA_ODD:
+                       case SCE_HEX_DATA_EVEN:
+                       case SCE_HEX_DATA_EMPTY:
+                       case SCE_HEX_DATA_UNKNOWN:
+                               recStartPos = GetSrecRecStartPosition(sc.currentPos, styler);
+                               cs1 = CalcSrecChecksum(recStartPos, styler);
+                               cs2 = GetSrecChecksum(recStartPos, styler);
+
+                               if (cs1 != cs2 || cs1 < 0 || cs2 < 0) {
+                                       sc.SetState(SCE_HEX_CHECKSUM_WRONG);
+                               } else {
+                                       sc.SetState(SCE_HEX_CHECKSUM);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+                       case SCE_HEX_CHECKSUM:
+                       case SCE_HEX_CHECKSUM_WRONG:
+                       case SCE_HEX_GARBAGE:
+                               // record finished or line too long
+                               sc.SetState(SCE_HEX_GARBAGE);
+                               ForwardWithinLine(sc);
+                               break;
+
+                       default:
+                               // prevent endless loop in faulty state
+                               sc.SetState(SCE_HEX_DEFAULT);
+                               break;
+               }
+       }
+       sc.Complete();
+}
+
+static void ColouriseIHexDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], 
Accessor &styler)
+{
+       StyleContext sc(startPos, length, initStyle, styler);
+
+       while (sc.More()) {
+               Sci_PositionU recStartPos;
+               int byteCount, addrFieldType, dataFieldSize, dataFieldType;
+               int cs1, cs2;
+
+               switch (sc.state) {
+                       case SCE_HEX_DEFAULT:
+                               if (sc.atLineStart && sc.Match(':')) {
+                                       sc.SetState(SCE_HEX_RECSTART);
+                               }
+                               ForwardWithinLine(sc);
+                               break;
+
+                       case SCE_HEX_RECSTART:
+                               recStartPos = sc.currentPos - 1;
+                               byteCount = GetIHexByteCount(recStartPos, styler);
+                               dataFieldSize = GetIHexRequiredDataFieldSize(recStartPos, styler);
+
+                               if (byteCount == CountIHexByteCount(recStartPos, styler)
+                                               && byteCount == dataFieldSize) {
+                                       sc.SetState(SCE_HEX_BYTECOUNT);
+                               } else {
+                                       sc.SetState(SCE_HEX_BYTECOUNT_WRONG);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+                       case SCE_HEX_BYTECOUNT:
+                       case SCE_HEX_BYTECOUNT_WRONG:
+                               recStartPos = sc.currentPos - 3;
+                               addrFieldType = GetIHexAddressFieldType(recStartPos, styler);
+
+                               sc.SetState(addrFieldType);
+                               ForwardWithinLine(sc, 4);
+                               break;
+
+                       case SCE_HEX_NOADDRESS:
+                       case SCE_HEX_DATAADDRESS:
+                       case SCE_HEX_ADDRESSFIELD_UNKNOWN:
+                               recStartPos = sc.currentPos - 7;
+                               addrFieldType = GetIHexAddressFieldType(recStartPos, styler);
+
+                               if (addrFieldType == SCE_HEX_ADDRESSFIELD_UNKNOWN) {
+                                       sc.SetState(SCE_HEX_RECTYPE_UNKNOWN);
+                               } else {
+                                       sc.SetState(SCE_HEX_RECTYPE);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+                       case SCE_HEX_RECTYPE:
+                       case SCE_HEX_RECTYPE_UNKNOWN:
+                               recStartPos = sc.currentPos - 9;
+                               dataFieldType = GetIHexDataFieldType(recStartPos, styler);
+
+                               // Using the required size here if possible has the effect that the
+                               // checksum is highlighted at a fixed position after this field for
+                               // specific record types, independent on the "byte count" value.
+                               dataFieldSize = GetIHexRequiredDataFieldSize(recStartPos, styler);
+
+                               sc.SetState(dataFieldType);
+
+                               if (dataFieldType == SCE_HEX_DATA_ODD) {
+                                       for (int i = 0; i < dataFieldSize * 2; i++) {
+                                               if ((i & 0x3) == 0) {
+                                                       sc.SetState(SCE_HEX_DATA_ODD);
+                                               } else if ((i & 0x3) == 2) {
+                                                       sc.SetState(SCE_HEX_DATA_EVEN);
+                                               }
+
+                                               if (!ForwardWithinLine(sc)) {
+                                                       break;
+                                               }
+                                       }
+                               } else {
+                                       ForwardWithinLine(sc, dataFieldSize * 2);
+                               }
+                               break;
+
+                       case SCE_HEX_DATA_ODD:
+                       case SCE_HEX_DATA_EVEN:
+                       case SCE_HEX_DATA_EMPTY:
+                       case SCE_HEX_EXTENDEDADDRESS:
+                       case SCE_HEX_STARTADDRESS:
+                       case SCE_HEX_DATA_UNKNOWN:
+                               recStartPos = GetIHexRecStartPosition(sc.currentPos, styler);
+                               cs1 = CalcIHexChecksum(recStartPos, styler);
+                               cs2 = GetIHexChecksum(recStartPos, styler);
+
+                               if (cs1 != cs2 || cs1 < 0 || cs2 < 0) {
+                                       sc.SetState(SCE_HEX_CHECKSUM_WRONG);
+                               } else {
+                                       sc.SetState(SCE_HEX_CHECKSUM);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+                       case SCE_HEX_CHECKSUM:
+                       case SCE_HEX_CHECKSUM_WRONG:
+                       case SCE_HEX_GARBAGE:
+                               // record finished or line too long
+                               sc.SetState(SCE_HEX_GARBAGE);
+                               ForwardWithinLine(sc);
+                               break;
+
+                       default:
+                               // prevent endless loop in faulty state
+                               sc.SetState(SCE_HEX_DEFAULT);
+                               break;
+               }
+       }
+       sc.Complete();
+}
+
+static void FoldIHexDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
+{
+       Sci_PositionU endPos = startPos + length;
+
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       int levelCurrent = SC_FOLDLEVELBASE;
+       if (lineCurrent > 0)
+               levelCurrent = styler.LevelAt(lineCurrent - 1);
+
+       Sci_PositionU lineStartNext = styler.LineStart(lineCurrent + 1);
+       int levelNext = SC_FOLDLEVELBASE; // default if no specific line found
+
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
+               bool atEOL = i == (lineStartNext - 1);
+               int style = styler.StyleAt(i);
+
+               // search for specific lines
+               if (style == SCE_HEX_EXTENDEDADDRESS) {
+                       // extended addres record
+                       levelNext = SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG;
+               } else if (style == SCE_HEX_DATAADDRESS
+                       || (style == SCE_HEX_DEFAULT
+                               && i == (Sci_PositionU)styler.LineStart(lineCurrent))) {
+                       // data record or no record start code at all
+                       if (levelCurrent & SC_FOLDLEVELHEADERFLAG) {
+                               levelNext = SC_FOLDLEVELBASE + 1;
+                       } else {
+                               // continue level 0 or 1, no fold point
+                               levelNext = levelCurrent;
+                       }
+               }
+
+               if (atEOL || (i == endPos - 1)) {
+                       styler.SetLevel(lineCurrent, levelNext);
+
+                       lineCurrent++;
+                       lineStartNext = styler.LineStart(lineCurrent + 1);
+                       levelCurrent = levelNext;
+                       levelNext = SC_FOLDLEVELBASE;
+               }
+       }
+}
+
+static void ColouriseTEHexDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], 
Accessor &styler)
+{
+       StyleContext sc(startPos, length, initStyle, styler);
+
+       while (sc.More()) {
+               Sci_PositionU recStartPos;
+               int digitCount, addrFieldType;
+               int cs1, cs2;
+
+               switch (sc.state) {
+                       case SCE_HEX_DEFAULT:
+                               if (sc.atLineStart && sc.Match('%')) {
+                                       sc.SetState(SCE_HEX_RECSTART);
+                               }
+                               ForwardWithinLine(sc);
+                               break;
+
+                       case SCE_HEX_RECSTART:
+
+                               recStartPos = sc.currentPos - 1;
+
+                               if (GetTEHexDigitCount(recStartPos, styler) == 
CountTEHexDigitCount(recStartPos, styler)) {
+                                       sc.SetState(SCE_HEX_BYTECOUNT);
+                               } else {
+                                       sc.SetState(SCE_HEX_BYTECOUNT_WRONG);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+                       case SCE_HEX_BYTECOUNT:
+                       case SCE_HEX_BYTECOUNT_WRONG:
+                               recStartPos = sc.currentPos - 3;
+                               addrFieldType = GetTEHexAddressFieldType(recStartPos, styler);
+
+                               if (addrFieldType == SCE_HEX_ADDRESSFIELD_UNKNOWN) {
+                                       sc.SetState(SCE_HEX_RECTYPE_UNKNOWN);
+                               } else {
+                                       sc.SetState(SCE_HEX_RECTYPE);
+                               }
+
+                               ForwardWithinLine(sc);
+                               break;
+
+                       case SCE_HEX_RECTYPE:
+                       case SCE_HEX_RECTYPE_UNKNOWN:
+                               recStartPos = sc.currentPos - 4;
+                               cs1 = CalcTEHexChecksum(recStartPos, styler);
+                               cs2 = GetTEHexChecksum(recStartPos, styler);
+
+                               if (cs1 != cs2 || cs1 < 0 || cs2 < 0) {
+                                       sc.SetState(SCE_HEX_CHECKSUM_WRONG);
+                               } else {
+                                       sc.SetState(SCE_HEX_CHECKSUM);
+                               }
+
+                               ForwardWithinLine(sc, 2);
+                               break;
+
+
+                       case SCE_HEX_CHECKSUM:
+                       case SCE_HEX_CHECKSUM_WRONG:
+                               recStartPos = sc.currentPos - 6;
+                               addrFieldType = GetTEHexAddressFieldType(recStartPos, styler);
+
+                               sc.SetState(addrFieldType);
+                               ForwardWithinLine(sc, 9);
+                               break;
+
+                       case SCE_HEX_DATAADDRESS:
+                       case SCE_HEX_STARTADDRESS:
+                       case SCE_HEX_ADDRESSFIELD_UNKNOWN:
+                               recStartPos = sc.currentPos - 15;
+                               digitCount = GetTEHexDigitCount(recStartPos, styler) - 14;
+
+                               sc.SetState(SCE_HEX_DATA_ODD);
+
+                               for (int i = 0; i < digitCount; i++) {
+                                       if ((i & 0x3) == 0) {
+                                               sc.SetState(SCE_HEX_DATA_ODD);
+                                       } else if ((i & 0x3) == 2) {
+                                               sc.SetState(SCE_HEX_DATA_EVEN);
+                                       }
+
+                                       if (!ForwardWithinLine(sc)) {
+                                               break;
+                                       }
+                               }
+                               break;
+
+                       case SCE_HEX_DATA_ODD:
+                       case SCE_HEX_DATA_EVEN:
+                       case SCE_HEX_GARBAGE:
+                               // record finished or line too long
+                               sc.SetState(SCE_HEX_GARBAGE);
+                               ForwardWithinLine(sc);
+                               break;
+
+                       default:
+                               // prevent endless loop in faulty state
+                               sc.SetState(SCE_HEX_DEFAULT);
+                               break;
+               }
+       }
+       sc.Complete();
+}
+
+LexerModule lmSrec(SCLEX_SREC, ColouriseSrecDoc, "srec", 0, NULL);
+LexerModule lmIHex(SCLEX_IHEX, ColouriseIHexDoc, "ihex", FoldIHexDoc, NULL);
+LexerModule lmTEHex(SCLEX_TEHEX, ColouriseTEHexDoc, "tehex", 0, NULL);
diff --git a/plugins/scintilla/scintilla/lexers/LexIndent.cxx 
b/plugins/scintilla/scintilla/lexers/LexIndent.cxx
new file mode 100644
index 0000000..ac25938
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexIndent.cxx
@@ -0,0 +1,73 @@
+// Scintilla source code edit control
+/** @file LexIndent.cxx
+ ** Lexer for no language. Used for indentation-based folding of files.
+ **/
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static void ColouriseIndentDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
+                            Accessor &styler) {
+       // Indent language means all style bytes are 0 so just mark the end - no need to fill in.
+       if (length > 0) {
+               styler.StartAt(startPos + length - 1);
+               styler.StartSegment(startPos + length - 1);
+               styler.ColourTo(startPos + length - 1, 0);
+       }
+}
+
+static void FoldIndentDoc(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList *[], 
Accessor &styler) {
+       int visibleCharsCurrent, visibleCharsNext;
+       int levelCurrent, levelNext;
+       Sci_PositionU i, lineEnd;
+       Sci_PositionU lengthDoc   = startPos + length;
+       Sci_Position  lineCurrent = styler.GetLine(startPos);
+
+       i       = styler.LineStart(lineCurrent  );
+       lineEnd = styler.LineStart(lineCurrent+1)-1;
+       if(lineEnd>=lengthDoc) lineEnd = lengthDoc-1;
+       while(styler[lineEnd]=='\n' || styler[lineEnd]=='\r') lineEnd--;
+       for(visibleCharsCurrent=0, levelCurrent=SC_FOLDLEVELBASE; !visibleCharsCurrent && i<=lineEnd; i++){
+               if(isspacechar(styler[i])) levelCurrent++;
+               else                       visibleCharsCurrent=1;
+       }
+
+       for(; i<lengthDoc; lineCurrent++) {
+               i       = styler.LineStart(lineCurrent+1);
+               lineEnd = styler.LineStart(lineCurrent+2)-1;
+               if(lineEnd>=lengthDoc) lineEnd = lengthDoc-1;
+               while(styler[lineEnd]=='\n' || styler[lineEnd]=='\r') lineEnd--;
+               for(visibleCharsNext=0, levelNext=SC_FOLDLEVELBASE; !visibleCharsNext && i<=lineEnd; i++){
+                       if(isspacechar(styler[i])) levelNext++;
+                       else                       visibleCharsNext=1;
+               }
+               int lev = levelCurrent;
+               if(!visibleCharsCurrent) lev |= SC_FOLDLEVELWHITEFLAG;
+               else if(levelNext > levelCurrent) lev |= SC_FOLDLEVELHEADERFLAG;
+               styler.SetLevel(lineCurrent, lev);
+               levelCurrent = levelNext;
+               visibleCharsCurrent = visibleCharsNext;
+       }
+}
+
+LexerModule lmIndent(SCLEX_INDENT, ColouriseIndentDoc, "indent", FoldIndentDoc);
diff --git a/plugins/scintilla/scintilla/lexers/LexInno.cxx b/plugins/scintilla/scintilla/lexers/LexInno.cxx
index a0f5b32..50aa25d 100644
--- a/plugins/scintilla/scintilla/lexers/LexInno.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexInno.cxx
@@ -27,14 +27,14 @@
 using namespace Scintilla;
 #endif
 
-static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor 
&styler) {
+static void ColouriseInnoDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], 
Accessor &styler) {
        int state = SCE_INNO_DEFAULT;
        char chPrev;
        char ch = 0;
        char chNext = styler[startPos];
-       int lengthDoc = startPos + length;
-       char *buffer = new char[length];
-       int bufferCount = 0;
+       Sci_Position lengthDoc = startPos + length;
+       char *buffer = new char[length+1];
+       Sci_Position bufferCount = 0;
        bool isBOL, isEOL, isWS, isBOLWS = 0;
        bool isCStyleComment = false;
 
@@ -45,7 +45,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
        WordList &pascalKeywords = *keywordLists[4];
        WordList &userKeywords = *keywordLists[5];
 
-       int curLine = styler.GetLine(startPos);
+       Sci_Position curLine = styler.GetLine(startPos);
        int curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : 0;
        bool isCode = (curLineState == 1);
 
@@ -53,7 +53,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
        // using the hand-written state machine shown below
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
-       for (int i = startPos; i < lengthDoc; i++) {
+       for (Sci_Position i = startPos; i < lengthDoc; i++) {
                chPrev = ch;
                ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
@@ -104,7 +104,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
                                } else if (ch == '\'') {
                                        // Start of a single-quote string
                                        state = SCE_INNO_STRING_SINGLE;
-                               } else if (isascii(ch) && (isalpha(ch) || (ch == '_'))) {
+                               } else if (IsASCII(ch) && (isalpha(ch) || (ch == '_'))) {
                                        // Start of an identifier
                                        bufferCount = 0;
                                        buffer[bufferCount++] = static_cast<char>(tolower(ch));
@@ -123,7 +123,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
                                break;
 
                        case SCE_INNO_IDENTIFIER:
-                               if (isascii(ch) && (isalnum(ch) || (ch == '_'))) {
+                               if (IsASCII(ch) && (isalnum(ch) || (ch == '_'))) {
                                        buffer[bufferCount++] = static_cast<char>(tolower(ch));
                                } else {
                                        state = SCE_INNO_DEFAULT;
@@ -160,7 +160,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
                                        } else {
                                                styler.ColourTo(i,SCE_INNO_DEFAULT);
                                        }
-                               } else if (isascii(ch) && (isalnum(ch) || (ch == '_'))) {
+                               } else if (IsASCII(ch) && (isalnum(ch) || (ch == '_'))) {
                                        buffer[bufferCount++] = static_cast<char>(tolower(ch));
                                } else {
                                        state = SCE_INNO_DEFAULT;
@@ -170,7 +170,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
 
                        case SCE_INNO_PREPROC:
                                if (isWS || isEOL) {
-                                       if (isascii(chPrev) && isalpha(chPrev)) {
+                                       if (IsASCII(chPrev) && isalpha(chPrev)) {
                                                state = SCE_INNO_DEFAULT;
                                                buffer[bufferCount] = '\0';
 
@@ -185,7 +185,7 @@ static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *k
                                                chNext = styler[i--];
                                                ch = chPrev;
                                        }
-                               } else if (isascii(ch) && isalpha(ch)) {
+                               } else if (IsASCII(ch) && isalpha(ch)) {
                                        if (chPrev == '#' || chPrev == ' ' || chPrev == '\t')
                                                bufferCount = 0;
                                        buffer[bufferCount++] = static_cast<char>(tolower(ch));
@@ -248,17 +248,17 @@ static const char * const innoWordListDesc[] = {
        0
 };
 
-static void FoldInnoDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
-       unsigned int endPos = startPos + length;
+static void FoldInnoDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
+       Sci_PositionU endPos = startPos + length;
        char chNext = styler[startPos];
 
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
 
        bool sectionFlag = false;
        int levelPrev = lineCurrent > 0 ? styler.LevelAt(lineCurrent - 1) : SC_FOLDLEVELBASE;
        int level;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler[i+1];
                bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
diff --git a/plugins/scintilla/scintilla/lexers/LexJSON.cxx b/plugins/scintilla/scintilla/lexers/LexJSON.cxx
new file mode 100644
index 0000000..32b7192
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexJSON.cxx
@@ -0,0 +1,499 @@
+// Scintilla source code edit control
+/**
+ * @file LexJSON.cxx
+ * @date February 19, 2016
+ * @brief Lexer for JSON and JSON-LD formats
+ * @author nkmathew
+ *
+ * The License.txt file describes the conditions under which this software may
+ * be distributed.
+ *
+ */
+
+#include <cstdlib>
+#include <cassert>
+#include <cctype>
+#include <cstdio>
+#include <string>
+#include <vector>
+#include <map>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+#include "OptionSet.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static const char *const JSONWordListDesc[] = {
+       "JSON Keywords",
+       "JSON-LD Keywords",
+       0
+};
+
+/**
+ * Used to detect compact IRI/URLs in JSON-LD without first looking ahead for the
+ * colon separating the prefix and suffix
+ *
+ * https://www.w3.org/TR/json-ld/#dfn-compact-iri
+ */
+struct CompactIRI {
+       int colonCount;
+       bool foundInvalidChar;
+       CharacterSet setCompactIRI;
+       CompactIRI() {
+               colonCount = 0;
+               foundInvalidChar = false;
+               setCompactIRI = CharacterSet(CharacterSet::setAlpha, "$_-");
+       }
+       void resetState() {
+               colonCount = 0;
+               foundInvalidChar = false;
+       }
+       void checkChar(int ch) {
+               if (ch == ':') {
+                       colonCount++;
+               } else {
+                       foundInvalidChar |= !setCompactIRI.Contains(ch);
+               }
+       }
+       bool shouldHighlight() const {
+               return !foundInvalidChar && colonCount == 1;
+       }
+};
+
+/**
+ * Keeps track of escaped characters in strings as per:
+ *
+ * https://tools.ietf.org/html/rfc7159#section-7
+ */
+struct EscapeSequence {
+       int digitsLeft;
+       CharacterSet setHexDigits;
+       CharacterSet setEscapeChars;
+       EscapeSequence() {
+               digitsLeft = 0;
+               setHexDigits = CharacterSet(CharacterSet::setDigits, "ABCDEFabcdef");
+               setEscapeChars = CharacterSet(CharacterSet::setNone, "\\\"tnbfru/");
+       }
+       // Returns true if the following character is a valid escaped character
+       bool newSequence(int nextChar) {
+               digitsLeft = 0;
+               if (nextChar == 'u') {
+                       digitsLeft = 5;
+               } else if (!setEscapeChars.Contains(nextChar)) {
+                       return false;
+               }
+               return true;
+       }
+       bool atEscapeEnd() const {
+               return digitsLeft <= 0;
+       }
+       bool isInvalidChar(int currChar) const {
+               return !setHexDigits.Contains(currChar);
+       }
+};
+
+struct OptionsJSON {
+       bool foldCompact;
+       bool fold;
+       bool allowComments;
+       bool escapeSequence;
+       OptionsJSON() {
+               foldCompact = false;
+               fold = false;
+               allowComments = false;
+               escapeSequence = false;
+       }
+};
+
+struct OptionSetJSON : public OptionSet<OptionsJSON> {
+       OptionSetJSON() {
+               DefineProperty("lexer.json.escape.sequence", &OptionsJSON::escapeSequence,
+                                          "Set to 1 to enable highlighting of escape sequences in strings");
+
+               DefineProperty("lexer.json.allow.comments", &OptionsJSON::allowComments,
+                                          "Set to 1 to enable highlighting of line/block comments in JSON");
+
+               DefineProperty("fold.compact", &OptionsJSON::foldCompact);
+               DefineProperty("fold", &OptionsJSON::fold);
+               DefineWordListSets(JSONWordListDesc);
+       }
+};
+
+class LexerJSON : public ILexer {
+       OptionsJSON options;
+       OptionSetJSON optSetJSON;
+       EscapeSequence escapeSeq;
+       WordList keywordsJSON;
+       WordList keywordsJSONLD;
+       CharacterSet setOperators;
+       CharacterSet setURL;
+       CharacterSet setKeywordJSONLD;
+       CharacterSet setKeywordJSON;
+       CompactIRI compactIRI;
+
+       static bool IsNextNonWhitespace(LexAccessor &styler, Sci_Position start, char ch) {
+               Sci_Position i = 0;
+               while (i < 50) {
+                       i++;
+                       char curr = styler.SafeGetCharAt(start+i, '\0');
+                       char next = styler.SafeGetCharAt(start+i+1, '\0');
+                       bool atEOL = (curr == '\r' && next != '\n') || (curr == '\n');
+                       if (curr == ch) {
+                               return true;
+                       } else if (!isspacechar(curr) || atEOL) {
+                               return false;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Looks for the colon following the end quote
+        *
+        * Assumes property names of lengths no longer than a 100 characters.
+        * The colon is also expected to be less than 50 spaces after the end
+        * quote for the string to be considered a property name
+        */
+       static bool AtPropertyName(LexAccessor &styler, Sci_Position start) {
+               Sci_Position i = 0;
+               bool escaped = false;
+               while (i < 100) {
+                       i++;
+                       char curr = styler.SafeGetCharAt(start+i, '\0');
+                       if (escaped) {
+                               escaped = false;
+                               continue;
+                       }
+                       escaped = curr == '\\';
+                       if (curr == '"') {
+                               return IsNextNonWhitespace(styler, start+i, ':');
+                       } else if (!curr) {
+                               return false;
+                       }
+               }
+               return false;
+       }
+
+       static bool IsNextWordInList(WordList &keywordList, CharacterSet wordSet,
+                                                                StyleContext &context, LexAccessor &styler) {
+               char word[51];
+               Sci_Position currPos = (Sci_Position) context.currentPos;
+               int i = 0;
+               while (i < 50) {
+                       char ch = styler.SafeGetCharAt(currPos + i);
+                       if (!wordSet.Contains(ch)) {
+                               break;
+                       }
+                       word[i] = ch;
+                       i++;
+               }
+               word[i] = '\0';
+               return keywordList.InList(word);
+       }
+
+       public:
+       LexerJSON() :
+               setOperators(CharacterSet::setNone, "[{}]:,"),
+               setURL(CharacterSet::setAlphaNum, "-._~:/?#[]@!$&'()*+,),="),
+               setKeywordJSONLD(CharacterSet::setAlpha, ":@"),
+               setKeywordJSON(CharacterSet::setAlpha, "$_") {
+       }
+       virtual ~LexerJSON() {}
+       int SCI_METHOD Version() const override {
+               return lvOriginal;
+       }
+       void SCI_METHOD Release() override {
+               delete this;
+       }
+       const char *SCI_METHOD PropertyNames() override {
+               return optSetJSON.PropertyNames();
+       }
+       int SCI_METHOD PropertyType(const char *name) override {
+               return optSetJSON.PropertyType(name);
+       }
+       const char *SCI_METHOD DescribeProperty(const char *name) override {
+               return optSetJSON.DescribeProperty(name);
+       }
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override {
+               if (optSetJSON.PropertySet(&options, key, val)) {
+                       return 0;
+               }
+               return -1;
+       }
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override {
+               WordList *wordListN = 0;
+               switch (n) {
+                       case 0:
+                               wordListN = &keywordsJSON;
+                               break;
+                       case 1:
+                               wordListN = &keywordsJSONLD;
+                               break;
+               }
+               Sci_Position firstModification = -1;
+               if (wordListN) {
+                       WordList wlNew;
+                       wlNew.Set(wl);
+                       if (*wordListN != wlNew) {
+                               wordListN->Set(wl);
+                               firstModification = 0;
+                       }
+               }
+               return firstModification;
+       }
+       void *SCI_METHOD PrivateCall(int, void *) override {
+               return 0;
+       }
+       static ILexer *LexerFactoryJSON() {
+               return new LexerJSON;
+       }
+       const char *SCI_METHOD DescribeWordListSets() override {
+               return optSetJSON.DescribeWordListSets();
+       }
+       void SCI_METHOD Lex(Sci_PositionU startPos,
+                                                               Sci_Position length,
+                                                               int initStyle,
+                                                               IDocument *pAccess) override;
+       void SCI_METHOD Fold(Sci_PositionU startPos,
+                                                                Sci_Position length,
+                                                                int initStyle,
+                                                                IDocument *pAccess) override;
+};
+
+void SCI_METHOD LexerJSON::Lex(Sci_PositionU startPos,
+                                                          Sci_Position length,
+                                                          int initStyle,
+                                                          IDocument *pAccess) {
+       LexAccessor styler(pAccess);
+       StyleContext context(startPos, length, initStyle, styler);
+       int stringStyleBefore = SCE_JSON_STRING;
+       while (context.More()) {
+               switch (context.state) {
+                       case SCE_JSON_BLOCKCOMMENT:
+                               if (context.Match("*/")) {
+                                       context.Forward();
+                                       context.ForwardSetState(SCE_JSON_DEFAULT);
+                               }
+                               break;
+                       case SCE_JSON_LINECOMMENT:
+                               if (context.atLineEnd) {
+                                       context.SetState(SCE_JSON_DEFAULT);
+                               }
+                               break;
+                       case SCE_JSON_STRINGEOL:
+                               if (context.atLineStart) {
+                                       context.SetState(SCE_JSON_DEFAULT);
+                               }
+                               break;
+                       case SCE_JSON_ESCAPESEQUENCE:
+                               escapeSeq.digitsLeft--;
+                               if (!escapeSeq.atEscapeEnd()) {
+                                       if (escapeSeq.isInvalidChar(context.ch)) {
+                                               context.SetState(SCE_JSON_ERROR);
+                                       }
+                                       break;
+                               }
+                               if (context.ch == '"') {
+                                       context.SetState(stringStyleBefore);
+                                       context.ForwardSetState(SCE_C_DEFAULT);
+                               } else if (context.ch == '\\') {
+                                       if (!escapeSeq.newSequence(context.chNext)) {
+                                               context.SetState(SCE_JSON_ERROR);
+                                       }
+                                       context.Forward();
+                               } else {
+                                       context.SetState(stringStyleBefore);
+                                       if (context.atLineEnd) {
+                                               context.ChangeState(SCE_JSON_STRINGEOL);
+                                       }
+                               }
+                               break;
+                       case SCE_JSON_PROPERTYNAME:
+                       case SCE_JSON_STRING:
+                               if (context.ch == '"') {
+                                       if (compactIRI.shouldHighlight()) {
+                                               context.ChangeState(SCE_JSON_COMPACTIRI);
+                                               context.ForwardSetState(SCE_JSON_DEFAULT);
+                                               compactIRI.resetState();
+                                       } else {
+                                               context.ForwardSetState(SCE_JSON_DEFAULT);
+                                       }
+                               } else if (context.atLineEnd) {
+                                       context.ChangeState(SCE_JSON_STRINGEOL);
+                               } else if (context.ch == '\\') {
+                                       stringStyleBefore = context.state;
+                                       if (options.escapeSequence) {
+                                               context.SetState(SCE_JSON_ESCAPESEQUENCE);
+                                               if (!escapeSeq.newSequence(context.chNext)) {
+                                                       context.SetState(SCE_JSON_ERROR);
+                                               }
+                                       }
+                                       context.Forward();
+                               } else if (context.Match("https://";) ||
+                                                  context.Match("http://";) ||
+                                                  context.Match("ssh://") ||
+                                                  context.Match("git://") ||
+                                                  context.Match("svn://") ||
+                                                  context.Match("ftp://";) ||
+                                                  context.Match("mailto:";)) {
+                                       // Handle most common URI schemes only
+                                       stringStyleBefore = context.state;
+                                       context.SetState(SCE_JSON_URI);
+                               } else if (context.ch == '@') {
+                                       // https://www.w3.org/TR/json-ld/#dfn-keyword
+                                       if (IsNextWordInList(keywordsJSONLD, setKeywordJSONLD, context, 
styler)) {
+                                               stringStyleBefore = context.state;
+                                               context.SetState(SCE_JSON_LDKEYWORD);
+                                       }
+                               } else {
+                                       compactIRI.checkChar(context.ch);
+                               }
+                               break;
+                       case SCE_JSON_LDKEYWORD:
+                       case SCE_JSON_URI:
+                               if ((!setKeywordJSONLD.Contains(context.ch) &&
+                                        (context.state == SCE_JSON_LDKEYWORD)) ||
+                                       (!setURL.Contains(context.ch))) {
+                                       context.SetState(stringStyleBefore);
+                               }
+                               if (context.ch == '"') {
+                                       context.ForwardSetState(SCE_JSON_DEFAULT);
+                               } else if (context.atLineEnd) {
+                                       context.ChangeState(SCE_JSON_STRINGEOL);
+                               }
+                               break;
+                       case SCE_JSON_OPERATOR:
+                       case SCE_JSON_NUMBER:
+                               context.SetState(SCE_JSON_DEFAULT);
+                               break;
+                       case SCE_JSON_ERROR:
+                               if (context.atLineEnd) {
+                                       context.SetState(SCE_JSON_DEFAULT);
+                               }
+                               break;
+                       case SCE_JSON_KEYWORD:
+                               if (!setKeywordJSON.Contains(context.ch)) {
+                                       context.SetState(SCE_JSON_DEFAULT);
+                               }
+                               break;
+               }
+               if (context.state == SCE_JSON_DEFAULT) {
+                       if (context.ch == '"') {
+                               compactIRI.resetState();
+                               context.SetState(SCE_JSON_STRING);
+                               Sci_Position currPos = static_cast<Sci_Position>(context.currentPos);
+                               if (AtPropertyName(styler, currPos)) {
+                                       context.SetState(SCE_JSON_PROPERTYNAME);
+                               }
+                       } else if (setOperators.Contains(context.ch)) {
+                               context.SetState(SCE_JSON_OPERATOR);
+                       } else if (options.allowComments && context.Match("/*")) {
+                               context.SetState(SCE_JSON_BLOCKCOMMENT);
+                               context.Forward();
+                       } else if (options.allowComments && context.Match("//")) {
+                               context.SetState(SCE_JSON_LINECOMMENT);
+                       } else if (setKeywordJSON.Contains(context.ch)) {
+                               if (IsNextWordInList(keywordsJSON, setKeywordJSON, context, styler)) {
+                                       context.SetState(SCE_JSON_KEYWORD);
+                               }
+                       }
+                       bool numberStart =
+                               IsADigit(context.ch) && (context.chPrev == '+'||
+                                                                                context.chPrev == '-' ||
+                                                                                context.atLineStart ||
+                                                                                IsASpace(context.chPrev) ||
+                                                                                
setOperators.Contains(context.chPrev));
+                       bool exponentPart =
+                               tolower(context.ch) == 'e' &&
+                               IsADigit(context.chPrev) &&
+                               (IsADigit(context.chNext) ||
+                                context.chNext == '+' ||
+                                context.chNext == '-');
+                       bool signPart =
+                               (context.ch == '-' || context.ch == '+') &&
+                               ((tolower(context.chPrev) == 'e' && IsADigit(context.chNext)) ||
+                                ((IsASpace(context.chPrev) || setOperators.Contains(context.chPrev))
+                                 && IsADigit(context.chNext)));
+                       bool adjacentDigit =
+                               IsADigit(context.ch) && IsADigit(context.chPrev);
+                       bool afterExponent = IsADigit(context.ch) && tolower(context.chPrev) == 'e';
+                       bool dotPart = context.ch == '.' &&
+                               IsADigit(context.chPrev) &&
+                               IsADigit(context.chNext);
+                       bool afterDot = IsADigit(context.ch) && context.chPrev == '.';
+                       if (numberStart ||
+                               exponentPart ||
+                               signPart ||
+                               adjacentDigit ||
+                               dotPart ||
+                               afterExponent ||
+                               afterDot) {
+                               context.SetState(SCE_JSON_NUMBER);
+                       } else if (context.state == SCE_JSON_DEFAULT && !IsASpace(context.ch)) {
+                               context.SetState(SCE_JSON_ERROR);
+                       }
+               }
+               context.Forward();
+       }
+       context.Complete();
+}
+
+void SCI_METHOD LexerJSON::Fold(Sci_PositionU startPos,
+                                                               Sci_Position length,
+                                                               int,
+                                                               IDocument *pAccess) {
+       if (!options.fold) {
+               return;
+       }
+       LexAccessor styler(pAccess);
+       Sci_PositionU currLine = styler.GetLine(startPos);
+       Sci_PositionU endPos = startPos + length;
+       int currLevel = SC_FOLDLEVELBASE;
+       if (currLine > 0)
+               currLevel = styler.LevelAt(currLine - 1) >> 16;
+       int nextLevel = currLevel;
+       int visibleChars = 0;
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
+               char curr = styler.SafeGetCharAt(i);
+               char next = styler.SafeGetCharAt(i+1);
+               bool atEOL = (curr == '\r' && next != '\n') || (curr == '\n');
+               if (styler.StyleAt(i) == SCE_JSON_OPERATOR) {
+                       if (curr == '{' || curr == '[') {
+                               nextLevel++;
+                       } else if (curr == '}' || curr == ']') {
+                               nextLevel--;
+                       }
+               }
+               if (atEOL || i == (endPos-1)) {
+                       int level = currLevel | nextLevel << 16;
+                       if (!visibleChars && options.foldCompact) {
+                               level |= SC_FOLDLEVELWHITEFLAG;
+                       } else if (nextLevel > currLevel) {
+                               level |= SC_FOLDLEVELHEADERFLAG;
+                       }
+                       if (level != styler.LevelAt(currLine)) {
+                               styler.SetLevel(currLine, level);
+                       }
+                       currLine++;
+                       currLevel = nextLevel;
+                       visibleChars = 0;
+               }
+               if (!isspacechar(curr)) {
+                       visibleChars++;
+               }
+       }
+}
+
+LexerModule lmJSON(SCLEX_JSON,
+                                  LexerJSON::LexerFactoryJSON,
+                                  "json",
+                                  JSONWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexKVIrc.cxx b/plugins/scintilla/scintilla/lexers/LexKVIrc.cxx
new file mode 100644
index 0000000..75cb833
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexKVIrc.cxx
@@ -0,0 +1,473 @@
+// Scintilla source code edit control
+/** @file LexKVIrc.cxx
+ ** Lexer for KVIrc script.
+ **/
+// Copyright 2013 by OmegaPhil <OmegaPhil+scintilla gmail com>, based in
+// part from LexPython Copyright 1998-2002 by Neil Hodgson <neilh scintilla org>
+// and LexCmake Copyright 2007 by Cristian Adam <cristian [dot] adam [at] gmx [dot] net>
+
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+
+/* KVIrc Script syntactic rules: http://www.kvirc.net/doc/doc_syntactic_rules.html */
+
+/* Utility functions */
+static inline bool IsAWordChar(int ch) {
+
+    /* Keyword list includes modules, i.e. words including '.', and
+     * alias namespaces include ':' */
+    return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'
+            || ch == ':');
+}
+static inline bool IsAWordStart(int ch) {
+
+    /* Functions (start with '$') are treated separately to keywords */
+    return (ch < 0x80) && (isalnum(ch) || ch == '_' );
+}
+
+/* Interface function called by Scintilla to request some text to be
+ syntax highlighted */
+static void ColouriseKVIrcDoc(Sci_PositionU startPos, Sci_Position length,
+                              int initStyle, WordList *keywordlists[],
+                              Accessor &styler)
+{
+    /* Fetching style context */
+    StyleContext sc(startPos, length, initStyle, styler);
+
+    /* Accessing keywords and function-marking keywords */
+    WordList &keywords = *keywordlists[0];
+    WordList &functionKeywords = *keywordlists[1];
+
+    /* Looping for all characters - only automatically moving forward
+     * when asked for (transitions leaving strings and keywords do this
+     * already) */
+    bool next = true;
+    for( ; sc.More(); next ? sc.Forward() : (void)0 )
+    {
+        /* Resetting next */
+        next = true;
+
+        /* Dealing with different states */
+        switch (sc.state)
+        {
+            case SCE_KVIRC_DEFAULT:
+
+                /* Detecting single-line comments
+                 * Unfortunately KVIrc script allows raw '#<channel
+                 * name>' to be used, and appending # to an array returns
+                 * its length...
+                 * Going for a compromise where single line comments not
+                 * starting on a newline are allowed in all cases except
+                 * when they are preceeded with an opening bracket or comma
+                 * (this will probably be the most common style a valid
+                 * string-less channel name will be used with), with the
+                 * array length case included
+                 */
+                if (
+                    (sc.ch == '#' && sc.atLineStart) ||
+                    (sc.ch == '#' && (
+                        sc.chPrev != '(' && sc.chPrev != ',' &&
+                        sc.chPrev != ']')
+                    )
+                )
+                {
+                    sc.SetState(SCE_KVIRC_COMMENT);
+                    break;
+                }
+
+                /* Detecting multi-line comments */
+                if (sc.Match('/', '*'))
+                {
+                    sc.SetState(SCE_KVIRC_COMMENTBLOCK);
+                    break;
+                }
+
+                /* Detecting strings */
+                if (sc.ch == '"')
+                {
+                    sc.SetState(SCE_KVIRC_STRING);
+                    break;
+                }
+
+                /* Detecting functions */
+                if (sc.ch == '$')
+                {
+                    sc.SetState(SCE_KVIRC_FUNCTION);
+                    break;
+                }
+
+                /* Detecting variables */
+                if (sc.ch == '%')
+                {
+                    sc.SetState(SCE_KVIRC_VARIABLE);
+                    break;
+                }
+
+                /* Detecting numbers - isdigit is unsafe as it does not
+                 * validate, use CharacterSet.h functions */
+                if (IsADigit(sc.ch))
+                {
+                    sc.SetState(SCE_KVIRC_NUMBER);
+                    break;
+                }
+
+                /* Detecting words */
+                if (IsAWordStart(sc.ch) && IsAWordChar(sc.chNext))
+                {
+                    sc.SetState(SCE_KVIRC_WORD);
+                    sc.Forward();
+                    break;
+                }
+
+                /* Detecting operators */
+                if (isoperator(sc.ch))
+                {
+                    sc.SetState(SCE_KVIRC_OPERATOR);
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_COMMENT:
+
+                /* Breaking out of single line comment when a newline
+                 * is introduced */
+                if (sc.ch == '\r' || sc.ch == '\n')
+                {
+                    sc.SetState(SCE_KVIRC_DEFAULT);
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_COMMENTBLOCK:
+
+                /* Detecting end of multi-line comment */
+                if (sc.Match('*', '/'))
+                {
+                    // Moving the current position forward two characters
+                    // so that '*/' is included in the comment
+                    sc.Forward(2);
+                    sc.SetState(SCE_KVIRC_DEFAULT);
+
+                    /* Comment has been exited and the current position
+                     * moved forward, yet the new current character
+                     * has yet to be defined - loop without moving
+                     * forward again */
+                    next = false;
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_STRING:
+
+                /* Detecting end of string - closing speechmarks */
+                if (sc.ch == '"')
+                {
+                    /* Allowing escaped speechmarks to pass */
+                    if (sc.chPrev == '\\')
+                        break;
+
+                    /* Moving the current position forward to capture the
+                     * terminating speechmarks, and ending string */
+                    sc.ForwardSetState(SCE_KVIRC_DEFAULT);
+
+                    /* String has been exited and the current position
+                     * moved forward, yet the new current character
+                     * has yet to be defined - loop without moving
+                     * forward again */
+                    next = false;
+                    break;
+                }
+
+                /* Functions and variables are now highlighted in strings
+                 * Detecting functions */
+                if (sc.ch == '$')
+                {
+                    /* Allowing escaped functions to pass */
+                    if (sc.chPrev == '\\')
+                        break;
+
+                    sc.SetState(SCE_KVIRC_STRING_FUNCTION);
+                    break;
+                }
+
+                /* Detecting variables */
+                if (sc.ch == '%')
+                {
+                    /* Allowing escaped variables to pass */
+                    if (sc.chPrev == '\\')
+                        break;
+
+                    sc.SetState(SCE_KVIRC_STRING_VARIABLE);
+                    break;
+                }
+
+                /* Breaking out of a string when a newline is introduced */
+                if (sc.ch == '\r' || sc.ch == '\n')
+                {
+                    /* Allowing escaped newlines */
+                    if (sc.chPrev == '\\')
+                        break;
+
+                    sc.SetState(SCE_KVIRC_DEFAULT);
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_FUNCTION:
+            case SCE_KVIRC_VARIABLE:
+
+                /* Detecting the end of a function/variable (word) */
+                if (!IsAWordChar(sc.ch))
+                {
+                    sc.SetState(SCE_KVIRC_DEFAULT);
+
+                    /* Word has been exited yet the current character
+                     * has yet to be defined - loop without moving
+                     * forward again */
+                    next = false;
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_STRING_FUNCTION:
+            case SCE_KVIRC_STRING_VARIABLE:
+
+                /* A function or variable in a string
+                 * Detecting the end of a function/variable (word) */
+                if (!IsAWordChar(sc.ch))
+                {
+                    sc.SetState(SCE_KVIRC_STRING);
+
+                    /* Word has been exited yet the current character
+                     * has yet to be defined - loop without moving
+                     * forward again */
+                    next = false;
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_NUMBER:
+
+                /* Detecting the end of a number */
+                if (!IsADigit(sc.ch))
+                {
+                    sc.SetState(SCE_KVIRC_DEFAULT);
+
+                    /* Number has been exited yet the current character
+                     * has yet to be defined - loop without moving
+                     * forward */
+                    next = false;
+                    break;
+                }
+
+                break;
+
+            case SCE_KVIRC_OPERATOR:
+
+                /* Because '%' is an operator but is also the marker for
+                 * a variable, I need to always treat operators as single
+                 * character strings and therefore redo their detection
+                 * after every character */
+                sc.SetState(SCE_KVIRC_DEFAULT);
+
+                /* Operator has been exited yet the current character
+                 * has yet to be defined - loop without moving
+                 * forward */
+                next = false;
+                break;
+
+            case SCE_KVIRC_WORD:
+
+                /* Detecting the end of a word */
+                if (!IsAWordChar(sc.ch))
+                {
+                    /* Checking if the word was actually a keyword -
+                     * fetching the current word, NULL-terminated like
+                     * the keyword list */
+                    char s[100];
+                    Sci_Position wordLen = sc.currentPos - styler.GetStartSegment();
+                    if (wordLen > 99)
+                        wordLen = 99;  /* Include '\0' in buffer */
+                    Sci_Position i;
+                    for( i = 0; i < wordLen; ++i )
+                    {
+                        s[i] = styler.SafeGetCharAt( styler.GetStartSegment() + i );
+                    }
+                    s[wordLen] = '\0';
+
+                    /* Actually detecting keywords and fixing the state */
+                    if (keywords.InList(s))
+                    {
+                        /* The SetState call actually commits the
+                         * previous keyword state */
+                        sc.ChangeState(SCE_KVIRC_KEYWORD);
+                    }
+                    else if (functionKeywords.InList(s))
+                    {
+                        // Detecting function keywords and fixing the state
+                        sc.ChangeState(SCE_KVIRC_FUNCTION_KEYWORD);
+                    }
+
+                    /* Transitioning to default and committing the previous
+                     * word state */
+                    sc.SetState(SCE_KVIRC_DEFAULT);
+
+                    /* Word has been exited yet the current character
+                     * has yet to be defined - loop without moving
+                     * forward again */
+                    next = false;
+                    break;
+                }
+
+                break;
+        }
+    }
+
+    /* Indicating processing is complete */
+    sc.Complete();
+}
+
+static void FoldKVIrcDoc(Sci_PositionU startPos, Sci_Position length, int /*initStyle - unused*/,
+                      WordList *[], Accessor &styler)
+{
+    /* Based on CMake's folder */
+
+    /* Exiting if folding isnt enabled */
+    if ( styler.GetPropertyInt("fold") == 0 )
+        return;
+
+    /* Obtaining current line number*/
+    Sci_Position currentLine = styler.GetLine(startPos);
+
+    /* Obtaining starting character - indentation is done on a line basis,
+     * not character */
+    Sci_PositionU safeStartPos = styler.LineStart( currentLine );
+
+    /* Initialising current level - this is defined as indentation level
+     * in the low 12 bits, with flag bits in the upper four bits.
+     * It looks like two indentation states are maintained in the returned
+     * 32bit value - 'nextLevel' in the most-significant bits, 'currentLevel'
+     * in the least-significant bits. Since the next level is the most
+     * up to date, this must refer to the current state of indentation.
+     * So the code bitshifts the old current level out of existence to
+     * get at the actual current state of indentation
+     * Based on the LexerCPP.cxx line 958 comment */
+    int currentLevel = SC_FOLDLEVELBASE;
+    if (currentLine > 0)
+        currentLevel = styler.LevelAt(currentLine - 1) >> 16;
+    int nextLevel = currentLevel;
+
+    // Looping for characters in range
+    for (Sci_PositionU i = safeStartPos; i < startPos + length; ++i)
+    {
+        /* Folding occurs after syntax highlighting, meaning Scintilla
+         * already knows where the comments are
+         * Fetching the current state */
+        int state = styler.StyleAt(i) & 31;
+
+        switch( styler.SafeGetCharAt(i) )
+        {
+            case '{':
+
+                /* Indenting only when the braces are not contained in
+                 * a comment */
+                if (state != SCE_KVIRC_COMMENT &&
+                    state != SCE_KVIRC_COMMENTBLOCK)
+                    ++nextLevel;
+                break;
+
+            case '}':
+
+                /* Outdenting only when the braces are not contained in
+                 * a comment */
+                if (state != SCE_KVIRC_COMMENT &&
+                    state != SCE_KVIRC_COMMENTBLOCK)
+                    --nextLevel;
+                break;
+
+            case '\n':
+            case '\r':
+
+                /* Preparing indentation information to return - combining
+                 * current and next level data */
+                int lev = currentLevel | nextLevel << 16;
+
+                /* If the next level increases the indent level, mark the
+                 * current line as a fold point - current level data is
+                 * in the least significant bits */
+                if (nextLevel > currentLevel )
+                    lev |= SC_FOLDLEVELHEADERFLAG;
+
+                /* Updating indentation level if needed */
+                if (lev != styler.LevelAt(currentLine))
+                    styler.SetLevel(currentLine, lev);
+
+                /* Updating variables */
+                ++currentLine;
+                currentLevel = nextLevel;
+
+                /* Dealing with problematic Windows newlines -
+                 * incrementing to avoid the extra newline breaking the
+                 * fold point */
+                if (styler.SafeGetCharAt(i) == '\r' &&
+                    styler.SafeGetCharAt(i + 1) == '\n')
+                    ++i;
+                break;
+        }
+    }
+
+    /* At this point the data has ended, so presumably the end of the line?
+     * Preparing indentation information to return - combining current
+     * and next level data */
+    int lev = currentLevel | nextLevel << 16;
+
+    /* If the next level increases the indent level, mark the current
+     * line as a fold point - current level data is in the least
+     * significant bits */
+    if (nextLevel > currentLevel )
+        lev |= SC_FOLDLEVELHEADERFLAG;
+
+    /* Updating indentation level if needed */
+    if (lev != styler.LevelAt(currentLine))
+        styler.SetLevel(currentLine, lev);
+}
+
+/* Registering wordlists */
+static const char *const kvircWordListDesc[] = {
+       "primary",
+       "function_keywords",
+       0
+};
+
+
+/* Registering functions and wordlists */
+LexerModule lmKVIrc(SCLEX_KVIRC, ColouriseKVIrcDoc, "kvirc", FoldKVIrcDoc,
+                    kvircWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexKix.cxx b/plugins/scintilla/scintilla/lexers/LexKix.cxx
index 32af263..82ff9a5 100644
--- a/plugins/scintilla/scintilla/lexers/LexKix.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexKix.cxx
@@ -4,6 +4,7 @@
  **/
 // Copyright 2004 by Manfred Becker <manfred becker-trdf de>
 // The License.txt file describes the conditions under which this software may be distributed.
+// Edited by Lee Wilmott (24-Jun-2014) added support for block comments
 
 #include <stdlib.h>
 #include <string.h>
@@ -36,7 +37,7 @@ static inline bool IsOperator(const int ch) {
        return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '&' || ch == '|' || ch == '<' || ch 
== '>' || ch == '=');
 }
 
-static void ColouriseKixDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseKixDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                            WordList *keywordlists[], Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
@@ -54,6 +55,10 @@ static void ColouriseKixDoc(unsigned int startPos, int length, int initStyle,
                        if (sc.atLineEnd) {
                                sc.SetState(SCE_KIX_DEFAULT);
                        }
+               } else if (sc.state == SCE_KIX_COMMENTSTREAM) {
+                       if (sc.ch == '/' && sc.chPrev == '*') {
+                               sc.ForwardSetState(SCE_KIX_DEFAULT);
+                       }
                } else if (sc.state == SCE_KIX_STRING1) {
                        // This is a doubles quotes string
                        if (sc.ch == '\"') {
@@ -104,6 +109,8 @@ static void ColouriseKixDoc(unsigned int startPos, int length, int initStyle,
                if (sc.state == SCE_KIX_DEFAULT) {
                        if (sc.ch == ';') {
                                sc.SetState(SCE_KIX_COMMENT);
+                       } else if (sc.ch == '/' && sc.chNext == '*') {
+                               sc.SetState(SCE_KIX_COMMENTSTREAM);
                        } else if (sc.ch == '\"') {
                                sc.SetState(SCE_KIX_STRING1);
                        } else if (sc.ch == '\'') {
diff --git a/plugins/scintilla/scintilla/lexers/LexLaTeX.cxx b/plugins/scintilla/scintilla/lexers/LexLaTeX.cxx
index f3b1405..612ef48 100644
--- a/plugins/scintilla/scintilla/lexers/LexLaTeX.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexLaTeX.cxx
@@ -48,41 +48,41 @@ struct latexFoldSave {
 class LexerLaTeX : public LexerBase {
 private:
        vector<int> modes;
-       void setMode(int line, int mode) {
-               if (line >= static_cast<int>(modes.size())) modes.resize(line + 1, 0);
+       void setMode(Sci_Position line, int mode) {
+               if (line >= static_cast<Sci_Position>(modes.size())) modes.resize(line + 1, 0);
                modes[line] = mode;
        }
-       int getMode(int line) {
-               if (line >= 0 && line < static_cast<int>(modes.size())) return modes[line];
+       int getMode(Sci_Position line) {
+               if (line >= 0 && line < static_cast<Sci_Position>(modes.size())) return modes[line];
                return 0;
        }
-       void truncModes(int numLines) {
-               if (static_cast<int>(modes.size()) > numLines * 2 + 256)
+       void truncModes(Sci_Position numLines) {
+               if (static_cast<Sci_Position>(modes.size()) > numLines * 2 + 256)
                        modes.resize(numLines + 128);
        }
-       
+
        vector<latexFoldSave> saves;
-       void setSave(int line, const latexFoldSave &save) {
-               if (line >= static_cast<int>(saves.size())) saves.resize(line + 1);
+       void setSave(Sci_Position line, const latexFoldSave &save) {
+               if (line >= static_cast<Sci_Position>(saves.size())) saves.resize(line + 1);
                saves[line] = save;
        }
-       void getSave(int line, latexFoldSave &save) {
-               if (line >= 0 && line < static_cast<int>(saves.size())) save = saves[line];
+       void getSave(Sci_Position line, latexFoldSave &save) {
+               if (line >= 0 && line < static_cast<Sci_Position>(saves.size())) save = saves[line];
                else {
                        save.structLev = 0;
                        for (int i = 0; i < 8; ++i) save.openBegins[i] = 0;
                }
        }
-       void truncSaves(int numLines) {
-               if (static_cast<int>(saves.size()) > numLines * 2 + 256)
+       void truncSaves(Sci_Position numLines) {
+               if (static_cast<Sci_Position>(saves.size()) > numLines * 2 + 256)
                        saves.resize(numLines + 128);
        }
 public:
        static ILexer *LexerFactoryLaTeX() {
                return new LexerLaTeX();
        }
-       void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 };
 
 static bool latexIsSpecial(int ch) {
@@ -99,10 +99,10 @@ static bool latexIsBlankAndNL(int ch) {
 }
 
 static bool latexIsLetter(int ch) {
-       return isascii(ch) && isalpha(ch);
+       return IsASCII(ch) && isalpha(ch);
 }
 
-static bool latexIsTagValid(int &i, int l, Accessor &styler) {
+static bool latexIsTagValid(Sci_Position &i, Sci_Position l, Accessor &styler) {
        while (i < l) {
                if (styler.SafeGetCharAt(i) == '{') {
                        while (i < l) {
@@ -122,7 +122,7 @@ static bool latexIsTagValid(int &i, int l, Accessor &styler) {
        return false;
 }
 
-static bool latexNextNotBlankIs(int i, Accessor &styler, char needle) {
+static bool latexNextNotBlankIs(Sci_Position i, Accessor &styler, char needle) {
   char ch;
        while (i < styler.Length()) {
     ch = styler.SafeGetCharAt(i);
@@ -137,10 +137,10 @@ static bool latexNextNotBlankIs(int i, Accessor &styler, char needle) {
        return false;
 }
 
-static bool latexLastWordIs(int start, Accessor &styler, const char *needle) {
-       unsigned int i = 0;
-       unsigned int l = static_cast<unsigned int>(strlen(needle));
-       int ini = start-l+1;
+static bool latexLastWordIs(Sci_Position start, Accessor &styler, const char *needle) {
+       Sci_PositionU i = 0;
+       Sci_PositionU l = static_cast<Sci_PositionU>(strlen(needle));
+       Sci_Position ini = start-l+1;
        char s[32];
 
        while (i < l && i < 31) {
@@ -152,8 +152,8 @@ static bool latexLastWordIs(int start, Accessor &styler, const char *needle) {
        return (strcmp(s, needle) == 0);
 }
 
-static bool latexLastWordIsMathEnv(int pos, Accessor &styler) {
-       int i, j;
+static bool latexLastWordIsMathEnv(Sci_Position pos, Accessor &styler) {
+       Sci_Position i, j;
        char s[32];
        const char *mathEnvs[] = { "align", "alignat", "flalign", "gather",
                "multiline", "displaymath", "eqnarray", "equation" };
@@ -184,7 +184,7 @@ static inline void latexStateReset(int &mode, int &state) {
 
 // There are cases not handled correctly, like $abcd\textrm{what is $x+y$}z+w$.
 // But I think it's already good enough.
-void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerLaTeX::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        // startPos is assumed to be the first character of a line
        Accessor styler(pAccess, &props);
        styler.StartAt(startPos);
@@ -192,13 +192,13 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
        int state = initStyle;
        if (state == SCE_L_ERROR || state == SCE_L_SHORTCMD || state == SCE_L_SPECIAL)   // should not happen
                latexStateReset(mode, state);
-       
+
        char chNext = styler.SafeGetCharAt(startPos);
        char chVerbatimDelim = '\0';
        styler.StartSegment(startPos);
-       int lengthDoc = startPos + length;
+       Sci_Position lengthDoc = startPos + length;
 
-       for (int i = startPos; i < lengthDoc; i++) {
+       for (Sci_Position i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -207,7 +207,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                        chNext = styler.SafeGetCharAt(i + 1);
                        continue;
                }
-               
+
                if (ch == '\r' || ch == '\n')
                        setMode(styler.GetLine(i), mode);
 
@@ -224,7 +224,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                                        chNext = styler.SafeGetCharAt(i + 1);
                                } else if (chNext == '\r' || chNext == '\n') {
                                        styler.ColourTo(i, SCE_L_ERROR);
-                               } else if (isascii(chNext)) {
+                               } else if (IsASCII(chNext)) {
                                        styler.ColourTo(i + 1, SCE_L_SHORTCMD);
                                        if (chNext == '(') {
                                                mode = 1;
@@ -256,7 +256,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                                state = SCE_L_COMMENT;
                                break;
                        }
-                       break;  
+                       break;
                // These 3 will never be reached.
                case SCE_L_ERROR:
                case SCE_L_SPECIAL:
@@ -325,7 +325,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                        case '\\' :
                                styler.ColourTo(i - 1, state);
                                if (latexIsLetter(chNext)) {
-                                       int match = i + 3;
+                                       Sci_Position match = i + 3;
                                        if (latexLastWordIs(match, styler, "\\end")) {
                                                match++;
                                                if (latexIsTagValid(match, lengthDoc, styler)) {
@@ -340,7 +340,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                                        chNext = styler.SafeGetCharAt(i + 1);
                                } else if (chNext == '\r' || chNext == '\n') {
                                        styler.ColourTo(i, SCE_L_ERROR);
-                               } else if (isascii(chNext)) {
+                               } else if (IsASCII(chNext)) {
                                        if (chNext == ')') {
                                                mode = 0;
                                                state = SCE_L_DEFAULT;
@@ -367,7 +367,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                        case '\\' :
                                styler.ColourTo(i - 1, state);
                                if (latexIsLetter(chNext)) {
-                                       int match = i + 3;
+                                       Sci_Position match = i + 3;
                                        if (latexLastWordIs(match, styler, "\\end")) {
                                                match++;
                                                if (latexIsTagValid(match, lengthDoc, styler)) {
@@ -382,7 +382,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                                        chNext = styler.SafeGetCharAt(i + 1);
                                } else if (chNext == '\r' || chNext == '\n') {
                                        styler.ColourTo(i, SCE_L_ERROR);
-                               } else if (isascii(chNext)) {
+                               } else if (IsASCII(chNext)) {
                                        if (chNext == ']') {
                                                mode = 0;
                                                state = SCE_L_DEFAULT;
@@ -400,7 +400,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                                        chNext = styler.SafeGetCharAt(i + 1);
                                        mode = 0;
                                        state = SCE_L_DEFAULT;
-                               } else { // This may not be an error, e.g. 
\begin{equation}\text{$a$}\end{equation}     
+                               } else { // This may not be an error, e.g. 
\begin{equation}\text{$a$}\end{equation}
                                        styler.ColourTo(i, SCE_L_SHORTCMD);
                                }
                                break;
@@ -418,7 +418,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                        break;
                case SCE_L_COMMENT2 :
                        if (ch == '\\') {
-                               int match = i + 3;
+                               Sci_Position match = i + 3;
                                if (latexLastWordIs(match, styler, "\\end")) {
                                        match++;
                                        if (latexIsTagValid(match, lengthDoc, styler)) {
@@ -432,7 +432,7 @@ void SCI_METHOD LexerLaTeX::Lex(unsigned int startPos, int length, int initStyle
                        break;
                case SCE_L_VERBATIM :
                        if (ch == '\\') {
-                               int match = i + 3;
+                               Sci_Position match = i + 3;
                                if (latexLastWordIs(match, styler, "\\end")) {
                                        match++;
                                        if (latexIsTagValid(match, lengthDoc, styler)) {
@@ -470,23 +470,24 @@ static int latexFoldSaveToInt(const latexFoldSave &save) {
 
 // Change folding state while processing a line
 // Return the level before the first relevant command
-void SCI_METHOD LexerLaTeX::Fold(unsigned int startPos, int length, int, IDocument *pAccess) {
+void SCI_METHOD LexerLaTeX::Fold(Sci_PositionU startPos, Sci_Position length, int, IDocument *pAccess) {
        const char *structWords[7] = {"part", "chapter", "section", "subsection",
                "subsubsection", "paragraph", "subparagraph"};
        Accessor styler(pAccess, &props);
-       unsigned int endPos = startPos + length;
-       int curLine = styler.GetLine(startPos);
+       Sci_PositionU endPos = startPos + length;
+       Sci_Position curLine = styler.GetLine(startPos);
        latexFoldSave save;
        getSave(curLine - 1, save);
        do {
                char ch, buf[16];
-               int i, j, lev = -1;
+               Sci_Position i, j;
+               int lev = -1;
                bool needFold = false;
-               for (i = static_cast<int>(startPos); i < static_cast<int>(endPos); ++i) {
+               for (i = static_cast<Sci_Position>(startPos); i < static_cast<Sci_Position>(endPos); ++i) {
                        ch = styler.SafeGetCharAt(i);
                        if (ch == '\r' || ch == '\n') break;
                        if (ch != '\\' || styler.StyleAt(i) != SCE_L_COMMAND) continue;
-                       for (j = 0; j < 15 && i + 1 < static_cast<int>(endPos); ++j, ++i) {
+                       for (j = 0; j < 15 && i + 1 < static_cast<Sci_Position>(endPos); ++j, ++i) {
                                buf[j] = styler.SafeGetCharAt(i + 1);
                                if (!latexIsLetter(buf[j])) break;
                        }
@@ -522,7 +523,7 @@ void SCI_METHOD LexerLaTeX::Fold(unsigned int startPos, int length, int, IDocume
                setSave(curLine, save);
                ++curLine;
                startPos = styler.LineStart(curLine);
-               if (static_cast<int>(startPos) == styler.Length()) {
+               if (static_cast<Sci_Position>(startPos) == styler.Length()) {
                        lev = latexFoldSaveToInt(save);
                        styler.SetLevel(curLine, lev);
                        setSave(curLine, save);
diff --git a/plugins/scintilla/scintilla/lexers/LexLisp.cxx b/plugins/scintilla/scintilla/lexers/LexLisp.cxx
index 08f765a..8d81eae 100644
--- a/plugins/scintilla/scintilla/lexers/LexLisp.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexLisp.cxx
@@ -33,7 +33,7 @@ using namespace Scintilla;
 #define SCE_LISP_MACRO_DISPATCH 31
 
 static inline bool isLispoperator(char ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        if (ch == '\'' || ch == '`' || ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '{' || ch == 
'}')
                return true;
@@ -41,15 +41,15 @@ static inline bool isLispoperator(char ch) {
 }
 
 static inline bool isLispwordstart(char ch) {
-       return isascii(ch) && ch != ';'  && !isspacechar(ch) && !isLispoperator(ch) &&
+       return IsASCII(ch) && ch != ';'  && !isspacechar(ch) && !isLispoperator(ch) &&
                ch != '\n' && ch != '\r' &&  ch != '\"';
 }
 
 
-static void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, WordList 
&keywords_kw, Accessor &styler) {
+static void classifyWordLisp(Sci_PositionU start, Sci_PositionU end, WordList &keywords, WordList 
&keywords_kw, Accessor &styler) {
        assert(end >= start);
        char s[100];
-       unsigned int i;
+       Sci_PositionU i;
        bool digit_flag = true;
        for (i = 0; (i < end - start + 1) && (i < 99); i++) {
                s[i] = styler[start + i];
@@ -74,7 +74,7 @@ static void classifyWordLisp(unsigned int start, unsigned int end, WordList &key
 }
 
 
-static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseLispDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
@@ -84,9 +84,9 @@ static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, W
 
        int state = initStyle, radix = -1;
        char chNext = styler[startPos];
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        styler.StartSegment(startPos);
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -142,7 +142,7 @@ static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, W
                                }
                        }
                } else if (state == SCE_LISP_MACRO_DISPATCH) {
-                       if (!(isascii(ch) && isdigit(ch))) {
+                       if (!(IsASCII(ch) && isdigit(ch))) {
                                if (ch != 'r' && ch != 'R' && (i - styler.GetStartSegment()) > 1) {
                                        state = SCE_LISP_DEFAULT;
                                } else {
@@ -233,16 +233,16 @@ static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, W
        styler.ColourTo(lengthDoc - 1, state);
 }
 
-static void FoldLispDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
+static void FoldLispDoc(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList *[],
                             Accessor &styler) {
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
diff --git a/plugins/scintilla/scintilla/lexers/LexLout.cxx b/plugins/scintilla/scintilla/lexers/LexLout.cxx
index 985b93b..3970982 100644
--- a/plugins/scintilla/scintilla/lexers/LexLout.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexLout.cxx
@@ -40,7 +40,7 @@ static inline bool IsAnOther(const int ch) {
        ch == ']' || ch == '^' || ch == '`' || ch == '|' || ch == '~');
 }
 
-static void ColouriseLoutDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseLoutDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                             WordList *keywordlists[], Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
@@ -140,20 +140,20 @@ static void ColouriseLoutDoc(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-static void FoldLoutDoc(unsigned int startPos, int length, int, WordList *[],
+static void FoldLoutDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
                         Accessor &styler) {
 
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        int styleNext = styler.StyleAt(startPos);
-       char s[10];
+       char s[10] = "";
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
@@ -162,7 +162,7 @@ static void FoldLoutDoc(unsigned int startPos, int length, int, WordList *[],
 
                if (style == SCE_LOUT_WORD) {
                        if (ch == '@') {
-                               for (unsigned int j = 0; j < 8; j++) {
+                               for (Sci_PositionU j = 0; j < 8; j++) {
                                        if (!IsAWordChar(styler[i + j])) {
                                                break;
                                        }
diff --git a/plugins/scintilla/scintilla/lexers/LexLua.cxx b/plugins/scintilla/scintilla/lexers/LexLua.cxx
index 62bb44d..9e86b8a 100644
--- a/plugins/scintilla/scintilla/lexers/LexLua.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexLua.cxx
@@ -42,20 +42,20 @@ static int LongDelimCheck(StyleContext &sc) {
 }
 
 static void ColouriseLuaDoc(
-       unsigned int startPos,
-       int length,
+       Sci_PositionU startPos,
+       Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler) {
 
-       WordList &keywords = *keywordlists[0];
-       WordList &keywords2 = *keywordlists[1];
-       WordList &keywords3 = *keywordlists[2];
-       WordList &keywords4 = *keywordlists[3];
-       WordList &keywords5 = *keywordlists[4];
-       WordList &keywords6 = *keywordlists[5];
-       WordList &keywords7 = *keywordlists[6];
-       WordList &keywords8 = *keywordlists[7];
+       const WordList &keywords = *keywordlists[0];
+       const WordList &keywords2 = *keywordlists[1];
+       const WordList &keywords3 = *keywordlists[2];
+       const WordList &keywords4 = *keywordlists[3];
+       const WordList &keywords5 = *keywordlists[4];
+       const WordList &keywords6 = *keywordlists[5];
+       const WordList &keywords7 = *keywordlists[6];
+       const WordList &keywords8 = *keywordlists[7];
 
        // Accepts accented characters
        CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
@@ -64,10 +64,10 @@ static void ColouriseLuaDoc(
        // but probably enough in most cases. [pP] is for hex floats.
        CharacterSet setNumber(CharacterSet::setDigits, ".-+abcdefpABCDEFP");
        CharacterSet setExponent(CharacterSet::setNone, "eEpP");
-       CharacterSet setLuaOperator(CharacterSet::setNone, "*/-+()={}~[];<>,.^%:#");
+       CharacterSet setLuaOperator(CharacterSet::setNone, "*/-+()={}~[];<>,.^%:#&|");
        CharacterSet setEscapeSkip(CharacterSet::setNone, "\"'\\");
 
-       int currentLine = styler.GetLine(startPos);
+       Sci_Position currentLine = styler.GetLine(startPos);
        // Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
        // if we are inside such a string. Block comment was introduced in Lua 5.0,
        // blocks with separators [=[ ... ]=] in Lua 5.1.
@@ -77,7 +77,7 @@ static void ColouriseLuaDoc(
        int stringWs = 0;
        if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT ||
                initStyle == SCE_LUA_STRING || initStyle == SCE_LUA_CHARACTER) {
-               int lineState = styler.GetLineState(currentLine - 1);
+               const int lineState = styler.GetLineState(currentLine - 1);
                nestLevel = lineState >> 9;
                sepCount = lineState & 0xFF;
                stringWs = lineState & 0x100;
@@ -89,8 +89,8 @@ static void ColouriseLuaDoc(
        }
 
        StyleContext sc(startPos, length, initStyle, styler);
-       if (startPos == 0 && sc.ch == '#') {
-               // shbang line: # is a comment only if first char of the script
+       if (startPos == 0 && sc.ch == '#' && sc.chNext == '!') {
+               // shbang line: "#!" is a comment only if located at the start of the script
                sc.SetState(SCE_LUA_COMMENTLINE);
        }
        for (; sc.More(); sc.Forward()) {
@@ -132,23 +132,23 @@ static void ColouriseLuaDoc(
                if (sc.state == SCE_LUA_OPERATOR) {
                        if (sc.ch == ':' && sc.chPrev == ':') { // :: <label> :: forward scan
                                sc.Forward();
-                               int ln = 0;
+                               Sci_Position ln = 0;
                                while (IsASpaceOrTab(sc.GetRelative(ln)))       // skip over spaces/tabs
                                        ln++;
-                               int ws1 = ln;
+                               Sci_Position ws1 = ln;
                                if (setWordStart.Contains(sc.GetRelative(ln))) {
                                        int c, i = 0;
                                        char s[100];
                                        while (setWord.Contains(c = sc.GetRelative(ln))) {      // get 
potential label
                                                if (i < 90)
-                                                       s[i++] = c;
+                                                       s[i++] = static_cast<char>(c);
                                                ln++;
                                        }
-                                       s[i] = '\0'; int lbl = ln;
+                                       s[i] = '\0'; Sci_Position lbl = ln;
                                        if (!keywords.InList(s)) {
                                                while (IsASpaceOrTab(sc.GetRelative(ln)))       // skip over 
spaces/tabs
                                                        ln++;
-                                               int ws2 = ln - lbl;
+                                               Sci_Position ws2 = ln - lbl;
                                                if (sc.GetRelative(ln) == ':' && sc.GetRelative(ln + 1) == 
':') {
                                                        // final :: found, complete valid label construct
                                                        sc.ChangeState(SCE_LUA_LABEL);
@@ -257,7 +257,7 @@ static void ColouriseLuaDoc(
                        }
                } else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
                        if (sc.ch == '[') {
-                               int sep = LongDelimCheck(sc);
+                               const int sep = LongDelimCheck(sc);
                                if (sep == 1 && sepCount == 1) {    // [[-only allowed to nest
                                        nestLevel++;
                                        sc.Forward();
@@ -347,27 +347,27 @@ static void ColouriseLuaDoc(
        sc.Complete();
 }
 
-static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
+static void FoldLuaDoc(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList *[],
                        Accessor &styler) {
-       unsigned int lengthDoc = startPos + length;
+       const Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
-       bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
+       const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        int styleNext = styler.StyleAt(startPos);
 
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
-               char ch = chNext;
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
+               const char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
-               int style = styleNext;
+               const int style = styleNext;
                styleNext = styler.StyleAt(i + 1);
-               bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+               const bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
                if (style == SCE_LUA_WORD) {
                        if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
                                char s[10] = "";
-                               for (unsigned int j = 0; j < 8; j++) {
+                               for (Sci_PositionU j = 0; j < 8; j++) {
                                        if (!iswordchar(styler[i + j])) {
                                                break;
                                        }
diff --git a/plugins/scintilla/scintilla/lexers/LexMMIXAL.cxx 
b/plugins/scintilla/scintilla/lexers/LexMMIXAL.cxx
index 43361d4..2a152b8 100644
--- a/plugins/scintilla/scintilla/lexers/LexMMIXAL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMMIXAL.cxx
@@ -35,7 +35,7 @@ static inline bool IsAWordChar(const int ch) {
 }
 
 inline bool isMMIXALOperator(char ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        if (ch == '+' || ch == '-' || ch == '|' || ch == '^' ||
                ch == '*' || ch == '/' ||
@@ -47,7 +47,7 @@ inline bool isMMIXALOperator(char ch) {
        return false;
 }
 
-static void ColouriseMMIXALDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseMMIXALDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
 
        WordList &opcodes = *keywordlists[0];
diff --git a/plugins/scintilla/scintilla/lexers/LexMPT.cxx b/plugins/scintilla/scintilla/lexers/LexMPT.cxx
index b3eed34..2732fb4 100644
--- a/plugins/scintilla/scintilla/lexers/LexMPT.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMPT.cxx
@@ -37,7 +37,7 @@ static int GetLotLineState(std::string &line) {
                // Now finds the first non-blank character
                unsigned i; // Declares counter here to make it persistent after the for loop
                for (i = 0; i < line.length(); ++i) {
-                       if (!(isascii(line[i]) && isspace(line[i])))
+                       if (!(IsASCII(line[i]) && isspace(line[i])))
                                break;
                }
 
@@ -80,7 +80,7 @@ static int GetLotLineState(std::string &line) {
        }
 }
 
-static void ColourizeLotDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
+static void ColourizeLotDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor 
&styler) {
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
        bool atLineStart = true;// Arms the 'at line start' flag
@@ -89,7 +89,7 @@ static void ColourizeLotDoc(unsigned int startPos, int length, int, WordList *[]
        line.reserve(256);      // Lot lines are less than 256 chars long most of the time. This should avoid 
reallocations
 
        // Styles LOT document
-       unsigned int i;                 // Declared here because it's used after the for loop
+       Sci_PositionU i;                        // Declared here because it's used after the for loop
        for (i = startPos; i < startPos + length; ++i) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
@@ -118,11 +118,11 @@ static void ColourizeLotDoc(unsigned int startPos, int length, int, WordList *[]
 // sections (headed by a set line)
 // passes (contiguous pass results within a section)
 // fails (contiguous fail results within a section)
-static void FoldLotDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
+static void FoldLotDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
        bool foldCompact = styler.GetPropertyInt("fold.compact", 0) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
 
        char chNext = styler.SafeGetCharAt(startPos);
        int style = SCE_LOT_DEFAULT;
@@ -133,7 +133,7 @@ static void FoldLotDoc(unsigned int startPos, int length, int, WordList *[], Acc
        if (startPos > 1)
                style = styler.StyleAt(startPos - 2);
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
diff --git a/plugins/scintilla/scintilla/lexers/LexMSSQL.cxx b/plugins/scintilla/scintilla/lexers/LexMSSQL.cxx
index ce60039..fa86db6 100644
--- a/plugins/scintilla/scintilla/lexers/LexMSSQL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMSSQL.cxx
@@ -35,21 +35,8 @@ using namespace Scintilla;
 #define KW_MSSQL_STORED_PROCEDURES  5
 #define KW_MSSQL_OPERATORS          6
 
-static bool isMSSQLOperator(char ch) {
-       if (isascii(ch) && isalnum(ch))
-               return false;
-       // '.' left out as it is used to make up numbers
-       if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
-        ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
-        ch == '<' || ch == '>' || ch == '/' ||
-        ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
-               ch == ',')
-               return true;
-       return false;
-}
-
-static char classifyWordSQL(unsigned int start,
-                            unsigned int end,
+static char classifyWordSQL(Sci_PositionU start,
+                            Sci_PositionU end,
                             WordList *keywordlists[],
                             Accessor &styler,
                             unsigned int actualState,
@@ -65,7 +52,7 @@ static char classifyWordSQL(unsigned int start,
     WordList &kwStoredProcedures    = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
     WordList &kwOperators           = *keywordlists[KW_MSSQL_OPERATORS];
 
-       for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
+       for (Sci_PositionU i = 0; i < end - start + 1 && i < 128; i++) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                s[i + 1] = '\0';
        }
@@ -114,14 +101,14 @@ static char classifyWordSQL(unsigned int start,
        return chAttr;
 }
 
-static void ColouriseMSSQLDoc(unsigned int startPos, int length,
+static void ColouriseMSSQLDoc(Sci_PositionU startPos, Sci_Position length,
                               int initStyle, WordList *keywordlists[], Accessor &styler) {
 
 
        styler.StartAt(startPos);
 
        bool fold = styler.GetPropertyInt("fold") != 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int spaceFlags = 0;
 
        int state = initStyle;
@@ -129,8 +116,8 @@ static void ColouriseMSSQLDoc(unsigned int startPos, int length,
        char chPrev = ' ';
        char chNext = styler[startPos];
        styler.StartSegment(startPos);
-       unsigned int lengthDoc = startPos + length;
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       Sci_PositionU lengthDoc = startPos + length;
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -220,7 +207,7 @@ static void ColouriseMSSQLDoc(unsigned int startPos, int length,
                                styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
                                prevState = state;
                                state = SCE_MSSQL_COLUMN_NAME_2;
-                       } else if (isMSSQLOperator(ch)) {
+                       } else if (isoperator(ch)) {
                                styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
                                styler.ColourTo(i, SCE_MSSQL_OPERATOR);
                 //~ style = SCE_MSSQL_DEFAULT;
@@ -290,18 +277,18 @@ static void ColouriseMSSQLDoc(unsigned int startPos, int length,
        styler.ColourTo(lengthDoc - 1, state);
 }
 
-static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
+static void FoldMSSQLDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
-    char s[10];
-       for (unsigned int i = startPos; i < endPos; i++) {
+    char s[10] = "";
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styler.StyleAt(i);
@@ -317,7 +304,7 @@ static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], A
         if (style == SCE_MSSQL_STATEMENT) {
             // Folding between begin or case and end
             if (ch == 'b' || ch == 'B' || ch == 'c' || ch == 'C' || ch == 'e' || ch == 'E') {
-                for (unsigned int j = 0; j < 5; j++) {
+                for (Sci_PositionU j = 0; j < 5; j++) {
                                        if (!iswordchar(styler[i + j])) {
                                                break;
                                        }
diff --git a/plugins/scintilla/scintilla/lexers/LexMagik.cxx b/plugins/scintilla/scintilla/lexers/LexMagik.cxx
index 992080d..4a2a7b9 100644
--- a/plugins/scintilla/scintilla/lexers/LexMagik.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMagik.cxx
@@ -87,7 +87,7 @@ static inline bool IsAlNumSym(int ch) {
  * \param  keywordslists The keywordslists, currently, number 5 is used
  * \param  styler The styler
  */
-static void ColouriseMagikDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseMagikDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                            WordList *keywordlists[], Accessor &styler) {
     styler.StartAt(startPos);
 
@@ -141,7 +141,7 @@ static void ColouriseMagikDoc(unsigned int startPos, int length, int initStyle,
                        char keywordChar = static_cast<char>(
                         tolower(styler.SafeGetCharAt(
                             scanPosition +
-                                static_cast<int>(sc.currentPos+1), ' ')));
+                                static_cast<Sci_Position>(sc.currentPos+1), ' ')));
                     if(IsAlpha(keywordChar)) {
                         keyword[scanPosition] = keywordChar;
                     } else {
@@ -359,24 +359,24 @@ static inline int IsFoldingContainer(WordList &keywordslist, char * keyword) {
  * \param  keywordslists The keywordslists, currently, number 5 is used
  * \param  styler The styler
  */
-static void FoldMagikDoc(unsigned int startPos, int length, int,
+static void FoldMagikDoc(Sci_PositionU startPos, Sci_Position length, int,
     WordList *keywordslists[], Accessor &styler) {
 
     bool compact = styler.GetPropertyInt("fold.compact") != 0;
 
     WordList &foldingElements = *keywordslists[5];
-    int endPos = startPos + length;
-    int line = styler.GetLine(startPos);
+    Sci_Position endPos = startPos + length;
+    Sci_Position line = styler.GetLine(startPos);
     int level = styler.LevelAt(line) & SC_FOLDLEVELNUMBERMASK;
     int flags = styler.LevelAt(line) & ~SC_FOLDLEVELNUMBERMASK;
 
     for(
-        int currentPos = startPos;
+        Sci_Position currentPos = startPos;
         currentPos < endPos;
         currentPos++) {
             char currentState = styler.StyleAt(currentPos);
             char c = styler.SafeGetCharAt(currentPos, ' ');
-            int prevLine = styler.GetLine(currentPos - 1);
+            Sci_Position prevLine = styler.GetLine(currentPos - 1);
             line = styler.GetLine(currentPos);
 
             // Default situation
diff --git a/plugins/scintilla/scintilla/lexers/LexMake.cxx b/plugins/scintilla/scintilla/lexers/LexMake.cxx
new file mode 100644
index 0000000..9e8dadf
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexMake.cxx
@@ -0,0 +1,144 @@
+// Scintilla source code edit control
+/** @file LexMake.cxx
+ ** Lexer for make files.
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
+       return (styler[i] == '\n') ||
+              ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
+}
+
+static void ColouriseMakeLine(
+    char *lineBuffer,
+    Sci_PositionU lengthLine,
+    Sci_PositionU startLine,
+    Sci_PositionU endPos,
+    Accessor &styler) {
+
+       Sci_PositionU i = 0;
+       Sci_Position lastNonSpace = -1;
+       unsigned int state = SCE_MAKE_DEFAULT;
+       bool bSpecial = false;
+
+       // check for a tab character in column 0 indicating a command
+       bool bCommand = false;
+       if ((lengthLine > 0) && (lineBuffer[0] == '\t'))
+               bCommand = true;
+
+       // Skip initial spaces
+       while ((i < lengthLine) && isspacechar(lineBuffer[i])) {
+               i++;
+       }
+       if (i < lengthLine) {
+               if (lineBuffer[i] == '#') {     // Comment
+                       styler.ColourTo(endPos, SCE_MAKE_COMMENT);
+                       return;
+               }
+               if (lineBuffer[i] == '!') {     // Special directive
+                       styler.ColourTo(endPos, SCE_MAKE_PREPROCESSOR);
+                       return;
+               }
+       }
+       int varCount = 0;
+       while (i < lengthLine) {
+               if (((i + 1) < lengthLine) && (lineBuffer[i] == '$' && lineBuffer[i + 1] == '(')) {
+                       styler.ColourTo(startLine + i - 1, state);
+                       state = SCE_MAKE_IDENTIFIER;
+                       varCount++;
+               } else if (state == SCE_MAKE_IDENTIFIER && lineBuffer[i] == ')') {
+                       if (--varCount == 0) {
+                               styler.ColourTo(startLine + i, state);
+                               state = SCE_MAKE_DEFAULT;
+                       }
+               }
+
+               // skip identifier and target styling if this is a command line
+               if (!bSpecial && !bCommand) {
+                       if (lineBuffer[i] == ':') {
+                               if (((i + 1) < lengthLine) && (lineBuffer[i + 1] == '=')) {
+                                       // it's a ':=', so style as an identifier
+                                       if (lastNonSpace >= 0)
+                                               styler.ColourTo(startLine + lastNonSpace, 
SCE_MAKE_IDENTIFIER);
+                                       styler.ColourTo(startLine + i - 1, SCE_MAKE_DEFAULT);
+                                       styler.ColourTo(startLine + i + 1, SCE_MAKE_OPERATOR);
+                               } else {
+                                       // We should check that no colouring was made since the beginning of 
the line,
+                                       // to avoid colouring stuff like /OUT:file
+                                       if (lastNonSpace >= 0)
+                                               styler.ColourTo(startLine + lastNonSpace, SCE_MAKE_TARGET);
+                                       styler.ColourTo(startLine + i - 1, SCE_MAKE_DEFAULT);
+                                       styler.ColourTo(startLine + i, SCE_MAKE_OPERATOR);
+                               }
+                               bSpecial = true;        // Only react to the first ':' of the line
+                               state = SCE_MAKE_DEFAULT;
+                       } else if (lineBuffer[i] == '=') {
+                               if (lastNonSpace >= 0)
+                                       styler.ColourTo(startLine + lastNonSpace, SCE_MAKE_IDENTIFIER);
+                               styler.ColourTo(startLine + i - 1, SCE_MAKE_DEFAULT);
+                               styler.ColourTo(startLine + i, SCE_MAKE_OPERATOR);
+                               bSpecial = true;        // Only react to the first '=' of the line
+                               state = SCE_MAKE_DEFAULT;
+                       }
+               }
+               if (!isspacechar(lineBuffer[i])) {
+                       lastNonSpace = i;
+               }
+               i++;
+       }
+       if (state == SCE_MAKE_IDENTIFIER) {
+               styler.ColourTo(endPos, SCE_MAKE_IDEOL);        // Error, variable reference not ended
+       } else {
+               styler.ColourTo(endPos, SCE_MAKE_DEFAULT);
+       }
+}
+
+static void ColouriseMakeDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor 
&styler) {
+       char lineBuffer[1024];
+       styler.StartAt(startPos);
+       styler.StartSegment(startPos);
+       Sci_PositionU linePos = 0;
+       Sci_PositionU startLine = startPos;
+       for (Sci_PositionU i = startPos; i < startPos + length; i++) {
+               lineBuffer[linePos++] = styler[i];
+               if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
+                       // End of line (or of line buffer) met, colourise it
+                       lineBuffer[linePos] = '\0';
+                       ColouriseMakeLine(lineBuffer, linePos, startLine, i, styler);
+                       linePos = 0;
+                       startLine = i + 1;
+               }
+       }
+       if (linePos > 0) {      // Last line does not have ending characters
+               ColouriseMakeLine(lineBuffer, linePos, startLine, startPos + length - 1, styler);
+       }
+}
+
+static const char *const emptyWordListDesc[] = {
+       0
+};
+
+LexerModule lmMake(SCLEX_MAKEFILE, ColouriseMakeDoc, "makefile", 0, emptyWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexMarkdown.cxx 
b/plugins/scintilla/scintilla/lexers/LexMarkdown.cxx
index a926977..a1a50f2 100644
--- a/plugins/scintilla/scintilla/lexers/LexMarkdown.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMarkdown.cxx
@@ -60,8 +60,8 @@ static inline bool IsNewline(const int ch) {
 }
 
 // True if can follow ch down to the end with possibly trailing whitespace
-static bool FollowToLineEnd(const int ch, const int state, const unsigned int endPos, StyleContext &sc) {
-    unsigned int i = 0;
+static bool FollowToLineEnd(const int ch, const int state, const Sci_PositionU endPos, StyleContext &sc) {
+    Sci_PositionU i = 0;
     while (sc.GetRelative(++i) == ch)
         ;
     // Skip over whitespace
@@ -78,7 +78,7 @@ static bool FollowToLineEnd(const int ch, const int state, const unsigned int en
 
 // Set the state on text section from current to length characters,
 // then set the rest until the newline to default, except for any characters matching token
-static void SetStateAndZoom(const int state, const int length, const int token, StyleContext &sc) {
+static void SetStateAndZoom(const int state, const Sci_Position length, const int token, StyleContext &sc) {
     sc.SetState(state);
     sc.Forward(length);
     sc.SetState(SCE_MARKDOWN_DEFAULT);
@@ -100,11 +100,11 @@ static void SetStateAndZoom(const int state, const int length, const int token,
 
 // Does the previous line have more than spaces and tabs?
 static bool HasPrevLineContent(StyleContext &sc) {
-    int i = 0;
+    Sci_Position i = 0;
     // Go back to the previous newline
-    while ((--i + (int)sc.currentPos) >= 0 && !IsNewline(sc.GetRelative(i)))
+    while ((--i + (Sci_Position)sc.currentPos) >= 0 && !IsNewline(sc.GetRelative(i)))
         ;
-    while ((--i + (int)sc.currentPos) >= 0) {
+    while ((--i + (Sci_Position)sc.currentPos) >= 0) {
         if (IsNewline(sc.GetRelative(i)))
             break;
         if (!IsASpaceOrTab(sc.GetRelative(i)))
@@ -114,14 +114,15 @@ static bool HasPrevLineContent(StyleContext &sc) {
 }
 
 static bool AtTermStart(StyleContext &sc) {
-    return sc.currentPos == 0 || isspacechar(sc.chPrev);
+    return sc.currentPos == 0 || sc.chPrev == 0 || isspacechar(sc.chPrev);
 }
 
-static bool IsValidHrule(const unsigned int endPos, StyleContext &sc) {
-    int c, count = 1;
-    unsigned int i = 0;
-    while (++i) {
-        c = sc.GetRelative(i);
+static bool IsValidHrule(const Sci_PositionU endPos, StyleContext &sc) {
+    int count = 1;
+    Sci_PositionU i = 0;
+    for (;;) {
+        ++i;
+        int c = sc.GetRelative(i);
         if (c == sc.ch)
             ++count;
         // hit a terminating character
@@ -140,12 +141,11 @@ static bool IsValidHrule(const unsigned int endPos, StyleContext &sc) {
             }
         }
     }
-    return false;
 }
 
-static void ColorizeMarkdownDoc(unsigned int startPos, int length, int initStyle,
+static void ColorizeMarkdownDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                WordList **, Accessor &styler) {
-    unsigned int endPos = startPos + length;
+    Sci_PositionU endPos = startPos + length;
     int precharCount = 0;
     // Don't advance on a new loop iteration and retry at the same position.
     // Useful in the corner case of having to start at the beginning file position
@@ -225,7 +225,7 @@ static void ColorizeMarkdownDoc(unsigned int startPos, int length, int initStyle
         }
         else if (sc.state == SCE_MARKDOWN_CODEBK) {
             if (sc.atLineStart && sc.Match("~~~")) {
-                int i = 1;
+                Sci_Position i = 1;
                 while (!IsNewline(sc.GetRelative(i)) && sc.currentPos + i < endPos)
                     i++;
                 sc.Forward(i);
@@ -347,8 +347,8 @@ static void ColorizeMarkdownDoc(unsigned int startPos, int length, int initStyle
             }
             // Links and Images
             if (sc.Match("![") || sc.ch == '[') {
-                int i = 0, j = 0, k = 0;
-                int len = endPos - sc.currentPos;
+                Sci_Position i = 0, j = 0, k = 0;
+                Sci_Position len = endPos - sc.currentPos;
                 while (i < len && (sc.GetRelative(++i) != ']' || sc.GetRelative(i - 1) == '\\'))
                     ;
                 if (sc.GetRelative(i) == ']') {
diff --git a/plugins/scintilla/scintilla/lexers/LexMatlab.cxx 
b/plugins/scintilla/scintilla/lexers/LexMatlab.cxx
index c59b8f9..45f0b69 100644
--- a/plugins/scintilla/scintilla/lexers/LexMatlab.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMatlab.cxx
@@ -12,6 +12,15 @@
  **   - added ... displayed as a comment
  **   - removed unused IsAWord functions
  **   - added some comments
+ **
+ ** Changes by John Donoghue 2014/08/01
+ **   - fix allowed transpose ' after {} operator
+ **
+ ** Changes by John Donoghue 2016/11/15
+ **   - update matlab code folding
+ **
+ ** Changes by John Donoghue 2017/01/18
+ **   - update matlab block comment detection
  **/
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
@@ -46,24 +55,48 @@ static bool IsOctaveCommentChar(int c) {
        return (c == '%' || c == '#') ;
 }
 
-static bool IsMatlabComment(Accessor &styler, int pos, int len) {
-       return len > 0 && IsMatlabCommentChar(styler[pos]) ;
+static inline int LowerCase(int c) {
+       if (c >= 'A' && c <= 'Z')
+               return 'a' + c - 'A';
+       return c;
 }
 
-static bool IsOctaveComment(Accessor &styler, int pos, int len) {
-       return len > 0 && IsOctaveCommentChar(styler[pos]) ;
+static int CheckKeywordFoldPoint(char *str) {
+       if (strcmp ("if", str) == 0 ||
+               strcmp ("for", str) == 0 ||
+               strcmp ("switch", str) == 0 ||
+               strcmp ("try", str) == 0 ||
+               strcmp ("do", str) == 0 ||
+               strcmp ("parfor", str) == 0 ||
+               strcmp ("function", str) == 0)
+               return 1;
+       if (strncmp("end", str, 3) == 0 ||
+               strcmp("until", str) == 0)
+               return -1;
+       return 0;
+}
+
+static bool IsSpaceToEOL(Sci_Position startPos, Accessor &styler) {
+       Sci_Position line = styler.GetLine(startPos);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = startPos; i < eol_pos; i++) {
+               char ch = styler[i];
+               if(!IsASpace(ch)) return false;
+       }
+       return true;
 }
 
 static void ColouriseMatlabOctaveDoc(
-            unsigned int startPos, int length, int initStyle,
+            Sci_PositionU startPos, Sci_Position length, int initStyle,
             WordList *keywordlists[], Accessor &styler,
-            bool (*IsCommentChar)(int)) {
+            bool (*IsCommentChar)(int),
+            bool ismatlab) {
 
        WordList &keywords = *keywordlists[0];
 
        styler.StartAt(startPos);
 
-       // boolean for when the ' is allowed to be transpose vs the start/end 
+       // boolean for when the ' is allowed to be transpose vs the start/end
        // of a string
        bool transpose = false;
 
@@ -73,7 +106,7 @@ static void ColouriseMatlabOctaveDoc(
        int column = 0;
 
         // use the line state of each line to store the block comment depth
-       int curLine = styler.GetLine(startPos);
+       Sci_Position curLine = styler.GetLine(startPos);
         int commentDepth = curLine > 0 ? styler.GetLineState(curLine-1) : 0;
 
 
@@ -82,13 +115,13 @@ static void ColouriseMatlabOctaveDoc(
        for (; sc.More(); sc.Forward(), column++) {
 
                        if(sc.atLineStart) {
-                       // set the line state to the current commentDepth 
+                       // set the line state to the current commentDepth
                        curLine = styler.GetLine(sc.currentPos);
                         styler.SetLineState(curLine, commentDepth);
 
                        // reset the column to 0, nonSpace to -1 (not set)
                        column = 0;
-                       nonSpaceColumn = -1; 
+                       nonSpaceColumn = -1;
                }
 
                // save the column position of first non space character in a line
@@ -107,7 +140,7 @@ static void ColouriseMatlabOctaveDoc(
                                        sc.ForwardSetState(SCE_MATLAB_DEFAULT);
                                        transpose = true;
                                 } else if(sc.ch == '.' && sc.chNext == '.') {
-                                        // we werent an operator, but a '...' 
+                                        // we werent an operator, but a '...'
                                         sc.ChangeState(SCE_MATLAB_COMMENT);
                                         transpose = false;
                                } else {
@@ -159,9 +192,9 @@ static void ColouriseMatlabOctaveDoc(
                        }
                } else if (sc.state == SCE_MATLAB_COMMENT) {
                        // end or start of a nested a block comment?
-                       if( IsCommentChar(sc.ch) && sc.chNext == '}' && nonSpaceColumn == column) {
+                       if( IsCommentChar(sc.ch) && sc.chNext == '}' && nonSpaceColumn == column && 
IsSpaceToEOL(sc.currentPos+2, styler)) {
                                if(commentDepth > 0) commentDepth --;
- 
+
                                curLine = styler.GetLine(sc.currentPos);
                                styler.SetLineState(curLine, commentDepth);
                                sc.Forward();
@@ -171,7 +204,7 @@ static void ColouriseMatlabOctaveDoc(
                                        transpose = false;
                                }
                         }
-                        else if( IsCommentChar(sc.ch) && sc.chNext == '{' && nonSpaceColumn == column)
+                        else if( IsCommentChar(sc.ch) && sc.chNext == '{' && nonSpaceColumn == column && 
IsSpaceToEOL(sc.currentPos+2, styler))
                         {
                                commentDepth ++;
 
@@ -193,13 +226,20 @@ static void ColouriseMatlabOctaveDoc(
                if (sc.state == SCE_MATLAB_DEFAULT) {
                        if (IsCommentChar(sc.ch)) {
                                // ncrement depth if we are a block comment
-                               if(sc.chNext == '{' && nonSpaceColumn == column)
-                                       commentDepth ++;
+                               if(sc.chNext == '{' && nonSpaceColumn == column) {
+                                       if(IsSpaceToEOL(sc.currentPos+2, styler)) {
+                                               commentDepth ++;
+                                       }
+                               }
                                curLine = styler.GetLine(sc.currentPos);
                                styler.SetLineState(curLine, commentDepth);
                                sc.SetState(SCE_MATLAB_COMMENT);
                        } else if (sc.ch == '!' && sc.chNext != '=' ) {
-                               sc.SetState(SCE_MATLAB_COMMAND);
+                               if(ismatlab) {
+                                       sc.SetState(SCE_MATLAB_COMMAND);
+                               } else {
+                                       sc.SetState(SCE_MATLAB_OPERATOR);
+                               }
                        } else if (sc.ch == '\'') {
                                if (transpose) {
                                        sc.SetState(SCE_MATLAB_OPERATOR);
@@ -213,7 +253,7 @@ static void ColouriseMatlabOctaveDoc(
                        } else if (isalpha(sc.ch)) {
                                sc.SetState(SCE_MATLAB_KEYWORD);
                        } else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '\\') {
-                               if (sc.ch == ')' || sc.ch == ']') {
+                               if (sc.ch == ')' || sc.ch == ']' || sc.ch == '}') {
                                        transpose = true;
                                } else {
                                        transpose = false;
@@ -227,68 +267,92 @@ static void ColouriseMatlabOctaveDoc(
        sc.Complete();
 }
 
-static void ColouriseMatlabDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseMatlabDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                WordList *keywordlists[], Accessor &styler) {
-       ColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar);
+       ColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar, 
true);
 }
 
-static void ColouriseOctaveDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseOctaveDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                WordList *keywordlists[], Accessor &styler) {
-       ColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar);
+       ColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar, 
false);
 }
 
-static void FoldMatlabOctaveDoc(unsigned int startPos, int length, int,
+static void FoldMatlabOctaveDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                 WordList *[], Accessor &styler,
-                                bool (*IsComment)(Accessor&, int, int)) {
-
-       int endPos = startPos + length;
-
-       // Backtrack to previous line in case need to fix its fold status
-       int lineCurrent = styler.GetLine(startPos);
-       if (startPos > 0) {
-               if (lineCurrent > 0) {
-                       lineCurrent--;
-                       startPos = styler.LineStart(lineCurrent);
-               }
-       }
-       int spaceFlags = 0;
-       int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsComment);
+                                bool (*IsComment)(int ch)) {
+
+       Sci_PositionU endPos = startPos + length;
+       int visibleChars = 0;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       int levelCurrent = SC_FOLDLEVELBASE;
+       if (lineCurrent > 0)
+               levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
+       int levelNext = levelCurrent;
        char chNext = styler[startPos];
-       for (int i = startPos; i < endPos; i++) {
+       int styleNext = styler.StyleAt(startPos);
+       int style = initStyle;
+       char word[100];
+       int wordlen = 0;
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
+               style = styleNext;
+               styleNext = styler.StyleAt(i + 1);
+               bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+
+               // a line that starts with a comment
+               if (style == SCE_MATLAB_COMMENT && IsComment(ch) && visibleChars == 0) {
+                       // start/end of block comment
+                       if (chNext == '{' && IsSpaceToEOL(i+2, styler))
+                               levelNext ++;
+                       if (chNext == '}' && IsSpaceToEOL(i+2, styler))
+                               levelNext --;
+               }
+               // keyword
+               if(style == SCE_MATLAB_KEYWORD) {
+                       word[wordlen++] = static_cast<char>(LowerCase(ch));
+                       if (wordlen == 100) {  // prevent overflow
+                               word[0] = '\0';
+                               wordlen = 1;
+                       }
+                       if (styleNext !=  SCE_MATLAB_KEYWORD) {
+                               word[wordlen] = '\0';
+                               wordlen = 0;
 
-               if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) {
-                       int lev = indentCurrent;
-                       int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsComment);
-                       if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
-                               // Only non whitespace lines can be headers
-                               if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & 
SC_FOLDLEVELNUMBERMASK)) {
-                                       lev |= SC_FOLDLEVELHEADERFLAG;
-                               } else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
-                                       // Line after is blank so check the next - maybe should continue 
further?
-                                       int spaceFlags2 = 0;
-                                       int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, 
IsComment);
-                                       if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & 
SC_FOLDLEVELNUMBERMASK)) {
-                                               lev |= SC_FOLDLEVELHEADERFLAG;
-                                       }
-                               }
+                               levelNext += CheckKeywordFoldPoint(word);
+                       }
+               }
+               if (!IsASpace(ch))
+                       visibleChars++;
+               if (atEOL || (i == endPos-1)) {
+                       int levelUse = levelCurrent;
+                       int lev = levelUse | levelNext << 16;
+                       if (visibleChars == 0)
+                               lev |= SC_FOLDLEVELWHITEFLAG;
+                       if (levelUse < levelNext)
+                               lev |= SC_FOLDLEVELHEADERFLAG;
+                       if (lev != styler.LevelAt(lineCurrent)) {
+                               styler.SetLevel(lineCurrent, lev);
                        }
-                       indentCurrent = indentNext;
-                       styler.SetLevel(lineCurrent, lev);
                        lineCurrent++;
+                       levelCurrent = levelNext;
+                       if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length() - 1))) {
+                               // There is an empty line at end of file so give it same level and empty
+                               styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | 
SC_FOLDLEVELWHITEFLAG);
+                       }
+                       visibleChars = 0;
                }
        }
 }
 
-static void FoldMatlabDoc(unsigned int startPos, int length, int initStyle,
+static void FoldMatlabDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                           WordList *keywordlists[], Accessor &styler) {
-       FoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabComment);
+       FoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar);
 }
 
-static void FoldOctaveDoc(unsigned int startPos, int length, int initStyle,
+static void FoldOctaveDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                           WordList *keywordlists[], Accessor &styler) {
-       FoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveComment);
+       FoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar);
 }
 
 static const char * const matlabWordListDesc[] = {
diff --git a/plugins/scintilla/scintilla/lexers/LexMetapost.cxx 
b/plugins/scintilla/scintilla/lexers/LexMetapost.cxx
index d049521..cbfe10f 100644
--- a/plugins/scintilla/scintilla/lexers/LexMetapost.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMetapost.cxx
@@ -62,7 +62,7 @@ using namespace Scintilla;
 
 // Auxiliary functions:
 
-static inline bool endOfLine(Accessor &styler, unsigned int i) {
+static inline bool endOfLine(Accessor &styler, Sci_PositionU i) {
        return
       (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')) ;
 }
@@ -119,18 +119,18 @@ static inline bool isMETAPOSTequal(int ch) {
 }
 
 static int CheckMETAPOSTInterface(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     Accessor &styler,
        int defaultInterface) {
 
     char lineBuffer[1024] ;
-       unsigned int linePos = 0 ;
+       Sci_PositionU linePos = 0 ;
 
        // some day we can make something lexer.metapost.mapping=(none,0)(metapost,1)(mp,1)(metafun,2)...
 
     if (styler.SafeGetCharAt(0) == '%') {
-        for (unsigned int i = 0; i < startPos + length; i++) {
+        for (Sci_PositionU i = 0; i < startPos + length; i++) {
             lineBuffer[linePos++] = styler.SafeGetCharAt(i) ;
             if (endOfLine(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
                 lineBuffer[linePos] = '\0';
@@ -154,8 +154,8 @@ static int CheckMETAPOSTInterface(
 }
 
 static void ColouriseMETAPOSTDoc(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int,
     WordList *keywordlists[],
     Accessor &styler) {
@@ -336,7 +336,7 @@ static int classifyFoldPointMetapost(const char* s,WordList *keywordlists[]) {
 
 }
 
-static int ParseMetapostWord(unsigned int pos, Accessor &styler, char *word)
+static int ParseMetapostWord(Sci_PositionU pos, Accessor &styler, char *word)
 {
   int length=0;
   char ch=styler.SafeGetCharAt(pos);
@@ -351,19 +351,19 @@ static int ParseMetapostWord(unsigned int pos, Accessor &styler, char *word)
   return length;
 }
 
-static void FoldMetapostDoc(unsigned int startPos, int length, int, WordList *keywordlists[], Accessor 
&styler)
+static void FoldMetapostDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordlists[], 
Accessor &styler)
 {
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos+length;
+       Sci_PositionU endPos = startPos+length;
        int visibleChars=0;
-       int lineCurrent=styler.GetLine(startPos);
+       Sci_Position lineCurrent=styler.GetLine(startPos);
        int levelPrev=styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent=levelPrev;
        char chNext=styler[startPos];
 
        char buffer[100]="";
 
-       for (unsigned int i=startPos; i < endPos; i++) {
+       for (Sci_PositionU i=startPos; i < endPos; i++) {
                char ch=chNext;
                chNext=styler.SafeGetCharAt(i+1);
                char chPrev=styler.SafeGetCharAt(i-1);
diff --git a/plugins/scintilla/scintilla/lexers/LexModula.cxx 
b/plugins/scintilla/scintilla/lexers/LexModula.cxx
index ed61560..c71cdd0 100644
--- a/plugins/scintilla/scintilla/lexers/LexModula.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexModula.cxx
@@ -34,7 +34,7 @@ using namespace Scintilla;
 
 #ifdef DEBUG_LEX_MODULA
 #define DEBUG_STATE( p, c )\
-               fprintf( stderr, "Unknown state: currentPos = %d, char = '%c'\n", p, c );
+               fprintf( stderr, "Unknown state: currentPos = %ud, char = '%c'\n", p, c );
 #else
 #define DEBUG_STATE( p, c )
 #endif
@@ -79,7 +79,7 @@ static inline unsigned IsOperator( StyleContext & sc, WordList & op ) {
        return 0;
 }
 
-static inline bool IsEOL( Accessor &styler, unsigned curPos ) {
+static inline bool IsEOL( Accessor &styler, Sci_PositionU curPos ) {
        unsigned ch = styler.SafeGetCharAt( curPos );
        if( ( ch == '\r' && styler.SafeGetCharAt( curPos + 1 ) == '\n' ) ||
                ( ch == '\n' ) ) {
@@ -90,7 +90,7 @@ static inline bool IsEOL( Accessor &styler, unsigned curPos ) {
 
 static inline bool checkStatement(
        Accessor &styler,
-       int &curPos,
+       Sci_Position &curPos,
        const char *stt, bool spaceAfter = true ) {
        int len = static_cast<int>(strlen( stt ));
        int i;
@@ -110,7 +110,7 @@ static inline bool checkStatement(
 
 static inline bool checkEndSemicolon(
        Accessor &styler,
-       int &curPos, int endPos )
+       Sci_Position &curPos, Sci_Position endPos )
 {
        const char *stt = "END";
        int len = static_cast<int>(strlen( stt ));
@@ -134,9 +134,9 @@ static inline bool checkEndSemicolon(
 static inline bool checkKeyIdentOper(
 
        Accessor &styler,
-       int &curPos, int endPos,
+       Sci_Position &curPos, Sci_Position endPos,
        const char *stt, const char etk ) {
-       int newPos = curPos;
+       Sci_Position newPos = curPos;
        if( ! checkStatement( styler, newPos, stt ) )
                return false;
        newPos++;
@@ -174,17 +174,17 @@ static inline bool checkKeyIdentOper(
        return true;
 }
 
-static void FoldModulaDoc( unsigned int startPos,
-                                                int length,
+static void FoldModulaDoc( Sci_PositionU startPos,
+                                                Sci_Position length,
                                                 int , WordList *[],
                                                 Accessor &styler)
 {
-       int curLine = styler.GetLine(startPos);
+       Sci_Position curLine = styler.GetLine(startPos);
        int curLevel = SC_FOLDLEVELBASE;
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
        if( curLine > 0 )
                curLevel = styler.LevelAt( curLine - 1 ) >> 16;
-       int curPos = startPos;
+       Sci_Position curPos = startPos;
        int style = styler.StyleAt( curPos );
        int visChars = 0;
        int nextLevel = curLevel;
@@ -250,9 +250,9 @@ static void FoldModulaDoc( unsigned int startPos,
                                nextLevel++;
                        else
                        if( checkKeyIdentOper( styler, curPos, endPos, "END", ';' ) ) {
-                               int cln = curLine;
+                               Sci_Position cln = curLine;
                                int clv_old = curLevel;
-                               int pos;
+                               Sci_Position pos;
                                char ch;
                                int clv_new;
                                while( cln > 0 ) {
@@ -325,8 +325,8 @@ static inline bool skipWhiteSpaces( StyleContext & sc ) {
        return true;
 }
 
-static void ColouriseModulaDoc(        unsigned int startPos,
-                                                                       int length,
+static void ColouriseModulaDoc(        Sci_PositionU startPos,
+                                                                       Sci_Position length,
                                                                        int initStyle,
                                                                        WordList *wl[],
                                                                        Accessor &styler ) {
@@ -342,7 +342,7 @@ static void ColouriseModulaDoc(     unsigned int startPos,
        char    buf[BUFLEN];
        int             i, kl;
 
-       int  charPos = 0;
+       Sci_Position  charPos = 0;
 
        StyleContext sc( startPos, length, initStyle, styler );
 
diff --git a/plugins/scintilla/scintilla/lexers/LexMySQL.cxx b/plugins/scintilla/scintilla/lexers/LexMySQL.cxx
index f4823f8..703b24d 100644
--- a/plugins/scintilla/scintilla/lexers/LexMySQL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexMySQL.cxx
@@ -40,13 +40,6 @@ static inline bool IsAWordStart(int ch) {
        return (ch < 0x80) && (isalpha(ch) || ch == '_');
 }
 
-static inline bool IsADoxygenChar(int ch) {
-       return (islower(ch) || ch == '$' || ch == '@' ||
-               ch == '\\' || ch == '&' || ch == '<' ||
-               ch == '>' || ch == '#' || ch == '{' ||
-               ch == '}' || ch == '[' || ch == ']');
-}
-
 static inline bool IsANumberChar(int ch) {
        // Not exactly following number definition (several dots are seen as OK, etc.)
        // but probably enough in most cases.
@@ -112,7 +105,7 @@ static void ForwardDefaultState(StyleContext& sc, int activeState)
     sc.ForwardSetState(SCE_MYSQL_HIDDENCOMMAND);
 }
 
-static void ColouriseMySQLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseMySQLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler)
 {
        StyleContext sc(startPos, length, initStyle, styler, 127);
@@ -157,7 +150,7 @@ static void ColouriseMySQLDoc(unsigned int startPos, int length, int initStyle,
       case SCE_MYSQL_SYSTEMVARIABLE:
         if (!IsAWordChar(sc.ch))
         {
-          int length = sc.LengthCurrent() + 1;
+          Sci_Position length = sc.LengthCurrent() + 1;
           char* s = new char[length];
           sc.GetCurrentLowered(s, length);
 
@@ -274,10 +267,13 @@ static void ColouriseMySQLDoc(unsigned int startPos, int length, int initStyle,
               {
                 sc.SetState(SCE_MYSQL_COMMENT | activeState);
 
-                // Skip comment introducer and check for hidden command.
-                sc.Forward(2);
-                if (sc.ch == '!')
+                // Skip first char of comment introducer and check for hidden command.
+                // The second char is skipped by the outer loop.
+                sc.Forward();
+                if (sc.GetRelativeCharacter(1) == '!')
                 {
+                  // Version comment found. Skip * now.
+                  sc.Forward();
                   activeState = HIDDENCOMMAND_STATE;
                   sc.ChangeState(SCE_MYSQL_HIDDENCOMMAND);
                 }
@@ -335,9 +331,9 @@ static bool IsStreamCommentStyle(int style)
  * Code copied from StyleContext and modified to work here. Should go into Accessor as a
  * companion to Match()...
  */
-bool MatchIgnoreCase(Accessor &styler, int currentPos, const char *s)
+static bool MatchIgnoreCase(Accessor &styler, Sci_Position currentPos, const char *s)
 {
-  for (int n = 0; *s; n++)
+  for (Sci_Position n = 0; *s; n++)
   {
     if (*s != tolower(styler.SafeGetCharAt(currentPos + n)))
       return false;
@@ -350,14 +346,14 @@ bool MatchIgnoreCase(Accessor &styler, int currentPos, const char *s)
 
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment.
-static void FoldMySQLDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler)
+static void FoldMySQLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], Accessor 
&styler)
 {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        bool foldOnlyBegin = styler.GetPropertyInt("fold.sql.only.begin", 0) != 0;
 
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16;
@@ -366,24 +362,24 @@ static void FoldMySQLDoc(unsigned int startPos, int length, int initStyle, WordL
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
   int activeState = (style == SCE_MYSQL_HIDDENCOMMAND) ? HIDDENCOMMAND_STATE : style & HIDDENCOMMAND_STATE;
-       
+
   bool endPending = false;
        bool whenPending = false;
        bool elseIfPending = false;
 
   char nextChar = styler.SafeGetCharAt(startPos);
-  for (unsigned int i = startPos; length > 0; i++, length--)
+  for (Sci_PositionU i = startPos; length > 0; i++, length--)
   {
                int stylePrev = style;
     int lastActiveState = activeState;
                style = styleNext;
                styleNext = styler.StyleAt(i + 1);
     activeState = (style == SCE_MYSQL_HIDDENCOMMAND) ? HIDDENCOMMAND_STATE : style & HIDDENCOMMAND_STATE;
-    
+
     char currentChar = nextChar;
     nextChar = styler.SafeGetCharAt(i + 1);
                bool atEOL = (currentChar == '\r' && nextChar != '\n') || (currentChar == '\n');
-       
+
     switch (MASKACTIVE(style))
     {
       case SCE_MYSQL_COMMENT:
@@ -396,7 +392,7 @@ static void FoldMySQLDoc(unsigned int startPos, int length, int initStyle, WordL
         break;
       case SCE_MYSQL_COMMENTLINE:
         if (foldComment)
-        { 
+        {
           // Not really a standard, but we add support for single line comments
           // with special curly braces syntax as foldable comments too.
           // MySQL needs -- comments to be followed by space or control char
@@ -504,12 +500,12 @@ static void FoldMySQLDoc(unsigned int startPos, int length, int initStyle, WordL
                 }
               }
             }
-          
+
           // Keep the current end state for the next round.
           endPending = endFound;
         }
         break;
-        
+
       default:
         if (!isspacechar(currentChar) && endPending)
         {
@@ -551,7 +547,7 @@ static void FoldMySQLDoc(unsigned int startPos, int length, int initStyle, WordL
         lev |= SC_FOLDLEVELHEADERFLAG;
       if (lev != styler.LevelAt(lineCurrent))
         styler.SetLevel(lineCurrent, lev);
-      
+
       lineCurrent++;
       levelCurrent = levelNext;
       visibleChars = 0;
@@ -577,4 +573,4 @@ static const char * const mysqlWordListDesc[] = {
        0
 };
 
-LexerModule lmMySQL(SCLEX_MYSQL, ColouriseMySQLDoc, "mysql", FoldMySQLDoc, mysqlWordListDesc, 7);
+LexerModule lmMySQL(SCLEX_MYSQL, ColouriseMySQLDoc, "mysql", FoldMySQLDoc, mysqlWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexNimrod.cxx 
b/plugins/scintilla/scintilla/lexers/LexNimrod.cxx
index 08b76fe..d232f9f 100644
--- a/plugins/scintilla/scintilla/lexers/LexNimrod.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexNimrod.cxx
@@ -33,7 +33,7 @@ static inline bool IsAWordChar(int ch) {
        return (ch >= 0x80) || isalnum(ch) || ch == '_';
 }
 
-static int tillEndOfTripleQuote(Accessor &styler, int pos, int max) {
+static Sci_Position tillEndOfTripleQuote(Accessor &styler, Sci_Position pos, Sci_Position max) {
   /* search for """ */
   for (;;) {
     if (styler.SafeGetCharAt(pos, '\0') == '\0') return pos;
@@ -52,7 +52,7 @@ static bool inline isNewLine(int ch) {
   return ch == CR || ch == LF;
 }
 
-static int scanString(Accessor &styler, int pos, int max, bool rawMode) {
+static Sci_Position scanString(Accessor &styler, Sci_Position pos, Sci_Position max, bool rawMode) {
   for (;;) {
     if (pos >= max) return pos;
     char ch = styler.SafeGetCharAt(pos, '\0');
@@ -66,7 +66,7 @@ static int scanString(Accessor &styler, int pos, int max, bool rawMode) {
   }
 }
 
-static int scanChar(Accessor &styler, int pos, int max) {
+static Sci_Position scanChar(Accessor &styler, Sci_Position pos, Sci_Position max) {
   for (;;) {
     if (pos >= max) return pos;
     char ch = styler.SafeGetCharAt(pos, '\0');
@@ -81,9 +81,9 @@ static int scanChar(Accessor &styler, int pos, int max) {
   }
 }
 
-static int scanIdent(Accessor &styler, int pos, WordList &keywords) {
+static Sci_Position scanIdent(Accessor &styler, Sci_Position pos, WordList &keywords) {
   char buf[100]; /* copy to lowercase and ignore underscores */
-  int i = 0;
+  Sci_Position i = 0;
 
   for (;;) {
     char ch = styler.SafeGetCharAt(pos, '\0');
@@ -104,7 +104,7 @@ static int scanIdent(Accessor &styler, int pos, WordList &keywords) {
   return pos;
 }
 
-static int scanNumber(Accessor &styler, int pos) {
+static Sci_Position scanNumber(Accessor &styler, Sci_Position pos) {
   char ch, ch2;
   ch = styler.SafeGetCharAt(pos, '\0');
   ch2 = styler.SafeGetCharAt(pos+1, '\0');
@@ -179,10 +179,10 @@ static int scanNumber(Accessor &styler, int pos) {
 /* rewritten from scratch, because I couldn't get rid of the bugs...
    (A character based approach sucks!)
 */
-static void ColouriseNimrodDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseNimrodDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                 WordList *keywordlists[], Accessor &styler) {
-  int pos = startPos;
-  int max = startPos + length;
+  Sci_Position pos = startPos;
+  Sci_Position max = startPos + length;
   char ch;
   WordList &keywords = *keywordlists[0];
 
@@ -264,10 +264,10 @@ static void ColouriseNimrodDoc(unsigned int startPos, int length, int initStyle,
   }
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eol_pos; i++) {
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
                char ch = styler[i];
                if (ch == '#')
                        return true;
@@ -277,18 +277,18 @@ static bool IsCommentLine(int line, Accessor &styler) {
        return false;
 }
 
-static bool IsQuoteLine(int line, Accessor &styler) {
+static bool IsQuoteLine(Sci_Position line, Accessor &styler) {
        int style = styler.StyleAt(styler.LineStart(line)) & 31;
        return ((style == SCE_P_TRIPLE) || (style == SCE_P_TRIPLEDOUBLE));
 }
 
 
-static void FoldNimrodDoc(unsigned int startPos, int length,
+static void FoldNimrodDoc(Sci_PositionU startPos, Sci_Position length,
                           int /*initStyle - unused*/,
                           WordList *[], Accessor &styler) {
-       const int maxPos = startPos + length;
-       const int maxLines = styler.GetLine(maxPos - 1); // Requested last line
-       const int docLines = styler.GetLine(styler.Length() - 1); // Available last line
+       const Sci_Position maxPos = startPos + length;
+       const Sci_Position maxLines = styler.GetLine(maxPos - 1); // Requested last line
+       const Sci_Position docLines = styler.GetLine(styler.Length() - 1); // Available last line
        const bool foldComment = styler.GetPropertyInt("fold.comment.nimrod") != 0;
        const bool foldQuotes = styler.GetPropertyInt("fold.quotes.nimrod") != 0;
 
@@ -297,7 +297,7 @@ static void FoldNimrodDoc(unsigned int startPos, int length,
        // and so we can fix any preceding fold level (which is why we go back
        // at least one line in all cases)
        int spaceFlags = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
        while (lineCurrent > 0) {
                lineCurrent--;
@@ -328,7 +328,7 @@ static void FoldNimrodDoc(unsigned int startPos, int length,
 
                // Gather info
                int lev = indentCurrent;
-               int lineNext = lineCurrent + 1;
+               Sci_Position lineNext = lineCurrent + 1;
                int indentNext = indentCurrent;
                int quote = false;
                if (lineNext <= docLines) {
@@ -388,7 +388,7 @@ static void FoldNimrodDoc(unsigned int startPos, int length,
                // which is indented more than the line after the end of
                // the comment-block, use the level of the block before
 
-               int skipLine = lineNext;
+               Sci_Position skipLine = lineNext;
                int skipLevel = levelAfterComments;
 
                while (--skipLine > lineCurrent) {
diff --git a/plugins/scintilla/scintilla/lexers/LexNsis.cxx b/plugins/scintilla/scintilla/lexers/LexNsis.cxx
index 599ccfb..2608349 100644
--- a/plugins/scintilla/scintilla/lexers/LexNsis.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexNsis.cxx
@@ -69,10 +69,10 @@ static bool isNsisLetter(char ch)
   return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
 }
 
-static bool NsisNextLineHasElse(unsigned int start, unsigned int end, Accessor &styler)
+static bool NsisNextLineHasElse(Sci_PositionU start, Sci_PositionU end, Accessor &styler)
 {
-  int nNextLine = -1;
-  for( unsigned int i = start; i < end; i++ )
+  Sci_Position nNextLine = -1;
+  for( Sci_PositionU i = start; i < end; i++ )
   {
     char cNext = styler.SafeGetCharAt( i );
     if( cNext == '\n' )
@@ -85,7 +85,7 @@ static bool NsisNextLineHasElse(unsigned int start, unsigned int end, Accessor &
   if( nNextLine == -1 ) // We never found the next line...
     return false;
 
-  for( unsigned int firstChar = nNextLine; firstChar < end; firstChar++ )
+  for( Sci_PositionU firstChar = nNextLine; firstChar < end; firstChar++ )
   {
     char cNext = styler.SafeGetCharAt( firstChar );
     if( cNext == ' ' )
@@ -111,7 +111,7 @@ static int NsisCmp( const char *s1, const char *s2, bool bIgnoreCase )
   return strcmp( s1, s2 );
 }
 
-static int calculateFoldNsis(unsigned int start, unsigned int end, int foldlevel, Accessor &styler, bool 
bElse, bool foldUtilityCmd )
+static int calculateFoldNsis(Sci_PositionU start, Sci_PositionU end, int foldlevel, Accessor &styler, bool 
bElse, bool foldUtilityCmd )
 {
   int style = styler.StyleAt(end);
 
@@ -143,7 +143,7 @@ static int calculateFoldNsis(unsigned int start, unsigned int end, int foldlevel
 
   char s[20]; // The key word we are looking for has atmost 13 characters
   s[0] = '\0';
-  for (unsigned int i = 0; i < end - start + 1 && i < 19; i++)
+  for (Sci_PositionU i = 0; i < end - start + 1 && i < 19; i++)
        {
                s[i] = static_cast<char>( styler[ start + i ] );
                s[i + 1] = '\0';
@@ -169,7 +169,7 @@ static int calculateFoldNsis(unsigned int start, unsigned int end, int foldlevel
   return newFoldlevel;
 }
 
-static int classifyWordNsis(unsigned int start, unsigned int end, WordList *keywordLists[], Accessor &styler 
)
+static int classifyWordNsis(Sci_PositionU start, Sci_PositionU end, WordList *keywordLists[], Accessor 
&styler )
 {
   bool bIgnoreCase = false;
   if( styler.GetPropertyInt("nsis.ignorecase") == 1 )
@@ -180,13 +180,15 @@ static int classifyWordNsis(unsigned int start, unsigned int end, WordList *keyw
     bUserVars = true;
 
        char s[100];
+       s[0] = '\0';
+       s[1] = '\0';
 
        WordList &Functions = *keywordLists[0];
        WordList &Variables = *keywordLists[1];
        WordList &Lables = *keywordLists[2];
        WordList &UserDefined = *keywordLists[3];
 
-       for (unsigned int i = 0; i < end - start + 1 && i < 99; i++)
+       for (Sci_PositionU i = 0; i < end - start + 1 && i < 99; i++)
        {
     if( bIgnoreCase )
       s[i] = static_cast<char>( tolower(styler[ start + i ] ) );
@@ -245,7 +247,7 @@ static int classifyWordNsis(unsigned int start, unsigned int end, WordList *keyw
   if( s[0] == '$' && bUserVars )
   {
     bool bHasSimpleNsisChars = true;
-    for (unsigned int j = 1; j < end - start + 1 && j < 99; j++)
+    for (Sci_PositionU j = 1; j < end - start + 1 && j < 99; j++)
          {
       if( !isNsisChar( s[j] ) )
       {
@@ -262,7 +264,7 @@ static int classifyWordNsis(unsigned int start, unsigned int end, WordList *keyw
   if( isNsisNumber( s[0] ) )
   {
     bool bHasSimpleNsisNumber = true;
-    for (unsigned int j = 1; j < end - start + 1 && j < 99; j++)
+    for (Sci_PositionU j = 1; j < end - start + 1 && j < 99; j++)
          {
       if( !isNsisNumber( s[j] ) )
       {
@@ -278,7 +280,7 @@ static int classifyWordNsis(unsigned int start, unsigned int end, WordList *keyw
        return SCE_NSIS_DEFAULT;
 }
 
-static void ColouriseNsisDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor 
&styler)
+static void ColouriseNsisDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], 
Accessor &styler)
 {
        int state = SCE_NSIS_DEFAULT;
   if( startPos > 0 )
@@ -287,14 +289,14 @@ static void ColouriseNsisDoc(unsigned int startPos, int length, int, WordList *k
        styler.StartAt( startPos );
        styler.GetLine( startPos );
 
-       unsigned int nLengthDoc = startPos + length;
+       Sci_PositionU nLengthDoc = startPos + length;
        styler.StartSegment( startPos );
 
        char cCurrChar;
        bool bVarInString = false;
   bool bClassicVarInString = false;
 
-       unsigned int i;
+       Sci_PositionU i;
        for( i = startPos; i < nLengthDoc; i++ )
        {
                cCurrChar = styler.SafeGetCharAt( i );
@@ -401,8 +403,8 @@ static void ColouriseNsisDoc(unsigned int startPos, int length, int, WordList *k
 
         if( cNextChar == '\r' || cNextChar == '\n' )
         {
-          int nCurLine = styler.GetLine(i+1);
-          int nBack = i;
+          Sci_Position nCurLine = styler.GetLine(i+1);
+          Sci_Position nBack = i;
           // We need to check if the previous line has a \ in it...
           bool bNextLine = false;
 
@@ -550,7 +552,7 @@ static void ColouriseNsisDoc(unsigned int startPos, int length, int, WordList *k
        styler.ColourTo(nLengthDoc-1,state);
 }
 
-static void FoldNsisDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldNsisDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
        // No folding enabled, no reason to continue...
        if( styler.GetPropertyInt("fold") == 0 )
@@ -560,11 +562,11 @@ static void FoldNsisDoc(unsigned int startPos, int length, int, WordList *[], Ac
   bool foldUtilityCmd = styler.GetPropertyInt("nsis.foldutilcmd", 1) == 1;
   bool blockComment = false;
 
-  int lineCurrent = styler.GetLine(startPos);
-  unsigned int safeStartPos = styler.LineStart( lineCurrent );
+  Sci_Position lineCurrent = styler.GetLine(startPos);
+  Sci_PositionU safeStartPos = styler.LineStart( lineCurrent );
 
   bool bArg1 = true;
-  int nWordStart = -1;
+  Sci_Position nWordStart = -1;
 
   int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
@@ -578,7 +580,7 @@ static void FoldNsisDoc(unsigned int startPos, int length, int, WordList *[], Ac
     blockComment = true;
   }
 
-  for (unsigned int i = safeStartPos; i < startPos + length; i++)
+  for (Sci_PositionU i = safeStartPos; i < startPos + length; i++)
        {
     char chCurr = styler.SafeGetCharAt(i);
     style = styler.StyleAt(i);
diff --git a/plugins/scintilla/scintilla/lexers/LexNull.cxx b/plugins/scintilla/scintilla/lexers/LexNull.cxx
new file mode 100644
index 0000000..3487677
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexNull.cxx
@@ -0,0 +1,40 @@
+// Scintilla source code edit control
+/** @file LexNull.cxx
+ ** Lexer for no language. Used for plain text and unrecognized files.
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static void ColouriseNullDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
+                            Accessor &styler) {
+       // Null language means all style bytes are 0 so just mark the end - no need to fill in.
+       if (length > 0) {
+               styler.StartAt(startPos + length - 1);
+               styler.StartSegment(startPos + length - 1);
+               styler.ColourTo(startPos + length - 1, 0);
+       }
+}
+
+LexerModule lmNull(SCLEX_NULL, ColouriseNullDoc, "null");
diff --git a/plugins/scintilla/scintilla/lexers/LexOScript.cxx 
b/plugins/scintilla/scintilla/lexers/LexOScript.cxx
index 9daff34..ee2dddd 100644
--- a/plugins/scintilla/scintilla/lexers/LexOScript.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexOScript.cxx
@@ -183,7 +183,7 @@ public:
 // ------------------------------------------------
 // Function colourising an excerpt of OScript code.
 
-static void ColouriseOScriptDoc(unsigned int startPos, int length,
+static void ColouriseOScriptDoc(Sci_PositionU startPos, Sci_Position length,
                                                                int initStyle, WordList *keywordlists[],
                                                                Accessor &styler) {
        // I wonder how whole-line styles ended by EOLN can escape the resetting
@@ -205,12 +205,12 @@ static void ColouriseOScriptDoc(unsigned int startPos, int length,
        bool isFirstToken = true;
        // It starts with true at the beginning of a line and changes to false as
        // soon as the first identifier on the line is passed by.
-       bool isFirstIdentifier = true; 
+       bool isFirstIdentifier = true;
        // It becomes false when #ifdef DOC (the preprocessor directive often
        // used to start a documentation comment) is encountered and remain false
        // until the end of the documentation block is not detected. This is done
        // by checking for the complementary #endif preprocessor directive.
-       bool endDocComment = false; 
+       bool endDocComment = false;
 
        for (; sc.More(); sc.Forward()) {
 
@@ -374,10 +374,10 @@ static inline bool IsBlockComment(int style) {
        return style == SCE_OSCRIPT_BLOCK_COMMENT;
 }
 
-static bool IsLineComment(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eolPos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eolPos; i++) {
+static bool IsLineComment(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eolPos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eolPos; i++) {
                char ch = styler[i];
                char chNext = styler.SafeGetCharAt(i + 1);
                int style = styler.StyleAt(i);
@@ -395,9 +395,9 @@ static inline bool IsPreprocessor(int style) {
                   style == SCE_OSCRIPT_DOC_COMMENT;
 }
 
-static void GetRangeLowered(unsigned int start, unsigned int end,
-                                                       Accessor &styler, char *s, unsigned int len) {
-       unsigned int i = 0;
+static void GetRangeLowered(Sci_PositionU start, Sci_PositionU end,
+                                                       Accessor &styler, char *s, Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while (i < end - start + 1 && i < len - 1) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                i++;
@@ -405,9 +405,9 @@ static void GetRangeLowered(unsigned int start, unsigned int end,
        s[i] = '\0';
 }
 
-static void GetForwardWordLowered(unsigned int start, Accessor &styler,
-                                                                 char *s, unsigned int len) {
-       unsigned int i = 0;
+static void GetForwardWordLowered(Sci_PositionU start, Accessor &styler,
+                                                                 char *s, Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while (i < len - 1 && IsAlpha(styler.SafeGetCharAt(start + i))) {
                s[i] = static_cast<char>(tolower(styler.SafeGetCharAt(start + i)));
                i++;
@@ -416,7 +416,7 @@ static void GetForwardWordLowered(unsigned int start, Accessor &styler,
 }
 
 static void UpdatePreprocessorFoldLevel(int &levelCurrent,
-               unsigned int startPos, Accessor &styler) {
+               Sci_PositionU startPos, Accessor &styler) {
        char s[7]; // Size of the longest possible keyword + null.
        GetForwardWordLowered(startPos, styler, s, sizeof(s));
 
@@ -431,8 +431,8 @@ static void UpdatePreprocessorFoldLevel(int &levelCurrent,
        }
 }
 
-static void UpdateKeywordFoldLevel(int &levelCurrent, unsigned int lastStart,
-               unsigned int currentPos, Accessor &styler) {
+static void UpdateKeywordFoldLevel(int &levelCurrent, Sci_PositionU lastStart,
+               Sci_PositionU currentPos, Accessor &styler) {
        char s[9];
        GetRangeLowered(lastStart, currentPos, styler, s, sizeof(s));
 
@@ -451,14 +451,14 @@ static void UpdateKeywordFoldLevel(int &levelCurrent, unsigned int lastStart,
 // ------------------------------
 // Function folding OScript code.
 
-static void FoldOScriptDoc(unsigned int startPos, int length, int initStyle,
+static void FoldOScriptDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                                   WordList *[], Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
@@ -466,7 +466,7 @@ static void FoldOScriptDoc(unsigned int startPos, int length, int initStyle,
        int style = initStyle;
        int lastStart = 0;
 
-       for (int i = startPos; i < endPos; i++) {
+       for (Sci_Position i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexOpal.cxx b/plugins/scintilla/scintilla/lexers/LexOpal.cxx
index 320fe9b..955927f 100644
--- a/plugins/scintilla/scintilla/lexers/LexOpal.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexOpal.cxx
@@ -26,9 +26,9 @@
 using namespace Scintilla;
 #endif
 
-inline static void getRange( unsigned int start, unsigned int end, Accessor & styler, char * s, unsigned int 
len )
+inline static void getRange( Sci_PositionU start, Sci_PositionU end, Accessor & styler, char * s, 
Sci_PositionU len )
 {
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        while( ( i < end - start + 1 ) && ( i < len - 1 ) )
        {
                s[i] = static_cast<char>( styler[ start + i ] );
@@ -37,7 +37,7 @@ inline static void getRange( unsigned int start, unsigned int end, Accessor & st
        s[ i ] = '\0';
 }
 
-inline bool HandleString( unsigned int & cur, unsigned int one_too_much, Accessor & styler )
+inline bool HandleString( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler )
 {
        char ch;
 
@@ -92,7 +92,7 @@ inline bool HandleString( unsigned int & cur, unsigned int one_too_much, Accesso
        }
 }
 
-inline bool HandleCommentBlock( unsigned int & cur, unsigned int one_too_much, Accessor & styler, bool 
could_fail )
+inline bool HandleCommentBlock( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler, bool 
could_fail )
 {
        char ch;
 
@@ -155,7 +155,7 @@ inline bool HandleCommentBlock( unsigned int & cur, unsigned int one_too_much, A
        }
 }
 
-inline bool HandleCommentLine( unsigned int & cur, unsigned int one_too_much, Accessor & styler, bool 
could_fail )
+inline bool HandleCommentLine( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler, bool 
could_fail )
 {
        char ch;
 
@@ -240,7 +240,7 @@ inline bool HandleCommentLine( unsigned int & cur, unsigned int one_too_much, Ac
        }
 }
 
-inline bool HandlePar( unsigned int & cur, Accessor & styler )
+inline bool HandlePar( Sci_PositionU & cur, Accessor & styler )
 {
        styler.ColourTo( cur, SCE_OPAL_PAR );
 
@@ -250,7 +250,7 @@ inline bool HandlePar( unsigned int & cur, Accessor & styler )
        return true;
 }
 
-inline bool HandleSpace( unsigned int & cur, unsigned int one_too_much, Accessor & styler )
+inline bool HandleSpace( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler )
 {
        char ch;
 
@@ -281,7 +281,7 @@ inline bool HandleSpace( unsigned int & cur, unsigned int one_too_much, Accessor
        }
 }
 
-inline bool HandleInteger( unsigned int & cur, unsigned int one_too_much, Accessor & styler )
+inline bool HandleInteger( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler )
 {
        char ch;
 
@@ -295,7 +295,7 @@ inline bool HandleInteger( unsigned int & cur, unsigned int one_too_much, Access
                }
 
                ch = styler.SafeGetCharAt( cur );
-               if( !( isascii( ch ) && isdigit( ch ) ) )
+               if( !( IsASCII( ch ) && isdigit( ch ) ) )
                {
                        styler.ColourTo( cur - 1, SCE_OPAL_INTEGER );
                        styler.StartSegment( cur );
@@ -304,17 +304,17 @@ inline bool HandleInteger( unsigned int & cur, unsigned int one_too_much, Access
        }
 }
 
-inline bool HandleWord( unsigned int & cur, unsigned int one_too_much, Accessor & styler, WordList * 
keywordlists[] )
+inline bool HandleWord( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler, WordList * 
keywordlists[] )
 {
        char ch;
-       const unsigned int beg = cur;
+       const Sci_PositionU beg = cur;
 
        cur++;
        for( ; ; )
        {
                ch = styler.SafeGetCharAt( cur );
                if( ( ch != '_' ) && ( ch != '-' ) &&
-                       !( isascii( ch ) && ( islower( ch ) || isupper( ch ) || isdigit( ch ) ) ) ) break;
+                       !( IsASCII( ch ) && ( islower( ch ) || isupper( ch ) || isdigit( ch ) ) ) ) break;
 
                cur++;
                if( cur >= one_too_much )
@@ -323,7 +323,7 @@ inline bool HandleWord( unsigned int & cur, unsigned int one_too_much, Accessor
                }
        }
 
-       const int ide_len = cur - beg + 1;
+       const Sci_Position ide_len = cur - beg + 1;
        char * ide = new char[ ide_len ];
        getRange( beg, cur, styler, ide, ide_len );
 
@@ -393,7 +393,7 @@ inline bool HandleWord( unsigned int & cur, unsigned int one_too_much, Accessor
 
 }
 
-inline bool HandleSkip( unsigned int & cur, unsigned int one_too_much, Accessor & styler )
+inline bool HandleSkip( Sci_PositionU & cur, Sci_PositionU one_too_much, Accessor & styler )
 {
        cur++;
        styler.ColourTo( cur - 1, SCE_OPAL_DEFAULT );
@@ -408,13 +408,13 @@ inline bool HandleSkip( unsigned int & cur, unsigned int one_too_much, Accessor
        }
 }
 
-static void ColouriseOpalDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], 
Accessor & styler )
+static void ColouriseOpalDoc( Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[], Accessor & styler )
 {
        styler.StartAt( startPos );
        styler.StartSegment( startPos );
 
-       unsigned int & cur = startPos;
-       const unsigned int one_too_much = startPos + length;
+       Sci_PositionU & cur = startPos;
+       const Sci_PositionU one_too_much = startPos + length;
 
        int state = initStyle;
 
@@ -490,13 +490,13 @@ static void ColouriseOpalDoc( unsigned int startPos, int length, int initStyle,
                                default:
                                        {
                                                // Integer
-                                               if( isascii( ch ) && isdigit( ch ) )
+                                               if( IsASCII( ch ) && isdigit( ch ) )
                                                {
                                                        if( !HandleInteger( cur, one_too_much, styler ) ) 
return;
                                                }
 
                                                // Keyword
-                                               else if( isascii( ch ) && ( islower( ch ) || isupper( ch ) ) )
+                                               else if( IsASCII( ch ) && ( islower( ch ) || isupper( ch ) ) )
                                                {
                                                        if( !HandleWord( cur, one_too_much, styler, 
keywordlists ) ) return;
 
diff --git a/plugins/scintilla/scintilla/lexers/LexPB.cxx b/plugins/scintilla/scintilla/lexers/LexPB.cxx
index a7b5690..49b8509 100644
--- a/plugins/scintilla/scintilla/lexers/LexPB.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPB.cxx
@@ -70,10 +70,10 @@ static inline bool IsAWordStart(const int ch)
     return (ch < 0x80) && (isalnum(ch) || ch == '_');
 }
 
-bool MatchUpperCase(Accessor &styler, int pos, const char *s)   //Same as styler.Match() but uppercase 
comparison (a-z,A-Z and space only)
+static bool MatchUpperCase(Accessor &styler, Sci_Position pos, const char *s)   //Same as styler.Match() but 
uppercase comparison (a-z,A-Z and space only)
 {
     char ch;
-    for (int i=0; *s; i++)
+    for (Sci_Position i=0; *s; i++)
     {
         ch=styler.SafeGetCharAt(pos+i);
         if (ch > 0x60) ch -= '\x20';
@@ -83,7 +83,7 @@ bool MatchUpperCase(Accessor &styler, int pos, const char *s)   //Same as styler
     return true;
 }
 
-static void ColourisePBDoc(unsigned int startPos, int length, int initStyle,WordList 
*keywordlists[],Accessor &styler) {
+static void ColourisePBDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,WordList 
*keywordlists[],Accessor &styler) {
 
     WordList &keywords = *keywordlists[0];
 
@@ -185,14 +185,14 @@ static void ColourisePBDoc(unsigned int startPos, int length, int initStyle,Word
 //GFA Basic which is dead now. After testing the feature of toggling FOR-NEXT loops, WHILE-WEND loops
 //and so on too I found this is more disturbing then helping (for me). So if You think in another way
 //you can (or must) write Your own toggling routine ;-)
-static void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldPBDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
     // No folding enabled, no reason to continue...
     if( styler.GetPropertyInt("fold") == 0 )
         return;
 
-    unsigned int endPos = startPos + length;
-    int lineCurrent = styler.GetLine(startPos);
+    Sci_PositionU endPos = startPos + length;
+    Sci_Position lineCurrent = styler.GetLine(startPos);
     int levelCurrent = SC_FOLDLEVELBASE;
     if (lineCurrent > 0)
         levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -202,7 +202,7 @@ static void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Acce
     bool fNewLine=true;
     bool fMightBeMultiLineMacro=false;
     bool fBeginOfCommentFound=false;
-    for (unsigned int i = startPos; i < endPos; i++)
+    for (Sci_PositionU i = startPos; i < endPos; i++)
     {
         char ch = chNext;
         chNext = styler.SafeGetCharAt(i + 1);
@@ -354,7 +354,7 @@ static void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Acce
                 break;
             }
         }  //switch (ch)
-    }  //for (unsigned int i = startPos; i < endPos; i++)
+    }  //for (Sci_PositionU i = startPos; i < endPos; i++)
 }
 
 static const char * const pbWordListDesc[] = {
diff --git a/plugins/scintilla/scintilla/lexers/LexPLM.cxx b/plugins/scintilla/scintilla/lexers/LexPLM.cxx
index 747d158..e306685 100644
--- a/plugins/scintilla/scintilla/lexers/LexPLM.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPLM.cxx
@@ -24,12 +24,12 @@
 using namespace Scintilla;
 #endif
 
-static void GetRange(unsigned int start,
-                     unsigned int end,
+static void GetRange(Sci_PositionU start,
+                     Sci_PositionU end,
                      Accessor &styler,
                      char *s,
-                     unsigned int len) {
-       unsigned int i = 0;
+                     Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                i++;
@@ -37,19 +37,19 @@ static void GetRange(unsigned int start,
        s[i] = '\0';
 }
 
-static void ColourisePlmDoc(unsigned int startPos,
-                            int length,
+static void ColourisePlmDoc(Sci_PositionU startPos,
+                            Sci_Position length,
                             int initStyle,
                             WordList *keywordlists[],
                             Accessor &styler)
 {
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int state = initStyle;
 
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = styler.SafeGetCharAt(i);
                char chNext = styler.SafeGetCharAt(i + 1);
 
@@ -99,7 +99,7 @@ static void ColourisePlmDoc(unsigned int startPos,
                        if (!isdigit(ch) && !isalpha(ch) && ch != '$') {
                                // Get the entire identifier.
                                char word[1024];
-                               int segmentStart = styler.GetStartSegment();
+                               Sci_Position segmentStart = styler.GetStartSegment();
                                GetRange(segmentStart, i - 1, styler, word, sizeof(word));
 
                                i--;
@@ -125,25 +125,25 @@ static void ColourisePlmDoc(unsigned int startPos,
        styler.ColourTo(endPos - 1, state);
 }
 
-static void FoldPlmDoc(unsigned int startPos,
-                       int length,
+static void FoldPlmDoc(Sci_PositionU startPos,
+                       Sci_Position length,
                        int initStyle,
                        WordList *[],
                        Accessor &styler)
 {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       int startKeyword = 0;
+       Sci_Position startKeyword = 0;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexPO.cxx b/plugins/scintilla/scintilla/lexers/LexPO.cxx
index 7b44107..fcf886d 100644
--- a/plugins/scintilla/scintilla/lexers/LexPO.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPO.cxx
@@ -35,13 +35,13 @@
 using namespace Scintilla;
 #endif
 
-static void ColourisePODoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) 
{
+static void ColourisePODoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], 
Accessor &styler) {
        StyleContext sc(startPos, length, initStyle, styler);
        bool escaped = false;
-       int curLine = styler.GetLine(startPos);
+       Sci_Position curLine = styler.GetLine(startPos);
        // the line state holds the last state on or before the line that isn't the default style
        int curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : SCE_PO_DEFAULT;
-       
+
        for (; sc.More(); sc.Forward()) {
                // whether we should leave a state
                switch (sc.state) {
@@ -57,19 +57,19 @@ static void ColourisePODoc(unsigned int startPos, int length, int initStyle, Wor
                                        // on its own like a keyword rather than changing the whole flags 
style
                                        sc.ChangeState(SCE_PO_FUZZY);
                                break;
-                       
+
                        case SCE_PO_MSGCTXT:
                        case SCE_PO_MSGID:
                        case SCE_PO_MSGSTR:
                                if (isspacechar(sc.ch))
                                        sc.SetState(SCE_PO_DEFAULT);
                                break;
-                       
+
                        case SCE_PO_ERROR:
                                if (sc.atLineEnd)
                                        sc.SetState(SCE_PO_DEFAULT);
                                break;
-                       
+
                        case SCE_PO_MSGCTXT_TEXT:
                        case SCE_PO_MSGID_TEXT:
                        case SCE_PO_MSGSTR_TEXT:
@@ -92,7 +92,7 @@ static void ColourisePODoc(unsigned int startPos, int length, int initStyle, Wor
                                }
                                break;
                }
-               
+
                // whether we should enter a new state
                if (sc.state == SCE_PO_DEFAULT) {
                        // forward to the first non-white character on the line
@@ -103,11 +103,11 @@ static void ColourisePODoc(unsigned int startPos, int length, int initStyle, Wor
                                // and anyway the styling don't use line state for comments
                                if (curLineState == SCE_PO_COMMENT)
                                        curLineState = SCE_PO_DEFAULT;
-                               
+
                                while (sc.More() && ! sc.atLineEnd && isspacechar(sc.ch))
                                        sc.Forward();
                        }
-                       
+
                        if (atLineStart && sc.ch == '#') {
                                if (sc.chNext == '.')
                                        sc.SetState(SCE_PO_PROGRAMMER_COMMENT);
@@ -134,11 +134,11 @@ static void ColourisePODoc(unsigned int startPos, int length, int initStyle, Wor
                                        sc.SetState(SCE_PO_ERROR);
                        } else if (! isspacechar(sc.ch))
                                sc.SetState(SCE_PO_ERROR);
-                       
+
                        if (sc.state != SCE_PO_DEFAULT)
                                curLineState = sc.state;
                }
-               
+
                if (sc.atLineEnd) {
                        // Update the line state, so it can be seen by next line
                        curLine = styler.GetLine(sc.currentPos);
@@ -148,9 +148,9 @@ static void ColourisePODoc(unsigned int startPos, int length, int initStyle, Wor
        sc.Complete();
 }
 
-static int FindNextNonEmptyLineState(unsigned int startPos, Accessor &styler) {
-       unsigned int length = styler.Length();
-       for (unsigned int i = startPos; i < length; i++) {
+static int FindNextNonEmptyLineState(Sci_PositionU startPos, Accessor &styler) {
+       Sci_PositionU length = styler.Length();
+       for (Sci_PositionU i = startPos; i < length; i++) {
                if (! isspacechar(styler[i])) {
                        return styler.GetLineState(styler.GetLine(i));
                }
@@ -158,31 +158,31 @@ static int FindNextNonEmptyLineState(unsigned int startPos, Accessor &styler) {
        return 0;
 }
 
-static void FoldPODoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
+static void FoldPODoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
        if (! styler.GetPropertyInt("fold"))
                return;
        bool foldCompact = styler.GetPropertyInt("fold.compact") != 0;
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
-       
-       unsigned int endPos = startPos + length;
-       int curLine = styler.GetLine(startPos);
+
+       Sci_PositionU endPos = startPos + length;
+       Sci_Position curLine = styler.GetLine(startPos);
        int lineState = styler.GetLineState(curLine);
        int nextLineState;
        int level = styler.LevelAt(curLine) & SC_FOLDLEVELNUMBERMASK;
        int nextLevel;
        int visible = 0;
        int chNext = styler[startPos];
-       
-       for (unsigned int i = startPos; i < endPos; i++) {
+
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                int ch = chNext;
                chNext = styler.SafeGetCharAt(i+1);
-               
+
                if (! isspacechar(ch)) {
                        visible++;
                } else if ((ch == '\r' && chNext != '\n') || ch == '\n' || i+1 >= endPos) {
                        int lvl = level;
-                       int nextLine = curLine + 1;
-                       
+                       Sci_Position nextLine = curLine + 1;
+
                        nextLineState = styler.GetLineState(nextLine);
                        if ((lineState != SCE_PO_COMMENT || foldComment) &&
                                        nextLineState == lineState &&
@@ -190,14 +190,14 @@ static void FoldPODoc(unsigned int startPos, int length, int, WordList *[], Acce
                                nextLevel = SC_FOLDLEVELBASE + 1;
                        else
                                nextLevel = SC_FOLDLEVELBASE;
-                       
+
                        if (nextLevel > level)
                                lvl |= SC_FOLDLEVELHEADERFLAG;
                        if (visible == 0 && foldCompact)
                                lvl |= SC_FOLDLEVELWHITEFLAG;
-                       
+
                        styler.SetLevel(curLine, lvl);
-                       
+
                        lineState = nextLineState;
                        curLine = nextLine;
                        level = nextLevel;
diff --git a/plugins/scintilla/scintilla/lexers/LexPOV.cxx b/plugins/scintilla/scintilla/lexers/LexPOV.cxx
index 353fbbe..c467447 100644
--- a/plugins/scintilla/scintilla/lexers/LexPOV.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPOV.cxx
@@ -53,8 +53,8 @@ static inline bool IsANumberChar(int ch) {
 }
 
 static void ColourisePovDoc(
-       unsigned int startPos,
-       int length,
+       Sci_PositionU startPos,
+       Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
     Accessor &styler) {
@@ -68,7 +68,7 @@ static void ColourisePovDoc(
        WordList &keywords7 = *keywordlists[6];
        WordList &keywords8 = *keywordlists[7];
 
-       int currentLine = styler.GetLine(startPos);
+       Sci_Position currentLine = styler.GetLine(startPos);
        // Initialize the block comment /* */ nesting level, if we are inside such a comment.
        int blockCommentLevel = 0;
        if (initStyle == SCE_POV_COMMENT) {
@@ -226,8 +226,8 @@ static void ColourisePovDoc(
 }
 
 static void FoldPovDoc(
-       unsigned int startPos,
-       int length,
+       Sci_PositionU startPos,
+       Sci_Position length,
        int initStyle,
        WordList *[],
        Accessor &styler) {
@@ -235,15 +235,15 @@ static void FoldPovDoc(
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldDirective = styler.GetPropertyInt("fold.directive") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -270,7 +270,7 @@ static void FoldPovDoc(
                }
                if (foldDirective && (style == SCE_POV_DIRECTIVE)) {
                        if (ch == '#') {
-                               unsigned int j=i+1;
+                               Sci_PositionU j=i+1;
                                while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                        j++;
                                }
diff --git a/plugins/scintilla/scintilla/lexers/LexPS.cxx b/plugins/scintilla/scintilla/lexers/LexPS.cxx
index 3661c4b..e4730ca 100644
--- a/plugins/scintilla/scintilla/lexers/LexPS.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPS.cxx
@@ -6,6 +6,12 @@
  ** The License.txt file describes the conditions under which this software may be distributed.
  **/
 
+// Previous releases of this lexer included support for marking token starts with
+// a style byte indicator. This was used by the wxGhostscript IDE/debugger.
+// Style byte indicators were removed in version 3.4.3.
+// Anyone wanting to restore this functionality for wxGhostscript using 'modern'
+// indicators can examine the earlier source in the Mercurial repository.
+
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -58,8 +64,8 @@ static inline bool IsABase85Char(const int ch) {
 }
 
 static void ColourisePSDoc(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int initStyle,
     WordList *keywordlists[],
     Accessor &styler) {
@@ -72,9 +78,8 @@ static void ColourisePSDoc(
 
     StyleContext sc(startPos, length, initStyle, styler);
 
-    bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0;
     int pslevel = styler.GetPropertyInt("ps.level", 3);
-    int lineCurrent = styler.GetLine(startPos);
+    Sci_Position lineCurrent = styler.GetLine(startPos);
     int nestTextCurrent = 0;
     if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
         nestTextCurrent = styler.GetLineState(lineCurrent - 1);
@@ -83,15 +88,6 @@ static void ColourisePSDoc(
     bool numHasExponent = false;
     bool numHasSign = false;
 
-    // Clear out existing tokenization
-    if (tokenizing && length > 0) {
-        styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));
-        styler.ColourTo(startPos + length-1, 0);
-        styler.Flush();
-        styler.StartAt(startPos);
-        styler.StartSegment(startPos);
-    }
-
     for (; sc.More(); sc.Forward()) {
         if (sc.atLineStart)
             lineCurrent = styler.GetLine(sc.currentPos);
@@ -196,7 +192,6 @@ static void ColourisePSDoc(
 
         // Determine if a new state should be entered.
         if (sc.state == SCE_C_DEFAULT) {
-            unsigned int tokenpos = sc.currentPos;
 
             if (sc.ch == '[' || sc.ch == ']') {
                 sc.SetState(SCE_PS_PAREN_ARRAY);
@@ -262,17 +257,6 @@ static void ColourisePSDoc(
             } else if (!IsAWhitespaceChar(sc.ch)) {
                 sc.SetState(SCE_PS_NAME);
             }
-
-            // Mark the start of tokens
-            if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&
-                sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {
-                styler.Flush();
-                styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));
-                styler.ColourTo(tokenpos, INDIC2_MASK);
-                styler.Flush();
-                styler.StartAt(tokenpos);
-                styler.StartSegment(tokenpos);
-            }
         }
 
         if (sc.atLineEnd)
@@ -282,13 +266,13 @@ static void ColourisePSDoc(
     sc.Complete();
 }
 
-static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
+static void FoldPSDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
                        Accessor &styler) {
     bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
     bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-    unsigned int endPos = startPos + length;
+    Sci_PositionU endPos = startPos + length;
     int visibleChars = 0;
-    int lineCurrent = styler.GetLine(startPos);
+    Sci_Position lineCurrent = styler.GetLine(startPos);
     int levelCurrent = SC_FOLDLEVELBASE;
     if (lineCurrent > 0)
         levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -296,11 +280,10 @@ static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
     int levelNext = levelCurrent;
     char chNext = styler[startPos];
     int styleNext = styler.StyleAt(startPos);
-    int style;
-    for (unsigned int i = startPos; i < endPos; i++) {
+    for (Sci_PositionU i = startPos; i < endPos; i++) {
         char ch = chNext;
         chNext = styler.SafeGetCharAt(i + 1);
-        style = styleNext;
+        int style = styleNext;
         styleNext = styler.StyleAt(i + 1);
         bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');  //mac??
         if ((style & 31) == SCE_PS_PAREN_PROC) {
diff --git a/plugins/scintilla/scintilla/lexers/LexPascal.cxx 
b/plugins/scintilla/scintilla/lexers/LexPascal.cxx
index 1e2be23..b7213bb 100644
--- a/plugins/scintilla/scintilla/lexers/LexPascal.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPascal.cxx
@@ -12,7 +12,7 @@
 A few words about features of the new completely rewritten LexPascal...
 
 Generally speaking LexPascal tries to support all available Delphi features (up
-to Delphi 2009 at this time), including .NET specific features.
+to Delphi XE4 at this time).
 
 ~ HIGHLIGHTING:
 
@@ -89,17 +89,18 @@ would be folded.
 ~ KEYWORDS:
 
 The list of keywords that can be used in pascal.properties file (up to Delphi
-2009):
+XE4):
 
 - Keywords: absolute abstract and array as asm assembler automated begin case
-cdecl class const constructor deprecated destructor dispid dispinterface div do
-downto dynamic else end except export exports external far file final
-finalization finally for forward function goto if implementation in inherited
-initialization inline interface is label library message mod near nil not object
-of on or out overload override packed pascal platform private procedure program
-property protected public published raise record register reintroduce repeat
-resourcestring safecall sealed set shl shr static stdcall strict string then
-threadvar to try type unit unsafe until uses var varargs virtual while with xor
+cdecl class const constructor 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 in inherited initialization inline interface is label library
+message mod near nil not object of on operator or out overload override packed
+pascal platform private procedure program property protected public published
+raise record reference register reintroduce repeat resourcestring safecall
+sealed set shl shr static stdcall strict string then threadvar to try type unit
+unsafe until uses var varargs virtual while winapi with xor
 
 - Keywords related to the "smart highlithing" feature: add default implements
 index name nodefault read readonly remove stored write writeonly
@@ -131,12 +132,12 @@ contains requires
 using namespace Scintilla;
 #endif
 
-static void GetRangeLowered(unsigned int start,
-               unsigned int end,
+static void GetRangeLowered(Sci_PositionU start,
+               Sci_PositionU end,
                Accessor &styler,
                char *s,
-               unsigned int len) {
-       unsigned int i = 0;
+               Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                i++;
@@ -144,12 +145,12 @@ static void GetRangeLowered(unsigned int start,
        s[i] = '\0';
 }
 
-static void GetForwardRangeLowered(unsigned int start,
+static void GetForwardRangeLowered(Sci_PositionU start,
                CharacterSet &charSet,
                Accessor &styler,
                char *s,
-               unsigned int len) {
-       unsigned int i = 0;
+               Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < len-1) && charSet.Contains(styler.SafeGetCharAt(start + i))) {
                s[i] = static_cast<char>(tolower(styler.SafeGetCharAt(start + i)));
                i++;
@@ -213,7 +214,7 @@ static void ClassifyPascalWord(WordList *keywordlists[], StyleContext &sc, int &
        sc.SetState(SCE_PAS_DEFAULT);
 }
 
-static void ColourisePascalDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColourisePascalDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                Accessor &styler) {
        bool bSmartHighlighting = styler.GetPropertyInt("lexer.pascal.smart.highlighting", 1) != 0;
 
@@ -223,7 +224,7 @@ static void ColourisePascalDoc(unsigned int startPos, int length, int initStyle,
        CharacterSet setHexNumber(CharacterSet::setDigits, "abcdefABCDEF");
        CharacterSet setOperator(CharacterSet::setNone, "#$&'()*+,-./:;<=>@[]^{}");
 
-       int curLine = styler.GetLine(startPos);
+       Sci_Position curLine = styler.GetLine(startPos);
        int curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : 0;
 
        StyleContext sc(startPos, length, initStyle, styler);
@@ -346,10 +347,10 @@ static bool IsStreamCommentStyle(int style) {
        return style == SCE_PAS_COMMENT || style == SCE_PAS_COMMENT2;
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eolPos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eolPos; i++) {
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eolPos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eolPos; i++) {
                char ch = styler[i];
                char chNext = styler.SafeGetCharAt(i + 1);
                int style = styler.StyleAt(i);
@@ -372,7 +373,7 @@ static void SetFoldInPreprocessorLevelFlag(int &lineFoldStateCurrent, unsigned i
 }
 
 static void ClassifyPascalPreprocessorFoldPoint(int &levelCurrent, int &lineFoldStateCurrent,
-               unsigned int startPos, Accessor &styler) {
+               Sci_PositionU startPos, Accessor &styler) {
        CharacterSet setWord(CharacterSet::setAlpha);
 
        char s[11];     // Size of the longest possible keyword + one additional character + null
@@ -404,10 +405,10 @@ static void ClassifyPascalPreprocessorFoldPoint(int &levelCurrent, int &lineFold
        }
 }
 
-static unsigned int SkipWhiteSpace(unsigned int currentPos, unsigned int endPos,
+static Sci_PositionU SkipWhiteSpace(Sci_PositionU currentPos, Sci_PositionU endPos,
                Accessor &styler, bool includeChars = false) {
        CharacterSet setWord(CharacterSet::setAlphaNum, "_");
-       unsigned int j = currentPos + 1;
+       Sci_PositionU j = currentPos + 1;
        char ch = styler.SafeGetCharAt(j);
        while ((j < endPos) && (IsASpaceOrTab(ch) || ch == '\r' || ch == '\n' ||
                IsStreamCommentStyle(styler.StyleAt(j)) || (includeChars && setWord.Contains(ch)))) {
@@ -418,8 +419,8 @@ static unsigned int SkipWhiteSpace(unsigned int currentPos, unsigned int endPos,
 }
 
 static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCurrent,
-               int startPos, unsigned int endPos,
-               unsigned int lastStart, unsigned int currentPos, Accessor &styler) {
+               Sci_Position startPos, Sci_PositionU endPos,
+               Sci_PositionU lastStart, Sci_PositionU currentPos, Accessor &styler) {
        char s[100];
        GetRangeLowered(lastStart, currentPos, styler, s, sizeof(s));
 
@@ -434,7 +435,7 @@ static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCur
        } else if (strcmp(s, "class") == 0 || strcmp(s, "object") == 0) {
                // "class" & "object" keywords require special handling...
                bool ignoreKeyword = false;
-               unsigned int j = SkipWhiteSpace(currentPos, endPos, styler);
+               Sci_PositionU j = SkipWhiteSpace(currentPos, endPos, styler);
                if (j < endPos) {
                        CharacterSet setWordStart(CharacterSet::setAlpha, "_");
                        CharacterSet setWord(CharacterSet::setAlphaNum, "_");
@@ -475,7 +476,7 @@ static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCur
        } else if (strcmp(s, "interface") == 0) {
                // "interface" keyword requires special handling...
                bool ignoreKeyword = true;
-               int j = lastStart - 1;
+               Sci_Position j = lastStart - 1;
                char ch = styler.SafeGetCharAt(j);
                while ((j >= startPos) && (IsASpaceOrTab(ch) || ch == '\r' || ch == '\n' ||
                        IsStreamCommentStyle(styler.StyleAt(j)))) {
@@ -486,7 +487,7 @@ static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCur
                        ignoreKeyword = false;
                }
                if (!ignoreKeyword) {
-                       unsigned int k = SkipWhiteSpace(currentPos, endPos, styler);
+                       Sci_PositionU k = SkipWhiteSpace(currentPos, endPos, styler);
                        if (k < endPos && styler.SafeGetCharAt(k) == ';') {
                                // Handle forward interface declarations ("type IMyInterface = interface;")
                                ignoreKeyword = true;
@@ -498,7 +499,7 @@ static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCur
        } else if (strcmp(s, "dispinterface") == 0) {
                // "dispinterface" keyword requires special handling...
                bool ignoreKeyword = false;
-               unsigned int j = SkipWhiteSpace(currentPos, endPos, styler);
+               Sci_PositionU j = SkipWhiteSpace(currentPos, endPos, styler);
                if (j < endPos && styler.SafeGetCharAt(j) == ';') {
                        // Handle forward dispinterface declarations ("type IMyInterface = dispinterface;")
                        ignoreKeyword = true;
@@ -515,14 +516,14 @@ static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCur
        }
 }
 
-static void FoldPascalDoc(unsigned int startPos, int length, int initStyle, WordList *[],
+static void FoldPascalDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],
                Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        int lineFoldStateCurrent = lineCurrent > 0 ? styler.GetLineState(lineCurrent - 1) & stateFoldMaskAll 
: 0;
@@ -530,10 +531,10 @@ static void FoldPascalDoc(unsigned int startPos, int length, int initStyle, Word
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
 
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
        CharacterSet setWord(CharacterSet::setAlphaNum, "_", 0x80, true);
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
diff --git a/plugins/scintilla/scintilla/lexers/LexPerl.cxx b/plugins/scintilla/scintilla/lexers/LexPerl.cxx
index de47474..03e3717 100644
--- a/plugins/scintilla/scintilla/lexers/LexPerl.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPerl.cxx
@@ -52,10 +52,10 @@ using namespace Scintilla;
 
 #define HERE_DELIM_MAX 256             // maximum length of HERE doc delimiter
 
-#define PERLNUM_BINARY         1       // order is significant: 1-4 cannot have a dot
-#define PERLNUM_HEX                    2
-#define PERLNUM_OCTAL          3
-#define PERLNUM_FLOAT_EXP      4       // exponent part only
+#define PERLNUM_BINARY         1       // order is significant: 1-3 cannot have a dot
+#define PERLNUM_OCTAL          2
+#define PERLNUM_FLOAT_EXP      3       // exponent part only
+#define PERLNUM_HEX                    4       // may be a hex float
 #define PERLNUM_DECIMAL                5       // 1-5 are numbers; 6-7 are strings
 #define PERLNUM_VECTOR         6
 #define PERLNUM_V_VECTOR       7
@@ -65,23 +65,29 @@ using namespace Scintilla;
 #define BACK_OPERATOR  1       // whitespace/comments are insignificant
 #define BACK_KEYWORD   2       // operators/keywords are needed for disambiguation
 
+#define SUB_BEGIN              0       // states for subroutine prototype scan:
+#define SUB_HAS_PROTO  1       // only 'prototype' attribute allows prototypes
+#define SUB_HAS_ATTRIB 2       // other attributes can exist leftward
+#define SUB_HAS_MODULE 3       // sub name can have a ::identifier part
+#define SUB_HAS_SUB            4       // 'sub' keyword
+
 // all interpolated styles are different from their parent styles by a constant difference
 // we also assume SCE_PL_STRING_VAR is the interpolated style with the smallest value
 #define        INTERPOLATE_SHIFT       (SCE_PL_STRING_VAR - SCE_PL_STRING)
 
-static bool isPerlKeyword(unsigned int start, unsigned int end, WordList &keywords, LexAccessor &styler) {
+static bool isPerlKeyword(Sci_PositionU start, Sci_PositionU end, WordList &keywords, LexAccessor &styler) {
        // old-style keyword matcher; needed because GetCurrent() needs
        // current segment to be committed, but we may abandon early...
        char s[100];
-       unsigned int i, len = end - start;
+       Sci_PositionU i, len = end - start;
        if (len > 30) { len = 30; }
        for (i = 0; i < len; i++, start++) s[i] = styler[start];
        s[i] = '\0';
        return keywords.InList(s);
 }
 
-static int disambiguateBareword(LexAccessor &styler, unsigned int bk, unsigned int fw,
-        int backFlag, unsigned int backPos, unsigned int endPos) {
+static int disambiguateBareword(LexAccessor &styler, Sci_PositionU bk, Sci_PositionU fw,
+        int backFlag, Sci_PositionU backPos, Sci_PositionU endPos) {
        // identifiers are recognized by Perl as barewords under some
        // conditions, the following attempts to do the disambiguation
        // by looking backward and forward; result in 2 LSB
@@ -93,7 +99,7 @@ static int disambiguateBareword(LexAccessor &styler, unsigned int bk, unsigned i
                return result;
        // first look backwards past whitespace/comments to set EOL flag
        // (some disambiguation patterns must be on a single line)
-       if (backPos <= static_cast<unsigned int>(styler.LineStart(styler.GetLine(bk))))
+       if (backPos <= static_cast<Sci_PositionU>(styler.LineStart(styler.GetLine(bk))))
                moreback = true;
        // look backwards at last significant lexed item for disambiguation
        bk = backPos - 1;
@@ -105,9 +111,11 @@ static int disambiguateBareword(LexAccessor &styler, unsigned int bk, unsigned i
                // &bareword: subroutine call
                || styler.Match(bk - 1, "->")
                // ->bareword: part of variable spec
+               || styler.Match(bk - 1, "::")
+               // ::bareword: part of module spec
                || styler.Match(bk - 2, "sub")) {
-               // sub bareword: subroutine declaration
-               // (implied BACK_KEYWORD, no keywords end in 'sub'!)
+               // sub bareword: subroutine declaration
+               // (implied BACK_KEYWORD, no keywords end in 'sub'!)
                result |= 1;
        }
        // next, scan forward after word past tab/spaces only;
@@ -121,14 +129,14 @@ static int disambiguateBareword(LexAccessor &styler, unsigned int bk, unsigned i
                if ((ch == '}' && brace)
                        // {bareword}: variable spec
                        || styler.Match(fw, "=>")) {
-                       // [{(, bareword=>: hash literal
+                       // [{(, bareword=>: hash literal
                        result |= 2;
                }
        }
        return result;
 }
 
-static void skipWhitespaceComment(LexAccessor &styler, unsigned int &p) {
+static void skipWhitespaceComment(LexAccessor &styler, Sci_PositionU &p) {
        // when backtracking, we need to skip whitespace and comments
        int style;
        while ((p > 0) && (style = styler.StyleAt(p),
@@ -136,7 +144,23 @@ static void skipWhitespaceComment(LexAccessor &styler, unsigned int &p) {
                p--;
 }
 
-static int styleBeforeBracePair(LexAccessor &styler, unsigned int bk) {
+static int findPrevLexeme(LexAccessor &styler, Sci_PositionU &bk, int &style) {
+       // scan backward past whitespace and comments to find a lexeme
+       skipWhitespaceComment(styler, bk);
+       if (bk == 0)
+               return 0;
+       int sz = 1;
+       style = styler.StyleAt(bk);
+       while (bk > 0) {        // find extent of lexeme
+               if (styler.StyleAt(bk - 1) == style) {
+                       bk--; sz++;
+               } else
+                       break;
+       }
+       return sz;
+}
+
+static int styleBeforeBracePair(LexAccessor &styler, Sci_PositionU bk) {
        // backtrack to find open '{' corresponding to a '}', balanced
        // return significant style to be tested for '/' disambiguation
        int braceCount = 1;
@@ -163,7 +187,7 @@ static int styleBeforeBracePair(LexAccessor &styler, unsigned int bk) {
        return SCE_PL_DEFAULT;
 }
 
-static int styleCheckIdentifier(LexAccessor &styler, unsigned int bk) {
+static int styleCheckIdentifier(LexAccessor &styler, Sci_PositionU bk) {
        // backtrack to classify sub-styles of identifier under test
        // return sub-style to be tested for '/' disambiguation
        if (styler.SafeGetCharAt(bk) == '>')    // inputsymbol, like <foo>
@@ -188,12 +212,12 @@ static int styleCheckIdentifier(LexAccessor &styler, unsigned int bk) {
        return 0;
 }
 
-static int podLineScan(LexAccessor &styler, unsigned int &pos, unsigned int endPos) {
+static int podLineScan(LexAccessor &styler, Sci_PositionU &pos, Sci_PositionU endPos) {
        // forward scan the current line to classify line for POD style
        int state = -1;
-       while (pos <= endPos) {
+       while (pos < endPos) {
                int ch = static_cast<unsigned char>(styler.SafeGetCharAt(pos));
-               if (ch == '\n' || ch == '\r' || pos >= endPos) {
+               if (ch == '\n' || ch == '\r') {
                        if (ch == '\r' && styler.SafeGetCharAt(pos + 1) == '\n') pos++;
                        break;
                }
@@ -212,22 +236,61 @@ static int podLineScan(LexAccessor &styler, unsigned int &pos, unsigned int endP
        return state;
 }
 
-static bool styleCheckSubPrototype(LexAccessor &styler, unsigned int bk) {
+static bool styleCheckSubPrototype(LexAccessor &styler, Sci_PositionU bk) {
        // backtrack to identify if we're starting a subroutine prototype
-       // we also need to ignore whitespace/comments:
-       // 'sub' [whitespace|comment] <identifier> [whitespace|comment]
+       // we also need to ignore whitespace/comments, format is like:
+       //     sub abc::pqr :const :prototype(...)
+       // lexemes are tested in pairs, e.g. '::'+'pqr', ':'+'const', etc.
+       // and a state machine generates legal subroutine syntax matches
        styler.Flush();
-       skipWhitespaceComment(styler, bk);
-       if (bk == 0 || styler.StyleAt(bk) != SCE_PL_IDENTIFIER) // check identifier
-               return false;
-       while (bk > 0 && (styler.StyleAt(bk) == SCE_PL_IDENTIFIER)) {
-               bk--;
-       }
-       skipWhitespaceComment(styler, bk);
-       if (bk < 2 || styler.StyleAt(bk) != SCE_PL_WORD // check "sub" keyword
-               || !styler.Match(bk - 2, "sub"))        // assume suffix is unique!
-               return false;
-       return true;
+       int state = SUB_BEGIN;
+       do {
+               // find two lexemes, lexeme 2 follows lexeme 1
+               int style2 = SCE_PL_DEFAULT;
+               Sci_PositionU pos2 = bk;
+               int len2 = findPrevLexeme(styler, pos2, style2);
+               int style1 = SCE_PL_DEFAULT;
+               Sci_PositionU pos1 = pos2;
+               if (pos1 > 0) pos1--;
+               int len1 = findPrevLexeme(styler, pos1, style1);
+               if (len1 == 0 || len2 == 0)             // lexeme pair must exist
+                       break;
+
+               // match parts of syntax, if invalid subroutine syntax, break off
+               if (style1 == SCE_PL_OPERATOR && len1 == 1 &&
+                   styler.SafeGetCharAt(pos1) == ':') {        // ':'
+                       if (style2 == SCE_PL_IDENTIFIER || style2 == SCE_PL_WORD) {
+                               if (len2 == 9 && styler.Match(pos2, "prototype")) {     // ':' 'prototype'
+                                       if (state == SUB_BEGIN) {
+                                               state = SUB_HAS_PROTO;
+                                       } else
+                                               break;
+                               } else {        // ':' <attribute>
+                                       if (state == SUB_HAS_PROTO || state == SUB_HAS_ATTRIB) {
+                                               state = SUB_HAS_ATTRIB;
+                                       } else
+                                               break;
+                               }
+                       } else
+                               break;
+               } else if (style1 == SCE_PL_OPERATOR && len1 == 2 &&
+                          styler.Match(pos1, "::")) {  // '::'
+                       if (style2 == SCE_PL_IDENTIFIER) {      // '::' <identifier>
+                               state = SUB_HAS_MODULE;
+                       } else
+                               break;
+               } else if (style1 == SCE_PL_WORD && len1 == 3 &&
+                          styler.Match(pos1, "sub")) { // 'sub'
+                       if (style2 == SCE_PL_IDENTIFIER) {      // 'sub' <identifier>
+                               state = SUB_HAS_SUB;
+                       } else
+                               break;
+               } else
+                       break;
+               bk = pos1;                      // set position for finding next lexeme pair
+               if (bk > 0) bk--;
+       } while (state != SUB_HAS_SUB);
+       return (state == SUB_HAS_SUB);
 }
 
 static int actualNumStyle(int numberStyle) {
@@ -247,10 +310,10 @@ static int opposite(int ch) {
        return ch;
 }
 
-static bool IsCommentLine(int line, LexAccessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eol_pos; i++) {
+static bool IsCommentLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
                char ch = styler[i];
                int style = styler.StyleAt(i);
                if (ch == '#' && style == SCE_PL_COMMENTLINE)
@@ -261,8 +324,8 @@ static bool IsCommentLine(int line, LexAccessor &styler) {
        return false;
 }
 
-static bool IsPackageLine(int line, LexAccessor &styler) {
-       int pos = styler.LineStart(line);
+static bool IsPackageLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
        int style = styler.StyleAt(pos);
        if (style == SCE_PL_WORD && styler.Match(pos, "package")) {
                return true;
@@ -270,7 +333,7 @@ static bool IsPackageLine(int line, LexAccessor &styler) {
        return false;
 }
 
-static int PodHeadingLevel(int pos, LexAccessor &styler) {
+static int PodHeadingLevel(Sci_Position pos, LexAccessor &styler) {
        int lvl = static_cast<unsigned char>(styler.SafeGetCharAt(pos + 5));
        if (lvl >= '1' && lvl <= '4') {
                return lvl - '0';
@@ -352,30 +415,30 @@ public:
        }
        virtual ~LexerPerl() {
        }
-       void SCI_METHOD Release() {
+       void SCI_METHOD Release() override {
                delete this;
        }
-       int SCI_METHOD Version() const {
+       int SCI_METHOD Version() const override {
                return lvOriginal;
        }
-       const char *SCI_METHOD PropertyNames() {
+       const char *SCI_METHOD PropertyNames() override {
                return osPerl.PropertyNames();
        }
-       int SCI_METHOD PropertyType(const char *name) {
+       int SCI_METHOD PropertyType(const char *name) override {
                return osPerl.PropertyType(name);
        }
-       const char *SCI_METHOD DescribeProperty(const char *name) {
+       const char *SCI_METHOD DescribeProperty(const char *name) override {
                return osPerl.DescribeProperty(name);
        }
-       int SCI_METHOD PropertySet(const char *key, const char *val);
-       const char *SCI_METHOD DescribeWordListSets() {
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char *SCI_METHOD DescribeWordListSets() override {
                return osPerl.DescribeWordListSets();
        }
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-       void *SCI_METHOD PrivateCall(int, void *) {
+       void *SCI_METHOD PrivateCall(int, void *) override {
                return 0;
        }
 
@@ -386,21 +449,21 @@ public:
        void InterpolateSegment(StyleContext &sc, int maxSeg, bool isPattern=false);
 };
 
-int SCI_METHOD LexerPerl::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerPerl::PropertySet(const char *key, const char *val) {
        if (osPerl.PropertySet(&options, key, val)) {
                return 0;
        }
        return -1;
 }
 
-int SCI_METHOD LexerPerl::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerPerl::WordListSet(int n, const char *wl) {
        WordList *wordListN = 0;
        switch (n) {
        case 0:
                wordListN = &keywords;
                break;
        }
-       int firstModification = -1;
+       Sci_Position firstModification = -1;
        if (wordListN) {
                WordList wlNew;
                wlNew.Set(wl);
@@ -515,7 +578,7 @@ void LexerPerl::InterpolateSegment(StyleContext &sc, int maxSeg, bool isPattern)
                sc.SetState(sc.state - INTERPOLATE_SHIFT);
 }
 
-void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerPerl::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        LexAccessor styler(pAccess);
 
        // keywords that forces /PATTERN/ at all times; should track vim's behaviour
@@ -537,7 +600,8 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
        CharacterSet &setPOD = setModifiers;
        CharacterSet setNonHereDoc(CharacterSet::setDigits, "=$@");
        CharacterSet setHereDocDelim(CharacterSet::setAlphaNum, "_");
-       CharacterSet setSubPrototype(CharacterSet::setNone, "\\[$@%&*+];");
+       CharacterSet setSubPrototype(CharacterSet::setNone, "\\[$@%&*+];_ \t");
+       CharacterSet setRepetition(CharacterSet::setDigits, ")\"'");
        // for format identifiers
        CharacterSet setFormatStart(CharacterSet::setAlpha, "_=");
        CharacterSet &setFormat = setHereDocDelim;
@@ -555,13 +619,12 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                int Quote;              // the char after '<<'
                bool Quoted;            // true if Quote in ('\'','"','`')
                int DelimiterLength;    // strlen(Delimiter)
-               char *Delimiter;        // the Delimiter, 256: sizeof PL_tokenbuf
+               char Delimiter[HERE_DELIM_MAX]; // the Delimiter
                HereDocCls() {
                        State = 0;
                        Quote = 0;
                        Quoted = false;
                        DelimiterLength = 0;
-                       Delimiter = new char[HERE_DELIM_MAX];
                        Delimiter[0] = '\0';
                }
                void Append(int ch) {
@@ -569,7 +632,6 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                        Delimiter[DelimiterLength] = '\0';
                }
                ~HereDocCls() {
-                       delete []Delimiter;
                }
        };
        HereDocCls HereDoc;             // TODO: FIFO for stacked here-docs
@@ -600,7 +662,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
        int numState = PERLNUM_DECIMAL;
        int dotCount = 0;
 
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
 
        // Backtrack to beginning of style if required...
        // If in a long distance lexical state, backtrack to find quote characters.
@@ -662,8 +724,8 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
        } else if (initStyle == SCE_PL_POD
                || initStyle == SCE_PL_POD_VERB
                  ) {
-               // POD backtracking finds preceeding blank lines and goes back past them
-               int ln = styler.GetLine(startPos);
+               // POD backtracking finds preceding blank lines and goes back past them
+               Sci_Position ln = styler.GetLine(startPos);
                if (ln > 0) {
                        initStyle = styler.StyleAt(styler.LineStart(--ln));
                        if (initStyle == SCE_PL_POD || initStyle == SCE_PL_POD_VERB) {
@@ -682,7 +744,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
        // Look backwards past whitespace and comments in order to detect either
        // operator or keyword. Later updated as we go along.
        int backFlag = BACK_NONE;
-       unsigned int backPos = startPos;
+       Sci_PositionU backPos = startPos;
        if (backPos > 0) {
                backPos--;
                skipWhitespaceComment(styler, backPos);
@@ -693,7 +755,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                backPos++;
        }
 
-       StyleContext sc(startPos, endPos - startPos, initStyle, styler, static_cast<char>(STYLE_MAX));
+       StyleContext sc(startPos, endPos - startPos, initStyle, styler);
 
        for (; sc.More(); sc.Forward()) {
 
@@ -762,6 +824,14 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                                        break;
                                                }
                                                // number then dot (go through)
+                                       } else if (numState == PERLNUM_HEX) {
+                                               if (dotCount <= 1 && IsADigit(sc.chNext, 16)) {
+                                                       break;  // hex with one dot is a hex float
+                                               } else {
+                                                       sc.SetState(SCE_PL_OPERATOR);
+                                                       break;
+                                               }
+                                               // hex then dot (go through)
                                        } else if (IsADigit(sc.chNext)) // vectors
                                                break;
                                        // vector then dot (go through)
@@ -780,8 +850,15 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                        break;
                                // number then word (go through)
                        } else if (numState == PERLNUM_HEX) {
-                               if (IsADigit(sc.ch, 16))
+                               if (sc.ch == 'P' || sc.ch == 'p') {     // hex float exponent, sign
+                                       numState = PERLNUM_FLOAT_EXP;
+                                       if (sc.chNext == '+' || sc.chNext == '-') {
+                                               sc.Forward();
+                                       }
+                                       break;
+                               } else if (IsADigit(sc.ch, 16))
                                        break;
+                               // hex or hex float then word (go through)
                        } else if (numState == PERLNUM_VECTOR || numState == PERLNUM_V_VECTOR) {
                                if (IsADigit(sc.ch))    // vector
                                        break;
@@ -814,7 +891,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                case SCE_PL_HERE_DELIM:
                        if (HereDoc.State == 0) { // '<<' encountered
                                int delim_ch = sc.chNext;
-                               int ws_skip = 0;
+                               Sci_Position ws_skip = 0;
                                HereDoc.State = 1;      // pre-init HERE doc class
                                HereDoc.Quote = sc.chNext;
                                HereDoc.Quoted = false;
@@ -822,7 +899,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0';
                                if (IsASpaceOrTab(delim_ch)) {
                                        // skip whitespace; legal only for quoted delimiters
-                                       unsigned int i = sc.currentPos + 1;
+                                       Sci_PositionU i = sc.currentPos + 1;
                                        while ((i < endPos) && IsASpaceOrTab(delim_ch)) {
                                                i++;
                                                delim_ch = static_cast<unsigned 
char>(styler.SafeGetCharAt(i));
@@ -861,10 +938,14 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                                        sc.Forward();
                                                }
                                                if (sc.ch != '\r') {    // skip CR if CRLF
-                                                       HereDoc.Append(sc.ch);
+                                                       int i = 0;                      // else append char, 
possibly an extended char
+                                                       while (i < sc.width) {
+                                                               HereDoc.Append(static_cast<unsigned 
char>(styler.SafeGetCharAt(sc.currentPos + i)));
+                                                               i++;
+                                                       }
                                                }
                                        }
-                               } else { // an unquoted here-doc delimiter
+                               } else { // an unquoted here-doc delimiter, no extended charsets
                                        if (setHereDocDelim.Contains(sc.ch)) {
                                                HereDoc.Append(sc.ch);
                                        } else {
@@ -885,7 +966,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                        if (HereDoc.DelimiterLength == 0 || sc.Match(HereDoc.Delimiter)) {
                                int c = sc.GetRelative(HereDoc.DelimiterLength);
                                if (c == '\r' || c == '\n') {   // peek first, do not consume match
-                                       sc.Forward(HereDoc.DelimiterLength);
+                                       sc.ForwardBytes(HereDoc.DelimiterLength);
                                        sc.SetState(SCE_PL_DEFAULT);
                                        backFlag = BACK_NONE;
                                        HereDoc.State = 0;
@@ -925,8 +1006,8 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                        break;
                case SCE_PL_POD:
                case SCE_PL_POD_VERB: {
-                               unsigned int fw = sc.currentPos;
-                               int ln = styler.GetLine(fw);
+                               Sci_PositionU fw = sc.currentPos;
+                               Sci_Position ln = styler.GetLine(fw);
                                if (sc.atLineStart && sc.Match("=cut")) {       // end of POD
                                        sc.SetState(SCE_PL_POD);
                                        sc.Forward(4);
@@ -938,8 +1019,8 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                styler.SetLineState(ln, pod);
                                if (pod == SCE_PL_DEFAULT) {
                                        if (sc.state == SCE_PL_POD_VERB) {
-                                               unsigned int fw2 = fw;
-                                               while (fw2 <= endPos && pod == SCE_PL_DEFAULT) {
+                                               Sci_PositionU fw2 = fw;
+                                               while (fw2 < (endPos - 1) && pod == SCE_PL_DEFAULT) {
                                                        fw = fw2++;     // penultimate line (last blank line)
                                                        pod = podLineScan(styler, fw2, endPos);
                                                        styler.SetLineState(styler.GetLine(fw2), pod);
@@ -961,7 +1042,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                        }
                                        sc.SetState(pod);
                                }
-                               sc.Forward(fw - sc.currentPos); // commit style
+                               sc.ForwardBytes(fw - sc.currentPos);    // commit style
                        }
                        break;
                case SCE_PL_REGEX:
@@ -1021,7 +1102,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                                // For '#', if no whitespace in between, it's a delimiter.
                                                if (IsASpace(c)) {
                                                        // Keep going
-                                               } else if (c == '#' && IsASpaceOrTab(sc.GetRelative(sLen - 
1))) {
+                                               } else if (c == '#' && 
IsASpaceOrTab(sc.GetRelativeCharacter(sLen - 1))) {
                                                        endType = 3;
                                                } else
                                                        Quote.Open(c);
@@ -1109,7 +1190,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                while (setSubPrototype.Contains(sc.GetRelative(i)))
                                        i++;
                                if (sc.GetRelative(i) == ')') { // valid sub prototype
-                                       sc.Forward(i);
+                                       sc.ForwardBytes(i);
                                        sc.ForwardSetState(SCE_PL_DEFAULT);
                                } else {
                                        // abandon prototype, restart from '('
@@ -1155,12 +1236,12 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                        sc.ForwardSetState(SCE_PL_DEFAULT);
                                        HereDoc.State = 3;
                                } else {
-                                       // invalid indentifier; inexact fallback, but hey
+                                       // invalid identifier; inexact fallback, but hey
                                        sc.ChangeState(SCE_PL_IDENTIFIER);
                                        sc.SetState(SCE_PL_DEFAULT);
                                }
                        } else {
-                               sc.ChangeState(SCE_PL_DEFAULT); // invalid indentifier
+                               sc.ChangeState(SCE_PL_DEFAULT); // invalid identifier
                        }
                        backFlag = BACK_NONE;
                        break;
@@ -1181,7 +1262,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                }
                                switch (HereDoc.Quote) {
                                case '\'':
-                                       st_new = SCE_PL_HERE_Q ;
+                                       st_new = SCE_PL_HERE_Q;
                                        break;
                                case '"' :
                                        st_new = SCE_PL_HERE_QQ;
@@ -1230,8 +1311,8 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                if (sc.chPrev == ':' && sc.GetRelative(-2) == ':') {
                                        sc.ChangeState(SCE_PL_IDENTIFIER);
                                }
-                               unsigned int bk = sc.currentPos;
-                               unsigned int fw = sc.currentPos + 1;
+                               Sci_PositionU bk = sc.currentPos;
+                               Sci_PositionU fw = sc.currentPos + 1;
                                // first check for possible quote-like delimiter
                                if (sc.ch == 's' && !setWord.Contains(sc.chNext)) {
                                        sc.ChangeState(SCE_PL_REGSUBST);
@@ -1261,7 +1342,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                        fw++;
                                } else if (sc.ch == 'x' && (sc.chNext == '=' || // repetition
                                        !setWord.Contains(sc.chNext) ||
-                                       (IsADigit(sc.chPrev) && IsADigit(sc.chNext)))) {
+                                       (setRepetition.Contains(sc.chPrev) && IsADigit(sc.chNext)))) {
                                        sc.ChangeState(SCE_PL_OPERATOR);
                                }
                                // if potentially a keyword, scan forward and grab word, then check
@@ -1322,7 +1403,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                if (setArray.Contains(sc.chNext)) {
                                        // no special treatment
                                } else if (sc.chNext == ':' && sc.GetRelative(2) == ':') {
-                                       sc.Forward(2);
+                                       sc.ForwardBytes(2);
                                } else if (sc.chNext == '{' || sc.chNext == '[') {
                                        sc.ForwardSetState(SCE_PL_OPERATOR);
                                } else {
@@ -1337,7 +1418,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                bool preferRE = false;
                                bool isHereDoc = sc.Match('<', '<');
                                bool hereDocSpace = false;              // for: SCALAR [whitespace] '<<'
-                               unsigned int bk = (sc.currentPos > 0) ? sc.currentPos - 1: 0;
+                               Sci_PositionU bk = (sc.currentPos > 0) ? sc.currentPos - 1: 0;
                                sc.Complete();
                                styler.Flush();
                                if (styler.StyleAt(bk) == SCE_PL_DEFAULT)
@@ -1406,7 +1487,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                                        // keywords always forced as /PATTERN/: split, if, 
elsif, while
                                                        // everything else /PATTERN/ unless digit/space 
immediately after '/'
                                                        // for '//', defined-or favoured unless special 
keywords
-                                                       unsigned int bkend = bk + 1;
+                                                       Sci_PositionU bkend = bk + 1;
                                                        while (bk > 0 && styler.StyleAt(bk - 1) == 
SCE_PL_WORD) {
                                                                bk--;
                                                        }
@@ -1434,7 +1515,10 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                }
                                backFlag = BACK_NONE;
                                if (isHereDoc) {        // handle '<<', HERE doc
-                                       if (preferRE) {
+                                       if (sc.Match("<<>>")) {         // double-diamond operator (5.22)
+                                               sc.SetState(SCE_PL_OPERATOR);
+                                               sc.Forward(3);
+                                       } else if (preferRE) {
                                                sc.SetState(SCE_PL_HERE_DELIM);
                                                HereDoc.State = 0;
                                        } else {                // << operator
@@ -1445,7 +1529,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                        if (preferRE) {
                                                sc.SetState(SCE_PL_SYMBOLTABLE);
                                                if (sc.chNext == ':' && sc.GetRelative(2) == ':') {
-                                                       sc.Forward(2);
+                                                       sc.ForwardBytes(2);
                                                } else if (sc.chNext == '{') {
                                                        sc.ForwardSetState(SCE_PL_OPERATOR);
                                                } else {
@@ -1462,7 +1546,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                                if (setHash.Contains(sc.chNext)) {
                                                        sc.Forward();
                                                } else if (sc.chNext == ':' && sc.GetRelative(2) == ':') {
-                                                       sc.Forward(2);
+                                                       sc.ForwardBytes(2);
                                                } else if (sc.chNext == '{') {
                                                        sc.ForwardSetState(SCE_PL_OPERATOR);
                                                } else {
@@ -1502,8 +1586,8 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
                                sc.SetState(SCE_PL_POD);
                                backFlag = BACK_NONE;
                        } else if (sc.ch == '-' && setWordStart.Contains(sc.chNext)) {  // extended '-' cases
-                               unsigned int bk = sc.currentPos;
-                               unsigned int fw = 2;
+                               Sci_PositionU bk = sc.currentPos;
+                               Sci_PositionU fw = 2;
                                if (setSingleCharOp.Contains(sc.chNext) &&      // file test operators
                                        !setWord.Contains(sc.GetRelative(2))) {
                                        sc.SetState(SCE_PL_WORD);
@@ -1553,16 +1637,16 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
 #define PERL_HEADFOLD_SHIFT            4
 #define PERL_HEADFOLD_MASK             0xF0
 
-void SCI_METHOD LexerPerl::Fold(unsigned int startPos, int length, int /* initStyle */, IDocument *pAccess) {
+void SCI_METHOD LexerPerl::Fold(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, IDocument 
*pAccess) {
 
        if (!options.fold)
                return;
 
        LexAccessor styler(pAccess);
 
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
 
        // Backtrack to previous line in case need to fix its fold status
        if (startPos > 0) {
@@ -1582,7 +1666,7 @@ void SCI_METHOD LexerPerl::Fold(unsigned int startPos, int length, int /* initSt
        // Used at end of line to determine if the line was a package definition
        bool isPackageLine = false;
        int podHeading = 0;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
@@ -1626,7 +1710,7 @@ void SCI_METHOD LexerPerl::Fold(unsigned int startPos, int length, int /* initSt
                                else if (styler.Match(i, "=head"))
                                        podHeading = PodHeadingLevel(i, styler);
                        } else if (style == SCE_PL_DATASECTION) {
-                               if (ch == '=' && isascii(chNext) && isalpha(chNext) && levelCurrent == 
SC_FOLDLEVELBASE)
+                               if (ch == '=' && IsASCII(chNext) && isalpha(chNext) && levelCurrent == 
SC_FOLDLEVELBASE)
                                        levelCurrent++;
                                else if (styler.Match(i, "=cut") && levelCurrent > SC_FOLDLEVELBASE)
                                        levelCurrent = (levelCurrent & ~PERL_HEADFOLD_MASK) - 1;
@@ -1722,4 +1806,4 @@ void SCI_METHOD LexerPerl::Fold(unsigned int startPos, int length, int /* initSt
        styler.SetLevel(lineCurrent, levelPrev | flagsNext);
 }
 
-LexerModule lmPerl(SCLEX_PERL, LexerPerl::LexerFactoryPerl, "perl", perlWordListDesc, 8);
+LexerModule lmPerl(SCLEX_PERL, LexerPerl::LexerFactoryPerl, "perl", perlWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexPowerPro.cxx 
b/plugins/scintilla/scintilla/lexers/LexPowerPro.cxx
index e8a7a66..7120c40 100644
--- a/plugins/scintilla/scintilla/lexers/LexPowerPro.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPowerPro.cxx
@@ -57,10 +57,10 @@ static inline bool IsLineEndChar(unsigned char ch) {
                        || ch == 0x0d;  //CR
 }
 
-static bool IsContinuationLine(unsigned int szLine, Accessor &styler)
+static bool IsContinuationLine(Sci_PositionU szLine, Accessor &styler)
 {
-       int startPos = styler.LineStart(szLine);
-       int endPos = styler.LineStart(szLine + 1) - 2;
+       Sci_Position startPos = styler.LineStart(szLine);
+       Sci_Position endPos = styler.LineStart(szLine + 1) - 2;
        while (startPos < endPos)
        {
                char stylech = styler.StyleAt(startPos);
@@ -78,10 +78,10 @@ static bool IsContinuationLine(unsigned int szLine, Accessor &styler)
 
 // Routine to find first none space on the current line and return its Style
 // needed for comment lines not starting on pos 1
-static int GetStyleFirstWord(int szLine, Accessor &styler)
+static int GetStyleFirstWord(Sci_Position szLine, Accessor &styler)
 {
-       int startPos = styler.LineStart(szLine);
-       int endPos = styler.LineStart(szLine + 1) - 1;
+       Sci_Position startPos = styler.LineStart(szLine);
+       Sci_Position endPos = styler.LineStart(szLine + 1) - 1;
        char ch = styler.SafeGetCharAt(startPos);
 
        while (ch > 0 && isspacechar(ch) && startPos < endPos)
@@ -97,15 +97,15 @@ static int GetStyleFirstWord(int szLine, Accessor &styler)
 //note:
 //             sample line (without quotes): "\tfunction asdf()
 //             currentPos will be the position of 'a'
-static bool IsFunction(Accessor &styler, unsigned int currentPos) {
+static bool IsFunction(Accessor &styler, Sci_PositionU currentPos) {
 
        const char function[10] = "function "; //10 includes \0
        unsigned int numberOfCharacters = sizeof(function) - 1;
-       unsigned int position = currentPos - numberOfCharacters;
+       Sci_PositionU position = currentPos - numberOfCharacters;
 
        //compare each character with the letters in the function array
        //return false if ALL don't match
-       for (unsigned int i = 0; i < numberOfCharacters; i++) {
+       for (Sci_PositionU i = 0; i < numberOfCharacters; i++) {
                char c = styler.SafeGetCharAt(position++);
                if (c != function[i])
                        return false;
@@ -114,7 +114,7 @@ static bool IsFunction(Accessor &styler, unsigned int currentPos) {
        //make sure that there are only spaces (or tabs) between the beginning
        //of the line and the function declaration
        position = currentPos - numberOfCharacters - 1;                 //-1 to move to char before 'function'
-       for (unsigned int j = 0; j < 16; j++) {                                 //check up to 16 preceeding 
characters
+       for (Sci_PositionU j = 0; j < 16; j++) {                                        //check up to 16 
preceeding characters
                char c = styler.SafeGetCharAt(position--, '\0');        //if can't read char, return NUL 
(past beginning of document)
                if (c <= 0)     //reached beginning of document
                        return true;
@@ -128,7 +128,7 @@ static bool IsFunction(Accessor &styler, unsigned int currentPos) {
        return false;
 }
 
-static void ColourisePowerProDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColourisePowerProDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler, bool caseSensitive) {
 
        WordList &keywords  = *keywordlists[0];
@@ -360,7 +360,7 @@ static void ColourisePowerProDoc(unsigned int startPos, int length, int initStyl
        sc.Complete();
 }
 
-static void FoldPowerProDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldPowerProDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
        //define the character sets
        CharacterSet setWordStart(CharacterSet::setAlpha, "_@", 0x80, true);
@@ -369,8 +369,8 @@ static void FoldPowerProDoc(unsigned int startPos, int length, int, WordList *[]
        //used to tell if we're recursively folding the whole document, or just a small piece (ie: if 
statement or 1 function)
        bool isFoldingAll = true;
 
-       int endPos = startPos + length;
-       int lastLine = styler.GetLine(styler.Length()); //used to help fold the last line correctly
+       Sci_Position endPos = startPos + length;
+       Sci_Position lastLine = styler.GetLine(styler.Length()); //used to help fold the last line correctly
 
        // get settings from the config files for folding comments and preprocessor lines
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
@@ -378,7 +378,7 @@ static void FoldPowerProDoc(unsigned int startPos, int length, int, WordList *[]
        bool foldCompact = true;
 
        // Backtrack to previous line in case need to fix its fold status
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0) {
                isFoldingAll = false;
                if (lineCurrent > 0) {
@@ -427,7 +427,7 @@ static void FoldPowerProDoc(unsigned int startPos, int length, int, WordList *[]
        char chPrevPrev = '\0';
        char chPrevPrevPrev = '\0';
 
-       for (int i = startPos; i < endPos; i++) {
+       for (Sci_Position i = startPos; i < endPos; i++) {
 
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
@@ -620,7 +620,7 @@ static const char * const powerProWordLists[] = {
             0,
         };
 
-static void ColourisePowerProDocWrapper(unsigned int startPos, int length, int initStyle, WordList 
*keywordlists[],
+static void ColourisePowerProDocWrapper(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                                        Accessor &styler) {
        ColourisePowerProDoc(startPos, length, initStyle, keywordlists, styler, false);
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexPowerShell.cxx 
b/plugins/scintilla/scintilla/lexers/LexPowerShell.cxx
index 1b568c0..0b744c4 100644
--- a/plugins/scintilla/scintilla/lexers/LexPowerShell.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPowerShell.cxx
@@ -32,8 +32,8 @@ static inline bool IsAWordChar(int ch) {
        return ch >= 0x80 || isalnum(ch) || ch == '-' || ch == '_';
 }
 
-static void ColourisePowerShellDoc(unsigned int startPos, int length, int initStyle,
-                           WordList *keywordlists[], Accessor &styler) {
+static void ColourisePowerShellDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+                                  WordList *keywordlists[], Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
        WordList &keywords2 = *keywordlists[1];
@@ -53,8 +53,8 @@ static void ColourisePowerShellDoc(unsigned int startPos, int length, int initSt
                                sc.SetState(SCE_POWERSHELL_DEFAULT);
                        }
                } else if (sc.state == SCE_POWERSHELL_COMMENTSTREAM) {
-                       if(sc.atLineStart) {
-                               while(IsASpaceOrTab(sc.ch)) {
+                       if (sc.atLineStart) {
+                               while (IsASpaceOrTab(sc.ch)) {
                                        sc.Forward();
                                }
                                if (sc.ch == '.' && IsAWordChar(sc.chNext)) {
@@ -65,7 +65,7 @@ static void ColourisePowerShellDoc(unsigned int startPos, int length, int initSt
                                sc.ForwardSetState(SCE_POWERSHELL_DEFAULT);
                        }
                } else if (sc.state == SCE_POWERSHELL_COMMENTDOCKEYWORD) {
-                       if(!IsAWordChar(sc.ch)) {
+                       if (!IsAWordChar(sc.ch)) {
                                char s[100];
                                sc.GetCurrentLowered(s, sizeof(s));
                                if (!keywords6.InList(s + 1)) {
@@ -77,11 +77,15 @@ static void ColourisePowerShellDoc(unsigned int startPos, int length, int initSt
                        // This is a doubles quotes string
                        if (sc.ch == '\"') {
                                sc.ForwardSetState(SCE_POWERSHELL_DEFAULT);
+                       } else if (sc.ch == '`') {
+                               sc.Forward(); // skip next escaped character
                        }
                } else if (sc.state == SCE_POWERSHELL_CHARACTER) {
                        // This is a single quote string
                        if (sc.ch == '\'') {
                                sc.ForwardSetState(SCE_POWERSHELL_DEFAULT);
+                       } else if (sc.ch == '`') {
+                               sc.Forward(); // skip next escaped character
                        }
                } else if (sc.state == SCE_POWERSHELL_HERE_STRING) {
                        // This is a doubles quotes here-string
@@ -149,6 +153,8 @@ static void ColourisePowerShellDoc(unsigned int startPos, int length, int initSt
                                sc.SetState(SCE_POWERSHELL_OPERATOR);
                        } else if (IsAWordChar(sc.ch)) {
                                sc.SetState(SCE_POWERSHELL_IDENTIFIER);
+                       } else if (sc.ch == '`') {
+                               sc.Forward(); // skip next escaped character
                        }
                }
        }
@@ -158,14 +164,14 @@ static void ColourisePowerShellDoc(unsigned int startPos, int length, int initSt
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
-static void FoldPowerShellDoc(unsigned int startPos, int length, int initStyle,
-                           WordList *[], Accessor &styler) {
+static void FoldPowerShellDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+                             WordList *[], Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -174,7 +180,7 @@ static void FoldPowerShellDoc(unsigned int startPos, int length, int initStyle,
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -200,7 +206,7 @@ static void FoldPowerShellDoc(unsigned int startPos, int length, int initStyle,
                        }
                } else if (foldComment && style == SCE_POWERSHELL_COMMENT) {
                        if (ch == '#') {
-                               unsigned int j = i + 1;
+                               Sci_PositionU j = i + 1;
                                while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                        j++;
                                }
@@ -234,7 +240,7 @@ static void FoldPowerShellDoc(unsigned int startPos, int length, int initStyle,
        }
 }
 
-static const char * const powershellWordLists[] = {
+static const char *const powershellWordLists[] = {
        "Commands",
        "Cmdlets",
        "Aliases",
diff --git a/plugins/scintilla/scintilla/lexers/LexProgress.cxx 
b/plugins/scintilla/scintilla/lexers/LexProgress.cxx
index 2031720..aaa3d4b 100644
--- a/plugins/scintilla/scintilla/lexers/LexProgress.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexProgress.cxx
@@ -3,14 +3,18 @@
  **  Lexer for Progress 4GL.
  ** Based on LexCPP.cxx of Neil Hodgson <neilh scintilla org>
   **/
-// Copyright 2006-2007 by Yuval Papish <Yuval YuvCom com>
+// Copyright 2006-2016 by Yuval Papish <Yuval YuvCom com>
 // The License.txt file describes the conditions under which this software may be distributed.
 
 /** TODO:
-WebSpeed support in html lexer
-Support "end triggers" expression of the triggers phrase
-Support more than 6 comments levels
+
+SpeedScript support in html lexer
+Differentiate between labels and variables
+  Option 1: By symbols table
+  Option 2: As a single unidentified symbol in a sytactical line 
+
 **/
+
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -18,265 +22,544 @@ Support more than 6 comments levels
 #include <assert.h>
 #include <ctype.h>
 
+#include <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+
 #include "ILexer.h"
 #include "Scintilla.h"
 #include "SciLexer.h"
 
 #include "WordList.h"
 #include "LexAccessor.h"
-#include "Accessor.h"
 #include "StyleContext.h"
 #include "CharacterSet.h"
 #include "LexerModule.h"
+#include "OptionSet.h"
+#include "SparseState.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
-static inline bool IsAWordChar(int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '_');
+namespace {
+   // Use an unnamed namespace to protect the functions and classes from name conflicts
+
+   bool IsSpaceEquiv(int state) {
+      return (state == SCE_ABL_COMMENT ||
+              state == SCE_ABL_LINECOMMENT ||
+              state == SCE_ABL_DEFAULT);
+   }
+
+   void highlightTaskMarker(StyleContext &sc, LexAccessor &styler, WordList &markerList){
+      if ((isoperator(sc.chPrev) || IsASpace(sc.chPrev)) && markerList.Length()) {
+         const int lengthMarker = 50;
+         char marker[lengthMarker+1];
+         Sci_Position currPos = (Sci_Position) sc.currentPos;
+         Sci_Position i = 0;
+         while (i < lengthMarker) {
+            char ch = styler.SafeGetCharAt(currPos + i);
+            if (IsASpace(ch) || isoperator(ch)) {
+               break;
+            }
+            marker[i] = ch;
+            i++;
+         }
+         marker[i] = '\0';
+         if (markerList.InListAbbreviated (marker,'(')) {
+            sc.SetState(SCE_ABL_TASKMARKER);
+         }
+      }
+   }
+
+   bool IsStreamCommentStyle(int style) {
+      return style == SCE_ABL_COMMENT;
+             // style == SCE_ABL_LINECOMMENT;  Only block comments are used for folding 
+   }
+
+   // Options used for LexerABL
+   struct OptionsABL {
+      bool fold;
+      bool foldSyntaxBased;
+      bool foldComment;
+      bool foldCommentMultiline;
+      bool foldCompact;
+      OptionsABL() {
+         fold = false;
+         foldSyntaxBased = true;
+         foldComment = true;
+         foldCommentMultiline = true;
+         foldCompact = false;
+      }
+   };
+
+   const char *const ablWordLists[] = {
+               "Primary keywords and identifiers",
+               "Keywords that opens a block, only when used to begin a syntactic line",
+               "Keywords that opens a block anywhere in a syntactic line",
+               "Task Marker", /* "END MODIFY START TODO" */
+               0,
+   };
+
+   struct OptionSetABL : public OptionSet<OptionsABL> {
+      OptionSetABL() {
+         DefineProperty("fold", &OptionsABL::fold);
+
+         DefineProperty("fold.abl.syntax.based", &OptionsABL::foldSyntaxBased,
+            "Set this property to 0 to disable syntax based folding.");
+
+         DefineProperty("fold.comment", &OptionsABL::foldComment,
+            "This option enables folding multi-line comments and explicit fold points when using the ABL 
lexer. ");
+
+         DefineProperty("fold.abl.comment.multiline", &OptionsABL::foldCommentMultiline,
+            "Set this property to 0 to disable folding multi-line comments when fold.comment=1.");
+
+         DefineProperty("fold.compact", &OptionsABL::foldCompact);
+
+         DefineWordListSets(ablWordLists);
+      }
+   };
 }
 
-static inline bool IsAWordStart(int ch) {
-       return (ch < 0x80) && (isalpha(ch) || ch == '_');
+class LexerABL : public ILexer {
+   CharacterSet setWord;
+   CharacterSet setNegationOp;
+   CharacterSet setArithmethicOp;
+   CharacterSet setRelOp;
+   CharacterSet setLogicalOp;
+   CharacterSet setWordStart;
+   WordList keywords1;      // regular keywords
+   WordList keywords2;      // block opening keywords, only when isSentenceStart
+   WordList keywords3;      // block opening keywords
+   WordList keywords4;      // Task Marker
+   OptionsABL options;
+   OptionSetABL osABL;
+public:
+   LexerABL() :
+      setWord(CharacterSet::setAlphaNum, "_", 0x80, true),
+      setNegationOp(CharacterSet::setNone, "!"),
+      setArithmethicOp(CharacterSet::setNone, "+-/*%"),
+      setRelOp(CharacterSet::setNone, "=!<>"),
+      setLogicalOp(CharacterSet::setNone, "|&"){
+   }
+   virtual ~LexerABL() {
+   }
+   void SCI_METHOD Release() override {
+      delete this;
+   }
+   int SCI_METHOD Version() const override {
+      return lvOriginal;
+   }
+   const char * SCI_METHOD PropertyNames() override {
+      return osABL.PropertyNames();
+   }
+   int SCI_METHOD PropertyType(const char *name) override {
+      return osABL.PropertyType(name);
+   }
+   const char * SCI_METHOD DescribeProperty(const char *name) override {
+      return osABL.DescribeProperty(name);
+   }
+   Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override ;
+   
+   const char * SCI_METHOD DescribeWordListSets() override {
+      return osABL.DescribeWordListSets();
+   }
+   Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+   void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+   void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+
+   void * SCI_METHOD PrivateCall(int, void *) override {
+      return 0;
+   }
+   int SCI_METHOD LineEndTypesSupported() {
+      return SC_LINE_END_TYPE_DEFAULT;
+   }
+   static ILexer *LexerFactoryABL() {
+      return new LexerABL();
+   }
+};
+
+Sci_Position SCI_METHOD LexerABL::PropertySet(const char *key, const char *val) {
+   if (osABL.PropertySet(&options, key, val)) {
+      return 0;
+   }
+   return -1;
 }
 
-enum SentenceStart { SetSentenceStart = 0xf, ResetSentenceStart = 0x10}; // true -> bit = 0
-
-static void Colourise4glDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
-                            Accessor &styler) {
-
-    WordList &keywords1 = *keywordlists[0];   // regular keywords
-    WordList &keywords2 = *keywordlists[1];   // block opening keywords, only when SentenceStart
-    WordList &keywords3 = *keywordlists[2];   // block opening keywords
-    //WordList &keywords4 = *keywordlists[3]; // preprocessor keywords. Not implemented
-
-
-       int visibleChars = 0;
-       int mask;
-
-       StyleContext sc(startPos, length, initStyle, styler);
-
-       for (; sc.More(); sc.Forward()) {
-
-               if (sc.atLineStart) {
-                       // Reset states to begining of colourise so no surprises
-                       // if different sets of lines lexed.
-                       visibleChars = 0;
-               }
-
-               // Handle line continuation generically.
-               if ((sc.state & 0xf) < SCE_4GL_COMMENT1) {
-               if (sc.ch == '~') {
-                       if (sc.chNext > ' ') {
-                               // skip special char after ~
-                               sc.Forward();
-                               continue;
-                       }
-                       else {
-                               // Skip whitespace between ~ and EOL
-                               while (sc.More() && (sc.chNext == ' ' || sc.chNext == '\t') ) {
-                                       sc.Forward();
-                               }
-                               if (sc.chNext == '\n' || sc.chNext == '\r') {
-                                       sc.Forward();
-                                       if (sc.ch == '\r' && sc.chNext == '\n') {
-                                               sc.Forward();
-                                       }
-                                       sc.Forward();
-                                       continue;
-                               }
-                       }
-               }
-               }
-               // Determine if a new state should be terminated.
-               mask = sc.state & 0x10;
-               switch (sc.state & 0xf) {
-                       case SCE_4GL_OPERATOR:
-                               sc.SetState(SCE_4GL_DEFAULT | mask);
-                               break;
-                       case SCE_4GL_NUMBER:
-                               if (!(IsADigit(sc.ch))) {
-                                       sc.SetState(SCE_4GL_DEFAULT | mask);
-                               }
-                               break;
-                       case SCE_4GL_IDENTIFIER:
-                               if (!IsAWordChar(sc.ch) && sc.ch != '-') {
-                                       char s[1000];
-                                       sc.GetCurrentLowered(s, sizeof(s));
-                                       if ((((sc.state & 0x10) == 0) && keywords2.InList(s)) || 
keywords3.InList(s)) {
-                                               sc.ChangeState(SCE_4GL_BLOCK | ResetSentenceStart);
-                                       }
-                                       else if (keywords1.InList(s)) {
-                                               if ((s[0] == 'e' && s[1] =='n' && s[2] == 'd' && 
!isalnum(s[3]) && s[3] != '-') ||
-                                                       (s[0] == 'f' && s[1] =='o' && s[2] == 'r' && s[3] == 
'w' && s[4] =='a' && s[5] == 'r' && s[6] == 'd'&& !isalnum(s[7]))) {
-                                                       sc.ChangeState(SCE_4GL_END | ResetSentenceStart);
-                                               }
-                                               else if ((s[0] == 'e' && s[1] =='l' && s[2] == 's' && s[3] == 
'e') ||
-                                                                (s[0] == 't' && s[1] =='h' && s[2] == 'e' && 
s[3] == 'n')) {
-                                                       sc.ChangeState(SCE_4GL_WORD & SetSentenceStart);
-                                               }
-                                               else {
-                                                       sc.ChangeState(SCE_4GL_WORD | ResetSentenceStart);
-                                               }
-                                       }
-                                       sc.SetState(SCE_4GL_DEFAULT | (sc.state & 0x10));
-                               }
-                               break;
-                       case SCE_4GL_PREPROCESSOR:
-                               if (sc.atLineStart) {
-                                       sc.SetState(SCE_4GL_DEFAULT & SetSentenceStart);
-                               }
-                               /* code removed to allow comments inside preprocessor
-                                       else if (sc.ch == '*' && sc.chNext == '/') {
-                                       sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState); } */
-                               break;
-                       case SCE_4GL_STRING:
-                               if (sc.ch == '\"') {
-                                       sc.ForwardSetState(SCE_4GL_DEFAULT | mask);
-                               }
-                               break;
-                       case SCE_4GL_CHARACTER:
-                               if (sc.ch == '\'') {
-                                       sc.ForwardSetState(SCE_4GL_DEFAULT | mask);
-                               }
-                               break;
-                       default:
-                               if ((sc.state & 0xf) >= SCE_4GL_COMMENT1) {
-                                       if (sc.ch == '*' && sc.chNext == '/') {
-                                               sc.Forward();
-                                               if ((sc.state & 0xf) == SCE_4GL_COMMENT1) {
-                                                       sc.ForwardSetState(SCE_4GL_DEFAULT | mask);
-                                               }
-                                               else
-                                                       sc.SetState((sc.state & 0x1f) - 1);
-                                       } else if (sc.ch == '/' && sc.chNext == '*') {
-                                               sc.Forward();
-                                               sc.SetState((sc.state & 0x1f) + 1);
-                                       }
-                               }
-               }
-
-               // Determine if a new state should be entered.
-               mask = sc.state & 0x10;
-               if ((sc.state & 0xf) == SCE_4GL_DEFAULT) {
-                       if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
-                               sc.SetState(SCE_4GL_NUMBER | ResetSentenceStart);
-                       } else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
-                               sc.SetState(SCE_4GL_IDENTIFIER | mask);
-                       } else if (sc.ch == '/' && sc.chNext == '*') {
-                               sc.SetState(SCE_4GL_COMMENT1 | mask);
-                               sc.Forward();
-                       } else if (sc.ch == '\"') {
-                               sc.SetState(SCE_4GL_STRING | ResetSentenceStart);
-                       } else if (sc.ch == '\'') {
-                               sc.SetState(SCE_4GL_CHARACTER | ResetSentenceStart);
-                       } else if (sc.ch == '&' && visibleChars == 0 && ((sc.state & 0x10) == 0)) {
-                               sc.SetState(SCE_4GL_PREPROCESSOR | ResetSentenceStart);
-                               // Skip whitespace between & and preprocessor word
-                               do {
-                                       sc.Forward();
-                               } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
-                       // Handle syntactical line termination
-                       } else if ((sc.ch == '.' || sc.ch == ':' || sc.ch == '}') && (sc.chNext == ' ' || 
sc.chNext == '\t' || sc.chNext == '\n' || sc.chNext == '\r')) {
-                               sc.SetState(sc.state & SetSentenceStart);
-                       } else if (isoperator(static_cast<char>(sc.ch))) {
-               /*      This code allows highlight of handles. Alas, it would cause the phrase 
"last-event:function"
-                       to be recognized as a BlockBegin */
-
-                               if (sc.ch == ':')
-                                       sc.SetState(SCE_4GL_OPERATOR & SetSentenceStart);
-                               /* else */
-                                       sc.SetState(SCE_4GL_OPERATOR | ResetSentenceStart);
-                       }
-               }
-
-               if (!IsASpace(sc.ch)) {
-                       visibleChars++;
-               }
-       }
-       sc.Complete();
+Sci_Position SCI_METHOD LexerABL::WordListSet(int n, const char *wl) {
+   WordList *wordListN = 0;
+   switch (n) {
+   case 0:
+      wordListN = &keywords1;
+      break;
+   case 1:
+      wordListN = &keywords2;
+      break;
+   case 2:
+      wordListN = &keywords3;
+      break;
+   case 3:
+      wordListN = &keywords4;
+      break;
+   }
+   Sci_Position firstModification = -1;
+   if (wordListN) {
+      WordList wlNew;
+      wlNew.Set(wl);
+      if (*wordListN != wlNew) {
+         wordListN->Set(wl);
+         firstModification = 0;
+      }
+   }
+   return firstModification;
 }
 
-static bool IsStreamCommentStyle(int style) {
-       return (style & 0xf) >= SCE_4GL_COMMENT1 ;
+void SCI_METHOD LexerABL::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
+   LexAccessor styler(pAccess);
+
+   setWordStart = CharacterSet(CharacterSet::setAlpha, "_", 0x80, true);
+
+   int visibleChars = 0;
+   int visibleChars1 = 0;
+   int styleBeforeTaskMarker = SCE_ABL_DEFAULT;
+   bool continuationLine = false;
+   int commentNestingLevel = 0;
+   bool isSentenceStart = true;
+   bool possibleOOLChange = false;
+
+   Sci_Position lineCurrent = styler.GetLine(startPos);
+   if (initStyle == SCE_ABL_PREPROCESSOR) {
+      // Set continuationLine if last character of previous line is '~'
+      if (lineCurrent > 0) {
+         Sci_Position endLinePrevious = styler.LineEnd(lineCurrent-1);
+         if (endLinePrevious > 0) {
+            continuationLine = styler.SafeGetCharAt(endLinePrevious-1) == '~';
+         }
+      }
+   } 
+
+    // Look back to set variables that are actually invisible secondary states. The reason to avoid formal 
states is to cut down on state's bits
+   if (startPos > 0) {
+      Sci_Position back = startPos;
+      bool checkCommentNestingLevel = (initStyle == SCE_ABL_COMMENT);
+      bool checkIsSentenceStart = (initStyle == SCE_ABL_DEFAULT || initStyle == SCE_ABL_IDENTIFIER);
+      char ch;
+      char st;
+      char chPrev;
+      char chPrev_1;
+      char chPrev_2;
+      char chPrev_3;
+
+      while (back >= 0 && (checkCommentNestingLevel || checkIsSentenceStart)) {
+         ch = styler.SafeGetCharAt(back);
+         styler.Flush();  // looking at styles so need to flush
+         st = styler.StyleAt(back);
+         
+         chPrev = styler.SafeGetCharAt(back-1);
+         // isSentenceStart is a non-visible state, used to identify where statements and preprocessor 
declerations can start 
+         if (checkIsSentenceStart && st != SCE_ABL_COMMENT && st != SCE_ABL_LINECOMMENT && st != 
SCE_ABL_CHARACTER  && st != SCE_ABL_STRING ) {
+            chPrev_1 = styler.SafeGetCharAt(back-2);
+            chPrev_2 = styler.SafeGetCharAt(back-3);
+            chPrev_3 = styler.SafeGetCharAt(back-4);
+            if ((chPrev == '.' || chPrev == ':' || chPrev == '}' ||
+               (chPrev_3 == 'e' && chPrev_2 == 'l' && chPrev_1 == 's' &&  chPrev == 'e') ||
+               (chPrev_3 == 't' && chPrev_2 == 'h' && chPrev_1 == 'e' &&  chPrev == 'n')) &&
+               (IsASpace(ch) || (ch == '/' && styler.SafeGetCharAt(back+1) == '*'))
+               ) {
+                  checkIsSentenceStart = false;
+                  isSentenceStart = true;
+            }
+            else if (IsASpace(chPrev) && ch == '{') {
+               checkIsSentenceStart = false;
+               isSentenceStart = false;
+            }
+         }
+
+         // commentNestingLevel is a non-visible state, used to identify the nesting level of a comment
+         if (checkCommentNestingLevel) {
+            if (chPrev == '/' && ch == '*') {
+               commentNestingLevel++;
+               // eat the '/' so we don't miscount a */ if we see /*/*
+               --back;
+            }
+            if (chPrev == '*' && ch == '/') {
+               commentNestingLevel--;
+               // eat the '*' so we don't miscount a /* if we see */*/
+               --back;
+            }
+         }         
+         --back;
+      }
+   }
+
+   StyleContext sc(startPos, length, initStyle, styler, static_cast<unsigned char>(0xff));
+   Sci_Position lineEndNext = styler.LineEnd(lineCurrent);
+
+   for (; sc.More();) {
+      if (sc.atLineStart) {
+         visibleChars = 0;
+         visibleChars1 = 0;
+      }
+      if (sc.atLineEnd) {
+         lineCurrent++;
+         lineEndNext = styler.LineEnd(lineCurrent);
+      }
+      // Handle line continuation generically.
+      if (sc.ch == '~') {
+         if (static_cast<Sci_Position>((sc.currentPos+1)) >= lineEndNext) {
+            lineCurrent++;
+            lineEndNext = styler.LineEnd(lineCurrent);
+            sc.Forward();
+            if (sc.ch == '\r' && sc.chNext == '\n') {
+               sc.Forward();
+            }
+            continuationLine = true;
+            sc.Forward();
+            continue;
+         }
+      }
+
+      const bool atLineEndBeforeSwitch = sc.atLineEnd;
+      // Determine if the current state should terminate.
+      switch (sc.state) {
+         case SCE_ABL_OPERATOR:
+            sc.SetState(SCE_ABL_DEFAULT);
+            break;
+         case SCE_ABL_NUMBER:
+            // We accept almost anything because of hex. and maybe number suffixes and scientific notations 
in the future
+            if (!(setWord.Contains(sc.ch)
+                                  || ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 
'E' ||
+                                                                         sc.chPrev == 'p' || sc.chPrev == 
'P')))) {
+               sc.SetState(SCE_ABL_DEFAULT);
+            }
+            break;
+         case SCE_ABL_IDENTIFIER:
+            if (sc.atLineStart || sc.atLineEnd || (!setWord.Contains(sc.ch) && sc.ch != '-')) {
+               char s[1000];
+               sc.GetCurrentLowered(s, sizeof(s));
+               bool isLastWordEnd = (s[0] == 'e' && s[1] =='n' && s[2] == 'd' && !IsAlphaNumeric(s[3]) && 
s[3] != '-');  // helps to identify "end trigger" phrase
+               if ((isSentenceStart && keywords2.InListAbbreviated (s,'(')) || (!isLastWordEnd && 
keywords3.InListAbbreviated (s,'('))) {
+                  sc.ChangeState(SCE_ABL_BLOCK);
+                  isSentenceStart = false;
+               }
+               else if (keywords1.InListAbbreviated (s,'(')) {
+                  if (isLastWordEnd ||
+                     (s[0] == 'f' && s[1] =='o' && s[2] == 'r' && s[3] == 'w' && s[4] =='a' && s[5] == 'r' 
&& s[6] == 'd'&& !IsAlphaNumeric(s[7]))) {
+                     sc.ChangeState(SCE_ABL_END);
+                     isSentenceStart = false;
+                  }
+                  else if ((s[0] == 'e' && s[1] =='l' && s[2] == 's' && s[3] == 'e') ||
+                         (s[0] == 't' && s[1] =='h' && s[2] == 'e' && s[3] == 'n')) {
+                     sc.ChangeState(SCE_ABL_WORD);
+                     isSentenceStart = true;
+                  }
+                  else {
+                     sc.ChangeState(SCE_ABL_WORD);
+                     isSentenceStart = false;
+                  }
+               }
+               sc.SetState(SCE_ABL_DEFAULT);
+            }
+            break;
+         case SCE_ABL_PREPROCESSOR:
+            if (sc.atLineStart && !continuationLine) {
+               sc.SetState(SCE_ABL_DEFAULT);
+               // Force Scintilla to acknowledge changed stated even though this change might happen outside 
of the current line
+               possibleOOLChange = true;
+               isSentenceStart = true;
+            }
+            break;
+         case SCE_ABL_LINECOMMENT:
+            if (sc.atLineStart && !continuationLine) {
+               sc.SetState(SCE_ABL_DEFAULT);
+               isSentenceStart = true;
+            } else {
+               styleBeforeTaskMarker = SCE_ABL_LINECOMMENT;
+               highlightTaskMarker(sc, styler, keywords4);
+            }
+            break;
+         case SCE_ABL_TASKMARKER:
+            if (isoperator(sc.ch) || IsASpace(sc.ch)) {
+               sc.SetState(styleBeforeTaskMarker);
+               styleBeforeTaskMarker = SCE_ABL_DEFAULT;
+            }
+            // fall through
+         case SCE_ABL_COMMENT:
+            if (sc.Match('*', '/')) {
+               sc.Forward();
+               commentNestingLevel--;
+               if (commentNestingLevel == 0) {
+                  sc.ForwardSetState(SCE_ABL_DEFAULT);
+                  possibleOOLChange = true;
+               }
+            } else if (sc.Match('/', '*')) {
+               commentNestingLevel++;
+               sc.Forward();
+            }
+            if (commentNestingLevel > 0) {
+               styleBeforeTaskMarker = SCE_ABL_COMMENT;
+               possibleOOLChange = true;
+               highlightTaskMarker(sc, styler, keywords4);
+            }
+            break;
+         case SCE_ABL_STRING:
+            if (sc.ch == '~') {
+               sc.Forward(); // Skip a character after a tilde
+            } else if (sc.ch == '\"') {
+                  sc.ForwardSetState(SCE_ABL_DEFAULT);
+            }
+            break;
+         case SCE_ABL_CHARACTER:
+            if (sc.ch == '~') {
+               sc.Forward(); // Skip a character after a tilde
+            } else if (sc.ch == '\'') {
+                  sc.ForwardSetState(SCE_ABL_DEFAULT);
+            }
+            break;
+      }
+
+      if (sc.atLineEnd && !atLineEndBeforeSwitch) {
+         // State exit processing consumed characters up to end of line.
+         lineCurrent++;
+         lineEndNext = styler.LineEnd(lineCurrent);
+      }
+
+      // Determine if a new state should be entered.
+      if (sc.state == SCE_ABL_DEFAULT) {
+         if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+               sc.SetState(SCE_ABL_NUMBER);
+               isSentenceStart = false;
+         } else if (!sc.atLineEnd && (setWordStart.Contains(sc.ch)) && sc.chPrev != '&') {
+               sc.SetState(SCE_ABL_IDENTIFIER);
+         } else if (sc.Match('/', '*')) {
+            if (sc.chPrev == '.' || sc.chPrev == ':' || sc.chPrev == '}') {
+               isSentenceStart = true;
+            }
+            sc.SetState(SCE_ABL_COMMENT);
+            possibleOOLChange = true;
+            commentNestingLevel++;
+            sc.Forward();   // Eat the * so it isn't used for the end of the comment
+         } else if (sc.ch == '\"') {
+               sc.SetState(SCE_ABL_STRING);
+               isSentenceStart = false;
+         } else if (sc.ch == '\'') {
+            sc.SetState(SCE_ABL_CHARACTER);
+            isSentenceStart = false;
+         } else if (sc.ch == '&' && visibleChars1 == 0 && isSentenceStart) {
+            // Preprocessor commands are alone on their line
+            sc.SetState(SCE_ABL_PREPROCESSOR);
+            // Force Scintilla to acknowledge changed stated even though this change might happen outside of 
the current line
+            possibleOOLChange = true;
+            // Skip whitespace between & and preprocessor word
+            do {
+               sc.Forward();
+            } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
+            if (sc.atLineEnd) {
+               sc.SetState(SCE_ABL_DEFAULT);
+            }
+         } else if (sc.Match('/','/') && (IsASpace(sc.chPrev) || isSentenceStart)) {
+            // Line comments are valid after a white space or EOL
+            sc.SetState(SCE_ABL_LINECOMMENT);
+            // Skip whitespace between // and preprocessor word
+            do {
+               sc.Forward();
+            } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
+            if (sc.atLineEnd) {
+               sc.SetState(SCE_ABL_DEFAULT);
+            }
+         } else if (isoperator(sc.ch)) {
+            sc.SetState(SCE_ABL_OPERATOR);
+            /*    This code allows highlight of handles. Alas, it would cause the phrase 
"last-event:function"
+               to be recognized as a BlockBegin */
+               isSentenceStart = false;
+         }
+         else if ((sc.chPrev == '.' || sc.chPrev == ':' || sc.chPrev == '}') && (IsASpace(sc.ch))) {
+            isSentenceStart = true;
+         }
+      }
+      if (!IsASpace(sc.ch)) {
+         visibleChars1++;
+      }
+      if (!IsASpace(sc.ch) && !IsSpaceEquiv(sc.state)) {
+         visibleChars++;
+      }
+      continuationLine = false;
+      sc.Forward();
+   }
+       if (possibleOOLChange)
+               styler.ChangeLexerState(startPos, startPos + length);
+   sc.Complete();
 }
 
+
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
-static void FoldNoBox4glDoc(unsigned int startPos, int length, int initStyle,
-                            Accessor &styler) {
-       bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
-       bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-       unsigned int endPos = startPos + length;
-       int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
-       int levelCurrent = SC_FOLDLEVELBASE;
-       if (lineCurrent > 0)
-               levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
-       int levelMinCurrent = levelCurrent;
-       int levelNext = levelCurrent;
-       char chNext = static_cast<char>(tolower(styler[startPos]));
-       int styleNext = styler.StyleAt(startPos);
-       int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
-               char ch = chNext;
-               chNext = static_cast<char>(tolower(styler.SafeGetCharAt(i + 1)));
-               int stylePrev = style;
-               style = styleNext;
-               styleNext = styler.StyleAt(i + 1);
-               bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
-               if (foldComment && IsStreamCommentStyle(style)) {
-                       if (!IsStreamCommentStyle(stylePrev)) {
-                               levelNext++;
-                       } else if (!IsStreamCommentStyle(styleNext)) { // && !atEOL) {
-                               // Comments don't end at end of line and the next character may be unstyled.
-                               levelNext--;
-                       }
-               }
-               else if ((style & 0xf) == SCE_4GL_BLOCK && !isalnum(chNext)) {
-                       levelNext++;
-               }
-               else if ((style & 0xf) == SCE_4GL_END  && (ch == 'e' || ch == 'f')) {
-                       levelNext--;
-               }
-               if (atEOL) {
-                       int levelUse = levelCurrent;
-                       if (foldAtElse) {
-                               levelUse = levelMinCurrent;
-                       }
-                       int lev = levelUse | levelNext << 16;
-                       if (visibleChars == 0 && foldCompact)
-                               lev |= SC_FOLDLEVELWHITEFLAG;
-                       if (levelUse < levelNext)
-                               lev |= SC_FOLDLEVELHEADERFLAG;
-                       if (lev != styler.LevelAt(lineCurrent)) {
-                               styler.SetLevel(lineCurrent, lev);
-                       }
-                       lineCurrent++;
-                       levelCurrent = levelNext;
-                       levelMinCurrent = levelCurrent;
-                       visibleChars = 0;
-               }
-               if (!isspacechar(ch))
-                       visibleChars++;
-       }
-}
 
-static void Fold4glDoc(unsigned int startPos, int length, int initStyle, WordList *[],
-                       Accessor &styler) {
-       FoldNoBox4glDoc(startPos, length, initStyle, styler);
-}
+void SCI_METHOD LexerABL::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
+
+   if (!options.fold)
+      return;
 
-static const char * const FglWordLists[] = {
-            "Primary keywords and identifiers",
-            "Secondary keywords and identifiers",
-            "Documentation comment keywords",
-            "Unused",
-            "Global classes and typedefs",
-            0,
-        };
+   LexAccessor styler(pAccess);
+
+   Sci_PositionU endPos = startPos + length;
+   int visibleChars = 0;
+   Sci_Position lineCurrent = styler.GetLine(startPos);
+   int levelCurrent = SC_FOLDLEVELBASE;
+   if (lineCurrent > 0)
+      levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
+   Sci_PositionU lineStartNext = styler.LineStart(lineCurrent+1);
+   int levelNext = levelCurrent;
+   char chNext = styler[startPos];
+   int styleNext = styler.StyleAt(startPos);
+   int style = initStyle;
+   for (Sci_PositionU i = startPos; i < endPos; i++) {
+      chNext = static_cast<char>(tolower(chNext));  // check tolower
+      char ch = chNext;
+      chNext = styler.SafeGetCharAt(i+1);
+      int stylePrev = style;
+      style = styleNext;
+      styleNext = styler.StyleAt(i+1);
+      bool atEOL = i == (lineStartNext-1);
+      if (options.foldComment && options.foldCommentMultiline && IsStreamCommentStyle(style)) {
+         if (!IsStreamCommentStyle(stylePrev)) {
+            levelNext++;
+         } else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
+            // Comments don't end at end of line and the next character may be unstyled.
+            levelNext--;
+         }
+      }
+      if (options.foldSyntaxBased) {
+         if (style == SCE_ABL_BLOCK && !IsAlphaNumeric(chNext)) {
+            levelNext++;
+         }
+         else if (style == SCE_ABL_END  && (ch == 'e' || ch == 'f')) {
+            levelNext--;
+         }
+      }
+      if (!IsASpace(ch))
+         visibleChars++;
+      if (atEOL || (i == endPos-1)) {
+         int lev = levelCurrent | levelNext << 16;
+         if (visibleChars == 0 && options.foldCompact)
+            lev |= SC_FOLDLEVELWHITEFLAG;
+         if (levelCurrent < levelNext)
+            lev |= SC_FOLDLEVELHEADERFLAG;
+         if (lev != styler.LevelAt(lineCurrent)) {
+            styler.SetLevel(lineCurrent, lev);
+         }
+         lineCurrent++;
+         lineStartNext = styler.LineStart(lineCurrent+1);
+         levelCurrent = levelNext;
+         if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length()-1))) {
+            // There is an empty line at end of file so give it same level and empty
+            styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | SC_FOLDLEVELWHITEFLAG);
+         }
+         visibleChars = 0;
+      }
+   }
+}
 
-LexerModule lmProgress(SCLEX_PROGRESS, Colourise4glDoc, "progress", Fold4glDoc, FglWordLists);
+LexerModule lmProgress(SCLEX_PROGRESS, LexerABL::LexerFactoryABL, "abl", ablWordLists);
diff --git a/plugins/scintilla/scintilla/lexers/LexProps.cxx b/plugins/scintilla/scintilla/lexers/LexProps.cxx
new file mode 100644
index 0000000..ddfecb0
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexProps.cxx
@@ -0,0 +1,189 @@
+// Scintilla source code edit control
+/** @file LexProps.cxx
+ ** Lexer for properties files.
+ **/
+// Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
+       return (styler[i] == '\n') ||
+              ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
+}
+
+static inline bool isassignchar(unsigned char ch) {
+       return (ch == '=') || (ch == ':');
+}
+
+static void ColourisePropsLine(
+       const char *lineBuffer,
+    Sci_PositionU lengthLine,
+    Sci_PositionU startLine,
+    Sci_PositionU endPos,
+    Accessor &styler,
+    bool allowInitialSpaces) {
+
+       Sci_PositionU i = 0;
+       if (allowInitialSpaces) {
+               while ((i < lengthLine) && isspacechar(lineBuffer[i]))  // Skip initial spaces
+                       i++;
+       } else {
+               if (isspacechar(lineBuffer[i])) // don't allow initial spaces
+                       i = lengthLine;
+       }
+
+       if (i < lengthLine) {
+               if (lineBuffer[i] == '#' || lineBuffer[i] == '!' || lineBuffer[i] == ';') {
+                       styler.ColourTo(endPos, SCE_PROPS_COMMENT);
+               } else if (lineBuffer[i] == '[') {
+                       styler.ColourTo(endPos, SCE_PROPS_SECTION);
+               } else if (lineBuffer[i] == '@') {
+                       styler.ColourTo(startLine + i, SCE_PROPS_DEFVAL);
+                       if (isassignchar(lineBuffer[i++]))
+                               styler.ColourTo(startLine + i, SCE_PROPS_ASSIGNMENT);
+                       styler.ColourTo(endPos, SCE_PROPS_DEFAULT);
+               } else {
+                       // Search for the '=' character
+                       while ((i < lengthLine) && !isassignchar(lineBuffer[i]))
+                               i++;
+                       if ((i < lengthLine) && isassignchar(lineBuffer[i])) {
+                               styler.ColourTo(startLine + i - 1, SCE_PROPS_KEY);
+                               styler.ColourTo(startLine + i, SCE_PROPS_ASSIGNMENT);
+                               styler.ColourTo(endPos, SCE_PROPS_DEFAULT);
+                       } else {
+                               styler.ColourTo(endPos, SCE_PROPS_DEFAULT);
+                       }
+               }
+       } else {
+               styler.ColourTo(endPos, SCE_PROPS_DEFAULT);
+       }
+}
+
+static void ColourisePropsDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor 
&styler) {
+       char lineBuffer[1024];
+       styler.StartAt(startPos);
+       styler.StartSegment(startPos);
+       Sci_PositionU linePos = 0;
+       Sci_PositionU startLine = startPos;
+
+       // property lexer.props.allow.initial.spaces
+       //      For properties files, set to 0 to style all lines that start with whitespace in the default 
style.
+       //      This is not suitable for SciTE .properties files which use indentation for flow control but
+       //      can be used for RFC2822 text where indentation is used for continuation lines.
+       const bool allowInitialSpaces = styler.GetPropertyInt("lexer.props.allow.initial.spaces", 1) != 0;
+
+       for (Sci_PositionU i = startPos; i < startPos + length; i++) {
+               lineBuffer[linePos++] = styler[i];
+               if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
+                       // End of line (or of line buffer) met, colourise it
+                       lineBuffer[linePos] = '\0';
+                       ColourisePropsLine(lineBuffer, linePos, startLine, i, styler, allowInitialSpaces);
+                       linePos = 0;
+                       startLine = i + 1;
+               }
+       }
+       if (linePos > 0) {      // Last line does not have ending characters
+               ColourisePropsLine(lineBuffer, linePos, startLine, startPos + length - 1, styler, 
allowInitialSpaces);
+       }
+}
+
+// adaption by ksc, using the "} else {" trick of 1.53
+// 030721
+static void FoldPropsDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {
+       const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
+
+       const Sci_PositionU endPos = startPos + length;
+       int visibleChars = 0;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+
+       char chNext = styler[startPos];
+       int styleNext = styler.StyleAt(startPos);
+       bool headerPoint = false;
+       int lev;
+
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
+               const char ch = chNext;
+               chNext = styler[i+1];
+
+               const int style = styleNext;
+               styleNext = styler.StyleAt(i + 1);
+               const bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+
+               if (style == SCE_PROPS_SECTION) {
+                       headerPoint = true;
+               }
+
+               if (atEOL) {
+                       lev = SC_FOLDLEVELBASE;
+
+                       if (lineCurrent > 0) {
+                               const int levelPrevious = styler.LevelAt(lineCurrent - 1);
+
+                               if (levelPrevious & SC_FOLDLEVELHEADERFLAG) {
+                                       lev = SC_FOLDLEVELBASE + 1;
+                               } else {
+                                       lev = levelPrevious & SC_FOLDLEVELNUMBERMASK;
+                               }
+                       }
+
+                       if (headerPoint) {
+                               lev = SC_FOLDLEVELBASE;
+                       }
+                       if (visibleChars == 0 && foldCompact)
+                               lev |= SC_FOLDLEVELWHITEFLAG;
+
+                       if (headerPoint) {
+                               lev |= SC_FOLDLEVELHEADERFLAG;
+                       }
+                       if (lev != styler.LevelAt(lineCurrent)) {
+                               styler.SetLevel(lineCurrent, lev);
+                       }
+
+                       lineCurrent++;
+                       visibleChars = 0;
+                       headerPoint = false;
+               }
+               if (!isspacechar(ch))
+                       visibleChars++;
+       }
+
+       if (lineCurrent > 0) {
+               const int levelPrevious = styler.LevelAt(lineCurrent - 1);
+               if (levelPrevious & SC_FOLDLEVELHEADERFLAG) {
+                       lev = SC_FOLDLEVELBASE + 1;
+               } else {
+                       lev = levelPrevious & SC_FOLDLEVELNUMBERMASK;
+               }
+       } else {
+               lev = SC_FOLDLEVELBASE;
+       }
+       int flagsNext = styler.LevelAt(lineCurrent);
+       styler.SetLevel(lineCurrent, lev | (flagsNext & ~SC_FOLDLEVELNUMBERMASK));
+}
+
+static const char *const emptyWordListDesc[] = {
+       0
+};
+
+LexerModule lmProps(SCLEX_PROPERTIES, ColourisePropsDoc, "props", FoldPropsDoc, emptyWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexPython.cxx 
b/plugins/scintilla/scintilla/lexers/LexPython.cxx
index fedc312..97943ca 100644
--- a/plugins/scintilla/scintilla/lexers/LexPython.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPython.cxx
@@ -12,39 +12,73 @@
 #include <assert.h>
 #include <ctype.h>
 
+#include <string>
+#include <vector>
+#include <map>
+
 #include "ILexer.h"
 #include "Scintilla.h"
 #include "SciLexer.h"
 
+#include "StringCopy.h"
 #include "WordList.h"
 #include "LexAccessor.h"
 #include "Accessor.h"
 #include "StyleContext.h"
 #include "CharacterSet.h"
+#include "CharacterCategory.h"
 #include "LexerModule.h"
+#include "OptionSet.h"
+#include "SubStyles.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
+namespace {
+// Use an unnamed namespace to protect the functions and classes from name conflicts
+
+/* Notes on f-strings: f-strings are strings prefixed with f (e.g. f'') that may
+   have arbitrary expressions in {}.  The tokens in the expressions are lexed as if
+   they were outside of any string.  Expressions may contain { and } characters as
+   long as there is a closing } for every {, may be 2+ lines in a triple quoted
+   string, and may have a formatting specifier following a ! or :, but both !
+   and : are valid inside of a bracketed expression and != is a valid
+   expression token even outside of a bracketed expression.
+
+   When in an f-string expression, the lexer keeps track of the state value of
+   the f-string and the nesting count for the expression (# of [, (, { seen - # of
+   }, ), ] seen).  f-strings may be nested (e.g. f'{ a + f"{1+2}"') so a stack of
+   states and nesting counts is kept.  If a f-string expression continues beyond
+   the end of a line, this stack is saved in a std::map that maps a line number to
+   the stack at the end of that line.  std::vector is used for the stack.
+
+   The PEP for f-strings is at https://www.python.org/dev/peps/pep-0498/
+*/
+struct SingleFStringExpState {
+       int state;
+       int nestingCount;
+};
+
 /* kwCDef, kwCTypeName only used for Cython */
 enum kwType { kwOther, kwClass, kwDef, kwImport, kwCDef, kwCTypeName, kwCPDef };
 
-static const int indicatorWhitespace = 1;
+enum literalsAllowed { litNone = 0, litU = 1, litB = 2, litF = 4 };
 
-static bool IsPyComment(Accessor &styler, int pos, int len) {
+const int indicatorWhitespace = 1;
+
+bool IsPyComment(Accessor &styler, Sci_Position pos, Sci_Position len) {
        return len > 0 && styler[pos] == '#';
 }
 
-enum literalsAllowed { litNone=0, litU=1, litB=2};
-
-static bool IsPyStringTypeChar(int ch, literalsAllowed allowed) {
+bool IsPyStringTypeChar(int ch, literalsAllowed allowed) {
        return
                ((allowed & litB) && (ch == 'b' || ch == 'B')) ||
-               ((allowed & litU) && (ch == 'u' || ch == 'U'));
+               ((allowed & litU) && (ch == 'u' || ch == 'U')) ||
+               ((allowed & litF) && (ch == 'f' || ch == 'F'));
 }
 
-static bool IsPyStringStart(int ch, int chNext, int chNext2, literalsAllowed allowed) {
+bool IsPyStringStart(int ch, int chNext, int chNext2, literalsAllowed allowed) {
        if (ch == '\'' || ch == '"')
                return true;
        if (IsPyStringTypeChar(ch, allowed)) {
@@ -59,12 +93,63 @@ static bool IsPyStringStart(int ch, int chNext, int chNext2, literalsAllowed all
        return false;
 }
 
+bool IsPyFStringState(int st) {
+       return ((st == SCE_P_FCHARACTER) || (st == SCE_P_FSTRING) ||
+               (st == SCE_P_FTRIPLE) || (st == SCE_P_FTRIPLEDOUBLE));
+}
+
+bool IsPySingleQuoteStringState(int st) {
+       return ((st == SCE_P_CHARACTER) || (st == SCE_P_STRING) ||
+               (st == SCE_P_FCHARACTER) || (st == SCE_P_FSTRING));
+}
+
+bool IsPyTripleQuoteStringState(int st) {
+       return ((st == SCE_P_TRIPLE) || (st == SCE_P_TRIPLEDOUBLE) ||
+               (st == SCE_P_FTRIPLE) || (st == SCE_P_FTRIPLEDOUBLE));
+}
+
+char GetPyStringQuoteChar(int st) {
+       if ((st == SCE_P_CHARACTER) || (st == SCE_P_FCHARACTER) ||
+                       (st == SCE_P_TRIPLE) || (st == SCE_P_FTRIPLE))
+               return '\'';
+       if ((st == SCE_P_STRING) || (st == SCE_P_FSTRING) ||
+                       (st == SCE_P_TRIPLEDOUBLE) || (st == SCE_P_FTRIPLEDOUBLE))
+               return '"';
+
+       return '\0';
+}
+
+void PushStateToStack(int state, std::vector<SingleFStringExpState> &stack, SingleFStringExpState 
*&currentFStringExp) {
+       SingleFStringExpState single = {state, 0};
+       stack.push_back(single);
+
+       currentFStringExp = &stack.back();
+}
+
+int PopFromStateStack(std::vector<SingleFStringExpState> &stack, SingleFStringExpState *&currentFStringExp) {
+       int state = 0;
+
+       if (!stack.empty()) {
+               state = stack.back().state;
+               stack.pop_back();
+       }
+
+       if (stack.empty()) {
+               currentFStringExp = NULL;
+       } else {
+               currentFStringExp = &stack.back();
+       }
+
+       return state;
+}
+
 /* Return the state to use for the string starting at i; *nextIndex will be set to the first index following 
the quote(s) */
-static int GetPyStringState(Accessor &styler, int i, unsigned int *nextIndex, literalsAllowed allowed) {
+int GetPyStringState(Accessor &styler, Sci_Position i, Sci_PositionU *nextIndex, literalsAllowed allowed) {
        char ch = styler.SafeGetCharAt(i);
        char chNext = styler.SafeGetCharAt(i + 1);
+       const int firstIsF = (ch == 'f' || ch == 'F');
 
-       // Advance beyond r, u, or ur prefix (or r, b, or br in Python 3.0), but bail if there are any 
unexpected chars
+       // Advance beyond r, u, or ur prefix (or r, b, or br in Python 2.7+ and r, f, or fr in Python 3.6+), 
but bail if there are any unexpected chars
        if (ch == 'r' || ch == 'R') {
                i++;
                ch = styler.SafeGetCharAt(i);
@@ -87,44 +172,319 @@ static int GetPyStringState(Accessor &styler, int i, unsigned int *nextIndex, li
                *nextIndex = i + 3;
 
                if (ch == '"')
-                       return SCE_P_TRIPLEDOUBLE;
+                       return (firstIsF ? SCE_P_FTRIPLEDOUBLE : SCE_P_TRIPLEDOUBLE);
                else
-                       return SCE_P_TRIPLE;
+                       return (firstIsF ? SCE_P_FTRIPLE : SCE_P_TRIPLE);
        } else {
                *nextIndex = i + 1;
 
                if (ch == '"')
-                       return SCE_P_STRING;
+                       return (firstIsF ? SCE_P_FSTRING : SCE_P_STRING);
                else
-                       return SCE_P_CHARACTER;
+                       return (firstIsF ? SCE_P_FCHARACTER : SCE_P_CHARACTER);
        }
 }
 
-static inline bool IsAWordChar(int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
+inline bool IsAWordChar(int ch, bool unicodeIdentifiers) {
+       if (ch < 0x80)
+               return (isalnum(ch) || ch == '.' || ch == '_');
+
+       if (!unicodeIdentifiers)
+               return false;
+
+       // Python uses the XID_Continue set from unicode data
+       return IsXidContinue(ch);
 }
 
-static inline bool IsAWordStart(int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '_');
+inline bool IsAWordStart(int ch, bool unicodeIdentifiers) {
+       if (ch < 0x80)
+               return (isalpha(ch) || ch == '_');
+
+       if (!unicodeIdentifiers)
+               return false;
+
+       // Python uses the XID_Start set from unicode data
+       return IsXidStart(ch);
 }
 
-static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
-        WordList *keywordlists[], Accessor &styler) {
+static bool IsFirstNonWhitespace(Sci_Position pos, Accessor &styler) {
+       Sci_Position line = styler.GetLine(pos);
+       Sci_Position start_pos = styler.LineStart(line);
+       for (Sci_Position i = start_pos; i < pos; i++) {
+               const char ch = styler[i];
+               if (!(ch == ' ' || ch == '\t'))
+                       return false;
+       }
+       return true;
+}
 
-       int endPos = startPos + length;
+// Options used for LexerPython
+struct OptionsPython {
+       int whingeLevel;
+       bool base2or8Literals;
+       bool stringsU;
+       bool stringsB;
+       bool stringsF;
+       bool stringsOverNewline;
+       bool keywords2NoSubIdentifiers;
+       bool fold;
+       bool foldQuotes;
+       bool foldCompact;
+       bool unicodeIdentifiers;
+
+       OptionsPython() {
+               whingeLevel = 0;
+               base2or8Literals = true;
+               stringsU = true;
+               stringsB = true;
+               stringsF = true;
+               stringsOverNewline = false;
+               keywords2NoSubIdentifiers = false;
+               fold = false;
+               foldQuotes = false;
+               foldCompact = false;
+               unicodeIdentifiers = true;
+       }
+
+       literalsAllowed AllowedLiterals() const {
+               literalsAllowed allowedLiterals = stringsU ? litU : litNone;
+               if (stringsB)
+                       allowedLiterals = static_cast<literalsAllowed>(allowedLiterals | litB);
+               if (stringsF)
+                       allowedLiterals = static_cast<literalsAllowed>(allowedLiterals | litF);
+               return allowedLiterals;
+       }
+};
+
+static const char *const pythonWordListDesc[] = {
+       "Keywords",
+       "Highlighted identifiers",
+       0
+};
+
+struct OptionSetPython : public OptionSet<OptionsPython> {
+       OptionSetPython() {
+               DefineProperty("tab.timmy.whinge.level", &OptionsPython::whingeLevel,
+                              "For Python code, checks whether indenting is consistent. "
+                              "The default, 0 turns off indentation checking, "
+                              "1 checks whether each line is potentially inconsistent with the previous 
line, "
+                              "2 checks whether any space characters occur before a tab character in the 
indentation, "
+                              "3 checks whether any spaces are in the indentation, and "
+                              "4 checks for any tab characters in the indentation. "
+                              "1 is a good level to use.");
+
+               DefineProperty("lexer.python.literals.binary", &OptionsPython::base2or8Literals,
+                              "Set to 0 to not recognise Python 3 binary and octal literals: 0b1011 0o712.");
+
+               DefineProperty("lexer.python.strings.u", &OptionsPython::stringsU,
+                              "Set to 0 to not recognise Python Unicode literals u\"x\" as used before 
Python 3.");
+
+               DefineProperty("lexer.python.strings.b", &OptionsPython::stringsB,
+                              "Set to 0 to not recognise Python 3 bytes literals b\"x\".");
+
+               DefineProperty("lexer.python.strings.f", &OptionsPython::stringsF,
+                              "Set to 0 to not recognise Python 3.6 f-string literals f\"var={var}\".");
+
+               DefineProperty("lexer.python.strings.over.newline", &OptionsPython::stringsOverNewline,
+                              "Set to 1 to allow strings to span newline characters.");
+
+               DefineProperty("lexer.python.keywords2.no.sub.identifiers", 
&OptionsPython::keywords2NoSubIdentifiers,
+                              "When enabled, it will not style keywords2 items that are used as a 
sub-identifier. "
+                              "Example: when set, will not highlight \"foo.open\" when \"open\" is a 
keywords2 item.");
+
+               DefineProperty("fold", &OptionsPython::fold);
+
+               DefineProperty("fold.quotes.python", &OptionsPython::foldQuotes,
+                              "This option enables folding multi-line quoted strings when using the Python 
lexer.");
+
+               DefineProperty("fold.compact", &OptionsPython::foldCompact);
+
+               DefineProperty("lexer.python.unicode.identifiers", &OptionsPython::unicodeIdentifiers,
+                              "Set to 0 to not recognise Python 3 unicode identifiers.");
+
+               DefineWordListSets(pythonWordListDesc);
+       }
+};
+
+const char styleSubable[] = { SCE_P_IDENTIFIER, 0 };
+
+}
+
+class LexerPython : public ILexerWithSubStyles {
+       WordList keywords;
+       WordList keywords2;
+       OptionsPython options;
+       OptionSetPython osPython;
+       enum { ssIdentifier };
+       SubStyles subStyles;
+       std::map<int, std::vector<SingleFStringExpState> > ftripleStateAtEol;
+public:
+       explicit LexerPython() :
+               subStyles(styleSubable, 0x80, 0x40, 0) {
+       }
+       virtual ~LexerPython() {
+       }
+       void SCI_METHOD Release() override {
+               delete this;
+       }
+       int SCI_METHOD Version() const override {
+               return lvSubStyles;
+       }
+       const char *SCI_METHOD PropertyNames() override {
+               return osPython.PropertyNames();
+       }
+       int SCI_METHOD PropertyType(const char *name) override {
+               return osPython.PropertyType(name);
+       }
+       const char *SCI_METHOD DescribeProperty(const char *name) override {
+               return osPython.DescribeProperty(name);
+       }
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char *SCI_METHOD DescribeWordListSets() override {
+               return osPython.DescribeWordListSets();
+       }
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+
+       void *SCI_METHOD PrivateCall(int, void *) override {
+               return 0;
+       }
+
+       int SCI_METHOD LineEndTypesSupported() override {
+               return SC_LINE_END_TYPE_UNICODE;
+       }
+
+       int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override {
+               return subStyles.Allocate(styleBase, numberStyles);
+       }
+       int SCI_METHOD SubStylesStart(int styleBase) override {
+               return subStyles.Start(styleBase);
+       }
+       int SCI_METHOD SubStylesLength(int styleBase) override {
+               return subStyles.Length(styleBase);
+       }
+       int SCI_METHOD StyleFromSubStyle(int subStyle) override {
+               const int styleBase = subStyles.BaseStyle(subStyle);
+               return styleBase;
+       }
+       int SCI_METHOD PrimaryStyleFromStyle(int style) override {
+               return style;
+       }
+       void SCI_METHOD FreeSubStyles() override {
+               subStyles.Free();
+       }
+       void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override {
+               subStyles.SetIdentifiers(style, identifiers);
+       }
+       int SCI_METHOD DistanceToSecondaryStyles() override {
+               return 0;
+       }
+       const char *SCI_METHOD GetSubStyleBases() override {
+               return styleSubable;
+       }
+
+       static ILexer *LexerFactoryPython() {
+               return new LexerPython();
+       }
+
+private:
+       void ProcessLineEnd(StyleContext &sc, std::vector<SingleFStringExpState> &fstringStateStack, 
SingleFStringExpState *&currentFStringExp, bool &inContinuedString);
+};
+
+Sci_Position SCI_METHOD LexerPython::PropertySet(const char *key, const char *val) {
+       if (osPython.PropertySet(&options, key, val)) {
+               return 0;
+       }
+       return -1;
+}
+
+Sci_Position SCI_METHOD LexerPython::WordListSet(int n, const char *wl) {
+       WordList *wordListN = 0;
+       switch (n) {
+       case 0:
+               wordListN = &keywords;
+               break;
+       case 1:
+               wordListN = &keywords2;
+               break;
+       }
+       Sci_Position firstModification = -1;
+       if (wordListN) {
+               WordList wlNew;
+               wlNew.Set(wl);
+               if (*wordListN != wlNew) {
+                       wordListN->Set(wl);
+                       firstModification = 0;
+               }
+       }
+       return firstModification;
+}
+
+void LexerPython::ProcessLineEnd(StyleContext &sc, std::vector<SingleFStringExpState> &fstringStateStack, 
SingleFStringExpState *&currentFStringExp, bool &inContinuedString) {
+       long deepestSingleStateIndex = -1;
+       unsigned long i;
+
+       // Find the deepest single quote state because that string will end; no \ continuation in f-string
+       for (i = 0; i < fstringStateStack.size(); i++) {
+               if (IsPySingleQuoteStringState(fstringStateStack[i].state)) {
+                       deepestSingleStateIndex = i;
+                       break;
+               }
+       }
+
+       if (deepestSingleStateIndex != -1) {
+               sc.SetState(fstringStateStack[deepestSingleStateIndex].state);
+               while (fstringStateStack.size() > static_cast<unsigned long>(deepestSingleStateIndex)) {
+                       PopFromStateStack(fstringStateStack, currentFStringExp);
+               }
+       }
+       if (!fstringStateStack.empty()) {
+               std::pair<int, std::vector<SingleFStringExpState> > val;
+               val.first = sc.currentLine;
+               val.second = fstringStateStack;
+
+               ftripleStateAtEol.insert(val);
+       }
+
+       if ((sc.state == SCE_P_DEFAULT)
+                       || IsPyTripleQuoteStringState(sc.state)) {
+               // Perform colourisation of white space and triple quoted strings at end of each line to allow
+               // tab marking to work inside white space and triple quoted strings
+               sc.SetState(sc.state);
+       }
+       if (IsPySingleQuoteStringState(sc.state)) {
+               if (inContinuedString || options.stringsOverNewline) {
+                       inContinuedString = false;
+               } else {
+                       sc.ChangeState(SCE_P_STRINGEOL);
+                       sc.ForwardSetState(SCE_P_DEFAULT);
+               }
+       }
+}
+
+void SCI_METHOD LexerPython::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
+       Accessor styler(pAccess, NULL);
+
+       // Track whether in f-string expression; vector is used for a stack to
+       // handle nested f-strings such as f"""{f'''{f"{f'{1}'}"}'''}"""
+       std::vector<SingleFStringExpState> fstringStateStack;
+       SingleFStringExpState *currentFStringExp = NULL;
+
+       const Sci_Position endPos = startPos + length;
 
        // Backtrack to previous line in case need to fix its tab whinging
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0) {
                if (lineCurrent > 0) {
                        lineCurrent--;
                        // Look for backslash-continued lines
                        while (lineCurrent > 0) {
-                               int eolPos = styler.LineStart(lineCurrent) - 1;
-                               int eolStyle = styler.StyleAt(eolPos);
+                               Sci_Position eolPos = styler.LineStart(lineCurrent) - 1;
+                               const int eolStyle = styler.StyleAt(eolPos);
                                if (eolStyle == SCE_P_STRING
-                                   || eolStyle == SCE_P_CHARACTER
-                                   || eolStyle == SCE_P_STRINGEOL) {
+                                               || eolStyle == SCE_P_CHARACTER
+                                               || eolStyle == SCE_P_STRINGEOL) {
                                        lineCurrent -= 1;
                                } else {
                                        break;
@@ -135,55 +495,36 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                initStyle = startPos == 0 ? SCE_P_DEFAULT : styler.StyleAt(startPos - 1);
        }
 
-       WordList &keywords = *keywordlists[0];
-       WordList &keywords2 = *keywordlists[1];
-
-       // property tab.timmy.whinge.level
-       //      For Python code, checks whether indenting is consistent.
-       //      The default, 0 turns off indentation checking,
-       //      1 checks whether each line is potentially inconsistent with the previous line,
-       //      2 checks whether any space characters occur before a tab character in the indentation,
-       //      3 checks whether any spaces are in the indentation, and
-       //      4 checks for any tab characters in the indentation.
-       //      1 is a good level to use.
-       const int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level");
-
-       // property lexer.python.literals.binary
-       //      Set to 0 to not recognise Python 3 binary and octal literals: 0b1011 0o712.
-       bool base2or8Literals = styler.GetPropertyInt("lexer.python.literals.binary", 1) != 0;
-
-       // property lexer.python.strings.u
-       //      Set to 0 to not recognise Python Unicode literals u"x" as used before Python 3.
-       literalsAllowed allowedLiterals = (styler.GetPropertyInt("lexer.python.strings.u", 1)) ? litU : 
litNone;
-
-       // property lexer.python.strings.b
-       //      Set to 0 to not recognise Python 3 bytes literals b"x".
-       if (styler.GetPropertyInt("lexer.python.strings.b", 1))
-               allowedLiterals = static_cast<literalsAllowed>(allowedLiterals | litB);
-
-       // property lexer.python.strings.over.newline
-       //      Set to 1 to allow strings to span newline characters.
-       bool stringsOverNewline = styler.GetPropertyInt("lexer.python.strings.over.newline") != 0;
-
-       // property lexer.python.keywords2.no.sub.identifiers
-       //      When enabled, it will not style keywords2 items that are used as a sub-identifier.
-       //      Example: when set, will not highlight "foo.open" when "open" is a keywords2 item.
-       const bool keywords2NoSubIdentifiers = 
styler.GetPropertyInt("lexer.python.keywords2.no.sub.identifiers") != 0;
+       const literalsAllowed allowedLiterals = options.AllowedLiterals();
 
        initStyle = initStyle & 31;
        if (initStyle == SCE_P_STRINGEOL) {
                initStyle = SCE_P_DEFAULT;
        }
 
+       // Set up fstate stack from last line and remove any subsequent ftriple at eol states
+       std::map<int, std::vector<SingleFStringExpState> >::iterator it;
+       it = ftripleStateAtEol.find(lineCurrent - 1);
+       if (it != ftripleStateAtEol.end() && !it->second.empty()) {
+               fstringStateStack = it->second;
+               currentFStringExp = &fstringStateStack.back();
+       }
+       it = ftripleStateAtEol.lower_bound(lineCurrent);
+       if (it != ftripleStateAtEol.end()) {
+               ftripleStateAtEol.erase(it, ftripleStateAtEol.end());
+       }
+
        kwType kwLast = kwOther;
        int spaceFlags = 0;
        styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
        bool base_n_number = false;
 
+       const WordClassifier &classifierIdentifiers = subStyles.Classifier(SCE_P_IDENTIFIER);
+
        StyleContext sc(startPos, endPos - startPos, initStyle, styler);
 
        bool indentGood = true;
-       int startIndicator = sc.currentPos;
+       Sci_Position startIndicator = sc.currentPos;
        bool inContinuedString = false;
 
        for (; sc.More(); sc.Forward()) {
@@ -191,13 +532,13 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                if (sc.atLineStart) {
                        styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
                        indentGood = true;
-                       if (whingeLevel == 1) {
+                       if (options.whingeLevel == 1) {
                                indentGood = (spaceFlags & wsInconsistent) == 0;
-                       } else if (whingeLevel == 2) {
+                       } else if (options.whingeLevel == 2) {
                                indentGood = (spaceFlags & wsSpaceTab) == 0;
-                       } else if (whingeLevel == 3) {
+                       } else if (options.whingeLevel == 3) {
                                indentGood = (spaceFlags & wsSpace) == 0;
-                       } else if (whingeLevel == 4) {
+                       } else if (options.whingeLevel == 4) {
                                indentGood = (spaceFlags & wsTab) == 0;
                        }
                        if (!indentGood) {
@@ -207,39 +548,25 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                }
 
                if (sc.atLineEnd) {
-                       if ((sc.state == SCE_P_DEFAULT) ||
-                               (sc.state == SCE_P_TRIPLE) ||
-                               (sc.state == SCE_P_TRIPLEDOUBLE)) {
-                               // Perform colourisation of white space and triple quoted strings at end of 
each line to allow
-                               // tab marking to work inside white space and triple quoted strings
-                               sc.SetState(sc.state);
-                       }
+                       ProcessLineEnd(sc, fstringStateStack, currentFStringExp, inContinuedString);
                        lineCurrent++;
-                       if ((sc.state == SCE_P_STRING) || (sc.state == SCE_P_CHARACTER)) {
-                               if (inContinuedString || stringsOverNewline) {
-                                       inContinuedString = false;
-                               } else {
-                                       sc.ChangeState(SCE_P_STRINGEOL);
-                                       sc.ForwardSetState(SCE_P_DEFAULT);
-                               }
-                       }
                        if (!sc.More())
                                break;
                }
 
                bool needEOLCheck = false;
 
-               // Check for a state end
+
                if (sc.state == SCE_P_OPERATOR) {
                        kwLast = kwOther;
                        sc.SetState(SCE_P_DEFAULT);
                } else if (sc.state == SCE_P_NUMBER) {
-                       if (!IsAWordChar(sc.ch) &&
-                               !(!base_n_number && ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || 
sc.chPrev == 'E')))) {
+                       if (!IsAWordChar(sc.ch, false) &&
+                                       !(!base_n_number && ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 
'e' || sc.chPrev == 'E')))) {
                                sc.SetState(SCE_P_DEFAULT);
                        }
                } else if (sc.state == SCE_P_IDENTIFIER) {
-                       if ((sc.ch == '.') || (!IsAWordChar(sc.ch))) {
+                       if ((sc.ch == '.') || (!IsAWordChar(sc.ch, options.unicodeIdentifiers))) {
                                char s[100];
                                sc.GetCurrent(s, sizeof(s));
                                int style = SCE_P_IDENTIFIER;
@@ -252,7 +579,7 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                } else if (kwLast == kwDef) {
                                        style = SCE_P_DEFNAME;
                                } else if (kwLast == kwCDef || kwLast == kwCPDef) {
-                                       int pos = sc.currentPos;
+                                       Sci_Position pos = sc.currentPos;
                                        unsigned char ch = styler.SafeGetCharAt(pos, '\0');
                                        while (ch != '\0') {
                                                if (ch == '(') {
@@ -269,16 +596,21 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                                }
                                        }
                                } else if (keywords2.InList(s)) {
-                                       if (keywords2NoSubIdentifiers) {
+                                       if (options.keywords2NoSubIdentifiers) {
                                                // We don't want to highlight keywords2
                                                // that are used as a sub-identifier,
                                                // i.e. not open in "foo.open".
-                                               int pos = styler.GetStartSegment() - 1;
+                                               Sci_Position pos = styler.GetStartSegment() - 1;
                                                if (pos < 0 || (styler.SafeGetCharAt(pos, '\0') != '.'))
                                                        style = SCE_P_WORD2;
                                        } else {
                                                style = SCE_P_WORD2;
                                        }
+                               } else {
+                                       int subStyle = classifierIdentifiers.ValueFor(s);
+                                       if (subStyle >= 0) {
+                                               style = subStyle;
+                                       }
                                }
                                sc.ChangeState(style);
                                sc.SetState(SCE_P_DEFAULT);
@@ -306,10 +638,10 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                sc.SetState(SCE_P_DEFAULT);
                        }
                } else if (sc.state == SCE_P_DECORATOR) {
-                       if (!IsAWordChar(sc.ch)) {
+                       if (!IsAWordStart(sc.ch, options.unicodeIdentifiers)) {
                                sc.SetState(SCE_P_DEFAULT);
                        }
-               } else if ((sc.state == SCE_P_STRING) || (sc.state == SCE_P_CHARACTER)) {
+               } else if (IsPySingleQuoteStringState(sc.state)) {
                        if (sc.ch == '\\') {
                                if ((sc.chNext == '\r') && (sc.GetRelative(2) == '\n')) {
                                        sc.Forward();
@@ -320,14 +652,11 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                        // Don't roll over the newline.
                                        sc.Forward();
                                }
-                       } else if ((sc.state == SCE_P_STRING) && (sc.ch == '\"')) {
-                               sc.ForwardSetState(SCE_P_DEFAULT);
-                               needEOLCheck = true;
-                       } else if ((sc.state == SCE_P_CHARACTER) && (sc.ch == '\'')) {
+                       } else if (sc.ch == GetPyStringQuoteChar(sc.state)) {
                                sc.ForwardSetState(SCE_P_DEFAULT);
                                needEOLCheck = true;
                        }
-               } else if (sc.state == SCE_P_TRIPLE) {
+               } else if ((sc.state == SCE_P_TRIPLE) || (sc.state == SCE_P_FTRIPLE)) {
                        if (sc.ch == '\\') {
                                sc.Forward();
                        } else if (sc.Match("\'\'\'")) {
@@ -336,7 +665,7 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                sc.ForwardSetState(SCE_P_DEFAULT);
                                needEOLCheck = true;
                        }
-               } else if (sc.state == SCE_P_TRIPLEDOUBLE) {
+               } else if ((sc.state == SCE_P_TRIPLEDOUBLE) || (sc.state == SCE_P_FTRIPLEDOUBLE)) {
                        if (sc.ch == '\\') {
                                sc.Forward();
                        } else if (sc.Match("\"\"\"")) {
@@ -347,6 +676,51 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                        }
                }
 
+               // Note if used and not if else because string states also match
+               // some of the above clauses
+               if (IsPyFStringState(sc.state) && sc.ch == '{') {
+                       if (sc.chNext == '{') {
+                               sc.Forward();
+                       } else {
+                               PushStateToStack(sc.state, fstringStateStack, currentFStringExp);
+                               sc.ForwardSetState(SCE_P_DEFAULT);
+                       }
+                       needEOLCheck = true;
+               }
+
+               // If in an f-string expression, check for the ending quote(s)
+               // and end f-string to handle syntactically incorrect cases like
+               // f'{' and f"""{"""
+               if (!fstringStateStack.empty() && (sc.ch == '\'' || sc.ch == '"')) {
+                       long matching_stack_i = -1;
+                       for (unsigned long stack_i = 0; stack_i < fstringStateStack.size() && 
matching_stack_i == -1; stack_i++) {
+                               const int stack_state = fstringStateStack[stack_i].state;
+                               const char quote = GetPyStringQuoteChar(stack_state);
+                               if (sc.ch == quote) {
+                                       if (IsPySingleQuoteStringState(stack_state)) {
+                                               matching_stack_i = stack_i;
+                                       } else if (quote == '"' ? sc.Match("\"\"\"") : sc.Match("'''")) {
+                                               matching_stack_i = stack_i;
+                                       }
+                               }
+                       }
+
+                       if (matching_stack_i != -1) {
+                               sc.SetState(fstringStateStack[matching_stack_i].state);
+                               if (IsPyTripleQuoteStringState(fstringStateStack[matching_stack_i].state)) {
+                                       sc.Forward();
+                                       sc.Forward();
+                               }
+                               sc.ForwardSetState(SCE_P_DEFAULT);
+                               needEOLCheck = true;
+
+                               while (fstringStateStack.size() > static_cast<unsigned 
long>(matching_stack_i)) {
+                                       PopFromStateStack(fstringStateStack, currentFStringExp);
+                               }
+                       }
+               }
+               // End of code to find the end of a state
+
                if (!indentGood && !IsASpaceOrTab(sc.ch)) {
                        styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 1);
                        startIndicator = sc.currentPos;
@@ -360,12 +734,26 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
 
                // State exit code may have moved on to end of line
                if (needEOLCheck && sc.atLineEnd) {
+                       ProcessLineEnd(sc, fstringStateStack, currentFStringExp, inContinuedString);
                        lineCurrent++;
                        styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
                        if (!sc.More())
                                break;
                }
 
+               // If in f-string expression, check for }, :, ! to resume f-string state or update nesting 
count
+               if (currentFStringExp != NULL && !IsPySingleQuoteStringState(sc.state) && 
!IsPyTripleQuoteStringState(sc.state)) {
+                       if (currentFStringExp->nestingCount == 0 && (sc.ch == '}' || sc.ch == ':' || (sc.ch 
== '!' && sc.chNext != '='))) {
+                               sc.SetState(PopFromStateStack(fstringStateStack, currentFStringExp));
+                       } else {
+                               if (sc.ch == '{' || sc.ch == '[' || sc.ch == '(') {
+                                       currentFStringExp->nestingCount++;
+                               } else if (sc.ch == '}' || sc.ch == ']' || sc.ch == ')') {
+                                       currentFStringExp->nestingCount--;
+                               }
+                       }
+               }
+
                // Check for a new state starting character
                if (sc.state == SCE_P_DEFAULT) {
                        if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
@@ -373,8 +761,8 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                        base_n_number = true;
                                        sc.SetState(SCE_P_NUMBER);
                                } else if (sc.ch == '0' &&
-                                       (sc.chNext == 'o' || sc.chNext == 'O' || sc.chNext == 'b' || 
sc.chNext == 'B')) {
-                                       if (base2or8Literals) {
+                                               (sc.chNext == 'o' || sc.chNext == 'O' || sc.chNext == 'b' || 
sc.chNext == 'B')) {
+                                       if (options.base2or8Literals) {
                                                base_n_number = true;
                                                sc.SetState(SCE_P_NUMBER);
                                        } else {
@@ -385,19 +773,22 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
                                        base_n_number = false;
                                        sc.SetState(SCE_P_NUMBER);
                                }
-                       } else if ((isascii(sc.ch) && isoperator(static_cast<char>(sc.ch))) || sc.ch == '`') {
+                       } else if ((IsASCII(sc.ch) && isoperator(static_cast<char>(sc.ch))) || sc.ch == '`') {
                                sc.SetState(SCE_P_OPERATOR);
                        } else if (sc.ch == '#') {
                                sc.SetState(sc.chNext == '#' ? SCE_P_COMMENTBLOCK : SCE_P_COMMENTLINE);
                        } else if (sc.ch == '@') {
-                               sc.SetState(SCE_P_DECORATOR);
+                               if (IsFirstNonWhitespace(sc.currentPos, styler))
+                                       sc.SetState(SCE_P_DECORATOR);
+                               else
+                                       sc.SetState(SCE_P_OPERATOR);
                        } else if (IsPyStringStart(sc.ch, sc.chNext, sc.GetRelative(2), allowedLiterals)) {
-                               unsigned int nextIndex = 0;
+                               Sci_PositionU nextIndex = 0;
                                sc.SetState(GetPyStringState(styler, sc.currentPos, &nextIndex, 
allowedLiterals));
                                while (nextIndex > (sc.currentPos + 1) && sc.More()) {
                                        sc.Forward();
                                }
-                       } else if (IsAWordStart(sc.ch)) {
+                       } else if (IsAWordStart(sc.ch, options.unicodeIdentifiers)) {
                                sc.SetState(SCE_P_IDENTIFIER);
                        }
                }
@@ -406,11 +797,11 @@ static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eol_pos; i++) {
-               char ch = styler[i];
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       const Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               const char ch = styler[i];
                if (ch == '#')
                        return true;
                else if (ch != ' ' && ch != '\t')
@@ -419,37 +810,35 @@ static bool IsCommentLine(int line, Accessor &styler) {
        return false;
 }
 
-static bool IsQuoteLine(int line, Accessor &styler) {
-       int style = styler.StyleAt(styler.LineStart(line)) & 31;
+static bool IsQuoteLine(Sci_Position line, const Accessor &styler) {
+       const int style = styler.StyleAt(styler.LineStart(line)) & 31;
        return ((style == SCE_P_TRIPLE) || (style == SCE_P_TRIPLEDOUBLE));
 }
 
 
-static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unused*/,
-                      WordList *[], Accessor &styler) {
-       const int maxPos = startPos + length;
-       const int maxLines = (maxPos == styler.Length()) ? styler.GetLine(maxPos) : styler.GetLine(maxPos - 
1); // Requested last line
-       const int docLines = styler.GetLine(styler.Length());   // Available last line
+void SCI_METHOD LexerPython::Fold(Sci_PositionU startPos, Sci_Position length, int /*initStyle - unused*/, 
IDocument *pAccess) {
+       if (!options.fold)
+               return;
 
-       // property fold.quotes.python
-       //      This option enables folding multi-line quoted strings when using the Python lexer.
-       const bool foldQuotes = styler.GetPropertyInt("fold.quotes.python") != 0;
+       Accessor styler(pAccess, NULL);
 
-       const bool foldCompact = styler.GetPropertyInt("fold.compact") != 0;
+       const Sci_Position maxPos = startPos + length;
+       const Sci_Position maxLines = (maxPos == styler.Length()) ? styler.GetLine(maxPos) : 
styler.GetLine(maxPos - 1);        // Requested last line
+       const Sci_Position docLines = styler.GetLine(styler.Length());  // Available last line
 
        // Backtrack to previous non-blank line so we can determine indent level
        // for any white space lines (needed esp. within triple quoted strings)
        // and so we can fix any preceding fold level (which is why we go back
        // at least one line in all cases)
        int spaceFlags = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
        while (lineCurrent > 0) {
                lineCurrent--;
                indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
                if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) &&
-                       (!IsCommentLine(lineCurrent, styler)) &&
-                       (!IsQuoteLine(lineCurrent, styler)))
+                               (!IsCommentLine(lineCurrent, styler)) &&
+                               (!IsQuoteLine(lineCurrent, styler)))
                        break;
        }
        int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
@@ -459,7 +848,7 @@ static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unuse
        int prev_state = SCE_P_DEFAULT & 31;
        if (lineCurrent >= 1)
                prev_state = styler.StyleAt(startPos - 1) & 31;
-       int prevQuote = foldQuotes && ((prev_state == SCE_P_TRIPLE) || (prev_state == SCE_P_TRIPLEDOUBLE));
+       int prevQuote = options.foldQuotes && ((prev_state == SCE_P_TRIPLE) || (prev_state == 
SCE_P_TRIPLEDOUBLE));
 
        // Process all characters to end of requested range or end of any triple quote
        //that hangs over the end of the range.  Cap processing in all cases
@@ -468,15 +857,15 @@ static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unuse
 
                // Gather info
                int lev = indentCurrent;
-               int lineNext = lineCurrent + 1;
+               Sci_Position lineNext = lineCurrent + 1;
                int indentNext = indentCurrent;
                int quote = false;
                if (lineNext <= docLines) {
                        // Information about next line is only available if not at end of document
                        indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);
-                       int lookAtPos = (styler.LineStart(lineNext) == styler.Length()) ? styler.Length() - 1 
: styler.LineStart(lineNext);
-                       int style = styler.StyleAt(lookAtPos) & 31;
-                       quote = foldQuotes && ((style == SCE_P_TRIPLE) || (style == SCE_P_TRIPLEDOUBLE));
+                       Sci_Position lookAtPos = (styler.LineStart(lineNext) == styler.Length()) ? 
styler.Length() - 1 : styler.LineStart(lineNext);
+                       const int style = styler.StyleAt(lookAtPos) & 31;
+                       quote = options.foldQuotes && ((style == SCE_P_TRIPLE) || (style == 
SCE_P_TRIPLEDOUBLE));
                }
                const int quote_start = (quote && !prevQuote);
                const int quote_continue = (quote && prevQuote);
@@ -498,32 +887,38 @@ static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unuse
                // Skip past any blank lines for next indent level info; we skip also
                // comments (all comments, not just those starting in column 0)
                // which effectively folds them into surrounding code rather
-               // than screwing up folding.
+               // than screwing up folding.  If comments end file, use the min
+               // comment indent as the level after
 
+               int minCommentLevel = indentCurrentLevel;
                while (!quote &&
-                       (lineNext < docLines) &&
-                       ((indentNext & SC_FOLDLEVELWHITEFLAG) ||
-                        (lineNext <= docLines && IsCommentLine(lineNext, styler)))) {
+                               (lineNext < docLines) &&
+                               ((indentNext & SC_FOLDLEVELWHITEFLAG) ||
+                                (lineNext <= docLines && IsCommentLine(lineNext, styler)))) {
+
+                       if (IsCommentLine(lineNext, styler) && indentNext < minCommentLevel) {
+                               minCommentLevel = indentNext;
+                       }
 
                        lineNext++;
                        indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);
                }
 
-               const int levelAfterComments = indentNext & SC_FOLDLEVELNUMBERMASK;
-               const int levelBeforeComments = Maximum(indentCurrentLevel,levelAfterComments);
+               const int levelAfterComments = ((lineNext < docLines) ? indentNext & SC_FOLDLEVELNUMBERMASK : 
minCommentLevel);
+               const int levelBeforeComments = Maximum(indentCurrentLevel, levelAfterComments);
 
                // Now set all the indent levels on the lines we skipped
                // Do this from end to start.  Once we encounter one line
                // which is indented more than the line after the end of
                // the comment-block, use the level of the block before
 
-               int skipLine = lineNext;
+               Sci_Position skipLine = lineNext;
                int skipLevel = levelAfterComments;
 
                while (--skipLine > lineCurrent) {
-                       int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, NULL);
+                       const int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, NULL);
 
-                       if (foldCompact) {
+                       if (options.foldCompact) {
                                if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments)
                                        skipLevel = levelBeforeComments;
 
@@ -532,8 +927,8 @@ static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unuse
                                styler.SetLevel(skipLine, skipLevel | whiteFlag);
                        } else {
                                if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments &&
-                                       !(skipLineIndent & SC_FOLDLEVELWHITEFLAG) &&
-                                       !IsCommentLine(skipLine, styler))
+                                               !(skipLineIndent & SC_FOLDLEVELWHITEFLAG) &&
+                                               !IsCommentLine(skipLine, styler))
                                        skipLevel = levelBeforeComments;
 
                                styler.SetLevel(skipLine, skipLevel);
@@ -550,7 +945,7 @@ static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unuse
                prevQuote = quote;
 
                // Set fold level for this line and move to next line
-               styler.SetLevel(lineCurrent, foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG);
+               styler.SetLevel(lineCurrent, options.foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG);
                indentCurrent = indentNext;
                lineCurrent = lineNext;
        }
@@ -560,12 +955,5 @@ static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unuse
        //styler.SetLevel(lineCurrent, indentCurrent);
 }
 
-static const char *const pythonWordListDesc[] = {
-       "Keywords",
-       "Highlighted identifiers",
-       0
-};
-
-LexerModule lmPython(SCLEX_PYTHON, ColourisePyDoc, "python", FoldPyDoc,
-                                        pythonWordListDesc);
-
+LexerModule lmPython(SCLEX_PYTHON, LexerPython::LexerFactoryPython, "python",
+                    pythonWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexR.cxx b/plugins/scintilla/scintilla/lexers/LexR.cxx
index d18fffb..c72937b 100644
--- a/plugins/scintilla/scintilla/lexers/LexR.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexR.cxx
@@ -37,7 +37,7 @@ static inline bool IsAWordStart(const int ch) {
 }
 
 static inline bool IsAnOperator(const int ch) {
-       if (isascii(ch) && isalnum(ch))
+       if (IsASCII(ch) && isalnum(ch))
                return false;
        // '.' left out as it is used to make up numbers
        if (ch == '-' || ch == '+' || ch == '!' || ch == '~' ||
@@ -50,7 +50,7 @@ static inline bool IsAnOperator(const int ch) {
        return false;
 }
 
-static void ColouriseRDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseRDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler) {
 
        WordList &keywords   = *keywordlists[0];
@@ -146,13 +146,13 @@ static void ColouriseRDoc(unsigned int startPos, int length, int initStyle, Word
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
-static void FoldRDoc(unsigned int startPos, int length, int, WordList *[],
+static void FoldRDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[],
                        Accessor &styler) {
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -160,7 +160,7 @@ static void FoldRDoc(unsigned int startPos, int length, int, WordList *[],
        int levelNext = levelCurrent;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
diff --git a/plugins/scintilla/scintilla/lexers/LexRebol.cxx b/plugins/scintilla/scintilla/lexers/LexRebol.cxx
index 7d000df..bce93df 100644
--- a/plugins/scintilla/scintilla/lexers/LexRebol.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexRebol.cxx
@@ -68,7 +68,7 @@ static inline bool IsBinaryStart(const int ch, const int ch2, const int ch3, con
 }
 
 
-static void ColouriseRebolDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], 
Accessor &styler) {
+static void ColouriseRebolDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[], Accessor &styler) {
 
        WordList &keywords = *keywordlists[0];
        WordList &keywords2 = *keywordlists[1];
@@ -79,7 +79,7 @@ static void ColouriseRebolDoc(unsigned int startPos, int length, int initStyle,
        WordList &keywords7 = *keywordlists[6];
        WordList &keywords8 = *keywordlists[7];
 
-       int currentLine = styler.GetLine(startPos);
+       Sci_Position currentLine = styler.GetLine(startPos);
        // Initialize the braced string {.. { ... } ..} nesting level, if we are inside such a string.
        int stringLevel = 0;
        if (initStyle == SCE_REBOL_BRACEDSTRING || initStyle == SCE_REBOL_COMMENTBLOCK) {
@@ -273,16 +273,16 @@ static void ColouriseRebolDoc(unsigned int startPos, int length, int initStyle,
 }
 
 
-static void FoldRebolDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
+static void FoldRebolDoc(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, WordList *[],
                             Accessor &styler) {
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int style = styleNext;
diff --git a/plugins/scintilla/scintilla/lexers/LexRegistry.cxx 
b/plugins/scintilla/scintilla/lexers/LexRegistry.cxx
new file mode 100644
index 0000000..43519e2
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexRegistry.cxx
@@ -0,0 +1,416 @@
+// Scintilla source code edit control
+/**
+ * @file LexRegistry.cxx
+ * @date July 26 2014
+ * @brief Lexer for Windows registration files(.reg)
+ * @author nkmathew
+ *
+ * The License.txt file describes the conditions under which this software may be
+ * distributed.
+ *
+ */
+
+#include <cstdlib>
+#include <cassert>
+#include <cctype>
+#include <cstdio>
+#include <string>
+#include <vector>
+#include <map>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+#include "OptionSet.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static const char *const RegistryWordListDesc[] = {
+       0
+};
+
+struct OptionsRegistry {
+       bool foldCompact;
+       bool fold;
+       OptionsRegistry() {
+               foldCompact = false;
+               fold = false;
+       }
+};
+
+struct OptionSetRegistry : public OptionSet<OptionsRegistry> {
+       OptionSetRegistry() {
+               DefineProperty("fold.compact", &OptionsRegistry::foldCompact);
+               DefineProperty("fold", &OptionsRegistry::fold);
+               DefineWordListSets(RegistryWordListDesc);
+       }
+};
+
+class LexerRegistry : public ILexer {
+       OptionsRegistry options;
+       OptionSetRegistry optSetRegistry;
+
+       static bool IsStringState(int state) {
+               return (state == SCE_REG_VALUENAME || state == SCE_REG_STRING);
+       }
+
+       static bool IsKeyPathState(int state) {
+               return (state == SCE_REG_ADDEDKEY || state == SCE_REG_DELETEDKEY);
+       }
+
+       static bool AtValueType(LexAccessor &styler, Sci_Position start) {
+               Sci_Position i = 0;
+               while (i < 10) {
+                       i++;
+                       char curr = styler.SafeGetCharAt(start+i, '\0');
+                       if (curr == ':') {
+                               return true;
+                       } else if (!curr) {
+                               return false;
+                       }
+               }
+               return false;
+       }
+
+       static bool IsNextNonWhitespace(LexAccessor &styler, Sci_Position start, char ch) {
+               Sci_Position i = 0;
+               while (i < 100) {
+                       i++;
+                       char curr = styler.SafeGetCharAt(start+i, '\0');
+                       char next = styler.SafeGetCharAt(start+i+1, '\0');
+                       bool atEOL = (curr == '\r' && next != '\n') || (curr == '\n');
+                       if (curr == ch) {
+                               return true;
+                       } else if (!isspacechar(curr) || atEOL) {
+                               return false;
+                       }
+               }
+               return false;
+       }
+
+       // Looks for the equal sign at the end of the string
+       static bool AtValueName(LexAccessor &styler, Sci_Position start) {
+               bool atEOL = false;
+               Sci_Position i = 0;
+               bool escaped = false;
+               while (!atEOL) {
+                       i++;
+                       char curr = styler.SafeGetCharAt(start+i, '\0');
+                       char next = styler.SafeGetCharAt(start+i+1, '\0');
+                       atEOL = (curr == '\r' && next != '\n') || (curr == '\n');
+                       if (escaped) {
+                               escaped = false;
+                               continue;
+                       }
+                       escaped = curr == '\\';
+                       if (curr == '"') {
+                               return IsNextNonWhitespace(styler, start+i, '=');
+                       } else if (!curr) {
+                               return false;
+                       }
+               }
+               return false;
+       }
+
+       static bool AtKeyPathEnd(LexAccessor &styler, Sci_Position start) {
+               bool atEOL = false;
+               Sci_Position i = 0;
+               while (!atEOL) {
+                       i++;
+                       char curr = styler.SafeGetCharAt(start+i, '\0');
+                       char next = styler.SafeGetCharAt(start+i+1, '\0');
+                       atEOL = (curr == '\r' && next != '\n') || (curr == '\n');
+                       if (curr == ']' || !curr) {
+                               // There's still at least one or more square brackets ahead
+                               return false;
+                       }
+               }
+               return true;
+       }
+
+       static bool AtGUID(LexAccessor &styler, Sci_Position start) {
+               int count = 8;
+               int portion = 0;
+               int offset = 1;
+               char digit = '\0';
+               while (portion < 5) {
+                       int i = 0;
+                       while (i < count) {
+                               digit = styler.SafeGetCharAt(start+offset);
+                               if (!(isxdigit(digit) || digit == '-')) {
+                                       return false;
+                               }
+                               offset++;
+                               i++;
+                       }
+                       portion++;
+                       count = (portion == 4) ? 13 : 5;
+               }
+               digit = styler.SafeGetCharAt(start+offset);
+               if (digit == '}') {
+                       return true;
+               } else {
+                       return false;
+               }
+       }
+
+public:
+       LexerRegistry() {}
+       virtual ~LexerRegistry() {}
+       int SCI_METHOD Version() const override {
+               return lvOriginal;
+       }
+       void SCI_METHOD Release() override {
+               delete this;
+       }
+       const char *SCI_METHOD PropertyNames() override {
+               return optSetRegistry.PropertyNames();
+       }
+       int SCI_METHOD PropertyType(const char *name) override {
+               return optSetRegistry.PropertyType(name);
+       }
+       const char *SCI_METHOD DescribeProperty(const char *name) override {
+               return optSetRegistry.DescribeProperty(name);
+       }
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override {
+               if (optSetRegistry.PropertySet(&options, key, val)) {
+                       return 0;
+               }
+               return -1;
+       }
+       Sci_Position SCI_METHOD WordListSet(int, const char *) override {
+               return -1;
+       }
+       void *SCI_METHOD PrivateCall(int, void *) override {
+               return 0;
+       }
+       static ILexer *LexerFactoryRegistry() {
+               return new LexerRegistry;
+       }
+       const char *SCI_METHOD DescribeWordListSets() override {
+               return optSetRegistry.DescribeWordListSets();
+       }
+       void SCI_METHOD Lex(Sci_PositionU startPos,
+                                                               Sci_Position length,
+                                                               int initStyle,
+                                                               IDocument *pAccess) override;
+       void SCI_METHOD Fold(Sci_PositionU startPos,
+                                                                Sci_Position length,
+                                                                int initStyle,
+                                                                IDocument *pAccess) override;
+};
+
+void SCI_METHOD LexerRegistry::Lex(Sci_PositionU startPos,
+                                                                  Sci_Position length,
+                                                                  int initStyle,
+                                                                  IDocument *pAccess) {
+       int beforeGUID = SCE_REG_DEFAULT;
+       int beforeEscape = SCE_REG_DEFAULT;
+       CharacterSet setOperators = CharacterSet(CharacterSet::setNone, "-,.=:\\@()");
+       LexAccessor styler(pAccess);
+       StyleContext context(startPos, length, initStyle, styler);
+       bool highlight = true;
+       bool afterEqualSign = false;
+       while (context.More()) {
+               if (context.atLineStart) {
+                       Sci_Position currPos = static_cast<Sci_Position>(context.currentPos);
+                       bool continued = styler[currPos-3] == '\\';
+                       highlight = continued ? true : false;
+               }
+               switch (context.state) {
+                       case SCE_REG_COMMENT:
+                               if (context.atLineEnd) {
+                                       context.SetState(SCE_REG_DEFAULT);
+                               }
+                               break;
+                       case SCE_REG_VALUENAME:
+                       case SCE_REG_STRING: {
+                                       Sci_Position currPos = static_cast<Sci_Position>(context.currentPos);
+                                       if (context.ch == '"') {
+                                               context.ForwardSetState(SCE_REG_DEFAULT);
+                                       } else if (context.ch == '\\') {
+                                               beforeEscape = context.state;
+                                               context.SetState(SCE_REG_ESCAPED);
+                                               context.Forward();
+                                       } else if (context.ch == '{') {
+                                               if (AtGUID(styler, currPos)) {
+                                                       beforeGUID = context.state;
+                                                       context.SetState(SCE_REG_STRING_GUID);
+                                               }
+                                       }
+                                       if (context.state == SCE_REG_STRING &&
+                                               context.ch == '%' &&
+                                               (isdigit(context.chNext) || context.chNext == '*')) {
+                                               context.SetState(SCE_REG_PARAMETER);
+                                       }
+                               }
+                               break;
+                       case SCE_REG_PARAMETER:
+                               context.ForwardSetState(SCE_REG_STRING);
+                               if (context.ch == '"') {
+                                       context.ForwardSetState(SCE_REG_DEFAULT);
+                               }
+                               break;
+                       case SCE_REG_VALUETYPE:
+                               if (context.ch == ':') {
+                                       context.SetState(SCE_REG_DEFAULT);
+                                       afterEqualSign = false;
+                               }
+                               break;
+                       case SCE_REG_HEXDIGIT:
+                       case SCE_REG_OPERATOR:
+                               context.SetState(SCE_REG_DEFAULT);
+                               break;
+                       case SCE_REG_DELETEDKEY:
+                       case SCE_REG_ADDEDKEY: {
+                                       Sci_Position currPos = static_cast<Sci_Position>(context.currentPos);
+                                       if (context.ch == ']' && AtKeyPathEnd(styler, currPos)) {
+                                               context.ForwardSetState(SCE_REG_DEFAULT);
+                                       } else if (context.ch == '{') {
+                                               if (AtGUID(styler, currPos)) {
+                                                       beforeGUID = context.state;
+                                                       context.SetState(SCE_REG_KEYPATH_GUID);
+                                               }
+                                       }
+                               }
+                               break;
+                       case SCE_REG_ESCAPED:
+                               if (context.ch == '"') {
+                                       context.SetState(beforeEscape);
+                                       context.ForwardSetState(SCE_REG_DEFAULT);
+                               } else if (context.ch == '\\') {
+                                       context.Forward();
+                               } else {
+                                       context.SetState(beforeEscape);
+                                       beforeEscape = SCE_REG_DEFAULT;
+                               }
+                               break;
+                       case SCE_REG_STRING_GUID:
+                       case SCE_REG_KEYPATH_GUID: {
+                                       if (context.ch == '}') {
+                                               context.ForwardSetState(beforeGUID);
+                                               beforeGUID = SCE_REG_DEFAULT;
+                                       }
+                                       Sci_Position currPos = static_cast<Sci_Position>(context.currentPos);
+                                       if (context.ch == '"' && IsStringState(context.state)) {
+                                               context.ForwardSetState(SCE_REG_DEFAULT);
+                                       } else if (context.ch == ']' &&
+                                                          AtKeyPathEnd(styler, currPos) &&
+                                                          IsKeyPathState(context.state)) {
+                                               context.ForwardSetState(SCE_REG_DEFAULT);
+                                       } else if (context.ch == '\\' && IsStringState(context.state)) {
+                                               beforeEscape = context.state;
+                                               context.SetState(SCE_REG_ESCAPED);
+                                               context.Forward();
+                                       }
+                               }
+                               break;
+               }
+               // Determine if a new state should be entered.
+               if (context.state == SCE_REG_DEFAULT) {
+                       Sci_Position currPos = static_cast<Sci_Position>(context.currentPos);
+                       if (context.ch == ';') {
+                               context.SetState(SCE_REG_COMMENT);
+                       } else if (context.ch == '"') {
+                               if (AtValueName(styler, currPos)) {
+                                       context.SetState(SCE_REG_VALUENAME);
+                               } else {
+                                       context.SetState(SCE_REG_STRING);
+                               }
+                       } else if (context.ch == '[') {
+                               if (IsNextNonWhitespace(styler, currPos, '-')) {
+                                       context.SetState(SCE_REG_DELETEDKEY);
+                               } else {
+                                       context.SetState(SCE_REG_ADDEDKEY);
+                               }
+                       } else if (context.ch == '=') {
+                               afterEqualSign = true;
+                               highlight = true;
+                       } else if (afterEqualSign) {
+                               bool wordStart = isalpha(context.ch) && !isalpha(context.chPrev);
+                               if (wordStart && AtValueType(styler, currPos)) {
+                                       context.SetState(SCE_REG_VALUETYPE);
+                               }
+                       } else if (isxdigit(context.ch) && highlight) {
+                               context.SetState(SCE_REG_HEXDIGIT);
+                       }
+                       highlight = (context.ch == '@') ? true : highlight;
+                       if (setOperators.Contains(context.ch) && highlight) {
+                               context.SetState(SCE_REG_OPERATOR);
+                       }
+               }
+               context.Forward();
+       }
+       context.Complete();
+}
+
+// Folding similar to that of FoldPropsDoc in LexOthers
+void SCI_METHOD LexerRegistry::Fold(Sci_PositionU startPos,
+                                                                       Sci_Position length,
+                                                                       int,
+                                                                       IDocument *pAccess) {
+       if (!options.fold) {
+               return;
+       }
+       LexAccessor styler(pAccess);
+       Sci_Position currLine = styler.GetLine(startPos);
+       int visibleChars = 0;
+       Sci_PositionU endPos = startPos + length;
+       bool atKeyPath = false;
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
+               atKeyPath = IsKeyPathState(styler.StyleAt(i)) ? true : atKeyPath;
+               char curr = styler.SafeGetCharAt(i);
+               char next = styler.SafeGetCharAt(i+1);
+               bool atEOL = (curr == '\r' && next != '\n') || (curr == '\n');
+               if (atEOL || i == (endPos-1)) {
+                       int level = SC_FOLDLEVELBASE;
+                       if (currLine > 0) {
+                               int prevLevel = styler.LevelAt(currLine-1);
+                               if (prevLevel & SC_FOLDLEVELHEADERFLAG) {
+                                       level += 1;
+                               } else {
+                                       level = prevLevel;
+                               }
+                       }
+                       if (!visibleChars && options.foldCompact) {
+                               level |= SC_FOLDLEVELWHITEFLAG;
+                       } else if (atKeyPath) {
+                               level = SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG;
+                       }
+                       if (level != styler.LevelAt(currLine)) {
+                               styler.SetLevel(currLine, level);
+                       }
+                       currLine++;
+                       visibleChars = 0;
+                       atKeyPath = false;
+               }
+               if (!isspacechar(curr)) {
+                       visibleChars++;
+               }
+       }
+
+       // Make the folding reach the last line in the file
+       int level = SC_FOLDLEVELBASE;
+       if (currLine > 0) {
+               int prevLevel = styler.LevelAt(currLine-1);
+               if (prevLevel & SC_FOLDLEVELHEADERFLAG) {
+                       level += 1;
+               } else {
+                       level = prevLevel;
+               }
+       }
+       styler.SetLevel(currLine, level);
+}
+
+LexerModule lmRegistry(SCLEX_REGISTRY,
+                                          LexerRegistry::LexerFactoryRegistry,
+                                          "registry",
+                                          RegistryWordListDesc);
+
diff --git a/plugins/scintilla/scintilla/lexers/LexRuby.cxx b/plugins/scintilla/scintilla/lexers/LexRuby.cxx
index 833ad59..42f30fd 100644
--- a/plugins/scintilla/scintilla/lexers/LexRuby.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexRuby.cxx
@@ -29,7 +29,7 @@ using namespace Scintilla;
 
 //XXX Identical to Perl, put in common area
 static inline bool isEOLChar(char ch) {
-       return (ch == '\r') || (ch == '\n');
+    return (ch == '\r') || (ch == '\n');
 }
 
 #define isSafeASCII(ch) ((unsigned int)(ch) <= 127)
@@ -60,7 +60,7 @@ static inline bool isSafeWordcharOrHigh(char ch) {
 }
 
 static bool inline iswhitespace(char ch) {
-       return ch == ' ' || ch == '\t';
+    return ch == ' ' || ch == '\t';
 }
 
 #define MAX_KEYWORD_LENGTH 200
@@ -68,26 +68,26 @@ static bool inline iswhitespace(char ch) {
 #define STYLE_MASK 63
 #define actual_style(style) (style & STYLE_MASK)
 
-static bool followsDot(unsigned int pos, Accessor &styler) {
+static bool followsDot(Sci_PositionU pos, Accessor &styler) {
     styler.Flush();
     for (; pos >= 1; --pos) {
         int style = actual_style(styler.StyleAt(pos));
         char ch;
         switch (style) {
-            case SCE_RB_DEFAULT:
-                ch = styler[pos];
-                if (ch == ' ' || ch == '\t') {
-                    //continue
-                } else {
-                    return false;
-                }
-                break;
+        case SCE_RB_DEFAULT:
+            ch = styler[pos];
+            if (ch == ' ' || ch == '\t') {
+                //continue
+            } else {
+                return false;
+            }
+            break;
 
-            case SCE_RB_OPERATOR:
-                return styler[pos] == '.';
+        case SCE_RB_OPERATOR:
+            return styler[pos] == '.';
 
-            default:
-                return false;
+        default:
+            return false;
         }
     }
     return false;
@@ -95,33 +95,33 @@ static bool followsDot(unsigned int pos, Accessor &styler) {
 
 // Forward declarations
 static bool keywordIsAmbiguous(const char *prevWord);
-static bool keywordDoStartsLoop(int pos,
+static bool keywordDoStartsLoop(Sci_Position pos,
                                 Accessor &styler);
 static bool keywordIsModifier(const char *word,
-                              int pos,
+                              Sci_Position pos,
                               Accessor &styler);
 
-static int ClassifyWordRb(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char 
*prevWord) {
-       char s[MAX_KEYWORD_LENGTH];
-    unsigned int i, j;
-       unsigned int lim = end - start + 1; // num chars to copy
-       if (lim >= MAX_KEYWORD_LENGTH) {
-               lim = MAX_KEYWORD_LENGTH - 1;
-       }
-       for (i = start, j = 0; j < lim; i++, j++) {
-               s[j] = styler[i];
-       }
+static int ClassifyWordRb(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler, char 
*prevWord) {
+    char s[MAX_KEYWORD_LENGTH];
+    Sci_PositionU i, j;
+    Sci_PositionU lim = end - start + 1; // num chars to copy
+    if (lim >= MAX_KEYWORD_LENGTH) {
+        lim = MAX_KEYWORD_LENGTH - 1;
+    }
+    for (i = start, j = 0; j < lim; i++, j++) {
+        s[j] = styler[i];
+    }
     s[j] = '\0';
-       int chAttr;
-       if (0 == strcmp(prevWord, "class"))
-               chAttr = SCE_RB_CLASSNAME;
-       else if (0 == strcmp(prevWord, "module"))
-               chAttr = SCE_RB_MODULE_NAME;
-       else if (0 == strcmp(prevWord, "def"))
-               chAttr = SCE_RB_DEFNAME;
+    int chAttr;
+    if (0 == strcmp(prevWord, "class"))
+        chAttr = SCE_RB_CLASSNAME;
+    else if (0 == strcmp(prevWord, "module"))
+        chAttr = SCE_RB_MODULE_NAME;
+    else if (0 == strcmp(prevWord, "def"))
+        chAttr = SCE_RB_DEFNAME;
     else if (keywords.InList(s) && ((start == 0) || !followsDot(start - 1, styler))) {
         if (keywordIsAmbiguous(s)
-            && keywordIsModifier(s, start, styler)) {
+                && keywordIsModifier(s, start, styler)) {
 
             // Demoted keywords are colored as keywords,
             // but do not affect changes in indentation.
@@ -136,39 +136,39 @@ static int ClassifyWordRb(unsigned int start, unsigned int end, WordList &keywor
         } else {
             chAttr = SCE_RB_WORD;
         }
-       } else
+    } else
         chAttr = SCE_RB_IDENTIFIER;
-       styler.ColourTo(end, chAttr);
-       if (chAttr == SCE_RB_WORD) {
-               strcpy(prevWord, s);
-       } else {
-               prevWord[0] = 0;
-       }
+    styler.ColourTo(end, chAttr);
+    if (chAttr == SCE_RB_WORD) {
+        strcpy(prevWord, s);
+    } else {
+        prevWord[0] = 0;
+    }
     return chAttr;
 }
 
 
 //XXX Identical to Perl, put in common area
-static bool isMatch(Accessor &styler, int lengthDoc, int pos, const char *val) {
-       if ((pos + static_cast<int>(strlen(val))) >= lengthDoc) {
-               return false;
-       }
-       while (*val) {
-               if (*val != styler[pos++]) {
-                       return false;
-               }
-               val++;
-       }
-       return true;
+static bool isMatch(Accessor &styler, Sci_Position lengthDoc, Sci_Position pos, const char *val) {
+    if ((pos + static_cast<int>(strlen(val))) >= lengthDoc) {
+        return false;
+    }
+    while (*val) {
+        if (*val != styler[pos++]) {
+            return false;
+        }
+        val++;
+    }
+    return true;
 }
 
 // Do Ruby better -- find the end of the line, work back,
 // and then check for leading white space
 
 // Precondition: the here-doc target can be indented
-static bool lookingAtHereDocDelim(Accessor        &styler,
-                                  int                  pos,
-                                  int                  lengthDoc,
+static bool lookingAtHereDocDelim(Accessor     &styler,
+                                  Sci_Position         pos,
+                                  Sci_Position         lengthDoc,
                                   const char   *HereDocDelim)
 {
     if (!isMatch(styler, lengthDoc, pos, HereDocDelim)) {
@@ -187,21 +187,21 @@ static bool lookingAtHereDocDelim(Accessor           &styler,
 
 //XXX Identical to Perl, put in common area
 static char opposite(char ch) {
-       if (ch == '(')
-               return ')';
-       if (ch == '[')
-               return ']';
-       if (ch == '{')
-               return '}';
-       if (ch == '<')
-               return '>';
-       return ch;
+    if (ch == '(')
+        return ')';
+    if (ch == '[')
+        return ']';
+    if (ch == '{')
+        return '}';
+    if (ch == '<')
+        return '>';
+    return ch;
 }
 
 // Null transitions when we see we've reached the end
 // and need to relex the curr char.
 
-static void redo_char(int &i, char &ch, char &chNext, char &chNext2,
+static void redo_char(Sci_Position &i, char &ch, char &chNext, char &chNext2,
                       int &state) {
     i--;
     chNext2 = chNext;
@@ -209,19 +209,19 @@ static void redo_char(int &i, char &ch, char &chNext, char &chNext2,
     state = SCE_RB_DEFAULT;
 }
 
-static void advance_char(int &i, char &ch, char &chNext, char &chNext2) {
+static void advance_char(Sci_Position &i, char &ch, char &chNext, char &chNext2) {
     i++;
     ch = chNext;
     chNext = chNext2;
 }
 
 // precondition: startPos points to one after the EOL char
-static bool currLineContainsHereDelims(int& startPos,
+static bool currLineContainsHereDelims(Sci_Position &startPos,
                                        Accessor &styler) {
     if (startPos <= 1)
         return false;
 
-    int pos;
+    Sci_Position pos;
     for (pos = startPos - 1; pos > 0; pos--) {
         char ch = styler.SafeGetCharAt(pos);
         if (isEOLChar(ch)) {
@@ -249,7 +249,7 @@ static bool currLineContainsHereDelims(int& startPos,
 // to be hoisted out of the function.
 
 class QuoteCls {
-    public:
+public:
     int  Count;
     char Up;
     char Down;
@@ -266,19 +266,19 @@ class QuoteCls {
         Up    = u;
         Down  = opposite(Up);
     }
-    QuoteCls(const QuoteCls& q) {
+    QuoteCls(const QuoteCls &q) {
         // copy constructor -- use this for copying in
         Count = q.Count;
         Up    = q.Up;
         Down  = q.Down;
     }
-    QuoteCls& operator=(const QuoteCls& q) { // assignment constructor
+    QuoteCls &operator=(const QuoteCls &q) { // assignment constructor
         if (this != &q) {
             Count = q.Count;
             Up    = q.Up;
             Down  = q.Down;
         }
-               return *this;
+        return *this;
     }
 
 };
@@ -287,11 +287,11 @@ class QuoteCls {
 static void enterInnerExpression(int  *p_inner_string_types,
                                  int  *p_inner_expn_brace_counts,
                                  QuoteCls *p_inner_quotes,
-                                 int&  inner_string_count,
-                                 int&  state,
-                                 int&  brace_counts,
+                                 int  &inner_string_count,
+                                 int  &state,
+                                 int  &brace_counts,
                                  QuoteCls curr_quote
-                                 ) {
+                                ) {
     p_inner_string_types[inner_string_count] = state;
     state = SCE_RB_DEFAULT;
     p_inner_expn_brace_counts[inner_string_count] = brace_counts;
@@ -301,43 +301,43 @@ static void enterInnerExpression(int  *p_inner_string_types,
 }
 
 static void exitInnerExpression(int *p_inner_string_types,
-                                 int *p_inner_expn_brace_counts,
-                                 QuoteCls *p_inner_quotes,
-                                 int& inner_string_count,
-                                 int& state,
-                                 int&  brace_counts,
-                                 QuoteCls& curr_quote
-                                ) {
+                                int *p_inner_expn_brace_counts,
+                                QuoteCls *p_inner_quotes,
+                                int &inner_string_count,
+                                int &state,
+                                int  &brace_counts,
+                                QuoteCls &curr_quote
+                               ) {
     --inner_string_count;
     state = p_inner_string_types[inner_string_count];
     brace_counts = p_inner_expn_brace_counts[inner_string_count];
     curr_quote = p_inner_quotes[inner_string_count];
 }
 
-static bool isEmptyLine(int pos,
+static bool isEmptyLine(Sci_Position pos,
                         Accessor &styler) {
-       int spaceFlags = 0;
-       int lineCurrent = styler.GetLine(pos);
-       int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
+    int spaceFlags = 0;
+    Sci_Position lineCurrent = styler.GetLine(pos);
+    int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
     return (indentCurrent & SC_FOLDLEVELWHITEFLAG) != 0;
 }
 
 static bool RE_CanFollowKeyword(const char *keyword) {
     if (!strcmp(keyword, "and")
-        || !strcmp(keyword, "begin")
-        || !strcmp(keyword, "break")
-        || !strcmp(keyword, "case")
-        || !strcmp(keyword, "do")
-        || !strcmp(keyword, "else")
-        || !strcmp(keyword, "elsif")
-        || !strcmp(keyword, "if")
-        || !strcmp(keyword, "next")
-        || !strcmp(keyword, "return")
-        || !strcmp(keyword, "when")
-        || !strcmp(keyword, "unless")
-        || !strcmp(keyword, "until")
-        || !strcmp(keyword, "not")
-        || !strcmp(keyword, "or")) {
+            || !strcmp(keyword, "begin")
+            || !strcmp(keyword, "break")
+            || !strcmp(keyword, "case")
+            || !strcmp(keyword, "do")
+            || !strcmp(keyword, "else")
+            || !strcmp(keyword, "elsif")
+            || !strcmp(keyword, "if")
+            || !strcmp(keyword, "next")
+            || !strcmp(keyword, "return")
+            || !strcmp(keyword, "when")
+            || !strcmp(keyword, "unless")
+            || !strcmp(keyword, "until")
+            || !strcmp(keyword, "not")
+            || !strcmp(keyword, "or")) {
         return true;
     }
     return false;
@@ -346,10 +346,10 @@ static bool RE_CanFollowKeyword(const char *keyword) {
 // Look at chars up to but not including endPos
 // Don't look at styles in case we're looking forward
 
-static int skipWhitespace(int startPos,
-                           int endPos,
-                           Accessor &styler) {
-    for (int i = startPos; i < endPos; i++) {
+static int skipWhitespace(Sci_Position startPos,
+                          Sci_Position endPos,
+                          Accessor &styler) {
+    for (Sci_Position i = startPos; i < endPos; i++) {
         if (!iswhitespace(styler[i])) {
             return i;
         }
@@ -363,23 +363,23 @@ static int skipWhitespace(int startPos,
 //
 // iPrev points to the start of <<
 
-static bool sureThisIsHeredoc(int iPrev,
+static bool sureThisIsHeredoc(Sci_Position iPrev,
                               Accessor &styler,
                               char *prevWord) {
 
     // Not so fast, since Ruby's so dynamic.  Check the context
     // to make sure we're OK.
     int prevStyle;
-    int lineStart = styler.GetLine(iPrev);
-    int lineStartPosn = styler.LineStart(lineStart);
+    Sci_Position lineStart = styler.GetLine(iPrev);
+    Sci_Position lineStartPosn = styler.LineStart(lineStart);
     styler.Flush();
 
     // Find the first word after some whitespace
-    int firstWordPosn = skipWhitespace(lineStartPosn, iPrev, styler);
+    Sci_Position firstWordPosn = skipWhitespace(lineStartPosn, iPrev, styler);
     if (firstWordPosn >= iPrev) {
         // Have something like {^     <<}
-               //XXX Look at the first previous non-comment non-white line
-               // to establish the context.  Not too likely though.
+        //XXX Look at the first previous non-comment non-white line
+        // to establish the context.  Not too likely though.
         return true;
     } else {
         switch (prevStyle = styler.StyleAt(firstWordPosn)) {
@@ -391,11 +391,11 @@ static bool sureThisIsHeredoc(int iPrev,
             return true;
         }
     }
-    int firstWordEndPosn = firstWordPosn;
+    Sci_Position firstWordEndPosn = firstWordPosn;
     char *dst = prevWord;
     for (;;) {
         if (firstWordEndPosn >= iPrev ||
-            styler.StyleAt(firstWordEndPosn) != prevStyle) {
+                styler.StyleAt(firstWordEndPosn) != prevStyle) {
             *dst = 0;
             break;
         }
@@ -404,8 +404,8 @@ static bool sureThisIsHeredoc(int iPrev,
     }
     //XXX Write a style-aware thing to regex scintilla buffer objects
     if (!strcmp(prevWord, "undef")
-        || !strcmp(prevWord, "def")
-        || !strcmp(prevWord, "alias")) {
+            || !strcmp(prevWord, "def")
+            || !strcmp(prevWord, "alias")) {
         // These keywords are what we were looking for
         return false;
     }
@@ -414,18 +414,18 @@ static bool sureThisIsHeredoc(int iPrev,
 
 // Routine that saves us from allocating a buffer for the here-doc target
 // targetEndPos points one past the end of the current target
-static bool haveTargetMatch(int currPos,
-                            int lengthDoc,
-                            int targetStartPos,
-                            int targetEndPos,
+static bool haveTargetMatch(Sci_Position currPos,
+                            Sci_Position lengthDoc,
+                            Sci_Position targetStartPos,
+                            Sci_Position targetEndPos,
                             Accessor &styler) {
     if (lengthDoc - currPos < targetEndPos - targetStartPos) {
         return false;
     }
-    int i, j;
+    Sci_Position i, j;
     for (i = targetStartPos, j = currPos;
-         i < targetEndPos && j < lengthDoc;
-         i++, j++) {
+            i < targetEndPos && j < lengthDoc;
+            i++, j++) {
         if (styler[i] != styler[j]) {
             return false;
         }
@@ -433,6 +433,32 @@ static bool haveTargetMatch(int currPos,
     return true;
 }
 
+// Finds the start position of the expression containing @p pos
+// @p min_pos should be a known expression start, e.g. the start of the line
+static Sci_Position findExpressionStart(Sci_Position pos,
+                                        Sci_Position min_pos,
+                                        Accessor &styler) {
+    int depth = 0;
+    for (; pos > min_pos; pos -= 1) {
+        int style = styler.StyleAt(pos - 1);
+        if (style == SCE_RB_OPERATOR) {
+            int ch = styler[pos - 1];
+            if (ch == '}' || ch == ')' || ch == ']') {
+                depth += 1;
+            } else if (ch == '{' || ch == '(' || ch == '[') {
+                if (depth == 0) {
+                    break;
+                } else {
+                    depth -= 1;
+                }
+            } else if (ch == ';' && depth == 0) {
+                break;
+            }
+        }
+    }
+    return pos;
+}
+
 // We need a check because the form
 // [identifier] <<[target]
 // is ambiguous.  The Ruby lexer/parser resolves it by
@@ -447,27 +473,31 @@ static bool haveTargetMatch(int currPos,
 
 // return true == yes, we have no heredocs
 
-static bool sureThisIsNotHeredoc(int lt2StartPos,
+static bool sureThisIsNotHeredoc(Sci_Position lt2StartPos,
                                  Accessor &styler) {
     int prevStyle;
-     // Use full document, not just part we're styling
-    int lengthDoc = styler.Length();
-    int lineStart = styler.GetLine(lt2StartPos);
-    int lineStartPosn = styler.LineStart(lineStart);
+    // Use full document, not just part we're styling
+    Sci_Position lengthDoc = styler.Length();
+    Sci_Position lineStart = styler.GetLine(lt2StartPos);
+    Sci_Position lineStartPosn = styler.LineStart(lineStart);
     styler.Flush();
     const bool definitely_not_a_here_doc = true;
     const bool looks_like_a_here_doc = false;
 
+    // find the expression start rather than the line start
+    Sci_Position exprStartPosn = findExpressionStart(lt2StartPos, lineStartPosn, styler);
+
     // Find the first word after some whitespace
-    int firstWordPosn = skipWhitespace(lineStartPosn, lt2StartPos, styler);
+    Sci_Position firstWordPosn = skipWhitespace(exprStartPosn, lt2StartPos, styler);
     if (firstWordPosn >= lt2StartPos) {
         return definitely_not_a_here_doc;
     }
     prevStyle = styler.StyleAt(firstWordPosn);
     // If we have '<<' following a keyword, it's not a heredoc
     if (prevStyle != SCE_RB_IDENTIFIER
-        && prevStyle != SCE_RB_INSTANCE_VAR
-        && prevStyle != SCE_RB_CLASS_VAR) {
+            && prevStyle != SCE_RB_SYMBOL
+            && prevStyle != SCE_RB_INSTANCE_VAR
+            && prevStyle != SCE_RB_CLASS_VAR) {
         return definitely_not_a_here_doc;
     }
     int newStyle = prevStyle;
@@ -503,17 +533,27 @@ static bool sureThisIsNotHeredoc(int lt2StartPos,
     }
     // Skip next batch of white-space
     firstWordPosn = skipWhitespace(firstWordPosn, lt2StartPos, styler);
+    // possible symbol for an implicit hash argument
+    if (firstWordPosn < lt2StartPos && styler.StyleAt(firstWordPosn) == SCE_RB_SYMBOL) {
+        for (; firstWordPosn <= lt2StartPos; firstWordPosn += 1) {
+            if (styler.StyleAt(firstWordPosn) != SCE_RB_SYMBOL) {
+                break;
+            }
+        }
+        // Skip next batch of white-space
+        firstWordPosn = skipWhitespace(firstWordPosn, lt2StartPos, styler);
+    }
     if (firstWordPosn != lt2StartPos) {
         // Have [[^ws[identifier]ws[*something_else*]ws<<
         return definitely_not_a_here_doc;
     }
     // OK, now 'j' will point to the current spot moving ahead
-       int j = firstWordPosn + 1;
+    Sci_Position j = firstWordPosn + 1;
     if (styler.StyleAt(j) != SCE_RB_OPERATOR || styler[j] != '<') {
         // This shouldn't happen
         return definitely_not_a_here_doc;
     }
-    int nextLineStartPosn = styler.LineStart(lineStart + 1);
+    Sci_Position nextLineStartPosn = styler.LineStart(lineStart + 1);
     if (nextLineStartPosn >= lengthDoc) {
         return definitely_not_a_here_doc;
     }
@@ -522,7 +562,7 @@ static bool sureThisIsNotHeredoc(int lt2StartPos,
         return definitely_not_a_here_doc;
     }
     bool allow_indent;
-    int target_start, target_end;
+    Sci_Position target_start, target_end;
     // From this point on no more styling, since we're looking ahead
     if (styler[j] == '-') {
         allow_indent = true;
@@ -560,10 +600,10 @@ static bool sureThisIsNotHeredoc(int lt2StartPos,
             // don't handle arbitrary expressions yet
 
             target_end = j;
-                       if (target_quote) {
-                               // Now we can move to the character after the string delimiter.
-                               j += 1;
-                       }
+            if (target_quote) {
+                // Now we can move to the character after the string delimiter.
+                j += 1;
+            }
             j = skipWhitespace(j, lengthDoc, styler);
             if (j >= lengthDoc) {
                 return definitely_not_a_here_doc;
@@ -580,12 +620,12 @@ static bool sureThisIsNotHeredoc(int lt2StartPos,
     }
 
     // Just look at the start of each line
-    int last_line = styler.GetLine(lengthDoc - 1);
+    Sci_Position last_line = styler.GetLine(lengthDoc - 1);
     // But don't go too far
     if (last_line > lineStart + 50) {
         last_line = lineStart + 50;
     }
-    for (int line_num = lineStart + 1; line_num <= last_line; line_num++) {
+    for (Sci_Position line_num = lineStart + 1; line_num <= last_line; line_num++) {
         if (allow_indent) {
             j = skipWhitespace(styler.LineStart(line_num), lengthDoc, styler);
         } else {
@@ -604,8 +644,8 @@ static bool sureThisIsNotHeredoc(int lt2StartPos,
 // move to the start of the first line that is not in a
 // multi-line construct
 
-static void synchronizeDocStart(unsigned int& startPos,
-                                int &length,
+static void synchronizeDocStart(Sci_PositionU &startPos,
+                                Sci_Position &length,
                                 int &initStyle,
                                 Accessor &styler,
                                 bool skipWhiteSpace=false) {
@@ -613,16 +653,16 @@ static void synchronizeDocStart(unsigned int& startPos,
     styler.Flush();
     int style = actual_style(styler.StyleAt(startPos));
     switch (style) {
-        case SCE_RB_STDIN:
-        case SCE_RB_STDOUT:
-        case SCE_RB_STDERR:
-            // Don't do anything else with these.
-            return;
+    case SCE_RB_STDIN:
+    case SCE_RB_STDOUT:
+    case SCE_RB_STDERR:
+        // Don't do anything else with these.
+        return;
     }
 
-    int pos = startPos;
+    Sci_Position pos = startPos;
     // Quick way to characterize each line
-    int lineStart;
+    Sci_Position lineStart;
     for (lineStart = styler.GetLine(pos); lineStart > 0; lineStart--) {
         // Now look at the style before the previous line's EOL
         pos = styler.LineStart(lineStart) - 1;
@@ -654,68 +694,68 @@ static void synchronizeDocStart(unsigned int& startPos,
     initStyle = SCE_RB_DEFAULT;
 }
 
-static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
-                                                  WordList *keywordlists[], Accessor &styler) {
+static void ColouriseRbDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
+                           WordList *keywordlists[], Accessor &styler) {
 
-       // Lexer for Ruby often has to backtrack to start of current style to determine
-       // which characters are being used as quotes, how deeply nested is the
-       // start position and what the termination string is for here documents
+    // Lexer for Ruby often has to backtrack to start of current style to determine
+    // which characters are being used as quotes, how deeply nested is the
+    // start position and what the termination string is for here documents
 
-       WordList &keywords = *keywordlists[0];
+    WordList &keywords = *keywordlists[0];
 
-       class HereDocCls {
-       public:
-               int State;
+    class HereDocCls {
+    public:
+        int State;
         // States
         // 0: '<<' encountered
-               // 1: collect the delimiter
+        // 1: collect the delimiter
         // 1b: text between the end of the delimiter and the EOL
-               // 2: here doc text (lines after the delimiter)
-               char Quote;             // the char after '<<'
-               bool Quoted;            // true if Quote in ('\'','"','`')
-               int DelimiterLength;    // strlen(Delimiter)
-               char Delimiter[256];    // the Delimiter, limit of 256: from Perl
+        // 2: here doc text (lines after the delimiter)
+        char Quote;            // the char after '<<'
+        bool Quoted;           // true if Quote in ('\'','"','`')
+        int DelimiterLength;   // strlen(Delimiter)
+        char Delimiter[256];   // the Delimiter, limit of 256: from Perl
         bool CanBeIndented;
-               HereDocCls() {
-                       State = 0;
-                       DelimiterLength = 0;
-                       Delimiter[0] = '\0';
+        HereDocCls() {
+            State = 0;
+            DelimiterLength = 0;
+            Delimiter[0] = '\0';
             CanBeIndented = false;
-               }
-       };
-       HereDocCls HereDoc;
+        }
+    };
+    HereDocCls HereDoc;
 
-       QuoteCls Quote;
+    QuoteCls Quote;
 
     int numDots = 0;  // For numbers --
-                      // Don't start lexing in the middle of a num
+    // Don't start lexing in the middle of a num
 
     synchronizeDocStart(startPos, length, initStyle, styler, // ref args
                         false);
 
-       bool preferRE = true;
+    bool preferRE = true;
     int state = initStyle;
-       int lengthDoc = startPos + length;
+    Sci_Position lengthDoc = startPos + length;
 
-       char prevWord[MAX_KEYWORD_LENGTH + 1]; // 1 byte for zero
-       prevWord[0] = '\0';
-       if (length == 0)
-               return;
+    char prevWord[MAX_KEYWORD_LENGTH + 1]; // 1 byte for zero
+    prevWord[0] = '\0';
+    if (length == 0)
+        return;
 
-       char chPrev = styler.SafeGetCharAt(startPos - 1);
-       char chNext = styler.SafeGetCharAt(startPos);
-       bool is_real_number = true;   // Differentiate between constants and ?-sequences.
-       // Ruby uses a different mask because bad indentation is marked by oring with 32
-       styler.StartAt(startPos, 127);
-       styler.StartSegment(startPos);
+    char chPrev = styler.SafeGetCharAt(startPos - 1);
+    char chNext = styler.SafeGetCharAt(startPos);
+    bool is_real_number = true;   // Differentiate between constants and ?-sequences.
+    styler.StartAt(startPos);
+    styler.StartSegment(startPos);
 
     static int q_states[] = {SCE_RB_STRING_Q,
                              SCE_RB_STRING_QQ,
                              SCE_RB_STRING_QR,
                              SCE_RB_STRING_QW,
                              SCE_RB_STRING_QW,
-                             SCE_RB_STRING_QX};
-    static const char* q_chars = "qQrwWx";
+                             SCE_RB_STRING_QX
+                            };
+    static const char *q_chars = "qQrwWx";
 
     // In most cases a value of 2 should be ample for the code in the
     // Ruby library, and the code the user is likely to enter.
@@ -731,7 +771,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
 
     // If anyone runs into this problem, I recommend raising this
     // value slightly higher to replacing the fixed array with a linked
-    // list.  Keep in mind this code will be called everytime the lexer
+    // list.  Keep in mind this code will be called every time the lexer
     // is invoked.
 
 #define INNER_STRINGS_MAX_COUNT 5
@@ -743,114 +783,114 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
     int inner_string_count = 0;
     int brace_counts = 0;   // Number of #{ ... } things within an expression
 
-    int i;
-       for (i = 0; i < INNER_STRINGS_MAX_COUNT; i++) {
+    Sci_Position i;
+    for (i = 0; i < INNER_STRINGS_MAX_COUNT; i++) {
         inner_string_types[i] = 0;
         inner_expn_brace_counts[i] = 0;
     }
-       for (i = startPos; i < lengthDoc; i++) {
-               char ch = chNext;
-               chNext = styler.SafeGetCharAt(i + 1);
-               char chNext2 = styler.SafeGetCharAt(i + 2);
+    for (i = startPos; i < lengthDoc; i++) {
+        char ch = chNext;
+        chNext = styler.SafeGetCharAt(i + 1);
+        char chNext2 = styler.SafeGetCharAt(i + 2);
 
         if (styler.IsLeadByte(ch)) {
-                       chNext = chNext2;
-                       chPrev = ' ';
-                       i += 1;
-                       continue;
-               }
+            chNext = chNext2;
+            chPrev = ' ';
+            i += 1;
+            continue;
+        }
 
         // skip on DOS/Windows
         //No, don't, because some things will get tagged on,
         // so we won't recognize keywords, for example
 #if 0
-               if (ch == '\r' && chNext == '\n') {
-               continue;
+        if (ch == '\r' && chNext == '\n') {
+            continue;
         }
 #endif
 
         if (HereDoc.State == 1 && isEOLChar(ch)) {
-                       // Begin of here-doc (the line after the here-doc delimiter):
-                       HereDoc.State = 2;
-                       styler.ColourTo(i-1, state);
+            // Begin of here-doc (the line after the here-doc delimiter):
+            HereDoc.State = 2;
+            styler.ColourTo(i-1, state);
             // Don't check for a missing quote, just jump into
             // the here-doc state
             state = SCE_RB_HERE_Q;
         }
 
         // Regular transitions
-               if (state == SCE_RB_DEFAULT) {
+        if (state == SCE_RB_DEFAULT) {
             if (isSafeDigit(ch)) {
-               styler.ColourTo(i - 1, state);
-                               state = SCE_RB_NUMBER;
+                styler.ColourTo(i - 1, state);
+                state = SCE_RB_NUMBER;
                 is_real_number = true;
                 numDots = 0;
             } else if (isHighBitChar(ch) || iswordstart(ch)) {
-               styler.ColourTo(i - 1, state);
-                               state = SCE_RB_WORD;
-                       } else if (ch == '#') {
-                               styler.ColourTo(i - 1, state);
-                               state = SCE_RB_COMMENTLINE;
-                       } else if (ch == '=') {
-                               // =begin indicates the start of a comment (doc) block
+                styler.ColourTo(i - 1, state);
+                state = SCE_RB_WORD;
+            } else if (ch == '#') {
+                styler.ColourTo(i - 1, state);
+                state = SCE_RB_COMMENTLINE;
+            } else if (ch == '=') {
+                // =begin indicates the start of a comment (doc) block
                 if ((i == 0 || isEOLChar(chPrev))
-                    && chNext == 'b'
-                    && styler.SafeGetCharAt(i + 2) == 'e'
-                    && styler.SafeGetCharAt(i + 3) == 'g'
-                    && styler.SafeGetCharAt(i + 4) == 'i'
-                    && styler.SafeGetCharAt(i + 5) == 'n'
-                    && !isSafeWordcharOrHigh(styler.SafeGetCharAt(i + 6))) {
+                        && chNext == 'b'
+                        && styler.SafeGetCharAt(i + 2) == 'e'
+                        && styler.SafeGetCharAt(i + 3) == 'g'
+                        && styler.SafeGetCharAt(i + 4) == 'i'
+                        && styler.SafeGetCharAt(i + 5) == 'n'
+                        && !isSafeWordcharOrHigh(styler.SafeGetCharAt(i + 6))) {
                     styler.ColourTo(i - 1, state);
                     state = SCE_RB_POD;
-                               } else {
-                                       styler.ColourTo(i - 1, state);
-                                       styler.ColourTo(i, SCE_RB_OPERATOR);
-                                       preferRE = true;
-                               }
-                       } else if (ch == '"') {
-                               styler.ColourTo(i - 1, state);
-                               state = SCE_RB_STRING;
-                               Quote.New();
-                               Quote.Open(ch);
-                       } else if (ch == '\'') {
+                } else {
+                    styler.ColourTo(i - 1, state);
+                    styler.ColourTo(i, SCE_RB_OPERATOR);
+                    preferRE = true;
+                }
+            } else if (ch == '"') {
+                styler.ColourTo(i - 1, state);
+                state = SCE_RB_STRING;
+                Quote.New();
+                Quote.Open(ch);
+            } else if (ch == '\'') {
                 styler.ColourTo(i - 1, state);
                 state = SCE_RB_CHARACTER;
                 Quote.New();
                 Quote.Open(ch);
-                       } else if (ch == '`') {
-                               styler.ColourTo(i - 1, state);
-                               state = SCE_RB_BACKTICKS;
-                               Quote.New();
-                               Quote.Open(ch);
-                       } else if (ch == '@') {
+            } else if (ch == '`') {
+                styler.ColourTo(i - 1, state);
+                state = SCE_RB_BACKTICKS;
+                Quote.New();
+                Quote.Open(ch);
+            } else if (ch == '@') {
                 // Instance or class var
-                               styler.ColourTo(i - 1, state);
+                styler.ColourTo(i - 1, state);
                 if (chNext == '@') {
                     state = SCE_RB_CLASS_VAR;
                     advance_char(i, ch, chNext, chNext2); // pass by ref
                 } else {
                     state = SCE_RB_INSTANCE_VAR;
                 }
-                       } else if (ch == '$') {
+            } else if (ch == '$') {
                 // Check for a builtin global
-                               styler.ColourTo(i - 1, state);
+                styler.ColourTo(i - 1, state);
                 // Recognize it bit by bit
                 state = SCE_RB_GLOBAL;
             } else if (ch == '/' && preferRE) {
                 // Ambigous operator
-                               styler.ColourTo(i - 1, state);
-                               state = SCE_RB_REGEX;
+                styler.ColourTo(i - 1, state);
+                state = SCE_RB_REGEX;
                 Quote.New();
                 Quote.Open(ch);
-                       } else if (ch == '<' && chNext == '<' && chNext2 != '=') {
+            } else if (ch == '<' && chNext == '<' && chNext2 != '=') {
 
                 // Recognise the '<<' symbol - either a here document or a binary op
-                               styler.ColourTo(i - 1, state);
+                styler.ColourTo(i - 1, state);
                 i++;
                 chNext = chNext2;
-                               styler.ColourTo(i, SCE_RB_OPERATOR);
+                styler.ColourTo(i, SCE_RB_OPERATOR);
 
-                if (! (strchr("\"\'`_-", chNext2) || isSafeAlpha(chNext2))) {
+                if (!(strchr("\"\'`_-", chNext2) || isSafeAlpha(chNext2))) {
                     // It's definitely not a here-doc,
                     // based on Ruby's lexer/parser in the
                     // heredoc_identifier routine.
@@ -874,22 +914,47 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                 }
                 preferRE = (state != SCE_RB_HERE_DELIM);
             } else if (ch == ':') {
-                               styler.ColourTo(i - 1, state);
+                styler.ColourTo(i - 1, state);
                 if (chNext == ':') {
                     // Mark "::" as an operator, not symbol start
                     styler.ColourTo(i + 1, SCE_RB_OPERATOR);
                     advance_char(i, ch, chNext, chNext2); // pass by ref
                     state = SCE_RB_DEFAULT;
-                                       preferRE = false;
+                    preferRE = false;
                 } else if (isSafeWordcharOrHigh(chNext)) {
-                                       state = SCE_RB_SYMBOL;
+                    state = SCE_RB_SYMBOL;
+                } else if ((chNext == '@' || chNext == '$') &&
+                           isSafeWordcharOrHigh(chNext2)) {
+                    // instance and global variable followed by an identifier
+                    advance_char(i, ch, chNext, chNext2);
+                    state = SCE_RB_SYMBOL;
+                } else if (((chNext == '@' && chNext2 == '@')  ||
+                            (chNext == '$' && chNext2 == '-')) &&
+                           isSafeWordcharOrHigh(styler.SafeGetCharAt(i+3))) {
+                    // class variables and special global variable "$-IDENTCHAR"
+                    state = SCE_RB_SYMBOL;
+                    // $-IDENTCHAR doesn't continue past the IDENTCHAR
+                    if (chNext == '$') {
+                        styler.ColourTo(i+3, SCE_RB_SYMBOL);
+                        state = SCE_RB_DEFAULT;
+                    }
+                    i += 3;
+                    ch = styler.SafeGetCharAt(i);
+                    chNext = styler.SafeGetCharAt(i+1);
+                } else if (chNext == '$' && strchr("_~*$?!@/\\;,.=:<>\"&`'+", chNext2)) {
+                    // single-character special global variables
+                    i += 2;
+                    ch = chNext2;
+                    chNext = styler.SafeGetCharAt(i+1);
+                    styler.ColourTo(i, SCE_RB_SYMBOL);
+                    state = SCE_RB_DEFAULT;
                 } else if (strchr("[*!~+-*/%=<>&^|", chNext)) {
                     // Do the operator analysis in-line, looking ahead
                     // Based on the table in pickaxe 2nd ed., page 339
                     bool doColoring = true;
                     switch (chNext) {
                     case '[':
-                        if (chNext2 == ']' ) {
+                        if (chNext2 == ']') {
                             char ch_tmp = styler.SafeGetCharAt(i + 3);
                             if (ch_tmp == '=') {
                                 i += 3;
@@ -955,11 +1020,11 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                         styler.ColourTo(i, SCE_RB_SYMBOL);
                         state = SCE_RB_DEFAULT;
                     }
-                               } else if (!preferRE) {
-                                       // Don't color symbol strings (yet)
-                                       // Just color the ":" and color rest as string
-                                       styler.ColourTo(i, SCE_RB_SYMBOL);
-                                       state = SCE_RB_DEFAULT;
+                } else if (!preferRE) {
+                    // Don't color symbol strings (yet)
+                    // Just color the ":" and color rest as string
+                    styler.ColourTo(i, SCE_RB_SYMBOL);
+                    state = SCE_RB_DEFAULT;
                 } else {
                     styler.ColourTo(i, SCE_RB_OPERATOR);
                     state = SCE_RB_DEFAULT;
@@ -976,7 +1041,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                         Quote.Open(chNext2);
                         i += 2;
                         ch = chNext2;
-                                               chNext = styler.SafeGetCharAt(i + 1);
+                        chNext = styler.SafeGetCharAt(i + 1);
                         have_string = true;
                     }
                 } else if (preferRE && !isSafeWordcharOrHigh(chNext)) {
@@ -1012,8 +1077,8 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                     is_real_number = false;
                 }
             } else if (isoperator(ch) || ch == '.') {
-                               styler.ColourTo(i - 1, state);
-                               styler.ColourTo(i, SCE_RB_OPERATOR);
+                styler.ColourTo(i - 1, state);
+                styler.ColourTo(i, SCE_RB_OPERATOR);
                 // If we're ending an expression or block,
                 // assume it ends an object, and the ambivalent
                 // constructs are binary operators
@@ -1040,7 +1105,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
             } else if (isEOLChar(ch)) {
                 // Make sure it's a true line-end, with no backslash
                 if ((ch == '\r' || (ch == '\n' && chPrev != '\r'))
-                    && chPrev != '\\') {
+                        && chPrev != '\\') {
                     // Assume we've hit the end of the statement.
                     preferRE = true;
                 }
@@ -1055,14 +1120,18 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                 // but we don't for now.
 
                 if (ch == '='
-                    && isSafeWordcharOrHigh(chPrev)
-                    && (chNext == '('
-                        || strchr(" \t\n\r", chNext) != NULL)
-                    && (!strcmp(prevWord, "def")
-                        || followsDot(styler.GetStartSegment(), styler))) {
+                        && isSafeWordcharOrHigh(chPrev)
+                        && (chNext == '('
+                            || strchr(" \t\n\r", chNext) != NULL)
+                        && (!strcmp(prevWord, "def")
+                            || followsDot(styler.GetStartSegment(), styler))) {
                     // <name>= is a name only when being def'd -- Get it the next time
                     // This means that <name>=<name> is always lexed as
                     // <name>, (op, =), <name>
+                } else if (ch == ':'
+                           && isSafeWordcharOrHigh(chPrev)
+                           && strchr(" \t\n\r", chNext) != NULL) {
+                    state = SCE_RB_SYMBOL;
                 } else if ((ch == '?' || ch == '!')
                            && isSafeWordcharOrHigh(chPrev)
                            && !isSafeWordcharOrHigh(chNext)) {
@@ -1078,28 +1147,28 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                     // No need to handle this state -- we'll just move to the end
                     preferRE = false;
                 } else {
-                                       int wordStartPos = styler.GetStartSegment();
+                    Sci_Position wordStartPos = styler.GetStartSegment();
                     int word_style = ClassifyWordRb(wordStartPos, i - 1, keywords, styler, prevWord);
                     switch (word_style) {
-                        case SCE_RB_WORD:
-                            preferRE = RE_CanFollowKeyword(prevWord);
-                                                       break;
+                    case SCE_RB_WORD:
+                        preferRE = RE_CanFollowKeyword(prevWord);
+                        break;
 
-                        case SCE_RB_WORD_DEMOTED:
-                            preferRE = true;
-                                                       break;
+                    case SCE_RB_WORD_DEMOTED:
+                        preferRE = true;
+                        break;
 
-                        case SCE_RB_IDENTIFIER:
-                            if (isMatch(styler, lengthDoc, wordStartPos, "print")) {
-                                preferRE = true;
-                            } else if (isEOLChar(ch)) {
-                                preferRE = true;
-                            } else {
-                                preferRE = false;
-                            }
-                                                       break;
-                        default:
+                    case SCE_RB_IDENTIFIER:
+                        if (isMatch(styler, lengthDoc, wordStartPos, "print")) {
+                            preferRE = true;
+                        } else if (isEOLChar(ch)) {
+                            preferRE = true;
+                        } else {
                             preferRE = false;
+                        }
+                        break;
+                    default:
+                        preferRE = false;
                     }
                     if (ch == '.') {
                         // We might be redefining an operator-method
@@ -1154,7 +1223,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                 preferRE = false;
             }
         } else if (state == SCE_RB_COMMENTLINE) {
-                       if (isEOLChar(ch)) {
+            if (isEOLChar(ch)) {
                 styler.ColourTo(i - 1, state);
                 state = SCE_RB_DEFAULT;
                 // Use whatever setting we had going into the comment
@@ -1164,8 +1233,8 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
             // Slightly different: if we find an immediate '-',
             // the target can appear indented.
 
-                       if (HereDoc.State == 0) { // '<<' encountered
-                               HereDoc.State = 1;
+            if (HereDoc.State == 0) { // '<<' encountered
+                HereDoc.State = 1;
                 HereDoc.DelimiterLength = 0;
                 if (ch == '-') {
                     HereDoc.CanBeIndented = true;
@@ -1190,7 +1259,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                         HereDoc.DelimiterLength = 1;
                     }
                 }
-                       } else if (HereDoc.State == 1) { // collect the delimiter
+            } else if (HereDoc.State == 1) { // collect the delimiter
                 if (isEOLChar(ch)) {
                     // End the quote now, and go back for more
                     styler.ColourTo(i - 1, state);
@@ -1199,32 +1268,32 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                     chNext = ch;
                     preferRE = false;
                 } else if (HereDoc.Quoted) {
-                                       if (ch == HereDoc.Quote) { // closing quote => end of delimiter
-                                               styler.ColourTo(i, state);
-                                               state = SCE_RB_DEFAULT;
+                    if (ch == HereDoc.Quote) { // closing quote => end of delimiter
+                        styler.ColourTo(i, state);
+                        state = SCE_RB_DEFAULT;
                         preferRE = false;
                     } else {
-                                               if (ch == '\\' && !isEOLChar(chNext)) {
+                        if (ch == '\\' && !isEOLChar(chNext)) {
                             advance_char(i, ch, chNext, chNext2);
-                                               }
-                                               HereDoc.Delimiter[HereDoc.DelimiterLength++] = ch;
-                                               HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0';
+                        }
+                        HereDoc.Delimiter[HereDoc.DelimiterLength++] = ch;
+                        HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0';
                     }
                 } else { // an unquoted here-doc delimiter
-                                       if (isSafeAlnumOrHigh(ch) || ch == '_') {
-                                               HereDoc.Delimiter[HereDoc.DelimiterLength++] = ch;
-                                               HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0';
-                                       } else {
-                                               styler.ColourTo(i - 1, state);
+                    if (isSafeAlnumOrHigh(ch) || ch == '_') {
+                        HereDoc.Delimiter[HereDoc.DelimiterLength++] = ch;
+                        HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0';
+                    } else {
+                        styler.ColourTo(i - 1, state);
                         redo_char(i, ch, chNext, chNext2, state);
                         preferRE = false;
-                                       }
+                    }
                 }
-                               if (HereDoc.DelimiterLength >= static_cast<int>(sizeof(HereDoc.Delimiter)) - 
1) {
-                                       styler.ColourTo(i - 1, state);
-                                       state = SCE_RB_ERROR;
+                if (HereDoc.DelimiterLength >= static_cast<int>(sizeof(HereDoc.Delimiter)) - 1) {
+                    styler.ColourTo(i - 1, state);
+                    state = SCE_RB_ERROR;
                     preferRE = false;
-                               }
+                }
             }
         } else if (state == SCE_RB_HERE_Q) {
             // Not needed: HereDoc.State == 2
@@ -1235,7 +1304,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
 
             if (!HereDoc.CanBeIndented) {
                 if (isEOLChar(chPrev)
-                    && isMatch(styler, lengthDoc, i, HereDoc.Delimiter)) {
+                        && isMatch(styler, lengthDoc, i, HereDoc.Delimiter)) {
                     styler.ColourTo(i - 1, state);
                     i += HereDoc.DelimiterLength - 1;
                     chNext = styler.SafeGetCharAt(i + 1);
@@ -1261,7 +1330,16 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
         } else if (state == SCE_RB_CLASS_VAR
                    || state == SCE_RB_INSTANCE_VAR
                    || state == SCE_RB_SYMBOL) {
-            if (!isSafeWordcharOrHigh(ch)) {
+            if (state == SCE_RB_SYMBOL &&
+                    // FIDs suffices '?' and '!'
+                    (((ch == '!' || ch == '?') && chNext != '=') ||
+                     // identifier suffix '='
+                     (ch == '=' && (chNext != '~' && chNext != '>' &&
+                                    (chNext != '=' || chNext2 == '>'))))) {
+                styler.ColourTo(i, state);
+                state = SCE_RB_DEFAULT;
+                preferRE = false;
+            } else if (!isSafeWordcharOrHigh(ch)) {
                 styler.ColourTo(i - 1, state);
                 redo_char(i, ch, chNext, chNext2, state); // pass by ref
                 preferRE = false;
@@ -1285,9 +1363,9 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
         } else if (state == SCE_RB_POD) {
             // PODs end with ^=end\s, -- any whitespace can follow =end
             if (strchr(" \t\n\r", ch) != NULL
-                && i > 5
-                && isEOLChar(styler[i - 5])
-                && isMatch(styler, lengthDoc, i - 4, "=end")) {
+                    && i > 5
+                    && isEOLChar(styler[i - 5])
+                    && isMatch(styler, lengthDoc, i - 4, "=end")) {
                 styler.ColourTo(i - 1, state);
                 state = SCE_RB_DEFAULT;
                 preferRE = false;
@@ -1302,7 +1380,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                     // Include the options
                     while (isSafeAlpha(chNext)) {
                         i++;
-                                               ch = chNext;
+                        ch = chNext;
                         chNext = styler.SafeGetCharAt(i + 1);
                     }
                     styler.ColourTo(i, state);
@@ -1313,9 +1391,9 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                 // Only if close quoter != open quoter
                 Quote.Count++;
 
-            } else if (ch == '#' ) {
+            } else if (ch == '#') {
                 if (chNext == '{'
-                    && inner_string_count < INNER_STRINGS_MAX_COUNT) {
+                        && inner_string_count < INNER_STRINGS_MAX_COUNT) {
                     // process #{ ... }
                     styler.ColourTo(i - 1, state);
                     styler.ColourTo(i + 1, SCE_RB_OPERATOR);
@@ -1355,7 +1433,7 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                     chNext = styler.SafeGetCharAt(i + 1);
                 }
             }
-        // Quotes of all kinds...
+            // Quotes of all kinds...
         } else if (state == SCE_RB_STRING_Q || state == SCE_RB_STRING_QQ ||
                    state == SCE_RB_STRING_QX || state == SCE_RB_STRING_QW ||
                    state == SCE_RB_STRING || state == SCE_RB_CHARACTER ||
@@ -1411,12 +1489,12 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
 // Helper functions for folding, disambiguation keywords
 // Assert that there are no high-bit chars
 
-static void getPrevWord(int pos,
+static void getPrevWord(Sci_Position pos,
                         char *prevWord,
                         Accessor &styler,
                         int word_state)
 {
-    int i;
+    Sci_Position i;
     styler.Flush();
     for (i = pos - 1; i > 0; i--) {
         if (actual_style(styler.StyleAt(i)) != word_state) {
@@ -1430,7 +1508,7 @@ static void getPrevWord(int pos,
     for (; i <= pos; i++) {
         *dst++ = styler[i];
     }
-       *dst = 0;
+    *dst = 0;
 }
 
 static bool keywordIsAmbiguous(const char *prevWord)
@@ -1438,11 +1516,11 @@ static bool keywordIsAmbiguous(const char *prevWord)
     // Order from most likely used to least likely
     // Lots of ways to do a loop in Ruby besides 'while/until'
     if (!strcmp(prevWord, "if")
-        || !strcmp(prevWord, "do")
-        || !strcmp(prevWord, "while")
-        || !strcmp(prevWord, "unless")
-        || !strcmp(prevWord, "until")
-        || !strcmp(prevWord, "for")) {
+            || !strcmp(prevWord, "do")
+            || !strcmp(prevWord, "while")
+            || !strcmp(prevWord, "unless")
+            || !strcmp(prevWord, "until")
+            || !strcmp(prevWord, "for")) {
         return true;
     } else {
         return false;
@@ -1454,7 +1532,7 @@ static bool keywordIsAmbiguous(const char *prevWord)
 // do after a while or until, as a noise word (like then after if)
 
 static bool keywordIsModifier(const char *word,
-                              int pos,
+                              Sci_Position pos,
                               Accessor &styler)
 {
     if (word[0] == 'd' && word[1] == 'o' && !word[2]) {
@@ -1462,8 +1540,8 @@ static bool keywordIsModifier(const char *word,
     }
     char ch, chPrev, chPrev2;
     int style = SCE_RB_DEFAULT;
-       int lineStart = styler.GetLine(pos);
-    int lineStartPosn = styler.LineStart(lineStart);
+    Sci_Position lineStart = styler.GetLine(pos);
+    Sci_Position lineStartPosn = styler.LineStart(lineStart);
     // We want to step backwards until we don't care about the current
     // position. But first move lineStartPosn back behind any
     // continuations immediately above word.
@@ -1482,20 +1560,20 @@ static bool keywordIsModifier(const char *word,
                 break;
             }
         } else {
-          break;
+            break;
         }
     }
 
     styler.Flush();
     while (--pos >= lineStartPosn) {
         style = actual_style(styler.StyleAt(pos));
-               if (style == SCE_RB_DEFAULT) {
-                       if (iswhitespace(ch = styler[pos])) {
-                               //continue
-                       } else if (ch == '\r' || ch == '\n') {
-                               // Scintilla's LineStart() and GetLine() routines aren't
-                               // platform-independent, so if we have text prepared with
-                               // a different system we can't rely on it.
+        if (style == SCE_RB_DEFAULT) {
+            if (iswhitespace(ch = styler[pos])) {
+                //continue
+            } else if (ch == '\r' || ch == '\n') {
+                // Scintilla's LineStart() and GetLine() routines aren't
+                // platform-independent, so if we have text prepared with
+                // a different system we can't rely on it.
 
                 // Also, lineStartPosn may have been moved to more than one
                 // line above word's line while pushing past continuations.
@@ -1508,40 +1586,40 @@ static bool keywordIsModifier(const char *word,
                     pos-=2;  // gloss over the "\\\r"
                     //continue
                 } else {
-                                   return false;
+                    return false;
                 }
-                       }
-               } else {
+            }
+        } else {
             break;
-               }
+        }
     }
     if (pos < lineStartPosn) {
         return false;
     }
     // First things where the action is unambiguous
     switch (style) {
-        case SCE_RB_DEFAULT:
-        case SCE_RB_COMMENTLINE:
-        case SCE_RB_POD:
-        case SCE_RB_CLASSNAME:
-        case SCE_RB_DEFNAME:
-        case SCE_RB_MODULE_NAME:
-            return false;
-        case SCE_RB_OPERATOR:
-            break;
-        case SCE_RB_WORD:
-            // Watch out for uses of 'else if'
-            //XXX: Make a list of other keywords where 'if' isn't a modifier
-            //     and can appear legitimately
-            // Formulate this to avoid warnings from most compilers
-            if (strcmp(word, "if") == 0) {
-                char prevWord[MAX_KEYWORD_LENGTH + 1];
-                getPrevWord(pos, prevWord, styler, SCE_RB_WORD);
-                return strcmp(prevWord, "else") != 0;
-            }
-            return true;
-        default:
-            return true;
+    case SCE_RB_DEFAULT:
+    case SCE_RB_COMMENTLINE:
+    case SCE_RB_POD:
+    case SCE_RB_CLASSNAME:
+    case SCE_RB_DEFNAME:
+    case SCE_RB_MODULE_NAME:
+        return false;
+    case SCE_RB_OPERATOR:
+        break;
+    case SCE_RB_WORD:
+        // Watch out for uses of 'else if'
+        //XXX: Make a list of other keywords where 'if' isn't a modifier
+        //     and can appear legitimately
+        // Formulate this to avoid warnings from most compilers
+        if (strcmp(word, "if") == 0) {
+            char prevWord[MAX_KEYWORD_LENGTH + 1];
+            getPrevWord(pos, prevWord, styler, SCE_RB_WORD);
+            return strcmp(prevWord, "else") != 0;
+        }
+        return true;
+    default:
+        return true;
     }
     // Assume that if the keyword follows an operator,
     // usually it's a block assignment, like
@@ -1549,12 +1627,12 @@ static bool keywordIsModifier(const char *word,
 
     ch = styler[pos];
     switch (ch) {
-        case ')':
-        case ']':
-        case '}':
-            return true;
-        default:
-            return false;
+    case ')':
+    case ']':
+    case '}':
+        return true;
+    default:
+        return false;
     }
 }
 
@@ -1565,32 +1643,32 @@ static bool keywordIsModifier(const char *word,
 // Nothing fancy -- look to see if we follow a while/until somewhere
 // on the current line
 
-static bool keywordDoStartsLoop(int pos,
+static bool keywordDoStartsLoop(Sci_Position pos,
                                 Accessor &styler)
 {
     char ch;
     int style;
-       int lineStart = styler.GetLine(pos);
-    int lineStartPosn = styler.LineStart(lineStart);
+    Sci_Position lineStart = styler.GetLine(pos);
+    Sci_Position lineStartPosn = styler.LineStart(lineStart);
     styler.Flush();
     while (--pos >= lineStartPosn) {
         style = actual_style(styler.StyleAt(pos));
-               if (style == SCE_RB_DEFAULT) {
-                       if ((ch = styler[pos]) == '\r' || ch == '\n') {
-                               // Scintilla's LineStart() and GetLine() routines aren't
-                               // platform-independent, so if we have text prepared with
-                               // a different system we can't rely on it.
-                               return false;
-                       }
-               } else if (style == SCE_RB_WORD) {
+        if (style == SCE_RB_DEFAULT) {
+            if ((ch = styler[pos]) == '\r' || ch == '\n') {
+                // Scintilla's LineStart() and GetLine() routines aren't
+                // platform-independent, so if we have text prepared with
+                // a different system we can't rely on it.
+                return false;
+            }
+        } else if (style == SCE_RB_WORD) {
             // Check for while or until, but write the word in backwards
             char prevWord[MAX_KEYWORD_LENGTH + 1]; // 1 byte for zero
             char *dst = prevWord;
             int wordLen = 0;
-            int start_word;
+            Sci_Position start_word;
             for (start_word = pos;
-                 start_word >= lineStartPosn && actual_style(styler.StyleAt(start_word)) == SCE_RB_WORD;
-                 start_word--) {
+                    start_word >= lineStartPosn && actual_style(styler.StyleAt(start_word)) == SCE_RB_WORD;
+                    start_word--) {
                 if (++wordLen < MAX_KEYWORD_LENGTH) {
                     *dst++ = styler[start_word];
                 }
@@ -1598,8 +1676,8 @@ static bool keywordDoStartsLoop(int pos,
             *dst = 0;
             // Did we see our keyword?
             if (!strcmp(prevWord, WHILE_BACKWARDS)
-                || !strcmp(prevWord, UNTIL_BACKWARDS)
-                || !strcmp(prevWord, FOR_BACKWARDS)) {
+                    || !strcmp(prevWord, UNTIL_BACKWARDS)
+                    || !strcmp(prevWord, FOR_BACKWARDS)) {
                 return true;
             }
             // We can move pos to the beginning of the keyword, and then
@@ -1617,6 +1695,19 @@ static bool keywordDoStartsLoop(int pos,
     return false;
 }
 
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+    Sci_Position pos = styler.LineStart(line);
+    Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+    for (Sci_Position i = pos; i < eol_pos; i++) {
+        char ch = styler[i];
+        if (ch == '#')
+            return true;
+        else if (ch != ' ' && ch != '\t')
+            return false;
+    }
+    return false;
+}
+
 /*
  *  Folding Ruby
  *
@@ -1671,46 +1762,57 @@ static bool keywordDoStartsLoop(int pos,
  *  Later offer to fold POD, here-docs, strings, and blocks of comments
  */
 
-static void FoldRbDoc(unsigned int startPos, int length, int initStyle,
+static void FoldRbDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                       WordList *[], Accessor &styler) {
-       const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
+    const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
+    bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
 
     synchronizeDocStart(startPos, length, initStyle, styler, // ref args
                         false);
-       unsigned int endPos = startPos + length;
-       int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
-       int levelPrev = startPos == 0 ? 0 : (styler.LevelAt(lineCurrent)
+    Sci_PositionU endPos = startPos + length;
+    int visibleChars = 0;
+    Sci_Position lineCurrent = styler.GetLine(startPos);
+    int levelPrev = startPos == 0 ? 0 : (styler.LevelAt(lineCurrent)
                                          & SC_FOLDLEVELNUMBERMASK
                                          & ~SC_FOLDLEVELBASE);
-       int levelCurrent = levelPrev;
-       char chNext = styler[startPos];
-       int styleNext = styler.StyleAt(startPos);
-       int stylePrev = startPos <= 1 ? SCE_RB_DEFAULT : styler.StyleAt(startPos - 1);
+    int levelCurrent = levelPrev;
+    char chNext = styler[startPos];
+    int styleNext = styler.StyleAt(startPos);
+    int stylePrev = startPos <= 1 ? SCE_RB_DEFAULT : styler.StyleAt(startPos - 1);
     bool buffer_ends_with_eol = false;
-       for (unsigned int i = startPos; i < endPos; i++) {
-               char ch = chNext;
-               chNext = styler.SafeGetCharAt(i + 1);
-               int style = styleNext;
-               styleNext = styler.StyleAt(i + 1);
-               bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+    for (Sci_PositionU i = startPos; i < endPos; i++) {
+        char ch = chNext;
+        chNext = styler.SafeGetCharAt(i + 1);
+        int style = styleNext;
+        styleNext = styler.StyleAt(i + 1);
+        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+
+        /*Mutiline comment patch*/
+        if (foldComment && atEOL && IsCommentLine(lineCurrent, styler)) {
+            if (!IsCommentLine(lineCurrent - 1, styler)
+                    && IsCommentLine(lineCurrent + 1, styler))
+                levelCurrent++;
+            else if (IsCommentLine(lineCurrent - 1, styler)
+                     && !IsCommentLine(lineCurrent + 1, styler))
+                levelCurrent--;
+        }
+
         if (style == SCE_RB_COMMENTLINE) {
             if (foldComment && stylePrev != SCE_RB_COMMENTLINE) {
                 if (chNext == '{') {
-                                       levelCurrent++;
-                               } else if (chNext == '}' && levelCurrent > 0) {
-                                       levelCurrent--;
-                               }
+                    levelCurrent++;
+                } else if (chNext == '}' && levelCurrent > 0) {
+                    levelCurrent--;
+                }
             }
         } else if (style == SCE_RB_OPERATOR) {
-                       if (strchr("[{(", ch)) {
-                               levelCurrent++;
-                       } else if (strchr(")}]", ch)) {
+            if (strchr("[{(", ch)) {
+                levelCurrent++;
+            } else if (strchr(")}]", ch)) {
                 // Don't decrement below 0
                 if (levelCurrent > 0)
                     levelCurrent--;
-                       }
+            }
         } else if (style == SCE_RB_WORD && styleNext != SCE_RB_WORD) {
             // Look at the keyword on the left and decide what to do
             char prevWord[MAX_KEYWORD_LENGTH + 1]; // 1 byte for zero
@@ -1720,7 +1822,7 @@ static void FoldRbDoc(unsigned int startPos, int length, int initStyle,
                 // Don't decrement below 0
                 if (levelCurrent > 0)
                     levelCurrent--;
-            } else if (   !strcmp(prevWord, "if")
+            } else if (!strcmp(prevWord, "if")
                        || !strcmp(prevWord, "def")
                        || !strcmp(prevWord, "class")
                        || !strcmp(prevWord, "module")
@@ -1731,49 +1833,49 @@ static void FoldRbDoc(unsigned int startPos, int length, int initStyle,
                        || !strcmp(prevWord, "unless")
                        || !strcmp(prevWord, "until")
                        || !strcmp(prevWord, "for")
-                          ) {
-                               levelCurrent++;
+                      ) {
+                levelCurrent++;
             }
-               } else if (style == SCE_RB_HERE_DELIM) {
-                       if (styler.SafeGetCharAt(i-2) == '<' && styler.SafeGetCharAt(i-1) == '<') {
-                               levelCurrent++;
-                       } else if (styleNext == SCE_RB_DEFAULT) {
-                               levelCurrent--;
-                       }
-               }
-               if (atEOL) {
-                       int lev = levelPrev;
-                       if (visibleChars == 0 && foldCompact)
-                               lev |= SC_FOLDLEVELWHITEFLAG;
-                       if ((levelCurrent > levelPrev) && (visibleChars > 0))
-                               lev |= SC_FOLDLEVELHEADERFLAG;
+        } else if (style == SCE_RB_HERE_DELIM) {
+            if (styler.SafeGetCharAt(i-2) == '<' && styler.SafeGetCharAt(i-1) == '<') {
+                levelCurrent++;
+            } else if (styleNext == SCE_RB_DEFAULT) {
+                levelCurrent--;
+            }
+        }
+        if (atEOL) {
+            int lev = levelPrev;
+            if (visibleChars == 0 && foldCompact)
+                lev |= SC_FOLDLEVELWHITEFLAG;
+            if ((levelCurrent > levelPrev) && (visibleChars > 0))
+                lev |= SC_FOLDLEVELHEADERFLAG;
             styler.SetLevel(lineCurrent, lev|SC_FOLDLEVELBASE);
-                       lineCurrent++;
-                       levelPrev = levelCurrent;
-                       visibleChars = 0;
+            lineCurrent++;
+            levelPrev = levelCurrent;
+            visibleChars = 0;
             buffer_ends_with_eol = true;
-               } else if (!isspacechar(ch)) {
-                       visibleChars++;
+        } else if (!isspacechar(ch)) {
+            visibleChars++;
             buffer_ends_with_eol = false;
         }
-               stylePrev = style;
+        stylePrev = style;
     }
-       // Fill in the real level of the next line, keeping the current flags as they will be filled in later
+    // Fill in the real level of the next line, keeping the current flags as they will be filled in later
     if (!buffer_ends_with_eol) {
         lineCurrent++;
         int new_lev = levelCurrent;
         if (visibleChars == 0 && foldCompact)
             new_lev |= SC_FOLDLEVELWHITEFLAG;
-                       if ((levelCurrent > levelPrev) && (visibleChars > 0))
-                               new_lev |= SC_FOLDLEVELHEADERFLAG;
-            levelCurrent = new_lev;
+        if ((levelCurrent > levelPrev) && (visibleChars > 0))
+            new_lev |= SC_FOLDLEVELHEADERFLAG;
+        levelCurrent = new_lev;
     }
-       styler.SetLevel(lineCurrent, levelCurrent|SC_FOLDLEVELBASE);
+    styler.SetLevel(lineCurrent, levelCurrent|SC_FOLDLEVELBASE);
 }
 
-static const char * const rubyWordListDesc[] = {
-       "Keywords",
-       0
+static const char *const rubyWordListDesc[] = {
+    "Keywords",
+    0
 };
 
-LexerModule lmRuby(SCLEX_RUBY, ColouriseRbDoc, "ruby", FoldRbDoc, rubyWordListDesc, 6);
+LexerModule lmRuby(SCLEX_RUBY, ColouriseRbDoc, "ruby", FoldRbDoc, rubyWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexRust.cxx b/plugins/scintilla/scintilla/lexers/LexRust.cxx
new file mode 100644
index 0000000..1f2b847
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexRust.cxx
@@ -0,0 +1,838 @@
+/** @file LexRust.cxx
+ ** Lexer for Rust.
+ **
+ ** Copyright (c) 2013 by SiegeLord <slabode aim com>
+ ** Converted to lexer object and added further folding features/properties by "Udo Lechner" 
<dlchnr(at)gmx(dot)net>
+ **/
+// Copyright 1998-2005 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include <string>
+#include <map>
+
+#include "ILexer.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+#include "PropSetSimple.h"
+#include "WordList.h"
+#include "LexAccessor.h"
+#include "Accessor.h"
+#include "StyleContext.h"
+#include "CharacterSet.h"
+#include "LexerModule.h"
+#include "OptionSet.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static const int NUM_RUST_KEYWORD_LISTS = 7;
+static const int MAX_RUST_IDENT_CHARS = 1023;
+
+static bool IsStreamCommentStyle(int style) {
+       return style == SCE_RUST_COMMENTBLOCK ||
+                  style == SCE_RUST_COMMENTBLOCKDOC;
+}
+
+// Options used for LexerRust
+struct OptionsRust {
+       bool fold;
+       bool foldSyntaxBased;
+       bool foldComment;
+       bool foldCommentMultiline;
+       bool foldCommentExplicit;
+       std::string foldExplicitStart;
+       std::string foldExplicitEnd;
+       bool foldExplicitAnywhere;
+       bool foldCompact;
+       int  foldAtElseInt;
+       bool foldAtElse;
+       OptionsRust() {
+               fold = false;
+               foldSyntaxBased = true;
+               foldComment = false;
+               foldCommentMultiline = true;
+               foldCommentExplicit = true;
+               foldExplicitStart = "";
+               foldExplicitEnd   = "";
+               foldExplicitAnywhere = false;
+               foldCompact = true;
+               foldAtElseInt = -1;
+               foldAtElse = false;
+       }
+};
+
+static const char * const rustWordLists[NUM_RUST_KEYWORD_LISTS + 1] = {
+                       "Primary keywords and identifiers",
+                       "Built in types",
+                       "Other keywords",
+                       "Keywords 4",
+                       "Keywords 5",
+                       "Keywords 6",
+                       "Keywords 7",
+                       0,
+               };
+
+struct OptionSetRust : public OptionSet<OptionsRust> {
+       OptionSetRust() {
+               DefineProperty("fold", &OptionsRust::fold);
+
+               DefineProperty("fold.comment", &OptionsRust::foldComment);
+
+               DefineProperty("fold.compact", &OptionsRust::foldCompact);
+
+               DefineProperty("fold.at.else", &OptionsRust::foldAtElse);
+
+               DefineProperty("fold.rust.syntax.based", &OptionsRust::foldSyntaxBased,
+                       "Set this property to 0 to disable syntax based folding.");
+
+               DefineProperty("fold.rust.comment.multiline", &OptionsRust::foldCommentMultiline,
+                       "Set this property to 0 to disable folding multi-line comments when fold.comment=1.");
+
+               DefineProperty("fold.rust.comment.explicit", &OptionsRust::foldCommentExplicit,
+                       "Set this property to 0 to disable folding explicit fold points when 
fold.comment=1.");
+
+               DefineProperty("fold.rust.explicit.start", &OptionsRust::foldExplicitStart,
+                       "The string to use for explicit fold start points, replacing the standard //{.");
+
+               DefineProperty("fold.rust.explicit.end", &OptionsRust::foldExplicitEnd,
+                       "The string to use for explicit fold end points, replacing the standard //}.");
+
+               DefineProperty("fold.rust.explicit.anywhere", &OptionsRust::foldExplicitAnywhere,
+                       "Set this property to 1 to enable explicit fold points anywhere, not just in line 
comments.");
+
+               DefineProperty("lexer.rust.fold.at.else", &OptionsRust::foldAtElseInt,
+                       "This option enables Rust folding on a \"} else {\" line of an if statement.");
+
+               DefineWordListSets(rustWordLists);
+       }
+};
+
+class LexerRust : public ILexer {
+       WordList keywords[NUM_RUST_KEYWORD_LISTS];
+       OptionsRust options;
+       OptionSetRust osRust;
+public:
+       virtual ~LexerRust() {
+       }
+       void SCI_METHOD Release() override {
+               delete this;
+       }
+       int SCI_METHOD Version() const override {
+               return lvOriginal;
+       }
+       const char * SCI_METHOD PropertyNames() override {
+               return osRust.PropertyNames();
+       }
+       int SCI_METHOD PropertyType(const char *name) override {
+               return osRust.PropertyType(name);
+       }
+       const char * SCI_METHOD DescribeProperty(const char *name) override {
+               return osRust.DescribeProperty(name);
+       }
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+       const char * SCI_METHOD DescribeWordListSets() override {
+               return osRust.DescribeWordListSets();
+       }
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void * SCI_METHOD PrivateCall(int, void *) override {
+               return 0;
+       }
+       static ILexer *LexerFactoryRust() {
+               return new LexerRust();
+       }
+};
+
+Sci_Position SCI_METHOD LexerRust::PropertySet(const char *key, const char *val) {
+       if (osRust.PropertySet(&options, key, val)) {
+               return 0;
+       }
+       return -1;
+}
+
+Sci_Position SCI_METHOD LexerRust::WordListSet(int n, const char *wl) {
+       Sci_Position firstModification = -1;
+       if (n < NUM_RUST_KEYWORD_LISTS) {
+               WordList *wordListN = &keywords[n];
+               WordList wlNew;
+               wlNew.Set(wl);
+               if (*wordListN != wlNew) {
+                       wordListN->Set(wl);
+                       firstModification = 0;
+               }
+       }
+       return firstModification;
+}
+
+static bool IsWhitespace(int c) {
+    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
+}
+
+/* This isn't quite right for Unicode identifiers */
+static bool IsIdentifierStart(int ch) {
+       return (IsASCII(ch) && (isalpha(ch) || ch == '_')) || !IsASCII(ch);
+}
+
+/* This isn't quite right for Unicode identifiers */
+static bool IsIdentifierContinue(int ch) {
+       return (IsASCII(ch) && (isalnum(ch) || ch == '_')) || !IsASCII(ch);
+}
+
+static void ScanWhitespace(Accessor& styler, Sci_Position& pos, Sci_Position max) {
+       while (IsWhitespace(styler.SafeGetCharAt(pos, '\0')) && pos < max) {
+               if (pos == styler.LineEnd(styler.GetLine(pos)))
+                       styler.SetLineState(styler.GetLine(pos), 0);
+               pos++;
+       }
+       styler.ColourTo(pos-1, SCE_RUST_DEFAULT);
+}
+
+static void GrabString(char* s, Accessor& styler, Sci_Position start, Sci_Position len) {
+       for (Sci_Position ii = 0; ii < len; ii++)
+               s[ii] = styler[ii + start];
+       s[len] = '\0';
+}
+
+static void ScanIdentifier(Accessor& styler, Sci_Position& pos, WordList *keywords) {
+       Sci_Position start = pos;
+       while (IsIdentifierContinue(styler.SafeGetCharAt(pos, '\0')))
+               pos++;
+
+       if (styler.SafeGetCharAt(pos, '\0') == '!') {
+               pos++;
+               styler.ColourTo(pos - 1, SCE_RUST_MACRO);
+       } else {
+               char s[MAX_RUST_IDENT_CHARS + 1];
+               int len = pos - start;
+               len = len > MAX_RUST_IDENT_CHARS ? MAX_RUST_IDENT_CHARS : len;
+               GrabString(s, styler, start, len);
+               bool keyword = false;
+               for (int ii = 0; ii < NUM_RUST_KEYWORD_LISTS; ii++) {
+                       if (keywords[ii].InList(s)) {
+                               styler.ColourTo(pos - 1, SCE_RUST_WORD + ii);
+                               keyword = true;
+                               break;
+                       }
+               }
+               if (!keyword) {
+                       styler.ColourTo(pos - 1, SCE_RUST_IDENTIFIER);
+               }
+       }
+}
+
+/* Scans a sequence of digits, returning true if it found any. */
+static bool ScanDigits(Accessor& styler, Sci_Position& pos, int base) {
+       Sci_Position old_pos = pos;
+       for (;;) {
+               int c = styler.SafeGetCharAt(pos, '\0');
+               if (IsADigit(c, base) || c == '_')
+                       pos++;
+               else
+                       break;
+       }
+       return old_pos != pos;
+}
+
+/* Scans an integer and floating point literals. */
+static void ScanNumber(Accessor& styler, Sci_Position& pos) {
+       int base = 10;
+       int c = styler.SafeGetCharAt(pos, '\0');
+       int n = styler.SafeGetCharAt(pos + 1, '\0');
+       bool error = false;
+       /* Scan the prefix, thus determining the base.
+        * 10 is default if there's no prefix. */
+       if (c == '0' && n == 'x') {
+               pos += 2;
+               base = 16;
+       } else if (c == '0' && n == 'b') {
+               pos += 2;
+               base = 2;
+       } else if (c == '0' && n == 'o') {
+               pos += 2;
+               base = 8;
+       }
+
+       /* Scan initial digits. The literal is malformed if there are none. */
+       error |= !ScanDigits(styler, pos, base);
+       /* See if there's an integer suffix. We mimic the Rust's lexer
+        * and munch it even if there was an error above. */
+       c = styler.SafeGetCharAt(pos, '\0');
+       if (c == 'u' || c == 'i') {
+               pos++;
+               c = styler.SafeGetCharAt(pos, '\0');
+               n = styler.SafeGetCharAt(pos + 1, '\0');
+               if (c == '8' || c == 's') {
+                       pos++;
+               } else if (c == '1' && n == '6') {
+                       pos += 2;
+               } else if (c == '3' && n == '2') {
+                       pos += 2;
+               } else if (c == '6' && n == '4') {
+                       pos += 2;
+               } else {
+                       error = true;
+               }
+       /* See if it's a floating point literal. These literals have to be base 10.
+        */
+       } else if (!error) {
+               /* If there's a period, it's a floating point literal unless it's
+                * followed by an identifier (meaning this is a method call, e.g.
+                * `1.foo()`) or another period, in which case it's a range (e.g. 1..2)
+                */
+               n = styler.SafeGetCharAt(pos + 1, '\0');
+               if (c == '.' && !(IsIdentifierStart(n) || n == '.')) {
+                       error |= base != 10;
+                       pos++;
+                       /* It's ok to have no digits after the period. */
+                       ScanDigits(styler, pos, 10);
+               }
+
+               /* Look for the exponentiation. */
+               c = styler.SafeGetCharAt(pos, '\0');
+               if (c == 'e' || c == 'E') {
+                       error |= base != 10;
+                       pos++;
+                       c = styler.SafeGetCharAt(pos, '\0');
+                       if (c == '-' || c == '+')
+                               pos++;
+                       /* It is invalid to have no digits in the exponent. */
+                       error |= !ScanDigits(styler, pos, 10);
+               }
+
+               /* Scan the floating point suffix. */
+               c = styler.SafeGetCharAt(pos, '\0');
+               if (c == 'f') {
+                       error |= base != 10;
+                       pos++;
+                       c = styler.SafeGetCharAt(pos, '\0');
+                       n = styler.SafeGetCharAt(pos + 1, '\0');
+                       if (c == '3' && n == '2') {
+                               pos += 2;
+                       } else if (c == '6' && n == '4') {
+                               pos += 2;
+                       } else {
+                               error = true;
+                       }
+               }
+       }
+
+       if (error)
+               styler.ColourTo(pos - 1, SCE_RUST_LEXERROR);
+       else
+               styler.ColourTo(pos - 1, SCE_RUST_NUMBER);
+}
+
+static bool IsOneCharOperator(int c) {
+       return c == ';' || c == ',' || c == '(' || c == ')'
+           || c == '{' || c == '}' || c == '[' || c == ']'
+           || c == '@' || c == '#' || c == '~' || c == '+'
+           || c == '*' || c == '/' || c == '^' || c == '%'
+           || c == '.' || c == ':' || c == '!' || c == '<'
+           || c == '>' || c == '=' || c == '-' || c == '&'
+           || c == '|' || c == '$' || c == '?';
+}
+
+static bool IsTwoCharOperator(int c, int n) {
+       return (c == '.' && n == '.') || (c == ':' && n == ':')
+           || (c == '!' && n == '=') || (c == '<' && n == '<')
+           || (c == '<' && n == '=') || (c == '>' && n == '>')
+           || (c == '>' && n == '=') || (c == '=' && n == '=')
+           || (c == '=' && n == '>') || (c == '-' && n == '>')
+           || (c == '&' && n == '&') || (c == '|' && n == '|')
+           || (c == '-' && n == '=') || (c == '&' && n == '=')
+           || (c == '|' && n == '=') || (c == '+' && n == '=')
+           || (c == '*' && n == '=') || (c == '/' && n == '=')
+           || (c == '^' && n == '=') || (c == '%' && n == '=');
+}
+
+static bool IsThreeCharOperator(int c, int n, int n2) {
+       return (c == '<' && n == '<' && n2 == '=')
+           || (c == '>' && n == '>' && n2 == '=');
+}
+
+static bool IsValidCharacterEscape(int c) {
+       return c == 'n'  || c == 'r' || c == 't' || c == '\\'
+           || c == '\'' || c == '"' || c == '0';
+}
+
+static bool IsValidStringEscape(int c) {
+       return IsValidCharacterEscape(c) || c == '\n' || c == '\r';
+}
+
+static bool ScanNumericEscape(Accessor &styler, Sci_Position& pos, Sci_Position num_digits, bool stop_asap) {
+       for (;;) {
+               int c = styler.SafeGetCharAt(pos, '\0');
+               if (!IsADigit(c, 16))
+                       break;
+               num_digits--;
+               pos++;
+               if (num_digits == 0 && stop_asap)
+                       return true;
+       }
+       if (num_digits == 0) {
+               return true;
+       } else {
+               return false;
+       }
+}
+
+/* This is overly permissive for character literals in order to accept UTF-8 encoded
+ * character literals. */
+static void ScanCharacterLiteralOrLifetime(Accessor &styler, Sci_Position& pos, bool ascii_only) {
+       pos++;
+       int c = styler.SafeGetCharAt(pos, '\0');
+       int n = styler.SafeGetCharAt(pos + 1, '\0');
+       bool done = false;
+       bool valid_lifetime = !ascii_only && IsIdentifierStart(c);
+       bool valid_char = true;
+       bool first = true;
+       while (!done) {
+               switch (c) {
+                       case '\\':
+                               done = true;
+                               if (IsValidCharacterEscape(n)) {
+                                       pos += 2;
+                               } else if (n == 'x') {
+                                       pos += 2;
+                                       valid_char = ScanNumericEscape(styler, pos, 2, false);
+                               } else if (n == 'u' && !ascii_only) {
+                                       pos += 2;
+                                       if (styler.SafeGetCharAt(pos, '\0') != '{') {
+                                               // old-style
+                                               valid_char = ScanNumericEscape(styler, pos, 4, false);
+                                       } else {
+                                               int n_digits = 0;
+                                               while (IsADigit(styler.SafeGetCharAt(++pos, '\0'), 16) && 
n_digits++ < 6) {
+                                               }
+                                               if (n_digits > 0 && styler.SafeGetCharAt(pos, '\0') == '}')
+                                                       pos++;
+                                               else
+                                                       valid_char = false;
+                                       }
+                               } else if (n == 'U' && !ascii_only) {
+                                       pos += 2;
+                                       valid_char = ScanNumericEscape(styler, pos, 8, false);
+                               } else {
+                                       valid_char = false;
+                               }
+                               break;
+                       case '\'':
+                               valid_char = !first;
+                               done = true;
+                               break;
+                       case '\t':
+                       case '\n':
+                       case '\r':
+                       case '\0':
+                               valid_char = false;
+                               done = true;
+                               break;
+                       default:
+                               if (ascii_only && !IsASCII((char)c)) {
+                                       done = true;
+                                       valid_char = false;
+                               } else if (!IsIdentifierContinue(c) && !first) {
+                                       done = true;
+                               } else {
+                                       pos++;
+                               }
+                               break;
+               }
+               c = styler.SafeGetCharAt(pos, '\0');
+               n = styler.SafeGetCharAt(pos + 1, '\0');
+
+               first = false;
+       }
+       if (styler.SafeGetCharAt(pos, '\0') == '\'') {
+               valid_lifetime = false;
+       } else {
+               valid_char = false;
+       }
+       if (valid_lifetime) {
+               styler.ColourTo(pos - 1, SCE_RUST_LIFETIME);
+       } else if (valid_char) {
+               pos++;
+               styler.ColourTo(pos - 1, ascii_only ? SCE_RUST_BYTECHARACTER : SCE_RUST_CHARACTER);
+       } else {
+               styler.ColourTo(pos - 1, SCE_RUST_LEXERROR);
+       }
+}
+
+enum CommentState {
+       UnknownComment,
+       DocComment,
+       NotDocComment
+};
+
+/*
+ * The rule for block-doc comments is as follows: /xxN and /x! (where x is an asterisk, N is a non-asterisk) 
start doc comments.
+ * Otherwise it's a regular comment.
+ */
+static void ResumeBlockComment(Accessor &styler, Sci_Position& pos, Sci_Position max, CommentState state, 
int level) {
+       int c = styler.SafeGetCharAt(pos, '\0');
+       bool maybe_doc_comment = false;
+       if (c == '*') {
+               int n = styler.SafeGetCharAt(pos + 1, '\0');
+               if (n != '*' && n != '/') {
+                       maybe_doc_comment = true;
+               }
+       } else if (c == '!') {
+               maybe_doc_comment = true;
+       }
+
+       for (;;) {
+               int n = styler.SafeGetCharAt(pos + 1, '\0');
+               if (pos == styler.LineEnd(styler.GetLine(pos)))
+                       styler.SetLineState(styler.GetLine(pos), level);
+               if (c == '*') {
+                       pos++;
+                       if (n == '/') {
+                               pos++;
+                               level--;
+                               if (level == 0) {
+                                       styler.SetLineState(styler.GetLine(pos), 0);
+                                       if (state == DocComment || (state == UnknownComment && 
maybe_doc_comment))
+                                               styler.ColourTo(pos - 1, SCE_RUST_COMMENTBLOCKDOC);
+                                       else
+                                               styler.ColourTo(pos - 1, SCE_RUST_COMMENTBLOCK);
+                                       break;
+                               }
+                       }
+               } else if (c == '/') {
+                       pos++;
+                       if (n == '*') {
+                               pos++;
+                               level++;
+                       }
+               }
+               else {
+                       pos++;
+               }
+               if (pos >= max) {
+                       if (state == DocComment || (state == UnknownComment && maybe_doc_comment))
+                               styler.ColourTo(pos - 1, SCE_RUST_COMMENTBLOCKDOC);
+                       else
+                               styler.ColourTo(pos - 1, SCE_RUST_COMMENTBLOCK);
+                       break;
+               }
+               c = styler.SafeGetCharAt(pos, '\0');
+       }
+}
+
+/*
+ * The rule for line-doc comments is as follows... ///N and //! (where N is a non slash) start doc comments.
+ * Otherwise it's a normal line comment.
+ */
+static void ResumeLineComment(Accessor &styler, Sci_Position& pos, Sci_Position max, CommentState state) {
+       bool maybe_doc_comment = false;
+       int c = styler.SafeGetCharAt(pos, '\0');
+       if (c == '/') {
+               if (pos < max) {
+                       pos++;
+                       c = styler.SafeGetCharAt(pos, '\0');
+                       if (c != '/') {
+                               maybe_doc_comment = true;
+                       }
+               }
+       } else if (c == '!') {
+               maybe_doc_comment = true;
+       }
+
+       while (pos < max && c != '\n') {
+               if (pos == styler.LineEnd(styler.GetLine(pos)))
+                       styler.SetLineState(styler.GetLine(pos), 0);
+               pos++;
+               c = styler.SafeGetCharAt(pos, '\0');
+       }
+
+       if (state == DocComment || (state == UnknownComment && maybe_doc_comment))
+               styler.ColourTo(pos - 1, SCE_RUST_COMMENTLINEDOC);
+       else
+               styler.ColourTo(pos - 1, SCE_RUST_COMMENTLINE);
+}
+
+static void ScanComments(Accessor &styler, Sci_Position& pos, Sci_Position max) {
+       pos++;
+       int c = styler.SafeGetCharAt(pos, '\0');
+       pos++;
+       if (c == '/')
+               ResumeLineComment(styler, pos, max, UnknownComment);
+       else if (c == '*')
+               ResumeBlockComment(styler, pos, max, UnknownComment, 1);
+}
+
+static void ResumeString(Accessor &styler, Sci_Position& pos, Sci_Position max, bool ascii_only) {
+       int c = styler.SafeGetCharAt(pos, '\0');
+       bool error = false;
+       while (c != '"' && !error) {
+               if (pos >= max) {
+                       error = true;
+                       break;
+               }
+               if (pos == styler.LineEnd(styler.GetLine(pos)))
+                       styler.SetLineState(styler.GetLine(pos), 0);
+               if (c == '\\') {
+                       int n = styler.SafeGetCharAt(pos + 1, '\0');
+                       if (IsValidStringEscape(n)) {
+                               pos += 2;
+                       } else if (n == 'x') {
+                               pos += 2;
+                               error = !ScanNumericEscape(styler, pos, 2, true);
+                       } else if (n == 'u' && !ascii_only) {
+                               pos += 2;
+                               if (styler.SafeGetCharAt(pos, '\0') != '{') {
+                                       // old-style
+                                       error = !ScanNumericEscape(styler, pos, 4, true);
+                               } else {
+                                       int n_digits = 0;
+                                       while (IsADigit(styler.SafeGetCharAt(++pos, '\0'), 16) && n_digits++ 
< 6) {
+                                       }
+                                       if (n_digits > 0 && styler.SafeGetCharAt(pos, '\0') == '}')
+                                               pos++;
+                                       else
+                                               error = true;
+                               }
+                       } else if (n == 'U' && !ascii_only) {
+                               pos += 2;
+                               error = !ScanNumericEscape(styler, pos, 8, true);
+                       } else {
+                               pos += 1;
+                               error = true;
+                       }
+               } else {
+                       if (ascii_only && !IsASCII((char)c))
+                               error = true;
+                       else
+                               pos++;
+               }
+               c = styler.SafeGetCharAt(pos, '\0');
+       }
+       if (!error)
+               pos++;
+       styler.ColourTo(pos - 1, ascii_only ? SCE_RUST_BYTESTRING : SCE_RUST_STRING);
+}
+
+static void ResumeRawString(Accessor &styler, Sci_Position& pos, Sci_Position max, int num_hashes, bool 
ascii_only) {
+       for (;;) {
+               if (pos == styler.LineEnd(styler.GetLine(pos)))
+                       styler.SetLineState(styler.GetLine(pos), num_hashes);
+
+               int c = styler.SafeGetCharAt(pos, '\0');
+               if (c == '"') {
+                       pos++;
+                       int trailing_num_hashes = 0;
+                       while (styler.SafeGetCharAt(pos, '\0') == '#' && trailing_num_hashes < num_hashes) {
+                               trailing_num_hashes++;
+                               pos++;
+                       }
+                       if (trailing_num_hashes == num_hashes) {
+                               styler.SetLineState(styler.GetLine(pos), 0);
+                               break;
+                       }
+               } else if (pos >= max) {
+                       break;
+               } else {
+                       if (ascii_only && !IsASCII((char)c))
+                               break;
+                       pos++;
+               }
+       }
+       styler.ColourTo(pos - 1, ascii_only ? SCE_RUST_BYTESTRINGR : SCE_RUST_STRINGR);
+}
+
+static void ScanRawString(Accessor &styler, Sci_Position& pos, Sci_Position max, bool ascii_only) {
+       pos++;
+       int num_hashes = 0;
+       while (styler.SafeGetCharAt(pos, '\0') == '#') {
+               num_hashes++;
+               pos++;
+       }
+       if (styler.SafeGetCharAt(pos, '\0') != '"') {
+               styler.ColourTo(pos - 1, SCE_RUST_LEXERROR);
+       } else {
+               pos++;
+               ResumeRawString(styler, pos, max, num_hashes, ascii_only);
+       }
+}
+
+void SCI_METHOD LexerRust::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
+       PropSetSimple props;
+       Accessor styler(pAccess, &props);
+       Sci_Position pos = startPos;
+       Sci_Position max = pos + length;
+
+       styler.StartAt(pos);
+       styler.StartSegment(pos);
+
+       if (initStyle == SCE_RUST_COMMENTBLOCK || initStyle == SCE_RUST_COMMENTBLOCKDOC) {
+               ResumeBlockComment(styler, pos, max, initStyle == SCE_RUST_COMMENTBLOCKDOC ? DocComment : 
NotDocComment, styler.GetLineState(styler.GetLine(pos) - 1));
+       } else if (initStyle == SCE_RUST_COMMENTLINE || initStyle == SCE_RUST_COMMENTLINEDOC) {
+               ResumeLineComment(styler, pos, max, initStyle == SCE_RUST_COMMENTLINEDOC ? DocComment : 
NotDocComment);
+       } else if (initStyle == SCE_RUST_STRING) {
+               ResumeString(styler, pos, max, false);
+       } else if (initStyle == SCE_RUST_BYTESTRING) {
+               ResumeString(styler, pos, max, true);
+       } else if (initStyle == SCE_RUST_STRINGR) {
+               ResumeRawString(styler, pos, max, styler.GetLineState(styler.GetLine(pos) - 1), false);
+       } else if (initStyle == SCE_RUST_BYTESTRINGR) {
+               ResumeRawString(styler, pos, max, styler.GetLineState(styler.GetLine(pos) - 1), true);
+       }
+
+       while (pos < max) {
+               int c = styler.SafeGetCharAt(pos, '\0');
+               int n = styler.SafeGetCharAt(pos + 1, '\0');
+               int n2 = styler.SafeGetCharAt(pos + 2, '\0');
+
+               if (pos == 0 && c == '#' && n == '!' && n2 != '[') {
+                       pos += 2;
+                       ResumeLineComment(styler, pos, max, NotDocComment);
+               } else if (IsWhitespace(c)) {
+                       ScanWhitespace(styler, pos, max);
+               } else if (c == '/' && (n == '/' || n == '*')) {
+                       ScanComments(styler, pos, max);
+               } else if (c == 'r' && (n == '#' || n == '"')) {
+                       ScanRawString(styler, pos, max, false);
+               } else if (c == 'b' && n == 'r' && (n2 == '#' || n2 == '"')) {
+                       pos++;
+                       ScanRawString(styler, pos, max, true);
+               } else if (c == 'b' && n == '"') {
+                       pos += 2;
+                       ResumeString(styler, pos, max, true);
+               } else if (c == 'b' && n == '\'') {
+                       pos++;
+                       ScanCharacterLiteralOrLifetime(styler, pos, true);
+               } else if (IsIdentifierStart(c)) {
+                       ScanIdentifier(styler, pos, keywords);
+               } else if (IsADigit(c)) {
+                       ScanNumber(styler, pos);
+               } else if (IsThreeCharOperator(c, n, n2)) {
+                       pos += 3;
+                       styler.ColourTo(pos - 1, SCE_RUST_OPERATOR);
+               } else if (IsTwoCharOperator(c, n)) {
+                       pos += 2;
+                       styler.ColourTo(pos - 1, SCE_RUST_OPERATOR);
+               } else if (IsOneCharOperator(c)) {
+                       pos++;
+                       styler.ColourTo(pos - 1, SCE_RUST_OPERATOR);
+               } else if (c == '\'') {
+                       ScanCharacterLiteralOrLifetime(styler, pos, false);
+               } else if (c == '"') {
+                       pos++;
+                       ResumeString(styler, pos, max, false);
+               } else {
+                       pos++;
+                       styler.ColourTo(pos - 1, SCE_RUST_LEXERROR);
+               }
+       }
+       styler.ColourTo(pos - 1, SCE_RUST_DEFAULT);
+       styler.Flush();
+}
+
+void SCI_METHOD LexerRust::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
+
+       if (!options.fold)
+               return;
+
+       LexAccessor styler(pAccess);
+
+       Sci_PositionU endPos = startPos + length;
+       int visibleChars = 0;
+       bool inLineComment = false;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       int levelCurrent = SC_FOLDLEVELBASE;
+       if (lineCurrent > 0)
+               levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
+       Sci_PositionU lineStartNext = styler.LineStart(lineCurrent+1);
+       int levelMinCurrent = levelCurrent;
+       int levelNext = levelCurrent;
+       char chNext = styler[startPos];
+       int styleNext = styler.StyleAt(startPos);
+       int style = initStyle;
+       const bool userDefinedFoldMarkers = !options.foldExplicitStart.empty() && 
!options.foldExplicitEnd.empty();
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
+               char ch = chNext;
+               chNext = styler.SafeGetCharAt(i + 1);
+               int stylePrev = style;
+               style = styleNext;
+               styleNext = styler.StyleAt(i + 1);
+               bool atEOL = i == (lineStartNext-1);
+               if ((style == SCE_RUST_COMMENTLINE) || (style == SCE_RUST_COMMENTLINEDOC))
+                       inLineComment = true;
+               if (options.foldComment && options.foldCommentMultiline && IsStreamCommentStyle(style) && 
!inLineComment) {
+                       if (!IsStreamCommentStyle(stylePrev)) {
+                               levelNext++;
+                       } else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
+                               // Comments don't end at end of line and the next character may be unstyled.
+                               levelNext--;
+                       }
+               }
+               if (options.foldComment && options.foldCommentExplicit && ((style == SCE_RUST_COMMENTLINE) || 
options.foldExplicitAnywhere)) {
+                       if (userDefinedFoldMarkers) {
+                               if (styler.Match(i, options.foldExplicitStart.c_str())) {
+                                       levelNext++;
+                               } else if (styler.Match(i, options.foldExplicitEnd.c_str())) {
+                                       levelNext--;
+                               }
+                       } else {
+                               if ((ch == '/') && (chNext == '/')) {
+                                       char chNext2 = styler.SafeGetCharAt(i + 2);
+                                       if (chNext2 == '{') {
+                                               levelNext++;
+                                       } else if (chNext2 == '}') {
+                                               levelNext--;
+                                       }
+                               }
+                       }
+               }
+               if (options.foldSyntaxBased && (style == SCE_RUST_OPERATOR)) {
+                       if (ch == '{') {
+                               // Measure the minimum before a '{' to allow
+                               // folding on "} else {"
+                               if (levelMinCurrent > levelNext) {
+                                       levelMinCurrent = levelNext;
+                               }
+                               levelNext++;
+                       } else if (ch == '}') {
+                               levelNext--;
+                       }
+               }
+               if (!IsASpace(ch))
+                       visibleChars++;
+               if (atEOL || (i == endPos-1)) {
+                       int levelUse = levelCurrent;
+                       if (options.foldSyntaxBased && options.foldAtElse) {
+                               levelUse = levelMinCurrent;
+                       }
+                       int lev = levelUse | levelNext << 16;
+                       if (visibleChars == 0 && options.foldCompact)
+                               lev |= SC_FOLDLEVELWHITEFLAG;
+                       if (levelUse < levelNext)
+                               lev |= SC_FOLDLEVELHEADERFLAG;
+                       if (lev != styler.LevelAt(lineCurrent)) {
+                               styler.SetLevel(lineCurrent, lev);
+                       }
+                       lineCurrent++;
+                       lineStartNext = styler.LineStart(lineCurrent+1);
+                       levelCurrent = levelNext;
+                       levelMinCurrent = levelCurrent;
+                       if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length()-1))) {
+                               // There is an empty line at end of file so give it same level and empty
+                               styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | 
SC_FOLDLEVELWHITEFLAG);
+                       }
+                       visibleChars = 0;
+                       inLineComment = false;
+               }
+       }
+}
+
+LexerModule lmRust(SCLEX_RUST, LexerRust::LexerFactoryRust, "rust", rustWordLists);
diff --git a/plugins/scintilla/scintilla/lexers/LexSML.cxx b/plugins/scintilla/scintilla/lexers/LexSML.cxx
index 6ab902d..76cfde0 100644
--- a/plugins/scintilla/scintilla/lexers/LexSML.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSML.cxx
@@ -33,8 +33,8 @@ inline int issmld(int c) {return isdigit(c) || c == '_';}
 using namespace Scintilla;
 #endif
 
-void ColouriseSMLDoc(
-       unsigned int startPos, int length,
+static void ColouriseSMLDoc(
+       Sci_PositionU startPos, Sci_Position length,
        int initStyle,
        WordList *keywordlists[],
        Accessor &styler)
@@ -46,7 +46,8 @@ void ColouriseSMLDoc(
        if (sc.state >= SCE_SML_COMMENT)
                nesting = (sc.state & 0x0f) - SCE_SML_COMMENT;
 
-       int chBase = 0, chToken = 0, chLit = 0;
+       Sci_PositionU chToken = 0;
+       int chBase = 0, chLit = 0;
        WordList& keywords  = *keywordlists[0];
        WordList& keywords2 = *keywordlists[1];
        WordList& keywords3 = *keywordlists[2];
@@ -54,7 +55,7 @@ void ColouriseSMLDoc(
 
        while (sc.More()) {
                int state2 = -1;
-               int chColor = sc.currentPos - 1;
+               Sci_Position chColor = sc.currentPos - 1;
                bool advance = true;
 
                switch (sc.state & 0x0f) {
@@ -89,10 +90,10 @@ void ColouriseSMLDoc(
 
                case SCE_SML_IDENTIFIER:
                        if (!(issml(sc.ch) || sc.Match('\''))) {
-                               const int n = sc.currentPos - chToken;
+                               const Sci_Position n = sc.currentPos - chToken;
                                if (n < 24) {
                                        char t[24];
-                                       for (int i = -n; i < 0; i++)
+                                       for (Sci_Position i = -n; i < 0; i++)
                                                t[n + i] = static_cast<char>(sc.GetRelative(i));
                                        t[n] = '\0';
                                        if ((n == 1 && sc.chPrev == '_') || keywords.InList(t))
@@ -204,8 +205,8 @@ void ColouriseSMLDoc(
        sc.Complete();
 }
 
-void FoldSMLDoc(
-       unsigned int, int,
+static void FoldSMLDoc(
+       Sci_PositionU, Sci_Position,
        int,
        WordList *[],
        Accessor &)
diff --git a/plugins/scintilla/scintilla/lexers/LexSQL.cxx b/plugins/scintilla/scintilla/lexers/LexSQL.cxx
index dc4bf66..6562839 100644
--- a/plugins/scintilla/scintilla/lexers/LexSQL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSQL.cxx
@@ -54,22 +54,23 @@ static inline bool IsADoxygenChar(int ch) {
                ch == '}' || ch == '[' || ch == ']');
 }
 
-static inline bool IsANumberChar(int ch) {
+static inline bool IsANumberChar(int ch, int chPrev) {
        // Not exactly following number definition (several dots are seen as OK, etc.)
        // but probably enough in most cases.
        return (ch < 0x80) &&
               (isdigit(ch) || toupper(ch) == 'E' ||
-               ch == '.' || ch == '-' || ch == '+');
+               ch == '.' || ((ch == '-' || ch == '+') && chPrev < 0x80 && toupper(chPrev) == 'E'));
 }
 
+typedef unsigned int sql_state_t;
 
 class SQLStates {
 public :
-       void Set(int lineNumber, unsigned short int sqlStatesLine) {
+       void Set(Sci_Position lineNumber, unsigned short int sqlStatesLine) {
                sqlStatement.Set(lineNumber, sqlStatesLine);
        }
 
-       unsigned short int IgnoreWhen (unsigned short int sqlStatesLine, bool enable) {
+       sql_state_t IgnoreWhen (sql_state_t sqlStatesLine, bool enable) {
                if (enable)
                        sqlStatesLine |= MASK_IGNORE_WHEN;
                else
@@ -78,7 +79,7 @@ public :
                return sqlStatesLine;
        }
 
-       unsigned short int IntoCondition (unsigned short int sqlStatesLine, bool enable) {
+       sql_state_t IntoCondition (sql_state_t sqlStatesLine, bool enable) {
                if (enable)
                        sqlStatesLine |= MASK_INTO_CONDITION;
                else
@@ -87,7 +88,7 @@ public :
                return sqlStatesLine;
        }
 
-       unsigned short int IntoExceptionBlock (unsigned short int sqlStatesLine, bool enable) {
+       sql_state_t IntoExceptionBlock (sql_state_t sqlStatesLine, bool enable) {
                if (enable)
                        sqlStatesLine |= MASK_INTO_EXCEPTION;
                else
@@ -96,7 +97,7 @@ public :
                return sqlStatesLine;
        }
 
-       unsigned short int IntoDeclareBlock (unsigned short int sqlStatesLine, bool enable) {
+       sql_state_t IntoDeclareBlock (sql_state_t sqlStatesLine, bool enable) {
                if (enable)
                        sqlStatesLine |= MASK_INTO_DECLARE;
                else
@@ -105,7 +106,7 @@ public :
                return sqlStatesLine;
        }
 
-       unsigned short int IntoMergeStatement (unsigned short int sqlStatesLine, bool enable) {
+       sql_state_t IntoMergeStatement (sql_state_t sqlStatesLine, bool enable) {
                if (enable)
                        sqlStatesLine |= MASK_MERGE_STATEMENT;
                else
@@ -114,7 +115,7 @@ public :
                return sqlStatesLine;
        }
 
-       unsigned short int CaseMergeWithoutWhenFound (unsigned short int sqlStatesLine, bool found) {
+       sql_state_t CaseMergeWithoutWhenFound (sql_state_t sqlStatesLine, bool found) {
                if (found)
                        sqlStatesLine |= MASK_CASE_MERGE_WITHOUT_WHEN_FOUND;
                else
@@ -122,7 +123,7 @@ public :
 
                return sqlStatesLine;
        }
-       unsigned short int IntoSelectStatementOrAssignment (unsigned short int sqlStatesLine, bool found) {
+       sql_state_t IntoSelectStatementOrAssignment (sql_state_t sqlStatesLine, bool found) {
                if (found)
                        sqlStatesLine |= MASK_INTO_SELECT_STATEMENT_OR_ASSIGNEMENT;
                else
@@ -130,67 +131,109 @@ public :
                return sqlStatesLine;
        }
 
-       unsigned short int BeginCaseBlock (unsigned short int sqlStatesLine) {
+       sql_state_t BeginCaseBlock (sql_state_t sqlStatesLine) {
                if ((sqlStatesLine & MASK_NESTED_CASES) < MASK_NESTED_CASES) {
                        sqlStatesLine++;
                }
                return sqlStatesLine;
        }
 
-       unsigned short int EndCaseBlock (unsigned short int sqlStatesLine) {
+       sql_state_t EndCaseBlock (sql_state_t sqlStatesLine) {
                if ((sqlStatesLine & MASK_NESTED_CASES) > 0) {
                        sqlStatesLine--;
                }
                return sqlStatesLine;
        }
 
-       bool IsIgnoreWhen (unsigned short int sqlStatesLine) {
+       sql_state_t IntoCreateStatement (sql_state_t sqlStatesLine, bool enable) {
+               if (enable)
+                       sqlStatesLine |= MASK_INTO_CREATE;
+               else
+                       sqlStatesLine &= ~MASK_INTO_CREATE;
+
+               return sqlStatesLine;
+       }
+
+       sql_state_t IntoCreateViewStatement (sql_state_t sqlStatesLine, bool enable) {
+               if (enable)
+                       sqlStatesLine |= MASK_INTO_CREATE_VIEW;
+               else
+                       sqlStatesLine &= ~MASK_INTO_CREATE_VIEW;
+
+               return sqlStatesLine;
+       }
+
+       sql_state_t IntoCreateViewAsStatement (sql_state_t sqlStatesLine, bool enable) {
+               if (enable)
+                       sqlStatesLine |= MASK_INTO_CREATE_VIEW_AS_STATEMENT;
+               else
+                       sqlStatesLine &= ~MASK_INTO_CREATE_VIEW_AS_STATEMENT;
+
+               return sqlStatesLine;
+       }
+
+       bool IsIgnoreWhen (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_IGNORE_WHEN) != 0;
        }
 
-       bool IsIntoCondition (unsigned short int sqlStatesLine) {
+       bool IsIntoCondition (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_INTO_CONDITION) != 0;
        }
 
-       bool IsIntoCaseBlock (unsigned short int sqlStatesLine) {
+       bool IsIntoCaseBlock (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_NESTED_CASES) != 0;
        }
 
-       bool IsIntoExceptionBlock (unsigned short int sqlStatesLine) {
+       bool IsIntoExceptionBlock (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_INTO_EXCEPTION) != 0;
        }
-       bool IsIntoSelectStatementOrAssignment (unsigned short int sqlStatesLine) {
+       bool IsIntoSelectStatementOrAssignment (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_INTO_SELECT_STATEMENT_OR_ASSIGNEMENT) != 0;
        }
-       bool IsCaseMergeWithoutWhenFound (unsigned short int sqlStatesLine) {
+       bool IsCaseMergeWithoutWhenFound (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_CASE_MERGE_WITHOUT_WHEN_FOUND) != 0;
        }
 
-       bool IsIntoDeclareBlock (unsigned short int sqlStatesLine) {
+       bool IsIntoDeclareBlock (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_INTO_DECLARE) != 0;
        }
 
-       bool IsIntoMergeStatement (unsigned short int sqlStatesLine) {
+       bool IsIntoMergeStatement (sql_state_t sqlStatesLine) {
                return (sqlStatesLine & MASK_MERGE_STATEMENT) != 0;
        }
 
-       unsigned short int ForLine(int lineNumber) {
+       bool IsIntoCreateStatement (sql_state_t sqlStatesLine) {
+               return (sqlStatesLine & MASK_INTO_CREATE) != 0;
+       }
+
+       bool IsIntoCreateViewStatement (sql_state_t sqlStatesLine) {
+               return (sqlStatesLine & MASK_INTO_CREATE_VIEW) != 0;
+       }
+
+       bool IsIntoCreateViewAsStatement (sql_state_t sqlStatesLine) {
+               return (sqlStatesLine & MASK_INTO_CREATE_VIEW_AS_STATEMENT) != 0;
+       }
+
+       sql_state_t ForLine(Sci_Position lineNumber) {
                return sqlStatement.ValueAt(lineNumber);
        }
 
        SQLStates() {}
 
 private :
-       SparseState <unsigned short int> sqlStatement;
+       SparseState <sql_state_t> sqlStatement;
        enum {
-               MASK_NESTED_CASES = 0x01FF,
-               MASK_INTO_SELECT_STATEMENT_OR_ASSIGNEMENT = 0x0200,
-               MASK_CASE_MERGE_WITHOUT_WHEN_FOUND = 0x0400,
-               MASK_MERGE_STATEMENT = 0x0800,
-               MASK_INTO_DECLARE = 0x1000,
-               MASK_INTO_EXCEPTION = 0x2000,
-               MASK_INTO_CONDITION = 0x4000,
-               MASK_IGNORE_WHEN = 0x8000
+               MASK_NESTED_CASES                         = 0x0001FF,
+               MASK_INTO_SELECT_STATEMENT_OR_ASSIGNEMENT = 0x000200,
+               MASK_CASE_MERGE_WITHOUT_WHEN_FOUND        = 0x000400,
+               MASK_MERGE_STATEMENT                      = 0x000800,
+               MASK_INTO_DECLARE                         = 0x001000,
+               MASK_INTO_EXCEPTION                       = 0x002000,
+               MASK_INTO_CONDITION                       = 0x004000,
+               MASK_IGNORE_WHEN                          = 0x008000,
+               MASK_INTO_CREATE                          = 0x010000,
+               MASK_INTO_CREATE_VIEW                     = 0x020000,
+               MASK_INTO_CREATE_VIEW_AS_STATEMENT        = 0x040000
        };
 };
 
@@ -265,42 +308,42 @@ public :
 
        virtual ~LexerSQL() {}
 
-       int SCI_METHOD Version () const {
+       int SCI_METHOD Version () const override {
                return lvOriginal;
        }
 
-       void SCI_METHOD Release() {
+       void SCI_METHOD Release() override {
                delete this;
        }
 
-       const char * SCI_METHOD PropertyNames() {
+       const char * SCI_METHOD PropertyNames() override {
                return osSQL.PropertyNames();
        }
 
-       int SCI_METHOD PropertyType(const char *name) {
+       int SCI_METHOD PropertyType(const char *name) override {
                return osSQL.PropertyType(name);
        }
 
-       const char * SCI_METHOD DescribeProperty(const char *name) {
+       const char * SCI_METHOD DescribeProperty(const char *name) override {
                return osSQL.DescribeProperty(name);
        }
 
-       int SCI_METHOD PropertySet(const char *key, const char *val) {
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override {
                if (osSQL.PropertySet(&options, key, val)) {
                        return 0;
                }
                return -1;
        }
 
-       const char * SCI_METHOD DescribeWordListSets() {
+       const char * SCI_METHOD DescribeWordListSets() override {
                return osSQL.DescribeWordListSets();
        }
 
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex (unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) override;
 
-       void * SCI_METHOD PrivateCall(int, void *) {
+       void * SCI_METHOD PrivateCall(int, void *) override {
                return 0;
        }
 
@@ -329,10 +372,10 @@ private:
                }
        }
 
-       bool IsCommentLine (int line, LexAccessor &styler) {
-               int pos = styler.LineStart(line);
-               int eol_pos = styler.LineStart(line + 1) - 1;
-               for (int i = pos; i + 1 < eol_pos; i++) {
+       bool IsCommentLine (Sci_Position line, LexAccessor &styler) {
+               Sci_Position pos = styler.LineStart(line);
+               Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+               for (Sci_Position i = pos; i + 1 < eol_pos; i++) {
                        int style = styler.StyleAt(i);
                        // MySQL needs -- comments to be followed by space or control char
                        if (style == SCE_SQL_COMMENTLINE && styler.Match(i, "--"))
@@ -357,7 +400,7 @@ private:
        WordList kw_user4;
 };
 
-int SCI_METHOD LexerSQL::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerSQL::WordListSet(int n, const char *wl) {
        WordList *wordListN = 0;
        switch (n) {
        case 0:
@@ -384,7 +427,7 @@ int SCI_METHOD LexerSQL::WordListSet(int n, const char *wl) {
        case 7:
                wordListN = &kw_user4;
        }
-       int firstModification = -1;
+       Sci_Position firstModification = -1;
        if (wordListN) {
                WordList wlNew;
                wlNew.Set(wl);
@@ -396,11 +439,12 @@ int SCI_METHOD LexerSQL::WordListSet(int n, const char *wl) {
        return firstModification;
 }
 
-void SCI_METHOD LexerSQL::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerSQL::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        LexAccessor styler(pAccess);
        StyleContext sc(startPos, length, initStyle, styler);
        int styleBeforeDCKeyword = SCE_SQL_DEFAULT;
-       int offset = 0;
+       Sci_Position offset = 0;
+
        for (; sc.More(); sc.Forward(), offset++) {
                // Determine if the current state should terminate.
                switch (sc.state) {
@@ -409,7 +453,7 @@ void SCI_METHOD LexerSQL::Lex(unsigned int startPos, int length, int initStyle,
                        break;
                case SCE_SQL_NUMBER:
                        // We stop the number definition on non-numerical non-dot non-eE non-sign char
-                       if (!IsANumberChar(sc.ch)) {
+                       if (!IsANumberChar(sc.ch, sc.chPrev)) {
                                sc.SetState(SCE_SQL_DEFAULT);
                        }
                        break;
@@ -513,11 +557,45 @@ void SCI_METHOD LexerSQL::Lex(unsigned int startPos, int length, int initStyle,
                                }
                        }
                        break;
+               case SCE_SQL_QOPERATOR:
+                       // Locate the unique Q operator character
+                       sc.Complete();
+                       char qOperator = 0x00;
+                       for (Sci_Position styleStartPos = sc.currentPos; styleStartPos > 0; --styleStartPos) {
+                               if (styler.StyleAt(styleStartPos - 1) != SCE_SQL_QOPERATOR) {
+                                       qOperator = styler.SafeGetCharAt(styleStartPos + 2);
+                                       break;
+                               }
+                       }
+
+                       char qComplement = 0x00;
+
+                       if (qOperator == '<') {
+                               qComplement = '>';
+                       } else if (qOperator == '(') {
+                               qComplement = ')';
+                       } else if (qOperator == '{') {
+                               qComplement = '}';
+                       } else if (qOperator == '[') {
+                               qComplement = ']';
+                       } else {
+                               qComplement = qOperator;
+                       }
+
+                       if (sc.Match(qComplement, '\'')) {
+                               sc.Forward();
+                               sc.ForwardSetState(SCE_SQL_DEFAULT);
+                       }
+                       break;
                }
 
                // Determine if a new state should be entered.
                if (sc.state == SCE_SQL_DEFAULT) {
-                       if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+                       if (sc.Match('q', '\'') || sc.Match('Q', '\'')) {
+                               sc.SetState(SCE_SQL_QOPERATOR);
+                               sc.Forward();
+                       } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext)) ||
+                                 ((sc.ch == '-' || sc.ch == '+') && IsADigit(sc.chNext) && 
!IsADigit(sc.chPrev))) {
                                sc.SetState(SCE_SQL_NUMBER);
                        } else if (IsAWordStart(sc.ch)) {
                                sc.SetState(SCE_SQL_IDENTIFIER);
@@ -550,23 +628,57 @@ void SCI_METHOD LexerSQL::Lex(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerSQL::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
        if (!options.fold)
                return;
        LexAccessor styler(pAccess);
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
 
        if (lineCurrent > 0) {
                // Backtrack to previous line in case need to fix its fold status for folding block of 
single-line comments (i.e. '--').
-               lineCurrent -= 1;
-               startPos = styler.LineStart(lineCurrent);
-
+               Sci_Position lastNLPos = -1;
+               // And keep going back until we find an operator ';' followed
+               // by white-space and/or comments. This will improve folding.
+               while (--startPos > 0) {
+                       char ch = styler[startPos];
+                       if (ch == '\n' || (ch == '\r' && styler[startPos + 1] != '\n')) {
+                               lastNLPos = startPos;
+                       } else if (ch == ';' &&
+                                  styler.StyleAt(startPos) == SCE_SQL_OPERATOR) {
+                               bool isAllClear = true;
+                               for (Sci_Position tempPos = startPos + 1;
+                                    tempPos < lastNLPos;
+                                    ++tempPos) {
+                                       int tempStyle = styler.StyleAt(tempPos);
+                                       if (!IsCommentStyle(tempStyle)
+                                           && tempStyle != SCE_SQL_DEFAULT) {
+                                               isAllClear = false;
+                                               break;
+                                       }
+                               }
+                               if (isAllClear) {
+                                       startPos = lastNLPos + 1;
+                                       break;
+                               }
+                       }
+               }
+               lineCurrent = styler.GetLine(startPos);
                if (lineCurrent > 0)
                        levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16;
        }
+       // And because folding ends at ';', keep going until we find one
+       // Otherwise if create ... view ... as is split over multiple
+       // lines the folding won't always update immediately.
+       Sci_PositionU docLength = styler.Length();
+       for (; endPos < docLength; ++endPos) {
+               if (styler.SafeGetCharAt(endPos) == ';') {
+                       break;
+               }
+       }
+
        int levelNext = levelCurrent;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
@@ -576,11 +688,11 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
        // this statementFound flag avoids to fold when the statement is on only one line by ignoring ELSE or 
ELSIF
        // eg. "IF condition1 THEN ... ELSIF condition2 THEN ... ELSE ... END IF;"
        bool statementFound = false;
-       unsigned short int sqlStatesCurrentLine = 0;
+       sql_state_t sqlStatesCurrentLine = 0;
        if (!options.foldOnlyBegin) {
                sqlStatesCurrentLine = sqlStates.ForLine(lineCurrent);
        }
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -606,6 +718,16 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
                        }
                        if (sqlStates.IsIntoSelectStatementOrAssignment(sqlStatesCurrentLine))
                                sqlStatesCurrentLine = 
sqlStates.IntoSelectStatementOrAssignment(sqlStatesCurrentLine, false);
+                       if (sqlStates.IsIntoCreateStatement(sqlStatesCurrentLine)) {
+                               if (sqlStates.IsIntoCreateViewStatement(sqlStatesCurrentLine)) {
+                                       if (sqlStates.IsIntoCreateViewAsStatement(sqlStatesCurrentLine)) {
+                                               levelNext--;
+                                               sqlStatesCurrentLine = 
sqlStates.IntoCreateViewAsStatement(sqlStatesCurrentLine, false);
+                                       }
+                                       sqlStatesCurrentLine = 
sqlStates.IntoCreateViewStatement(sqlStatesCurrentLine, false);
+                               }
+                               sqlStatesCurrentLine = sqlStates.IntoCreateStatement(sqlStatesCurrentLine, 
false);
+                       }
                }
                if (ch == ':' && chNext == '=' && !IsCommentStyle(style))
                        sqlStatesCurrentLine = 
sqlStates.IntoSelectStatementOrAssignment(sqlStatesCurrentLine, true);
@@ -805,6 +927,19 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
                                sqlStatesCurrentLine = 
sqlStates.CaseMergeWithoutWhenFound(sqlStatesCurrentLine, true);
                                levelNext++;
                                statementFound = true;
+                       } else if ((!options.foldOnlyBegin) &&
+                                  strcmp(s, "create") == 0) {
+                               sqlStatesCurrentLine = sqlStates.IntoCreateStatement(sqlStatesCurrentLine, 
true);
+                       } else if ((!options.foldOnlyBegin) &&
+                                  strcmp(s, "view") == 0 &&
+                                  sqlStates.IsIntoCreateStatement(sqlStatesCurrentLine)) {
+                               sqlStatesCurrentLine = 
sqlStates.IntoCreateViewStatement(sqlStatesCurrentLine, true);
+                       } else if ((!options.foldOnlyBegin) &&
+                                  strcmp(s, "as") == 0 &&
+                                  sqlStates.IsIntoCreateViewStatement(sqlStatesCurrentLine) &&
+                                  ! sqlStates.IsIntoCreateViewAsStatement(sqlStatesCurrentLine)) {
+                               sqlStatesCurrentLine = 
sqlStates.IntoCreateViewAsStatement(sqlStatesCurrentLine, true);
+                               levelNext++;
                        }
                }
                if (atEOL) {
diff --git a/plugins/scintilla/scintilla/lexers/LexSTTXT.cxx b/plugins/scintilla/scintilla/lexers/LexSTTXT.cxx
index c58d054..b7ac8f4 100644
--- a/plugins/scintilla/scintilla/lexers/LexSTTXT.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSTTXT.cxx
@@ -60,7 +60,7 @@ static void ClassifySTTXTWord(WordList *keywordlists[], StyleContext &sc)
        sc.SetState(SCE_STTXT_DEFAULT);
 }
 
-static void ColouriseSTTXTDoc (unsigned int startPos, int length, int initStyle,
+static void ColouriseSTTXTDoc (Sci_PositionU startPos, Sci_Position length, int initStyle,
                                                          WordList *keywordlists[], Accessor &styler)
 {
        StyleContext sc(startPos, length, initStyle, styler);
@@ -85,17 +85,22 @@ static void ColouriseSTTXTDoc (unsigned int startPos, int length, int initStyle,
                                break;
                        }
                        case SCE_STTXT_HEXNUMBER: {
-                               if(setHexNumber.Contains(sc.ch))
+                               if (setHexNumber.Contains(sc.ch))
                                        continue;
                                else if(setDataTime.Contains(sc.ch))
-                                       sc.SetState(SCE_STTXT_DATETIME);
+                                       sc.ChangeState(SCE_STTXT_DATETIME);
+                               else if(setWord.Contains(sc.ch))
+                                       sc.ChangeState(SCE_STTXT_DEFAULT);
                                else
                                        sc.SetState(SCE_STTXT_DEFAULT);
-
                                break;
                        }
                        case SCE_STTXT_DATETIME: {
-                               if(!setDataTime.Contains(sc.ch))
+                               if (setDataTime.Contains(sc.ch))
+                                       continue;
+                               else if(setWord.Contains(sc.ch))
+                                       sc.ChangeState(SCE_STTXT_DEFAULT);
+                               else
                                        sc.SetState(SCE_STTXT_DEFAULT);
                                break;
                        }
@@ -194,12 +199,12 @@ static const char * const STTXTWordListDesc[] = {
        0
 };
 
-static bool IsCommentLine(int line, Accessor &styler, bool type)
+static bool IsCommentLine(Sci_Position line, Accessor &styler, bool type)
 {
-       int pos = styler.LineStart(line);
-       int eolPos = styler.LineStart(line + 1) - 1;
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eolPos = styler.LineStart(line + 1) - 1;
 
-       for (int i = pos; i < eolPos; i++)
+       for (Sci_Position i = pos; i < eolPos; i++)
        {
                char ch = styler[i];
                char chNext = styler.SafeGetCharAt(i + 1);
@@ -216,7 +221,7 @@ static bool IsCommentLine(int line, Accessor &styler, bool type)
                        return false;
        }
 
-       for (int i = eolPos-2; i>pos; i--)
+       for (Sci_Position i = eolPos-2; i>pos; i--)
        {
                char ch = styler[i];
                char chPrev = styler.SafeGetCharAt(i-1);
@@ -231,12 +236,12 @@ static bool IsCommentLine(int line, Accessor &styler, bool type)
        return false;
 }
 
-static bool IsPragmaLine(int line, Accessor &styler)
+static bool IsPragmaLine(Sci_Position line, Accessor &styler)
 {
-       int pos = styler.LineStart(line);
-       int eolPos = styler.LineStart(line+1) - 1;
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eolPos = styler.LineStart(line+1) - 1;
 
-       for (int i = pos ; i < eolPos ; i++)
+       for (Sci_Position i = pos ; i < eolPos ; i++)
        {
                char ch = styler[i];
                int style = styler.StyleAt(i);
@@ -249,9 +254,9 @@ static bool IsPragmaLine(int line, Accessor &styler)
        return false;
 }
 
-static void GetRangeUpper(unsigned int start,unsigned int end,Accessor &styler,char *s,unsigned int len)
+static void GetRangeUpper(Sci_PositionU start,Sci_PositionU end,Accessor &styler,char *s,Sci_PositionU len)
 {
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(toupper(styler[start + i]));
                i++;
@@ -259,8 +264,8 @@ static void GetRangeUpper(unsigned int start,unsigned int end,Accessor &styler,c
        s[i] = '\0';
 }
 
-static void ClassifySTTXTWordFoldPoint(int &levelCurrent,unsigned int lastStart,
-                                                                        unsigned int currentPos, Accessor 
&styler)
+static void ClassifySTTXTWordFoldPoint(int &levelCurrent,Sci_PositionU lastStart,
+                                                                        Sci_PositionU currentPos, Accessor 
&styler)
 {
        char s[256];
        GetRangeUpper(lastStart, currentPos, styler, s, sizeof(s));
@@ -316,24 +321,24 @@ static void ClassifySTTXTWordFoldPoint(int &levelCurrent,unsigned int lastStart,
        }
 }
 
-static void FoldSTTXTDoc(unsigned int startPos, int length, int initStyle, WordList *[],Accessor &styler)
+static void FoldSTTXTDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],Accessor 
&styler)
 {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style = initStyle;
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
 
        CharacterSet setWord(CharacterSet::setAlphaNum, "_", 0x80, true);
 
-       for (unsigned int i = startPos; i < endPos; i++)
+       for (Sci_PositionU i = startPos; i < endPos; i++)
        {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
diff --git a/plugins/scintilla/scintilla/lexers/LexScriptol.cxx 
b/plugins/scintilla/scintilla/lexers/LexScriptol.cxx
index 4b91923..9c9d9c4 100644
--- a/plugins/scintilla/scintilla/lexers/LexScriptol.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexScriptol.cxx
@@ -25,11 +25,11 @@
 using namespace Scintilla;
 #endif
 
-static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char 
*prevWord)
+static void ClassifyWordSol(Sci_PositionU start, Sci_PositionU end, WordList &keywords, Accessor &styler, 
char *prevWord)
 {
-    char s[100];
+    char s[100] = "";
     bool wordIsNumber = isdigit(styler[start]) != 0;
-    for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
+    for (Sci_PositionU i = 0; i < end - start + 1 && i < 30; i++)
      {
            s[i] = styler[start + i];
            s[i + 1] = '\0';
@@ -38,7 +38,7 @@ static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keyw
     if (0 == strcmp(prevWord, "class"))       chAttr = SCE_SCRIPTOL_CLASSNAME;
     else if (wordIsNumber)                    chAttr = SCE_SCRIPTOL_NUMBER;
     else if (keywords.InList(s))              chAttr = SCE_SCRIPTOL_KEYWORD;
-    else for (unsigned int i = 0; i < end - start + 1; i++)  // test dotted idents
+    else for (Sci_PositionU i = 0; i < end - start + 1; i++)  // test dotted idents
     {
         if (styler[start + i] == '.')
         {
@@ -50,7 +50,7 @@ static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keyw
     strcpy(prevWord, s);
 }
 
-static bool IsSolComment(Accessor &styler, int pos, int len)
+static bool IsSolComment(Accessor &styler, Sci_Position pos, Sci_Position len)
 {
    if(len > 0)
    {
@@ -81,7 +81,7 @@ static bool IsSolWordStart(char ch)
 }
 
 
-static int GetSolStringState(Accessor &styler, int i, int *nextIndex)
+static int GetSolStringState(Accessor &styler, Sci_Position i, Sci_Position *nextIndex)
 {
        char ch = styler.SafeGetCharAt(i);
        char chNext = styler.SafeGetCharAt(i + 1);
@@ -109,16 +109,16 @@ static int GetSolStringState(Accessor &styler, int i, int *nextIndex)
 }
 
 
-static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseSolDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                             WordList *keywordlists[], Accessor &styler)
  {
 
-       int lengthDoc = startPos + length;
+       Sci_Position lengthDoc = startPos + length;
         char stringType = '\"';
 
        if (startPos > 0)
         {
-            int lineCurrent = styler.GetLine(startPos);
+            Sci_Position lineCurrent = styler.GetLine(startPos);
             if (lineCurrent > 0)
             {
               startPos = styler.LineStart(lineCurrent-1);
@@ -127,53 +127,24 @@ static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
             }
        }
 
-       styler.StartAt(startPos, 127);
+       styler.StartAt(startPos);
 
        WordList &keywords = *keywordlists[0];
 
-       int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level");
        char prevWord[200];
        prevWord[0] = '\0';
         if (length == 0)  return;
 
        int state = initStyle & 31;
 
-       int nextIndex = 0;
+       Sci_Position nextIndex = 0;
         char chPrev  = ' ';
         char chPrev2 = ' ';
         char chNext  = styler[startPos];
        styler.StartSegment(startPos);
-       bool atStartLine = true;
-       int spaceFlags = 0;
-       for (int i = startPos; i < lengthDoc; i++)
+       for (Sci_Position i = startPos; i < lengthDoc; i++)
         {
 
-         if (atStartLine)
-         {
-         char chBad = static_cast<char>(64);
-         char chGood = static_cast<char>(0);
-         char chFlags = chGood;
-
-         if (whingeLevel == 1)
-         {
-             chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;
-         }
-         else if (whingeLevel == 2)
-         {
-             chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;
-         }
-         else if (whingeLevel == 3)
-         {
-             chFlags = (spaceFlags & wsSpace) ? chBad : chGood;
-         }
-         else if (whingeLevel == 4)
-         {
-              chFlags = (spaceFlags & wsTab) ? chBad : chGood;
-         }
-         styler.SetFlags(chFlags, static_cast<char>(state));
-         atStartLine = false;
-       }
-
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);
 
@@ -185,7 +156,6 @@ static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
           {
               styler.ColourTo(i, state);
           }
-          atStartLine = true;
         }
 
         if (styler.IsLeadByte(ch))
@@ -347,12 +317,12 @@ static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
        }
 }
 
-static void FoldSolDoc(unsigned int startPos, int length, int initStyle,
+static void FoldSolDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                                   WordList *[], Accessor &styler)
  {
-       int lengthDoc = startPos + length;
+       Sci_Position lengthDoc = startPos + length;
 
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0)
         {
           if (lineCurrent > 0)
@@ -371,7 +341,7 @@ static void FoldSolDoc(unsigned int startPos, int length, int initStyle,
         if (state == SCE_SCRIPTOL_TRIPLE)
              indentCurrent |= SC_FOLDLEVELWHITEFLAG;
        char chNext = styler[startPos];
-       for (int i = startPos; i < lengthDoc; i++)
+       for (Sci_Position i = startPos; i < lengthDoc; i++)
          {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
diff --git a/plugins/scintilla/scintilla/lexers/LexSmalltalk.cxx 
b/plugins/scintilla/scintilla/lexers/LexSmalltalk.cxx
index 7c7c067..4c72eb3 100644
--- a/plugins/scintilla/scintilla/lexers/LexSmalltalk.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSmalltalk.cxx
@@ -265,7 +265,7 @@ static void handleLetter(StyleContext& sc, WordList* specialSelectorList)
     sc.ChangeState(state);
 }
 
-static void colorizeSmalltalkDoc(unsigned int startPos, int length, int initStyle, WordList *wordLists[], 
Accessor &styler)
+static void colorizeSmalltalkDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*wordLists[], Accessor &styler)
 {
     StyleContext sc(startPos, length, initStyle, styler);
 
diff --git a/plugins/scintilla/scintilla/lexers/LexSorcus.cxx 
b/plugins/scintilla/scintilla/lexers/LexSorcus.cxx
index ba5588b..6a13806 100644
--- a/plugins/scintilla/scintilla/lexers/LexSorcus.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSorcus.cxx
@@ -61,7 +61,7 @@ static inline bool IsSorcusOperator(const int ch)
 }
 
 
-static void ColouriseSorcusDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseSorcusDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                                Accessor &styler)
 {
 
diff --git a/plugins/scintilla/scintilla/lexers/LexSpecman.cxx 
b/plugins/scintilla/scintilla/lexers/LexSpecman.cxx
index 1b96482..72a9737 100644
--- a/plugins/scintilla/scintilla/lexers/LexSpecman.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSpecman.cxx
@@ -8,10 +8,10 @@
 
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h>
 #include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <ctype.h>
 
 #include "ILexer.h"
 #include "Scintilla.h"
@@ -40,7 +40,7 @@ static inline bool IsAWordStart(const int ch) {
        return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '`');
 }
 
-static void ColouriseSpecmanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseSpecmanDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
                             Accessor &styler, bool caseSensitive) {
 
        WordList &keywords = *keywordlists[0];
@@ -200,14 +200,14 @@ static void ColouriseSpecmanDoc(unsigned int startPos, int length, int initStyle
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
-static void FoldNoBoxSpecmanDoc(unsigned int startPos, int length, int,
+static void FoldNoBoxSpecmanDoc(Sci_PositionU startPos, Sci_Position length, int,
                             Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
        bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -216,7 +216,7 @@ static void FoldNoBoxSpecmanDoc(unsigned int startPos, int length, int,
        char chNext = styler[startPos];
        int styleNext = styler.StyleAt(startPos);
        int style;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                //int stylePrev = style;
@@ -269,7 +269,7 @@ static void FoldNoBoxSpecmanDoc(unsigned int startPos, int length, int,
        }
 }
 
-static void FoldSpecmanDoc(unsigned int startPos, int length, int initStyle, WordList *[],
+static void FoldSpecmanDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],
                        Accessor &styler) {
        FoldNoBoxSpecmanDoc(startPos, length, initStyle, styler);
 }
@@ -283,7 +283,7 @@ static const char * const specmanWordLists[] = {
             0,
         };
 
-static void ColouriseSpecmanDocSensitive(unsigned int startPos, int length, int initStyle, WordList 
*keywordlists[],
+static void ColouriseSpecmanDocSensitive(Sci_PositionU startPos, Sci_Position length, int initStyle, 
WordList *keywordlists[],
                                      Accessor &styler) {
        ColouriseSpecmanDoc(startPos, length, initStyle, keywordlists, styler, true);
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexSpice.cxx b/plugins/scintilla/scintilla/lexers/LexSpice.cxx
index 5fb5dd7..d834e26 100644
--- a/plugins/scintilla/scintilla/lexers/LexSpice.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSpice.cxx
@@ -34,8 +34,8 @@ using namespace Scintilla;
  */
 
 static void ColouriseDocument(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int initStyle,
     WordList *keywordlists[],
     Accessor &styler);
@@ -60,11 +60,7 @@ static void ColouriseWhiteSpace(StyleContext& sc, bool& apostropheStartsAttribut
 static void ColouriseWord(StyleContext& sc, WordList& keywords, WordList& keywords2, WordList& keywords3, 
bool& apostropheStartsAttribute);
 
 static inline bool IsDelimiterCharacter(int ch);
-static inline bool IsNumberStartCharacter(int ch);
-static inline bool IsNumberCharacter(int ch);
 static inline bool IsSeparatorOrDelimiterCharacter(int ch);
-static inline bool IsWordStartCharacter(int ch);
-static inline bool IsWordCharacter(int ch);
 
 static void ColouriseComment(StyleContext& sc, bool&) {
     sc.SetState(SCE_SPICE_COMMENTLINE);
@@ -140,8 +136,8 @@ static void ColouriseWord(StyleContext& sc, WordList& keywords, WordList& keywor
 // ColouriseDocument
 //
 static void ColouriseDocument(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int initStyle,
     WordList *keywordlists[],
     Accessor &styler) {
@@ -149,7 +145,7 @@ static void ColouriseDocument(
     WordList &keywords2 = *keywordlists[1];
     WordList &keywords3 = *keywordlists[2];
     StyleContext sc(startPos, length, initStyle, styler);
-    int lineCurrent = styler.GetLine(startPos);
+    Sci_Position lineCurrent = styler.GetLine(startPos);
     bool apostropheStartsAttribute = (styler.GetLineState(lineCurrent) & 1) != 0;
     while (sc.More()) {
         if (sc.atLineEnd) {
@@ -205,27 +201,6 @@ static inline bool IsDelimiterCharacter(int ch) {
     }
 }
 
-static inline bool IsNumberCharacter(int ch) {
-    return IsNumberStartCharacter(ch) ||
-           ch == '_' ||
-           ch == '.' ||
-           ch == '#' ||
-           (ch >= 'a' && ch <= 'f') ||
-           (ch >= 'A' && ch <= 'F');
-}
-
-static inline bool IsNumberStartCharacter(int ch) {
-    return IsADigit(ch);
-}
-
 static inline bool IsSeparatorOrDelimiterCharacter(int ch) {
     return IsASpace(ch) || IsDelimiterCharacter(ch);
 }
-
-static inline bool IsWordCharacter(int ch) {
-    return IsWordStartCharacter(ch) || IsADigit(ch);
-}
-
-static inline bool IsWordStartCharacter(int ch) {
-    return (isascii(ch) && isalpha(ch)) || ch == '_';
-}
diff --git a/plugins/scintilla/scintilla/lexers/LexTACL.cxx b/plugins/scintilla/scintilla/lexers/LexTACL.cxx
index fb7d695..c7a15f2 100644
--- a/plugins/scintilla/scintilla/lexers/LexTACL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTACL.cxx
@@ -45,12 +45,12 @@ inline bool isTACLwordstart(char ch)
        return ch == '#' || ch == '|' || ch == '_' || iswordstart(ch);
        }
 
-static void getRange(unsigned int start,
-               unsigned int end,
+static void getRange(Sci_PositionU start,
+               Sci_PositionU end,
                Accessor &styler,
                char *s,
-               unsigned int len) {
-       unsigned int i = 0;
+               Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                i++;
@@ -65,7 +65,7 @@ static bool IsStreamCommentStyle(int style) {
                style == SCE_C_COMMENTDOCKEYWORDERROR;
 }
 
-static void ColourTo(Accessor &styler, unsigned int end, unsigned int attr, bool bInAsm) {
+static void ColourTo(Accessor &styler, Sci_PositionU end, unsigned int attr, bool bInAsm) {
        if ((bInAsm) && (attr == SCE_C_OPERATOR || attr == SCE_C_NUMBER || attr == SCE_C_DEFAULT || attr == 
SCE_C_WORD || attr == SCE_C_IDENTIFIER)) {
                styler.ColourTo(end, SCE_C_REGEX);
        } else
@@ -73,7 +73,7 @@ static void ColourTo(Accessor &styler, unsigned int end, unsigned int attr, bool
 }
 
 // returns 1 if the item starts a class definition, and -1 if the word is "end", and 2 if the word is "asm"
-static int classifyWordTACL(unsigned int start, unsigned int end, /*WordList &keywords*/WordList 
*keywordlists[], Accessor &styler, bool bInAsm) {
+static int classifyWordTACL(Sci_PositionU start, Sci_PositionU end, /*WordList &keywords*/WordList 
*keywordlists[], Accessor &styler, bool bInAsm) {
        int ret = 0;
 
        WordList& keywords = *keywordlists[0];
@@ -122,7 +122,7 @@ static int classifyFoldPointTACL(const char* s) {
        return lev;
 }
 
-static void ColouriseTACLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseTACLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
        Accessor &styler) {
 
        styler.StartAt(startPos);
@@ -132,11 +132,11 @@ static void ColouriseTACLDoc(unsigned int startPos, int length, int initStyle, W
                state = SCE_C_DEFAULT;
        char chPrev = ' ';
        char chNext = styler[startPos];
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
 
        bool bInClassDefinition;
 
-       int currentLine = styler.GetLine(startPos);
+       Sci_Position currentLine = styler.GetLine(startPos);
        if (currentLine > 0) {
                styler.SetLineState(currentLine, styler.GetLineState(currentLine-1));
                bInClassDefinition = (styler.GetLineState(currentLine) == 1);
@@ -151,7 +151,7 @@ static void ColouriseTACLDoc(unsigned int startPos, int length, int initStyle, W
 
        styler.StartSegment(startPos);
        int visibleChars = 0;
-       unsigned int i;
+       Sci_PositionU i;
        for (i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
 
@@ -250,7 +250,7 @@ static void ColouriseTACLDoc(unsigned int startPos, int length, int initStyle, W
                                if (ch == '}' || (ch == '\r' || ch == '\n')) {
                                        if (((i > styler.GetStartSegment() + 2) || (
                                                (initStyle == SCE_C_COMMENTDOC) &&
-                                               (styler.GetStartSegment() == static_cast<unsigned 
int>(startPos))))) {
+                                               (styler.GetStartSegment() == 
static_cast<Sci_PositionU>(startPos))))) {
                                                        ColourTo(styler, i, state, bInAsm);
                                                        state = SCE_C_DEFAULT;
                                        }
@@ -280,14 +280,14 @@ static void ColouriseTACLDoc(unsigned int startPos, int length, int initStyle, W
                ColourTo(styler, lengthDoc - 1, state, bInAsm);
 }
 
-static void FoldTACLDoc(unsigned int startPos, int length, int initStyle, WordList *[],
+static void FoldTACLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],
                             Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
@@ -295,9 +295,9 @@ static void FoldTACLDoc(unsigned int startPos, int length, int initStyle, WordLi
        int style = initStyle;
        bool section = false;
 
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -346,7 +346,7 @@ static void FoldTACLDoc(unsigned int startPos, int length, int initStyle, WordLi
 
                if (foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
                        if (ch == '{' && chNext == '$') {
-                               unsigned int j=i+2; // skip {$
+                               Sci_PositionU j=i+2; // skip {$
                                while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                        j++;
                                }
diff --git a/plugins/scintilla/scintilla/lexers/LexTADS3.cxx b/plugins/scintilla/scintilla/lexers/LexTADS3.cxx
index 54cb88a..03e82d3 100644
--- a/plugins/scintilla/scintilla/lexers/LexTADS3.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTADS3.cxx
@@ -269,7 +269,7 @@ static void ColouriseTADS3HTMLTag(StyleContext &sc, int &lineState) {
 }
 
 static void ColouriseTADS3Keyword(StyleContext &sc,
-                                                        WordList *keywordlists[],       unsigned int endPos) 
{
+                                                        WordList *keywordlists[],       Sci_PositionU 
endPos) {
         char s[250];
         WordList &keywords = *keywordlists[0];
         WordList &userwords1 = *keywordlists[1];
@@ -283,7 +283,7 @@ static void ColouriseTADS3Keyword(StyleContext &sc,
         sc.GetCurrent(s, sizeof(s));
         if ( strcmp(s, "is") == 0 || strcmp(s, "not") == 0) {
                 // have to find if "in" is next
-                int n = 1;
+                Sci_Position n = 1;
                 while (n + sc.currentPos < endPos && IsASpaceOrTab(sc.GetRelative(n)))
                         n++;
                 if (sc.GetRelative(n) == 'i' && sc.GetRelative(n+1) == 'n') {
@@ -513,13 +513,13 @@ static void ColouriseTADS3Number(StyleContext &sc) {
         sc.SetState(endState);
 }
 
-static void ColouriseTADS3Doc(unsigned int startPos, int length, int initStyle,
+static void ColouriseTADS3Doc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                                            WordList *keywordlists[], Accessor &styler) {
         int visibleChars = 0;
         int bracketLevel = 0;
         int lineState = 0;
-        unsigned int endPos = startPos + length;
-        int lineCurrent = styler.GetLine(startPos);
+        Sci_PositionU endPos = startPos + length;
+        Sci_Position lineCurrent = styler.GetLine(startPos);
         if (lineCurrent > 0) {
                 lineState = styler.GetLineState(lineCurrent-1);
         }
@@ -707,9 +707,9 @@ static inline bool IsSpaceEquivalent(const int ch, const int style) {
                 || style == SCE_T3_PREPROCESSOR;
 }
 
-static char peekAhead(unsigned int startPos, unsigned int endPos,
+static char peekAhead(Sci_PositionU startPos, Sci_PositionU endPos,
                                           Accessor &styler) {
-        for (unsigned int i = startPos; i < endPos; i++) {
+        for (Sci_PositionU i = startPos; i < endPos; i++) {
                 int style = styler.StyleAt(i);
                 char ch = styler[i];
                 if (!IsSpaceEquivalent(ch, style)) {
@@ -728,10 +728,10 @@ static char peekAhead(unsigned int startPos, unsigned int endPos,
         return ' ';
 }
 
-static void FoldTADS3Doc(unsigned int startPos, int length, int initStyle,
+static void FoldTADS3Doc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                             WordList *[], Accessor &styler) {
-        unsigned int endPos = startPos + length;
-        int lineCurrent = styler.GetLine(startPos);
+        Sci_PositionU endPos = startPos + length;
+        Sci_Position lineCurrent = styler.GetLine(startPos);
         int levelCurrent = SC_FOLDLEVELBASE;
         if (lineCurrent > 0)
                 levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
@@ -747,7 +747,7 @@ static void FoldTADS3Doc(unsigned int startPos, int length, int initStyle,
         char ch = chNext;
         int stylePrev = style;
         bool redo = false;
-        for (unsigned int i = startPos; i < endPos; i++) {
+        for (Sci_PositionU i = startPos; i < endPos; i++) {
                 if (redo) {
                         redo = false;
                         i--;
diff --git a/plugins/scintilla/scintilla/lexers/LexTAL.cxx b/plugins/scintilla/scintilla/lexers/LexTAL.cxx
index 15dc741..e7f28ea 100644
--- a/plugins/scintilla/scintilla/lexers/LexTAL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTAL.cxx
@@ -45,12 +45,12 @@ inline bool isTALwordstart(char ch)
        return ch == '$' || ch == '^' || iswordstart(ch);
        }
 
-static void getRange(unsigned int start,
-               unsigned int end,
+static void getRange(Sci_PositionU start,
+               Sci_PositionU end,
                Accessor &styler,
                char *s,
-               unsigned int len) {
-       unsigned int i = 0;
+               Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                i++;
@@ -65,7 +65,7 @@ static bool IsStreamCommentStyle(int style) {
                style == SCE_C_COMMENTDOCKEYWORDERROR;
 }
 
-static void ColourTo(Accessor &styler, unsigned int end, unsigned int attr, bool bInAsm) {
+static void ColourTo(Accessor &styler, Sci_PositionU end, unsigned int attr, bool bInAsm) {
        if ((bInAsm) && (attr == SCE_C_OPERATOR || attr == SCE_C_NUMBER || attr == SCE_C_DEFAULT || attr == 
SCE_C_WORD || attr == SCE_C_IDENTIFIER)) {
                styler.ColourTo(end, SCE_C_REGEX);
        } else
@@ -73,7 +73,7 @@ static void ColourTo(Accessor &styler, unsigned int end, unsigned int attr, bool
 }
 
 // returns 1 if the item starts a class definition, and -1 if the word is "end", and 2 if the word is "asm"
-static int classifyWordTAL(unsigned int start, unsigned int end, /*WordList &keywords*/WordList 
*keywordlists[], Accessor &styler, bool bInAsm) {
+static int classifyWordTAL(Sci_PositionU start, Sci_PositionU end, /*WordList &keywords*/WordList 
*keywordlists[], Accessor &styler, bool bInAsm) {
        int ret = 0;
 
        WordList& keywords = *keywordlists[0];
@@ -122,7 +122,7 @@ static int classifyFoldPointTAL(const char* s) {
        return lev;
 }
 
-static void ColouriseTALDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+static void ColouriseTALDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList 
*keywordlists[],
        Accessor &styler) {
 
        styler.StartAt(startPos);
@@ -132,11 +132,11 @@ static void ColouriseTALDoc(unsigned int startPos, int length, int initStyle, Wo
                state = SCE_C_DEFAULT;
        char chPrev = ' ';
        char chNext = styler[startPos];
-       unsigned int lengthDoc = startPos + length;
+       Sci_PositionU lengthDoc = startPos + length;
 
        bool bInClassDefinition;
 
-       int currentLine = styler.GetLine(startPos);
+       Sci_Position currentLine = styler.GetLine(startPos);
        if (currentLine > 0) {
                styler.SetLineState(currentLine, styler.GetLineState(currentLine-1));
                bInClassDefinition = (styler.GetLineState(currentLine) == 1);
@@ -151,7 +151,7 @@ static void ColouriseTALDoc(unsigned int startPos, int length, int initStyle, Wo
 
        styler.StartSegment(startPos);
        int visibleChars = 0;
-       for (unsigned int i = startPos; i < lengthDoc; i++) {
+       for (Sci_PositionU i = startPos; i < lengthDoc; i++) {
                char ch = chNext;
 
                chNext = styler.SafeGetCharAt(i + 1);
@@ -244,7 +244,7 @@ static void ColouriseTALDoc(unsigned int startPos, int length, int initStyle, Wo
                                if (ch == '!' || (ch == '\r' || ch == '\n')) {
                                        if (((i > styler.GetStartSegment() + 2) || (
                                                (initStyle == SCE_C_COMMENTDOC) &&
-                                               (styler.GetStartSegment() == static_cast<unsigned 
int>(startPos))))) {
+                                               (styler.GetStartSegment() == 
static_cast<Sci_PositionU>(startPos))))) {
                                                        ColourTo(styler, i, state, bInAsm);
                                                        state = SCE_C_DEFAULT;
                                        }
@@ -268,14 +268,14 @@ static void ColouriseTALDoc(unsigned int startPos, int length, int initStyle, Wo
        ColourTo(styler, lengthDoc - 1, state, bInAsm);
 }
 
-static void FoldTALDoc(unsigned int startPos, int length, int initStyle, WordList *[],
+static void FoldTALDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],
                             Accessor &styler) {
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos + length;
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent = levelPrev;
        char chNext = styler[startPos];
@@ -284,9 +284,9 @@ static void FoldTALDoc(unsigned int startPos, int length, int initStyle, WordLis
        bool was_end = false;
        bool section = false;
 
-       int lastStart = 0;
+       Sci_Position lastStart = 0;
 
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
@@ -345,7 +345,7 @@ static void FoldTALDoc(unsigned int startPos, int length, int initStyle, WordLis
 
                if (foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
                        if (ch == '{' && chNext == '$') {
-                               unsigned int j=i+2; // skip {$
+                               Sci_PositionU j=i+2; // skip {$
                                while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
                                        j++;
                                }
diff --git a/plugins/scintilla/scintilla/lexers/LexTCL.cxx b/plugins/scintilla/scintilla/lexers/LexTCL.cxx
index f6924e0..48af1e7 100644
--- a/plugins/scintilla/scintilla/lexers/LexTCL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTCL.cxx
@@ -30,7 +30,7 @@ using namespace Scintilla;
 // Extended to accept accented characters
 static inline bool IsAWordChar(int ch) {
        return ch >= 0x80 ||
-        (isalnum(ch) || ch == '_' || ch ==':' || ch=='.'); // : name space separator
+              (isalnum(ch) || ch == '_' || ch ==':' || ch=='.'); // : name space separator
 }
 
 static inline bool IsAWordStart(int ch) {
@@ -45,21 +45,22 @@ static inline bool IsANumberChar(int ch) {
                ch == '.' || ch == '-' || ch == '+');
 }
 
-static void ColouriseTCLDoc(unsigned int startPos, int length, int , WordList *keywordlists[], Accessor 
&styler) {
+static void ColouriseTCLDoc(Sci_PositionU startPos, Sci_Position length, int , WordList *keywordlists[], 
Accessor &styler) {
 #define  isComment(s) (s==SCE_TCL_COMMENT || s==SCE_TCL_COMMENTLINE || s==SCE_TCL_COMMENT_BOX || 
s==SCE_TCL_BLOCK_COMMENT)
        bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
        bool commentLevel = false;
-    bool subBrace = false; // substitution begin with a brace ${.....}
+       bool subBrace = false; // substitution begin with a brace ${.....}
        enum tLineState {LS_DEFAULT, LS_OPEN_COMMENT, LS_OPEN_DOUBLE_QUOTE, LS_COMMENT_BOX, LS_MASK_STATE = 
0xf,
-        LS_COMMAND_EXPECTED = 16, LS_BRACE_ONLY = 32 } lineState = LS_DEFAULT;
+                        LS_COMMAND_EXPECTED = 16, LS_BRACE_ONLY = 32
+                       } lineState = LS_DEFAULT;
        bool prevSlash = false;
        int currentLevel = 0;
-    bool expected = 0;
-    bool subParen = 0;
+       bool expected = 0;
+       bool subParen = 0;
 
-       int currentLine = styler.GetLine(startPos);
-    if (currentLine > 0)
-        currentLine--;
+       Sci_Position currentLine = styler.GetLine(startPos);
+       if (currentLine > 0)
+               currentLine--;
        length += startPos - styler.LineStart(currentLine);
        // make sure lines overlap
        startPos = styler.LineStart(currentLine);
@@ -71,14 +72,14 @@ static void ColouriseTCLDoc(unsigned int startPos, int length, int , WordList *k
        WordList &keywords5 = *keywordlists[4];
        WordList &keywords6 = *keywordlists[5];
        WordList &keywords7 = *keywordlists[6];
-    WordList &keywords8 = *keywordlists[7];
-    WordList &keywords9 = *keywordlists[8];
+       WordList &keywords8 = *keywordlists[7];
+       WordList &keywords9 = *keywordlists[8];
 
        if (currentLine > 0) {
-        int ls = styler.GetLineState(currentLine - 1);
+               int ls = styler.GetLineState(currentLine - 1);
                lineState = tLineState(ls & LS_MASK_STATE);
                expected = LS_COMMAND_EXPECTED == tLineState(ls & LS_COMMAND_EXPECTED);
-        subBrace = LS_BRACE_ONLY == tLineState(ls & LS_BRACE_ONLY);
+               subBrace = LS_BRACE_ONLY == tLineState(ls & LS_BRACE_ONLY);
                currentLevel = styler.LevelAt(currentLine - 1) >> 17;
                commentLevel = (styler.LevelAt(currentLine - 1) >> 16) & 1;
        } else
@@ -86,105 +87,104 @@ static void ColouriseTCLDoc(unsigned int startPos, int length, int , WordList *k
        bool visibleChars = false;
 
        int previousLevel = currentLevel;
-    StyleContext sc(startPos, length, SCE_TCL_DEFAULT, styler);
+       StyleContext sc(startPos, length, SCE_TCL_DEFAULT, styler);
        for (; ; sc.Forward()) {
 next:
-        if (sc.ch=='\r' && sc.chNext == '\n') // only ignore \r on PC process on the mac
-            continue;
-        bool atEnd = !sc.More();  // make sure we coloured the last word
-        if (lineState != LS_DEFAULT) {
-            sc.SetState(SCE_TCL_DEFAULT);
-            if (lineState == LS_OPEN_COMMENT)
-                sc.SetState(SCE_TCL_COMMENTLINE);
-            else if (lineState == LS_OPEN_DOUBLE_QUOTE)
-                sc.SetState(SCE_TCL_IN_QUOTE);
-            else if (lineState == LS_COMMENT_BOX && (sc.ch == '#' || (sc.ch == ' ' && sc.chNext=='#')))
-                sc.SetState(SCE_TCL_COMMENT_BOX);
-            lineState = LS_DEFAULT;
-        }
-        if (subBrace) { // ${ overrides every thing even \ except }
-            if (sc.ch == '}') {
-                subBrace = false;
-                sc.SetState(SCE_TCL_OPERATOR);
-                sc.ForwardSetState(SCE_TCL_DEFAULT);
-                goto next;
-            }
-            else
-                sc.SetState(SCE_TCL_SUB_BRACE);
-            if (!sc.atLineEnd)
-                continue;
-        } else if (sc.state == SCE_TCL_DEFAULT || sc.state ==SCE_TCL_OPERATOR) {
-            expected &= isspacechar(static_cast<unsigned char>(sc.ch)) || IsAWordStart(sc.ch) || sc.ch =='#';
-        } else if (sc.state == SCE_TCL_SUBSTITUTION) {
-            switch(sc.ch) {
-            case '(':
-                subParen=true;
-                sc.SetState(SCE_TCL_OPERATOR);
-                sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
-                continue;
-            case ')':
-                sc.SetState(SCE_TCL_OPERATOR);
-                subParen=false;
-                continue;
-            case '$':
-                continue;
-            case ',':
-                sc.SetState(SCE_TCL_OPERATOR);
-                if (subParen)
-                    sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
-                continue;
-            default :
-                // maybe spaces should be allowed ???
-                if (!IsAWordChar(sc.ch)) { // probably the code is wrong
-                    sc.SetState(SCE_TCL_DEFAULT);
-                    subParen = 0;
-                }
-                break;
-            }
-        } else if (isComment(sc.state)) {
-        } else if (!IsAWordChar(sc.ch)) {
-            if ((sc.state == SCE_TCL_IDENTIFIER && expected) ||  sc.state == SCE_TCL_MODIFIER) {
-                char w[100];
-                char *s=w;
-                sc.GetCurrent(w, sizeof(w));
-                if (w[strlen(w)-1]=='\r')
-                    w[strlen(w)-1]=0;
-                while(*s == ':') // ignore leading : like in ::set a 10
-                    ++s;
-                bool quote = sc.state == SCE_TCL_IN_QUOTE;
-                if (commentLevel  || expected) {
-                    if (keywords.InList(s)) {
-                        sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD);
-                    } else if (keywords2.InList(s)) {
-                        sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD2);
-                    } else if (keywords3.InList(s)) {
-                        sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD3);
-                    } else if (keywords4.InList(s)) {
-                        sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD4);
-                    } else if (sc.GetRelative(-static_cast<int>(strlen(s))-1) == '{' &&
-                        keywords5.InList(s) && sc.ch == '}') { // {keyword} exactly no spaces
-                            sc.ChangeState(SCE_TCL_EXPAND);
-                    }
-                    if (keywords6.InList(s)) {
-                        sc.ChangeState(SCE_TCL_WORD5);
-                    } else if (keywords7.InList(s)) {
-                        sc.ChangeState(SCE_TCL_WORD6);
-                    } else if (keywords8.InList(s)) {
-                        sc.ChangeState(SCE_TCL_WORD7);
-                    } else if (keywords9.InList(s)) {
-                        sc.ChangeState(SCE_TCL_WORD8);
-                    }
-                }
-                expected = false;
-                sc.SetState(quote ? SCE_TCL_IN_QUOTE : SCE_TCL_DEFAULT);
-            } else if (sc.state == SCE_TCL_MODIFIER || sc.state == SCE_TCL_IDENTIFIER) {
-                sc.SetState(SCE_TCL_DEFAULT);
-            }
-        }
+               if (sc.ch=='\r' && sc.chNext == '\n') // only ignore \r on PC process on the mac
+                       continue;
+               bool atEnd = !sc.More();  // make sure we coloured the last word
+               if (lineState != LS_DEFAULT) {
+                       sc.SetState(SCE_TCL_DEFAULT);
+                       if (lineState == LS_OPEN_COMMENT)
+                               sc.SetState(SCE_TCL_COMMENTLINE);
+                       else if (lineState == LS_OPEN_DOUBLE_QUOTE)
+                               sc.SetState(SCE_TCL_IN_QUOTE);
+                       else if (lineState == LS_COMMENT_BOX && (sc.ch == '#' || (sc.ch == ' ' && 
sc.chNext=='#')))
+                               sc.SetState(SCE_TCL_COMMENT_BOX);
+                       lineState = LS_DEFAULT;
+               }
+               if (subBrace) { // ${ overrides every thing even \ except }
+                       if (sc.ch == '}') {
+                               subBrace = false;
+                               sc.SetState(SCE_TCL_OPERATOR);
+                               sc.ForwardSetState(SCE_TCL_DEFAULT);
+                               goto next;
+                       } else
+                               sc.SetState(SCE_TCL_SUB_BRACE);
+                       if (!sc.atLineEnd)
+                               continue;
+               } else if (sc.state == SCE_TCL_DEFAULT || sc.state ==SCE_TCL_OPERATOR) {
+                       expected &= isspacechar(static_cast<unsigned char>(sc.ch)) || IsAWordStart(sc.ch) || 
sc.ch =='#';
+               } else if (sc.state == SCE_TCL_SUBSTITUTION) {
+                       switch (sc.ch) {
+                       case '(':
+                               subParen=true;
+                               sc.SetState(SCE_TCL_OPERATOR);
+                               sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
+                               continue;
+                       case ')':
+                               sc.SetState(SCE_TCL_OPERATOR);
+                               subParen=false;
+                               continue;
+                       case '$':
+                               continue;
+                       case ',':
+                               sc.SetState(SCE_TCL_OPERATOR);
+                               if (subParen)
+                                       sc.ForwardSetState(SCE_TCL_SUBSTITUTION);
+                               continue;
+                       default :
+                               // maybe spaces should be allowed ???
+                               if (!IsAWordChar(sc.ch)) { // probably the code is wrong
+                                       sc.SetState(SCE_TCL_DEFAULT);
+                                       subParen = 0;
+                               }
+                               break;
+                       }
+               } else if (isComment(sc.state)) {
+               } else if (!IsAWordChar(sc.ch)) {
+                       if ((sc.state == SCE_TCL_IDENTIFIER && expected) ||  sc.state == SCE_TCL_MODIFIER) {
+                               char w[100];
+                               char *s=w;
+                               sc.GetCurrent(w, sizeof(w));
+                               if (w[strlen(w)-1]=='\r')
+                                       w[strlen(w)-1]=0;
+                               while (*s == ':') // ignore leading : like in ::set a 10
+                                       ++s;
+                               bool quote = sc.state == SCE_TCL_IN_QUOTE;
+                               if (commentLevel  || expected) {
+                                       if (keywords.InList(s)) {
+                                               sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD);
+                                       } else if (keywords2.InList(s)) {
+                                               sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD2);
+                                       } else if (keywords3.InList(s)) {
+                                               sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD3);
+                                       } else if (keywords4.InList(s)) {
+                                               sc.ChangeState(quote ? SCE_TCL_WORD_IN_QUOTE : SCE_TCL_WORD4);
+                                       } else if (sc.GetRelative(-static_cast<int>(strlen(s))-1) == '{' &&
+                                                  keywords5.InList(s) && sc.ch == '}') { // {keyword} 
exactly no spaces
+                                               sc.ChangeState(SCE_TCL_EXPAND);
+                                       }
+                                       if (keywords6.InList(s)) {
+                                               sc.ChangeState(SCE_TCL_WORD5);
+                                       } else if (keywords7.InList(s)) {
+                                               sc.ChangeState(SCE_TCL_WORD6);
+                                       } else if (keywords8.InList(s)) {
+                                               sc.ChangeState(SCE_TCL_WORD7);
+                                       } else if (keywords9.InList(s)) {
+                                               sc.ChangeState(SCE_TCL_WORD8);
+                                       }
+                               }
+                               expected = false;
+                               sc.SetState(quote ? SCE_TCL_IN_QUOTE : SCE_TCL_DEFAULT);
+                       } else if (sc.state == SCE_TCL_MODIFIER || sc.state == SCE_TCL_IDENTIFIER) {
+                               sc.SetState(SCE_TCL_DEFAULT);
+                       }
+               }
                if (atEnd)
                        break;
-        if (sc.atLineEnd) {
-            lineState = LS_DEFAULT;
+               if (sc.atLineEnd) {
+                       lineState = LS_DEFAULT;
                        currentLine = styler.GetLine(sc.currentPos);
                        if (foldComment && sc.state!=SCE_TCL_COMMENT && isComment(sc.state)) {
                                if (currentLevel == 0) {
@@ -206,45 +206,45 @@ next:
                        styler.SetLevel(currentLine, flag + previousLevel + SC_FOLDLEVELBASE + (currentLevel 
<< 17) + (commentLevel << 16));
 
                        // Update the line state, so it can be seen by next line
-                       if (sc.state == SCE_TCL_IN_QUOTE)
+                       if (sc.state == SCE_TCL_IN_QUOTE) {
                                lineState = LS_OPEN_DOUBLE_QUOTE;
-                       else {
-                            if (prevSlash) {
-                                   if (isComment(sc.state))
-                                           lineState = LS_OPEN_COMMENT;
-                } else if (sc.state == SCE_TCL_COMMENT_BOX)
-                    lineState = LS_COMMENT_BOX;
+                       } else {
+                               if (prevSlash) {
+                                       if (isComment(sc.state))
+                                               lineState = LS_OPEN_COMMENT;
+                               } else if (sc.state == SCE_TCL_COMMENT_BOX)
+                                       lineState = LS_COMMENT_BOX;
                        }
-            styler.SetLineState(currentLine,
-                (subBrace ? LS_BRACE_ONLY : 0) |
-                (expected ? LS_COMMAND_EXPECTED : 0)  | lineState);
-            if (lineState == LS_COMMENT_BOX)
-                sc.ForwardSetState(SCE_TCL_COMMENT_BOX);
-            else if (lineState == LS_OPEN_DOUBLE_QUOTE)
-                sc.ForwardSetState(SCE_TCL_IN_QUOTE);
-            else
-                sc.ForwardSetState(SCE_TCL_DEFAULT);
+                       styler.SetLineState(currentLine,
+                                           (subBrace ? LS_BRACE_ONLY : 0) |
+                                           (expected ? LS_COMMAND_EXPECTED : 0)  | lineState);
+                       if (lineState == LS_COMMENT_BOX)
+                               sc.ForwardSetState(SCE_TCL_COMMENT_BOX);
+                       else if (lineState == LS_OPEN_DOUBLE_QUOTE)
+                               sc.ForwardSetState(SCE_TCL_IN_QUOTE);
+                       else
+                               sc.ForwardSetState(SCE_TCL_DEFAULT);
                        prevSlash = false;
                        previousLevel = currentLevel;
                        goto next;
                }
 
                if (prevSlash) {
-            prevSlash = false;
-            if (sc.ch == '#' && IsANumberChar(sc.chNext))
-                sc.ForwardSetState(SCE_TCL_NUMBER);
-            continue;
+                       prevSlash = false;
+                       if (sc.ch == '#' && IsANumberChar(sc.chNext))
+                               sc.ForwardSetState(SCE_TCL_NUMBER);
+                       continue;
                }
-        prevSlash = sc.ch == '\\';
-        if (isComment(sc.state))
-            continue;
+               prevSlash = sc.ch == '\\';
+               if (isComment(sc.state))
+                       continue;
                if (sc.atLineStart) {
                        visibleChars = false;
                        if (sc.state!=SCE_TCL_IN_QUOTE && !isComment(sc.state))
-            {
+                       {
                                sc.SetState(SCE_TCL_DEFAULT);
-                expected = IsAWordStart(sc.ch)|| isspacechar(static_cast<unsigned char>(sc.ch));
-            }
+                               expected = IsAWordStart(sc.ch)|| isspacechar(static_cast<unsigned 
char>(sc.ch));
+                       }
                }
 
                switch (sc.state) {
@@ -259,28 +259,28 @@ next:
                                goto next;
                        } else if (sc.ch == '[' || sc.ch == ']' || sc.ch == '$') {
                                sc.SetState(SCE_TCL_OPERATOR);
-                expected = sc.ch == '[';
-                sc.ForwardSetState(SCE_TCL_IN_QUOTE);
+                               expected = sc.ch == '[';
+                               sc.ForwardSetState(SCE_TCL_IN_QUOTE);
                                goto next;
                        }
-            continue;
-        case SCE_TCL_OPERATOR:
+                       continue;
+               case SCE_TCL_OPERATOR:
                        sc.SetState(SCE_TCL_DEFAULT);
                        break;
                }
 
                if (sc.ch == '#') {
                        if (visibleChars) {
-                if (sc.state != SCE_TCL_IN_QUOTE && expected)
+                               if (sc.state != SCE_TCL_IN_QUOTE && expected)
                                        sc.SetState(SCE_TCL_COMMENT);
                        } else {
-                sc.SetState(SCE_TCL_COMMENTLINE);
-                if (sc.chNext == '~')
-                    sc.SetState(SCE_TCL_BLOCK_COMMENT);
-                if (sc.atLineStart && (sc.chNext == '#' || sc.chNext == '-'))
-                        sc.SetState(SCE_TCL_COMMENT_BOX);
-            }
-        }
+                               sc.SetState(SCE_TCL_COMMENTLINE);
+                               if (sc.chNext == '~')
+                                       sc.SetState(SCE_TCL_BLOCK_COMMENT);
+                               if (sc.atLineStart && (sc.chNext == '#' || sc.chNext == '-'))
+                                       sc.SetState(SCE_TCL_COMMENT_BOX);
+                       }
+               }
 
                if (!isspacechar(static_cast<unsigned char>(sc.ch))) {
                        visibleChars = true;
@@ -293,7 +293,7 @@ next:
 
                // Determine if a new state should be entered.
                if (sc.state == SCE_TCL_DEFAULT) {
-            if (IsAWordStart(sc.ch)) {
+                       if (IsAWordStart(sc.ch)) {
                                sc.SetState(SCE_TCL_IDENTIFIER);
                        } else if (IsADigit(sc.ch) && !IsAWordChar(sc.chPrev)) {
                                sc.SetState(SCE_TCL_NUMBER);
@@ -313,39 +313,38 @@ next:
                                        --currentLevel;
                                        break;
                                case '[':
-                    expected = true;
+                                       expected = true;
                                case ']':
                                case '(':
                                case ')':
                                        sc.SetState(SCE_TCL_OPERATOR);
                                        break;
                                case ';':
-                    expected = true;
+                                       expected = true;
+                                       break;
+                               case '$':
+                                       subParen = 0;
+                                       if (sc.chNext != '{') {
+                                               sc.SetState(SCE_TCL_SUBSTITUTION);
+                                       } else {
+                                               sc.SetState(SCE_TCL_OPERATOR);  // $
+                                               sc.Forward();  // {
+                                               sc.ForwardSetState(SCE_TCL_SUB_BRACE);
+                                               subBrace = true;
+                                       }
+                                       break;
+                               case '#':
+                                       if ((isspacechar(static_cast<unsigned char>(sc.chPrev))||
+                                               isoperator(static_cast<char>(sc.chPrev))) && 
IsADigit(sc.chNext,0x10))
+                                               sc.SetState(SCE_TCL_NUMBER);
+                                       break;
+                               case '-':
+                                       sc.SetState(IsADigit(sc.chNext)? SCE_TCL_NUMBER: SCE_TCL_MODIFIER);
                                        break;
-                case '$':
-                    subParen = 0;
-                    if (sc.chNext != '{') {
-                        sc.SetState(SCE_TCL_SUBSTITUTION);
-                    }
-                    else {
-                        sc.SetState(SCE_TCL_OPERATOR);  // $
-                        sc.Forward();  // {
-                        sc.ForwardSetState(SCE_TCL_SUB_BRACE);
-                        subBrace = true;
-                    }
-                    break;
-                case '#':
-                    if ((isspacechar(static_cast<unsigned char>(sc.chPrev))||
-                            isoperator(static_cast<char>(sc.chPrev))) && IsADigit(sc.chNext,0x10))
-                        sc.SetState(SCE_TCL_NUMBER);
-                    break;
-                case '-':
-                    sc.SetState(IsADigit(sc.chNext)? SCE_TCL_NUMBER: SCE_TCL_MODIFIER);
-                    break;
-                default:
-                    if (isoperator(static_cast<char>(sc.ch))) {
-                        sc.SetState(SCE_TCL_OPERATOR);
-                    }
+                               default:
+                                       if (isoperator(static_cast<char>(sc.ch))) {
+                                               sc.SetState(SCE_TCL_OPERATOR);
+                                       }
                                }
                        }
                }
@@ -353,18 +352,18 @@ next:
        sc.Complete();
 }
 
-static const char * const tclWordListDesc[] = {
-            "TCL Keywords",
-            "TK Keywords",
-            "iTCL Keywords",
-            "tkCommands",
-            "expand"
-            "user1",
-            "user2",
-            "user3",
-            "user4",
-            0
-        };
+static const char *const tclWordListDesc[] = {
+       "TCL Keywords",
+       "TK Keywords",
+       "iTCL Keywords",
+       "tkCommands",
+       "expand",
+       "user1",
+       "user2",
+       "user3",
+       "user4",
+       0
+};
 
 // this code supports folding in the colourizer
 LexerModule lmTCL(SCLEX_TCL, ColouriseTCLDoc, "tcl", 0, tclWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexTCMD.cxx b/plugins/scintilla/scintilla/lexers/LexTCMD.cxx
index ed747da..03895c5 100644
--- a/plugins/scintilla/scintilla/lexers/LexTCMD.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTCMD.cxx
@@ -30,10 +30,10 @@ using namespace Scintilla;
 
 
 static bool IsAlphabetic(int ch) {
-       return isascii(ch) && isalpha(ch);
+       return IsASCII(ch) && isalpha(ch);
 }
 
-static inline bool AtEOL(Accessor &styler, unsigned int i) {
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
        return (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
 }
 
@@ -47,17 +47,12 @@ static bool IsBSeparator(char ch) {
        return (ch == '\\') || (ch == '.') || (ch == ';') || (ch == ' ') || (ch == '\t') || (ch == '[') || 
(ch == ']') || (ch == '\"') || (ch == '\'') || (ch == '/');
 }
 
-// Tests for Environment Variable symbol
-static inline bool IsEnvironmentVar(char ch) {
-       return isalpha(ch) || isdigit(ch) || (ch == '_') || (ch == '$');
-}
-
 // Find length of CMD FOR variable with modifier (%~...) or return 0
 static unsigned int GetBatchVarLen( char *wordBuffer )
 {
        int nLength = 0;
        if ( wordBuffer[0] == '%' ) {
-               
+
                if ( wordBuffer[1] == '~' )
                        nLength = 2;
                else if (( wordBuffer[1] == '%' ) && ( wordBuffer[2] == '~' ))
@@ -97,12 +92,12 @@ static unsigned int GetBatchVarLen( char *wordBuffer )
 }
 
 
-static void ColouriseTCMDLine( char *lineBuffer, unsigned int lengthLine, unsigned int startLine, unsigned 
int endPos, WordList *keywordlists[], Accessor &styler)
+static void ColouriseTCMDLine( char *lineBuffer, Sci_PositionU lengthLine, Sci_PositionU startLine, 
Sci_PositionU endPos, WordList *keywordlists[], Accessor &styler)
 {
-       unsigned int offset = 0;        // Line Buffer Offset
+       Sci_PositionU offset = 0;       // Line Buffer Offset
        char wordBuffer[260];           // Word Buffer - large to catch long paths
-       unsigned int wbl;                       // Word Buffer Length
-       unsigned int wbo;                       // Word Buffer Offset - also Special Keyword Buffer Length
+       Sci_PositionU wbl;                      // Word Buffer Length
+       Sci_PositionU wbo;                      // Word Buffer Offset - also Special Keyword Buffer Length
        WordList &keywords = *keywordlists[0];      // Internal Commands
 //     WordList &keywords2 = *keywordlists[1];     // Aliases (optional)
        bool isDelayedExpansion = 1;                            // !var!
@@ -112,7 +107,7 @@ static void ColouriseTCMDLine( char *lineBuffer, unsigned int lengthLine, unsign
        // Examples are: cd. cd\ echo: echo. path=
        bool inString = false; // Used for processing while ""
        // Special Keyword Buffer used to determine if the first n characters is a Keyword
-       char sKeywordBuffer[260];       // Special Keyword Buffer
+       char sKeywordBuffer[260] = "";  // Special Keyword Buffer
        bool sKeywordFound;             // Exit Special Keyword for-loop if found
 
        // Skip leading whitespace
@@ -249,7 +244,7 @@ static void ColouriseTCMDLine( char *lineBuffer, unsigned int lengthLine, unsign
                        if ((CompareCaseInsensitive(sKeywordBuffer, "echo") == 0) ||
                          (CompareCaseInsensitive(sKeywordBuffer, "echos") == 0) ||
                          (CompareCaseInsensitive(sKeywordBuffer, "echoerr") == 0) ||
-                         (CompareCaseInsensitive(sKeywordBuffer, "echoserr") == 0) || 
+                         (CompareCaseInsensitive(sKeywordBuffer, "echoserr") == 0) ||
                          (CompareCaseInsensitive(sKeywordBuffer, "cd") == 0) ||
                          (CompareCaseInsensitive(sKeywordBuffer, "path") == 0) ||
                          (CompareCaseInsensitive(sKeywordBuffer, "prompt") == 0)) {
@@ -257,7 +252,7 @@ static void ColouriseTCMDLine( char *lineBuffer, unsigned int lengthLine, unsign
                                // no further Regular Keyword Checking
                                continueProcessing = false;
                                sKeywordFound = true;
-                               wbo = (unsigned int)strlen( sKeywordBuffer );
+                               wbo = (Sci_PositionU)strlen( sKeywordBuffer );
 
                                // Colorize Special Keyword as Regular Keyword
                                styler.ColourTo(startLine + offset - 1 - (wbl - wbo), SCE_TCMD_WORD);
@@ -406,15 +401,15 @@ ColorizeArg:
        styler.ColourTo(endPos, SCE_TCMD_DEFAULT);
 }
 
-static void ColouriseTCMDDoc( unsigned int startPos, int length, int /*initStyle*/, WordList 
*keywordlists[], Accessor &styler )
+static void ColouriseTCMDDoc( Sci_PositionU startPos, Sci_Position length, int /*initStyle*/, WordList 
*keywordlists[], Accessor &styler )
 {
        char lineBuffer[16384];
 
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
-       unsigned int linePos = 0;
-       unsigned int startLine = startPos;
-       for (unsigned int i = startPos; i < startPos + length; i++) {
+       Sci_PositionU linePos = 0;
+       Sci_PositionU startLine = startPos;
+       for (Sci_PositionU i = startPos; i < startPos + length; i++) {
                lineBuffer[linePos++] = styler[i];
                if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
                        // End of line (or of line buffer) met, colourise it
@@ -439,18 +434,18 @@ static void StrUpr(char *s) {
 }
 
 // Folding support (for DO, IFF, SWITCH, TEXT, and command groups)
-static void FoldTCMDDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldTCMDDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
-       int line = styler.GetLine(startPos);
+       Sci_Position line = styler.GetLine(startPos);
        int level = styler.LevelAt(line);
        int levelIndent = 0;
-       unsigned int endPos = startPos + length;
-       char s[16];
+       Sci_PositionU endPos = startPos + length;
+       char s[16] = "";
 
     char chPrev = styler.SafeGetCharAt(startPos - 1);
 
        // Scan for ( and )
-       for (unsigned int i = startPos; i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
 
                int c = styler.SafeGetCharAt(i, '\n');
                int style = styler.StyleAt(i);
@@ -466,7 +461,7 @@ static void FoldTCMDDoc(unsigned int startPos, int length, int, WordList *[], Ac
                }
 
         if (( bLineStart ) && ( style == SCE_TCMD_WORD )) {
-            for (unsigned int j = 0; j < 10; j++) {
+            for (Sci_PositionU j = 0; j < 10; j++) {
                 if (!iswordchar(styler[i + j])) {
                     break;
                 }
diff --git a/plugins/scintilla/scintilla/lexers/LexTeX.cxx b/plugins/scintilla/scintilla/lexers/LexTeX.cxx
index 062c7ab..0014160 100644
--- a/plugins/scintilla/scintilla/lexers/LexTeX.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTeX.cxx
@@ -69,7 +69,7 @@ using namespace Scintilla;
 
 // Auxiliary functions:
 
-static inline bool endOfLine(Accessor &styler, unsigned int i) {
+static inline bool endOfLine(Accessor &styler, Sci_PositionU i) {
        return
       (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')) ;
 }
@@ -122,18 +122,18 @@ static inline bool isTeXseven(int ch) {
 // Interface determination
 
 static int CheckTeXInterface(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     Accessor &styler,
        int defaultInterface) {
 
     char lineBuffer[1024] ;
-       unsigned int linePos = 0 ;
+       Sci_PositionU linePos = 0 ;
 
     // some day we can make something lexer.tex.mapping=(all,0)(nl,1)(en,2)...
 
     if (styler.SafeGetCharAt(0) == '%') {
-        for (unsigned int i = 0; i < startPos + length; i++) {
+        for (Sci_PositionU i = 0; i < startPos + length; i++) {
             lineBuffer[linePos++] = styler.SafeGetCharAt(i) ;
             if (endOfLine(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
                 lineBuffer[linePos] = '\0';
@@ -170,8 +170,8 @@ static int CheckTeXInterface(
 }
 
 static void ColouriseTeXDoc(
-    unsigned int startPos,
-    int length,
+    Sci_PositionU startPos,
+    Sci_Position length,
     int,
     WordList *keywordlists[],
     Accessor &styler) {
@@ -297,9 +297,9 @@ static inline bool isWordChar(int ch) {
        return ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'));
 }
 
-static int ParseTeXCommand(unsigned int pos, Accessor &styler, char *command)
+static int ParseTeXCommand(Sci_PositionU pos, Accessor &styler, char *command)
 {
-  int length=0;
+  Sci_Position length=0;
   char ch=styler.SafeGetCharAt(pos+1);
 
   if(ch==',' || ch==':' || ch==';' || ch=='%'){
@@ -362,11 +362,11 @@ static int classifyFoldPointTeXUnpaired(const char* s) {
        return lev;
 }
 
-static bool IsTeXCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
+static bool IsTeXCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
 
-       int startpos = pos;
+       Sci_Position startpos = pos;
 
        while (startpos<eol_pos){
                char ch = styler[startpos];
@@ -380,18 +380,18 @@ static bool IsTeXCommentLine(int line, Accessor &styler) {
 
 // FoldTeXDoc: borrowed from VisualTeX with modifications
 
-static void FoldTexDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
+static void FoldTexDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler)
 {
        bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       unsigned int endPos = startPos+length;
+       Sci_PositionU endPos = startPos+length;
        int visibleChars=0;
-       int lineCurrent=styler.GetLine(startPos);
+       Sci_Position lineCurrent=styler.GetLine(startPos);
        int levelPrev=styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
        int levelCurrent=levelPrev;
        char chNext=styler[startPos];
        char buffer[100]="";
 
-       for (unsigned int i=startPos; i < endPos; i++) {
+       for (Sci_PositionU i=startPos; i < endPos; i++) {
                char ch=chNext;
                chNext=styler.SafeGetCharAt(i+1);
                bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
diff --git a/plugins/scintilla/scintilla/lexers/LexTxt2tags.cxx 
b/plugins/scintilla/scintilla/lexers/LexTxt2tags.cxx
index 8f8e181..7e57e11 100644
--- a/plugins/scintilla/scintilla/lexers/LexTxt2tags.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTxt2tags.cxx
@@ -45,8 +45,8 @@ static inline bool IsNewline(const int ch) {
 }
 
 // True if can follow ch down to the end with possibly trailing whitespace
-static bool FollowToLineEnd(const int ch, const int state, const unsigned int endPos, StyleContext &sc) {
-    unsigned int i = 0;
+static bool FollowToLineEnd(const int ch, const int state, const Sci_PositionU endPos, StyleContext &sc) {
+    Sci_PositionU i = 0;
     while (sc.GetRelative(++i) == ch)
         ;
     // Skip over whitespace
@@ -63,7 +63,7 @@ static bool FollowToLineEnd(const int ch, const int state, const unsigned int en
 
 // Does the previous line have more than spaces and tabs?
 static bool HasPrevLineContent(StyleContext &sc) {
-    int i = 0;
+    Sci_Position i = 0;
     // Go back to the previous newline
     while ((--i + sc.currentPos) && !IsNewline(sc.GetRelative(i)))
         ;
@@ -77,11 +77,12 @@ static bool HasPrevLineContent(StyleContext &sc) {
 }
 
 // Separator line
-static bool IsValidHrule(const unsigned int endPos, StyleContext &sc) {
-    int c, count = 1;
-    unsigned int i = 0;
-    while (++i) {
-        c = sc.GetRelative(i);
+static bool IsValidHrule(const Sci_PositionU endPos, StyleContext &sc) {
+    int count = 1;
+    Sci_PositionU i = 0;
+    for (;;) {
+        ++i;
+        int c = sc.GetRelative(i);
         if (c == sc.ch)
             ++count;
         // hit a terminating character
@@ -100,12 +101,11 @@ static bool IsValidHrule(const unsigned int endPos, StyleContext &sc) {
             }
         }
     }
-    return false;
 }
 
-static void ColorizeTxt2tagsDoc(unsigned int startPos, int length, int initStyle,
+static void ColorizeTxt2tagsDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                                WordList **, Accessor &styler) {
-    unsigned int endPos = startPos + length;
+    Sci_PositionU endPos = startPos + length;
     int precharCount = 0;
     // Don't advance on a new loop iteration and retry at the same position.
     // Useful in the corner case of having to start at the beginning file position
@@ -188,7 +188,7 @@ static void ColorizeTxt2tagsDoc(unsigned int startPos, int length, int initStyle
                 if (IsNewline(sc.ch))
                 sc.SetState(SCE_TXT2TAGS_LINE_BEGIN);
             if (sc.atLineStart && sc.Match("```")) {
-                int i = 1;
+                Sci_Position i = 1;
                 while (!IsNewline(sc.GetRelative(i)) && sc.currentPos + i < endPos)
                     i++;
                 sc.Forward(i);
@@ -375,7 +375,7 @@ static void ColorizeTxt2tagsDoc(unsigned int startPos, int length, int initStyle
             }
             // Ordered list
             else if (IsADigit(sc.ch)) {
-                int digitCount = 0;
+                Sci_Position digitCount = 0;
                 while (IsADigit(sc.GetRelative(++digitCount)))
                     ;
                 if (sc.GetRelative(digitCount) == '.' &&
@@ -405,8 +405,8 @@ static void ColorizeTxt2tagsDoc(unsigned int startPos, int length, int initStyle
          //   }
             // Links and Images
             if (sc.Match("![") || sc.ch == '[') {
-                int i = 0, j = 0, k = 0;
-                int len = endPos - sc.currentPos;
+                Sci_Position i = 0, j = 0, k = 0;
+                Sci_Position len = endPos - sc.currentPos;
                 while (i < len && (sc.GetRelative(++i) != ']' || sc.GetRelative(i - 1) == '\\'))
                     ;
                 if (sc.GetRelative(i) == ']') {
diff --git a/plugins/scintilla/scintilla/lexers/LexVB.cxx b/plugins/scintilla/scintilla/lexers/LexVB.cxx
index 54050c7..d221dd4 100644
--- a/plugins/scintilla/scintilla/lexers/LexVB.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexVB.cxx
@@ -31,7 +31,7 @@ using namespace Scintilla;
 #define SCE_B_FILENUMBER SCE_B_DEFAULT+100
 
 
-static bool IsVBComment(Accessor &styler, int pos, int len) {
+static bool IsVBComment(Accessor &styler, Sci_Position pos, Sci_Position len) {
        return len > 0 && styler[pos] == '\'';
 }
 
@@ -58,7 +58,7 @@ static inline bool IsANumberChar(int ch) {
              ch == '.' || ch == '-' || ch == '+');
 }
 
-static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseVBDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                            WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) {
 
        WordList &keywords = *keywordlists[0];
@@ -254,12 +254,12 @@ static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle,
        sc.Complete();
 }
 
-static void FoldVBDoc(unsigned int startPos, int length, int,
+static void FoldVBDoc(Sci_PositionU startPos, Sci_Position length, int,
                                                   WordList *[], Accessor &styler) {
-       int endPos = startPos + length;
+       Sci_Position endPos = startPos + length;
 
        // Backtrack to previous line in case need to fix its fold status
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        if (startPos > 0) {
                if (lineCurrent > 0) {
                        lineCurrent--;
@@ -269,7 +269,7 @@ static void FoldVBDoc(unsigned int startPos, int length, int,
        int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment);
        char chNext = styler[startPos];
-       for (int i = startPos; i < endPos; i++) {
+       for (Sci_Position i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
 
@@ -296,12 +296,12 @@ static void FoldVBDoc(unsigned int startPos, int length, int,
        }
 }
 
-static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseVBNetDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                            WordList *keywordlists[], Accessor &styler) {
        ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false);
 }
 
-static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle,
+static void ColouriseVBScriptDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
                            WordList *keywordlists[], Accessor &styler) {
        ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true);
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexVHDL.cxx b/plugins/scintilla/scintilla/lexers/LexVHDL.cxx
index ee9d662..a1d75b2 100644
--- a/plugins/scintilla/scintilla/lexers/LexVHDL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexVHDL.cxx
@@ -12,10 +12,10 @@
 
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h>
 #include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <ctype.h>
 
 #include "ILexer.h"
 #include "Scintilla.h"
@@ -33,8 +33,8 @@ using namespace Scintilla;
 #endif
 
 static void ColouriseVHDLDoc(
-  unsigned int startPos,
-  int length,
+  Sci_PositionU startPos,
+  Sci_Position length,
   int initStyle,
   WordList *keywordlists[],
   Accessor &styler);
@@ -51,14 +51,14 @@ static inline bool IsAWordStart(const int ch) {
 }
 
 /***************************************/
-inline bool IsABlank(unsigned int ch) {
+static inline bool IsABlank(unsigned int ch) {
     return (ch == ' ') || (ch == 0x09) || (ch == 0x0b) ;
 }
 
 /***************************************/
 static void ColouriseVHDLDoc(
-  unsigned int startPos,
-  int length,
+  Sci_PositionU startPos,
+  Sci_Position length,
   int initStyle,
   WordList *keywordlists[],
   Accessor &styler)
@@ -72,6 +72,7 @@ static void ColouriseVHDLDoc(
   WordList &User       = *keywordlists[6];
 
   StyleContext sc(startPos, length, initStyle, styler);
+  bool isExtendedId = false;    // true when parsing an extended identifier
 
   for (; sc.More(); sc.Forward())
   {
@@ -84,7 +85,7 @@ static void ColouriseVHDLDoc(
         sc.SetState(SCE_VHDL_DEFAULT);
       }
     } else if (sc.state == SCE_VHDL_IDENTIFIER) {
-      if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
+      if (!isExtendedId && (!IsAWordChar(sc.ch) || (sc.ch == '.'))) {
         char s[100];
         sc.GetCurrentLowered(s, sizeof(s));
         if (Keywords.InList(s)) {
@@ -103,6 +104,10 @@ static void ColouriseVHDLDoc(
           sc.ChangeState(SCE_VHDL_USERWORD);
         }
         sc.SetState(SCE_VHDL_DEFAULT);
+      } else if (isExtendedId && ((sc.ch == '\\') || sc.atLineEnd)) {
+        // extended identifiers are terminated by backslash, check for end of line in case we have invalid 
syntax
+        isExtendedId = false;
+        sc.ForwardSetState(SCE_VHDL_DEFAULT);
       }
     } else if (sc.state == SCE_VHDL_COMMENT || sc.state == SCE_VHDL_COMMENTLINEBANG) {
       if (sc.atLineEnd) {
@@ -119,6 +124,11 @@ static void ColouriseVHDLDoc(
         sc.ChangeState(SCE_VHDL_STRINGEOL);
         sc.ForwardSetState(SCE_VHDL_DEFAULT);
       }
+    } else if (sc.state == SCE_VHDL_BLOCK_COMMENT){
+      if(sc.ch == '*' && sc.chNext == '/'){
+        sc.Forward();
+        sc.ForwardSetState(SCE_VHDL_DEFAULT);
+      }
     }
 
     // Determine if a new state should be entered.
@@ -132,8 +142,13 @@ static void ColouriseVHDLDoc(
           sc.SetState(SCE_VHDL_COMMENTLINEBANG);
         else
           sc.SetState(SCE_VHDL_COMMENT);
+      } else if (sc.Match('/', '*')){
+        sc.SetState(SCE_VHDL_BLOCK_COMMENT);
       } else if (sc.ch == '\"') {
         sc.SetState(SCE_VHDL_STRING);
+      } else if (sc.ch == '\\') {
+        isExtendedId = true;
+        sc.SetState(SCE_VHDL_IDENTIFIER);
       } else if (isoperator(static_cast<char>(sc.ch))) {
         sc.SetState(SCE_VHDL_OPERATOR);
       }
@@ -142,10 +157,10 @@ static void ColouriseVHDLDoc(
   sc.Complete();
 }
 //=============================================================================
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eol_pos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eol_pos; i++) {
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
                char ch = styler[i];
                char chNext = styler[i+1];
                if ((ch == '-') && (chNext == '-'))
@@ -155,20 +170,53 @@ static bool IsCommentLine(int line, Accessor &styler) {
        }
        return false;
 }
+static bool IsCommentBlockStart(Sci_Position line, Accessor &styler)
+{
+    Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               char chNext = styler[i+1];
+        char style = styler.StyleAt(i);
+               if ((style == SCE_VHDL_BLOCK_COMMENT) && (ch == '/') && (chNext == '*'))
+                       return true;
+       }
+       return false;
+}
+
+static bool IsCommentBlockEnd(Sci_Position line, Accessor &styler)
+{
+    Sci_Position pos = styler.LineStart(line);
+       Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
+
+       for (Sci_Position i = pos; i < eol_pos; i++) {
+               char ch = styler[i];
+               char chNext = styler[i+1];
+        char style = styler.StyleAt(i);
+               if ((style == SCE_VHDL_BLOCK_COMMENT) && (ch == '*') && (chNext == '/'))
+                       return true;
+       }
+       return false;
+}
+
+static bool IsCommentStyle(char style)
+{
+    return style == SCE_VHDL_BLOCK_COMMENT || style == SCE_VHDL_COMMENT || style == SCE_VHDL_COMMENTLINEBANG;
+}
 
 //=============================================================================
 // Folding the code
 static void FoldNoBoxVHDLDoc(
-  unsigned int startPos,
-  int length,
+  Sci_PositionU startPos,
+  Sci_Position length,
   int,
   Accessor &styler)
 {
   // Decided it would be smarter to have the lexer have all keywords included. Therefore I
   // don't check if the style for the keywords that I use to adjust the levels.
   char words[] =
-    "architecture begin case component else elsif end entity generate loop package process record then "
-    "procedure function when";
+    "architecture begin block case component else elsif end entity generate loop package process record then 
"
+    "procedure protected function when units";
   WordList keywords;
   keywords.Set(words);
 
@@ -180,9 +228,9 @@ static void FoldNoBoxVHDLDoc(
   //bool foldAtWhen       = styler.GetPropertyInt("fold.at.When", 1) != 0;  //< fold at when in case 
statements
 
   int  visibleChars     = 0;
-  unsigned int endPos   = startPos + length;
+  Sci_PositionU endPos   = startPos + length;
 
-  int lineCurrent       = styler.GetLine(startPos);
+  Sci_Position lineCurrent       = styler.GetLine(startPos);
   int levelCurrent      = SC_FOLDLEVELBASE;
   if(lineCurrent > 0)
     levelCurrent        = styler.LevelAt(lineCurrent-1) >> 16;
@@ -192,34 +240,34 @@ static void FoldNoBoxVHDLDoc(
   int levelNext         = levelCurrent;
 
   /***************************************/
-  int lastStart         = 0;
+  Sci_Position lastStart         = 0;
   char prevWord[32]     = "";
 
   /***************************************/
   // Find prev word
   // The logic for going up or down a level depends on a the previous keyword
   // This code could be cleaned up.
-  int end = 0;
-  unsigned int j;
+  Sci_Position end = 0;
+  Sci_PositionU j;
   for(j = startPos; j>0; j--)
   {
     char ch       = styler.SafeGetCharAt(j);
     char chPrev   = styler.SafeGetCharAt(j-1);
     int style     = styler.StyleAt(j);
     int stylePrev = styler.StyleAt(j-1);
-    if ((stylePrev != SCE_VHDL_COMMENT) && (stylePrev != SCE_VHDL_STRING))
+    if ((!IsCommentStyle(style)) && (stylePrev != SCE_VHDL_STRING))
     {
       if(IsAWordChar(chPrev) && !IsAWordChar(ch))
       {
         end = j-1;
       }
     }
-    if ((style != SCE_VHDL_COMMENT) && (style != SCE_VHDL_STRING))
+    if ((!IsCommentStyle(style)) && (style != SCE_VHDL_STRING))
     {
       if(!IsAWordChar(chPrev) && IsAWordStart(ch) && (end != 0))
       {
         char s[32];
-        unsigned int k;
+        Sci_PositionU k;
         for(k=0; (k<31 ) && (k<end-j+1 ); k++) {
           s[k] = static_cast<char>(tolower(styler[j+k]));
         }
@@ -232,11 +280,11 @@ static void FoldNoBoxVHDLDoc(
       }
     }
   }
-  for(j=j+static_cast<unsigned int>(strlen(prevWord)); j<endPos; j++)
+  for(j=j+static_cast<Sci_PositionU>(strlen(prevWord)); j<endPos; j++)
   {
     char ch       = styler.SafeGetCharAt(j);
     int style     = styler.StyleAt(j);
-    if ((style != SCE_VHDL_COMMENT) && (style != SCE_VHDL_STRING))
+    if ((!IsCommentStyle(style)) && (style != SCE_VHDL_STRING))
     {
       if((ch == ';') && (strcmp(prevWord, "end") == 0))
       {
@@ -252,13 +300,13 @@ static void FoldNoBoxVHDLDoc(
   //Platform::DebugPrintf("Line[%04d] Prev[%20s] ************************* Level[%x]\n", lineCurrent+1, 
prevWord, levelCurrent);
 
   /***************************************/
-  for (unsigned int i = startPos; i < endPos; i++)
+  for (Sci_PositionU i = startPos; i < endPos; i++)
   {
     char ch         = chNext;
     chNext          = styler.SafeGetCharAt(i + 1);
     chPrev          = styler.SafeGetCharAt(i - 1);
     chNextNonBlank  = chNext;
-    unsigned int j  = i+1;
+    Sci_PositionU j  = i+1;
     while(IsABlank(chNextNonBlank) && j<endPos)
     {
       j ++ ;
@@ -268,15 +316,29 @@ static void FoldNoBoxVHDLDoc(
     styleNext       = styler.StyleAt(i + 1);
     bool atEOL      = (ch == '\r' && chNext != '\n') || (ch == '\n');
 
-               if (foldComment && atEOL && IsCommentLine(lineCurrent, styler))
+    if (foldComment && atEOL)
     {
-      if(!IsCommentLine(lineCurrent-1, styler) && IsCommentLine(lineCurrent+1, styler))
+      if(IsCommentLine(lineCurrent, styler))
       {
-        levelNext++;
+        if(!IsCommentLine(lineCurrent-1, styler) && IsCommentLine(lineCurrent+1, styler))
+        {
+          levelNext++;
+        }
+        else if(IsCommentLine(lineCurrent-1, styler) && !IsCommentLine(lineCurrent+1, styler))
+        {
+          levelNext--;
+        }
       }
-      else if(IsCommentLine(lineCurrent-1, styler) && !IsCommentLine(lineCurrent+1, styler))
+      else
       {
-        levelNext--;
+        if (IsCommentBlockStart(lineCurrent, styler) && !IsCommentBlockEnd(lineCurrent, styler))
+        {
+          levelNext++;
+        }
+        else if (IsCommentBlockEnd(lineCurrent, styler) && !IsCommentBlockStart(lineCurrent, styler))
+        {
+          levelNext--;
+        }
       }
     }
 
@@ -289,7 +351,7 @@ static void FoldNoBoxVHDLDoc(
       }
     }
 
-    if ((style != SCE_VHDL_COMMENT) && (style != SCE_VHDL_STRING))
+    if ((!IsCommentStyle(style)) && (style != SCE_VHDL_STRING))
     {
       if((ch == ';') && (strcmp(prevWord, "end") == 0))
       {
@@ -301,9 +363,9 @@ static void FoldNoBoxVHDLDoc(
         lastStart = i;
       }
 
-      if(iswordchar(ch) && !iswordchar(chNext)) {
+      if(IsAWordChar(ch) && !IsAWordChar(chNext)) {
         char s[32];
-        unsigned int k;
+        Sci_PositionU k;
         for(k=0; (k<31 ) && (k<i-lastStart+1 ); k++) {
           s[k] = static_cast<char>(tolower(styler[lastStart+k]));
         }
@@ -314,14 +376,15 @@ static void FoldNoBoxVHDLDoc(
           if (
             strcmp(s, "architecture") == 0  ||
             strcmp(s, "case") == 0          ||
-            strcmp(s, "component") == 0     ||
-            strcmp(s, "entity") == 0        ||
             strcmp(s, "generate") == 0      ||
+            strcmp(s, "block") == 0         ||
             strcmp(s, "loop") == 0          ||
             strcmp(s, "package") ==0        ||
             strcmp(s, "process") == 0       ||
+            strcmp(s, "protected") == 0     ||
             strcmp(s, "record") == 0        ||
-            strcmp(s, "then") == 0)
+            strcmp(s, "then") == 0          ||
+            strcmp(s, "units") == 0)
           {
             if (strcmp(prevWord, "end") != 0)
             {
@@ -331,6 +394,35 @@ static void FoldNoBoxVHDLDoc(
               levelNext++;
             }
           } else if (
+            strcmp(s, "component") == 0      ||
+            strcmp(s, "entity") == 0         ||
+            strcmp(s, "configuration") == 0 )
+          {
+            if (strcmp(prevWord, "end") != 0)
+            { // check for instantiated unit by backward searching for the colon.
+              Sci_PositionU pos = lastStart;
+              char chAtPos=0, styleAtPos;
+              do{// skip white spaces
+                if(!pos)
+                  break;
+                pos--;
+                styleAtPos = styler.StyleAt(pos);
+                chAtPos = styler.SafeGetCharAt(pos);
+              }while(pos &&
+                     (chAtPos == ' ' || chAtPos == '\t' ||
+                      chAtPos == '\n' || chAtPos == '\r' ||
+                      IsCommentStyle(styleAtPos)));
+
+              // check for a colon (':') before the instantiated units "entity", "component" or 
"configuration". Don't fold thereafter.
+              if (chAtPos != ':')
+              {
+                if (levelMinCurrentElse > levelNext) {
+                  levelMinCurrentElse = levelNext;
+                }
+                levelNext++;
+              }
+            }
+          } else if (
             strcmp(s, "procedure") == 0     ||
             strcmp(s, "function") == 0)
           {
@@ -338,19 +430,19 @@ static void FoldNoBoxVHDLDoc(
             { // This code checks to see if the procedure / function is a definition within a "package"
               // rather than the actual code in the body.
               int BracketLevel = 0;
-              for(int j=i+1; j<styler.Length(); j++)
+              for(Sci_Position pos=i+1; pos<styler.Length(); pos++)
               {
-                int LocalStyle = styler.StyleAt(j);
-                char LocalCh = styler.SafeGetCharAt(j);
-                if(LocalCh == '(') BracketLevel++;
-                if(LocalCh == ')') BracketLevel--;
+                int styleAtPos = styler.StyleAt(pos);
+                char chAtPos = styler.SafeGetCharAt(pos);
+                if(chAtPos == '(') BracketLevel++;
+                if(chAtPos == ')') BracketLevel--;
                 if(
                   (BracketLevel == 0) &&
-                  (LocalStyle != SCE_VHDL_COMMENT) &&
-                  (LocalStyle != SCE_VHDL_STRING) &&
-                  !iswordchar(styler.SafeGetCharAt(j-1)) &&
-                  styler.Match(j, "is") &&
-                  !iswordchar(styler.SafeGetCharAt(j+2)))
+                  (!IsCommentStyle(styleAtPos)) &&
+                  (styleAtPos != SCE_VHDL_STRING) &&
+                  !iswordchar(styler.SafeGetCharAt(pos-1)) &&
+                  (chAtPos|' ')=='i' && (styler.SafeGetCharAt(pos+1)|' ')=='s' &&
+                  !iswordchar(styler.SafeGetCharAt(pos+2)))
                 {
                   if (levelMinCurrentElse > levelNext) {
                     levelMinCurrentElse = levelNext;
@@ -358,7 +450,7 @@ static void FoldNoBoxVHDLDoc(
                   levelNext++;
                   break;
                 }
-                if((BracketLevel == 0) && (LocalCh == ';'))
+                if((BracketLevel == 0) && (chAtPos == ';'))
                 {
                   break;
                 }
@@ -421,7 +513,7 @@ static void FoldNoBoxVHDLDoc(
 }
 
 //=============================================================================
-static void FoldVHDLDoc(unsigned int startPos, int length, int initStyle, WordList *[],
+static void FoldVHDLDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],
                        Accessor &styler) {
   FoldNoBoxVHDLDoc(startPos, length, initStyle, styler);
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexVerilog.cxx 
b/plugins/scintilla/scintilla/lexers/LexVerilog.cxx
index ed39c2b..28b8dfb 100644
--- a/plugins/scintilla/scintilla/lexers/LexVerilog.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexVerilog.cxx
@@ -13,6 +13,11 @@
 #include <assert.h>
 #include <ctype.h>
 
+#include <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+
 #include "ILexer.h"
 #include "Scintilla.h"
 #include "SciLexer.h"
@@ -24,127 +29,733 @@
 #include "CharacterSet.h"
 #include "LexerModule.h"
 
+#include "OptionSet.h"
+#include "SubStyles.h"
+
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
+namespace {
+       // Use an unnamed namespace to protect the functions and classes from name conflicts
+
+struct PPDefinition {
+       Sci_Position line;
+       std::string key;
+       std::string value;
+       bool isUndef;
+       std::string arguments;
+       PPDefinition(Sci_Position line_, const std::string &key_, const std::string &value_, bool isUndef_ = 
false, std::string arguments_="") :
+               line(line_), key(key_), value(value_), isUndef(isUndef_), arguments(arguments_) {
+       }
+};
+
+class LinePPState {
+       int state;
+       int ifTaken;
+       int level;
+       bool ValidLevel() const {
+               return level >= 0 && level < 32;
+       }
+       int maskLevel() const {
+               return 1 << level;
+       }
+public:
+       LinePPState() : state(0), ifTaken(0), level(-1) {
+       }
+       bool IsInactive() const {
+               return state != 0;
+       }
+       bool CurrentIfTaken() const {
+               return (ifTaken & maskLevel()) != 0;
+       }
+       void StartSection(bool on) {
+               level++;
+               if (ValidLevel()) {
+                       if (on) {
+                               state &= ~maskLevel();
+                               ifTaken |= maskLevel();
+                       } else {
+                               state |= maskLevel();
+                               ifTaken &= ~maskLevel();
+                       }
+               }
+       }
+       void EndSection() {
+               if (ValidLevel()) {
+                       state &= ~maskLevel();
+                       ifTaken &= ~maskLevel();
+               }
+               level--;
+       }
+       void InvertCurrentLevel() {
+               if (ValidLevel()) {
+                       state ^= maskLevel();
+                       ifTaken |= maskLevel();
+               }
+       }
+};
+
+// Hold the preprocessor state for each line seen.
+// Currently one entry per line but could become sparse with just one entry per preprocessor line.
+class PPStates {
+       std::vector<LinePPState> vlls;
+public:
+       LinePPState ForLine(Sci_Position line) const {
+               if ((line > 0) && (vlls.size() > static_cast<size_t>(line))) {
+                       return vlls[line];
+               } else {
+                       return LinePPState();
+               }
+       }
+       void Add(Sci_Position line, LinePPState lls) {
+               vlls.resize(line+1);
+               vlls[line] = lls;
+       }
+};
+
+// Options used for LexerVerilog
+struct OptionsVerilog {
+       bool foldComment;
+       bool foldPreprocessor;
+       bool foldPreprocessorElse;
+       bool foldCompact;
+       bool foldAtElse;
+       bool foldAtModule;
+       bool trackPreprocessor;
+       bool updatePreprocessor;
+       bool portStyling;
+       bool allUppercaseDocKeyword;
+       OptionsVerilog() {
+               foldComment = false;
+               foldPreprocessor = false;
+               foldPreprocessorElse = false;
+               foldCompact = false;
+               foldAtElse = false;
+               foldAtModule = false;
+               // for backwards compatibility, preprocessor functionality is disabled by default
+               trackPreprocessor = false;
+               updatePreprocessor = false;
+               // for backwards compatibility, treat input/output/inout as regular keywords
+               portStyling = false;
+               // for backwards compatibility, don't treat all uppercase identifiers as documentation 
keywords
+               allUppercaseDocKeyword = false;
+       }
+};
+
+struct OptionSetVerilog : public OptionSet<OptionsVerilog> {
+       OptionSetVerilog() {
+               DefineProperty("fold.comment", &OptionsVerilog::foldComment,
+                       "This option enables folding multi-line comments when using the Verilog lexer.");
+               DefineProperty("fold.preprocessor", &OptionsVerilog::foldPreprocessor,
+                       "This option enables folding preprocessor directives when using the Verilog lexer.");
+               DefineProperty("fold.compact", &OptionsVerilog::foldCompact);
+               DefineProperty("fold.at.else", &OptionsVerilog::foldAtElse,
+                       "This option enables folding on the else line of an if statement.");
+               DefineProperty("fold.verilog.flags", &OptionsVerilog::foldAtModule,
+                       "This option enables folding module definitions. Typically source files "
+                       "contain only one module definition so this option is somewhat useless.");
+               DefineProperty("lexer.verilog.track.preprocessor", &OptionsVerilog::trackPreprocessor,
+                       "Set to 1 to interpret `if/`else/`endif to grey out code that is not active.");
+               DefineProperty("lexer.verilog.update.preprocessor", &OptionsVerilog::updatePreprocessor,
+                       "Set to 1 to update preprocessor definitions when `define, `undef, or `undefineall 
found.");
+               DefineProperty("lexer.verilog.portstyling", &OptionsVerilog::portStyling,
+                       "Set to 1 to style input, output, and inout ports differently from regular 
keywords.");
+               DefineProperty("lexer.verilog.allupperkeywords", &OptionsVerilog::allUppercaseDocKeyword,
+                       "Set to 1 to style identifiers that are all uppercase as documentation keyword.");
+               DefineProperty("lexer.verilog.fold.preprocessor.else", &OptionsVerilog::foldPreprocessorElse,
+                       "This option enables folding on `else and `elsif preprocessor directives.");
+       }
+};
+
+const char styleSubable[] = {0};
+
+}
+
+class LexerVerilog : public ILexerWithSubStyles {
+       CharacterSet setWord;
+       WordList keywords;
+       WordList keywords2;
+       WordList keywords3;
+       WordList keywords4;
+       WordList keywords5;
+       WordList ppDefinitions;
+       PPStates vlls;
+       std::vector<PPDefinition> ppDefineHistory;
+       struct SymbolValue {
+               std::string value;
+               std::string arguments;
+               SymbolValue(const std::string &value_="", const std::string &arguments_="") : value(value_), 
arguments(arguments_) {
+               }
+               SymbolValue &operator = (const std::string &value_) {
+                       value = value_;
+                       arguments.clear();
+                       return *this;
+               }
+               bool IsMacro() const {
+                       return !arguments.empty();
+               }
+       };
+       typedef std::map<std::string, SymbolValue> SymbolTable;
+       SymbolTable preprocessorDefinitionsStart;
+       OptionsVerilog options;
+       OptionSetVerilog osVerilog;
+       enum { activeFlag = 0x40 };
+       SubStyles subStyles;
+
+       // states at end of line (EOL) during fold operations:
+       //              foldExternFlag: EOL while parsing an extern function/task declaration terminated by 
';'
+       //              foldWaitDisableFlag: EOL while parsing wait or disable statement, terminated by 
"fork" or '('
+       //              typdefFlag: EOL while parsing typedef statement, terminated by ';'
+       enum {foldExternFlag = 0x01, foldWaitDisableFlag = 0x02, typedefFlag = 0x04, protectedFlag = 0x08};
+       // map using line number as key to store fold state information
+       std::map<Sci_Position, int> foldState;
+
+public:
+       LexerVerilog() :
+               setWord(CharacterSet::setAlphaNum, "._", 0x80, true),
+               subStyles(styleSubable, 0x80, 0x40, activeFlag) {
+               }
+       virtual ~LexerVerilog() {}
+       int SCI_METHOD Version() const override {
+               return lvSubStyles;
+       }
+       void SCI_METHOD Release() override {
+               delete this;
+       }
+       const char* SCI_METHOD PropertyNames() override {
+               return osVerilog.PropertyNames();
+       }
+       int SCI_METHOD PropertyType(const char* name) override {
+               return osVerilog.PropertyType(name);
+       }
+       const char* SCI_METHOD DescribeProperty(const char* name) override {
+               return osVerilog.DescribeProperty(name);
+       }
+       Sci_Position SCI_METHOD PropertySet(const char* key, const char* val) override {
+           return osVerilog.PropertySet(&options, key, val);
+       }
+       const char* SCI_METHOD DescribeWordListSets() override {
+               return osVerilog.DescribeWordListSets();
+       }
+       Sci_Position SCI_METHOD WordListSet(int n, const char* wl) override;
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+       void* SCI_METHOD PrivateCall(int, void*) override {
+               return 0;
+       }
+       int SCI_METHOD LineEndTypesSupported() override {
+               return SC_LINE_END_TYPE_UNICODE;
+       }
+       int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override {
+               return subStyles.Allocate(styleBase, numberStyles);
+       }
+       int SCI_METHOD SubStylesStart(int styleBase) override {
+               return subStyles.Start(styleBase);
+       }
+       int SCI_METHOD SubStylesLength(int styleBase) override {
+               return subStyles.Length(styleBase);
+       }
+       int SCI_METHOD StyleFromSubStyle(int subStyle) override {
+               int styleBase = subStyles.BaseStyle(MaskActive(subStyle));
+               int active = subStyle & activeFlag;
+               return styleBase | active;
+       }
+       int SCI_METHOD PrimaryStyleFromStyle(int style) override {
+               return MaskActive(style);
+       }
+       void SCI_METHOD FreeSubStyles() override {
+               subStyles.Free();
+       }
+       void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override {
+               subStyles.SetIdentifiers(style, identifiers);
+       }
+       int SCI_METHOD DistanceToSecondaryStyles() override {
+               return activeFlag;
+       }
+       const char * SCI_METHOD GetSubStyleBases() override {
+               return styleSubable;
+       }
+       static ILexer* LexerFactoryVerilog() {
+               return new LexerVerilog();
+       }
+       static int MaskActive(int style) {
+               return style & ~activeFlag;
+       }
+       std::vector<std::string> Tokenize(const std::string &expr) const;
+};
+
+Sci_Position SCI_METHOD LexerVerilog::WordListSet(int n, const char *wl) {
+       WordList *wordListN = 0;
+       switch (n) {
+       case 0:
+               wordListN = &keywords;
+               break;
+       case 1:
+               wordListN = &keywords2;
+               break;
+       case 2:
+               wordListN = &keywords3;
+               break;
+       case 3:
+               wordListN = &keywords4;
+               break;
+       case 4:
+               wordListN = &keywords5;
+               break;
+       case 5:
+               wordListN = &ppDefinitions;
+               break;
+       }
+       Sci_Position firstModification = -1;
+       if (wordListN) {
+               WordList wlNew;
+               wlNew.Set(wl);
+               if (*wordListN != wlNew) {
+                       wordListN->Set(wl);
+                       firstModification = 0;
+                       if (n == 5) {
+                               // Rebuild preprocessorDefinitions
+                               preprocessorDefinitionsStart.clear();
+                               for (int nDefinition = 0; nDefinition < ppDefinitions.Length(); 
nDefinition++) {
+                                       const char *cpDefinition = ppDefinitions.WordAt(nDefinition);
+                                       const char *cpEquals = strchr(cpDefinition, '=');
+                                       if (cpEquals) {
+                                               std::string name(cpDefinition, cpEquals - cpDefinition);
+                                               std::string val(cpEquals+1);
+                                               size_t bracket = name.find('(');
+                                               size_t bracketEnd = name.find(')');
+                                               if ((bracket != std::string::npos) && (bracketEnd != 
std::string::npos)) {
+                                                       // Macro
+                                                       std::string args = name.substr(bracket + 1, 
bracketEnd - bracket - 1);
+                                                       name = name.substr(0, bracket);
+                                                       preprocessorDefinitionsStart[name] = SymbolValue(val, 
args);
+                                               } else {
+                                                       preprocessorDefinitionsStart[name] = val;
+                                               }
+                                       } else {
+                                               std::string name(cpDefinition);
+                                               std::string val("1");
+                                               preprocessorDefinitionsStart[name] = val;
+                                       }
+                               }
+                       }
+               }
+       }
+       return firstModification;
+}
+
 static inline bool IsAWordChar(const int ch) {
-       return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '\''|| ch == '$');
+       return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '\''|| ch == '$');
 }
 
 static inline bool IsAWordStart(const int ch) {
        return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '$');
 }
 
-static void ColouriseVerilogDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
-                            Accessor &styler) {
+static inline bool AllUpperCase(const char *a) {
+       while (*a) {
+               if (*a >= 'a' && *a <= 'z') return false;
+               a++;
+       }
+       return true;
+}
+
+// Functor used to truncate history
+struct After {
+       Sci_Position line;
+       explicit After(Sci_Position line_) : line(line_) {}
+       bool operator()(PPDefinition &p) const {
+               return p.line > line;
+       }
+};
+
+static std::string GetRestOfLine(LexAccessor &styler, Sci_Position start, bool allowSpace) {
+       std::string restOfLine;
+       Sci_Position i =0;
+       char ch = styler.SafeGetCharAt(start, '\n');
+       Sci_Position endLine = styler.LineEnd(styler.GetLine(start));
+       while (((start+i) < endLine) && (ch != '\r')) {
+               char chNext = styler.SafeGetCharAt(start + i + 1, '\n');
+               if (ch == '/' && (chNext == '/' || chNext == '*'))
+                       break;
+               if (allowSpace || (ch != ' '))
+                       restOfLine += ch;
+               i++;
+               ch = chNext;
+       }
+       return restOfLine;
+}
+
+static bool IsSpaceOrTab(int ch) {
+       return ch == ' ' || ch == '\t';
+}
+
+void SCI_METHOD LexerVerilog::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess)
+{
+       LexAccessor styler(pAccess);
 
-       WordList &keywords = *keywordlists[0];
-       WordList &keywords2 = *keywordlists[1];
-       WordList &keywords3 = *keywordlists[2];
-       WordList &keywords4 = *keywordlists[3];
+       const int kwOther=0, kwDot=0x100, kwInput=0x200, kwOutput=0x300, kwInout=0x400, kwProtected=0x800;
+       int lineState = kwOther;
+       bool continuationLine = false;
+
+       Sci_Position curLine = styler.GetLine(startPos);
+       if (curLine > 0) lineState = styler.GetLineState(curLine - 1);
 
        // Do not leak onto next line
        if (initStyle == SCE_V_STRINGEOL)
                initStyle = SCE_V_DEFAULT;
 
+       if ((MaskActive(initStyle) == SCE_V_PREPROCESSOR) ||
+                       (MaskActive(initStyle) == SCE_V_COMMENTLINE) ||
+                       (MaskActive(initStyle) == SCE_V_COMMENTLINEBANG)) {
+               // Set continuationLine if last character of previous line is '\'
+               if (curLine > 0) {
+                       Sci_Position endLinePrevious = styler.LineEnd(curLine - 1);
+                       if (endLinePrevious > 0) {
+                               continuationLine = styler.SafeGetCharAt(endLinePrevious-1) == '\\';
+                       }
+               }
+       }
+
        StyleContext sc(startPos, length, initStyle, styler);
+       LinePPState preproc = vlls.ForLine(curLine);
+
+       bool definitionsChanged = false;
+
+       // Truncate ppDefineHistory before current line
+
+       if (!options.updatePreprocessor)
+               ppDefineHistory.clear();
+
+       std::vector<PPDefinition>::iterator itInvalid = std::find_if(ppDefineHistory.begin(), 
ppDefineHistory.end(), After(curLine-1));
+       if (itInvalid != ppDefineHistory.end()) {
+               ppDefineHistory.erase(itInvalid, ppDefineHistory.end());
+               definitionsChanged = true;
+       }
+
+       SymbolTable preprocessorDefinitions = preprocessorDefinitionsStart;
+       for (std::vector<PPDefinition>::iterator itDef = ppDefineHistory.begin(); itDef != 
ppDefineHistory.end(); ++itDef) {
+               if (itDef->isUndef)
+                       preprocessorDefinitions.erase(itDef->key);
+               else
+                       preprocessorDefinitions[itDef->key] = SymbolValue(itDef->value, itDef->arguments);
+       }
+
+       int activitySet = preproc.IsInactive() ? activeFlag : 0;
+       Sci_Position lineEndNext = styler.LineEnd(curLine);
+       bool isEscapedId = false;    // true when parsing an escaped Identifier
+       bool isProtected = (lineState&kwProtected) != 0;        // true when parsing a protected region
 
        for (; sc.More(); sc.Forward()) {
+               if (sc.atLineStart) {
+                       if (sc.state == SCE_V_STRING) {
+                               // Prevent SCE_V_STRINGEOL from leaking back to previous line
+                               sc.SetState(SCE_V_STRING);
+                       }
+                       if ((MaskActive(sc.state) == SCE_V_PREPROCESSOR) && (!continuationLine)) {
+                               sc.SetState(SCE_V_DEFAULT|activitySet);
+                       }
+                       if (preproc.IsInactive()) {
+                               activitySet = activeFlag;
+                               sc.SetState(sc.state | activitySet);
+                       }
+               }
 
-               if (sc.atLineStart && (sc.state == SCE_V_STRING)) {
-                       // Prevent SCE_V_STRINGEOL from leaking back to previous line
-                       sc.SetState(SCE_V_STRING);
+               if (sc.atLineEnd) {
+                       curLine++;
+                       lineEndNext = styler.LineEnd(curLine);
+                       vlls.Add(curLine, preproc);
+                       // Update the line state, so it can be seen by next line
+                       styler.SetLineState(curLine, lineState);
+                       isEscapedId = false;    // EOL terminates an escaped Identifier
                }
 
                // Handle line continuation generically.
                if (sc.ch == '\\') {
-                       if (sc.chNext == '\n' || sc.chNext == '\r') {
+                       if (static_cast<Sci_Position>((sc.currentPos+1)) >= lineEndNext) {
+                               curLine++;
+                               lineEndNext = styler.LineEnd(curLine);
+                               vlls.Add(curLine, preproc);
+                               // Update the line state, so it can be seen by next line
+                               styler.SetLineState(curLine, lineState);
                                sc.Forward();
                                if (sc.ch == '\r' && sc.chNext == '\n') {
+                                       // Even in UTF-8, \r and \n are separate
                                        sc.Forward();
                                }
+                               continuationLine = true;
+                               sc.Forward();
                                continue;
                        }
                }
 
-               // Determine if the current state should terminate.
-               if (sc.state == SCE_V_OPERATOR) {
-                       sc.SetState(SCE_V_DEFAULT);
-               } else if (sc.state == SCE_V_NUMBER) {
-                       if (!IsAWordChar(sc.ch)) {
-                               sc.SetState(SCE_V_DEFAULT);
+               // for comment keyword
+               if (MaskActive(sc.state) == SCE_V_COMMENT_WORD && !IsAWordChar(sc.ch)) {
+                       char s[100];
+                       int state = lineState & 0xff;
+                       sc.GetCurrent(s, sizeof(s));
+                       if (keywords5.InList(s)) {
+                               sc.ChangeState(SCE_V_COMMENT_WORD|activitySet);
+                       } else {
+                               sc.ChangeState(state|activitySet);
                        }
-               } else if (sc.state == SCE_V_IDENTIFIER) {
-                       if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
-                               char s[100];
-                                sc.GetCurrent(s, sizeof(s));
-                               if (keywords.InList(s)) {
-                                       sc.ChangeState(SCE_V_WORD);
-                               } else if (keywords2.InList(s)) {
-                                       sc.ChangeState(SCE_V_WORD2);
-                               } else if (keywords3.InList(s)) {
-                                       sc.ChangeState(SCE_V_WORD3);
-                                } else if (keywords4.InList(s)) {
-                                       sc.ChangeState(SCE_V_USER);
+                       sc.SetState(state|activitySet);
+               }
+
+               const bool atLineEndBeforeSwitch = sc.atLineEnd;
+
+               // Determine if the current state should terminate.
+               switch (MaskActive(sc.state)) {
+                       case SCE_V_OPERATOR:
+                               sc.SetState(SCE_V_DEFAULT|activitySet);
+                               break;
+                       case SCE_V_NUMBER:
+                               if (!(IsAWordChar(sc.ch) || (sc.ch == '?'))) {
+                                       sc.SetState(SCE_V_DEFAULT|activitySet);
                                }
-                               sc.SetState(SCE_V_DEFAULT);
-                       }
-               } else if (sc.state == SCE_V_PREPROCESSOR) {
-                        if (!IsAWordChar(sc.ch)) {
-                                sc.SetState(SCE_V_DEFAULT);
-                        }
-               } else if (sc.state == SCE_V_COMMENT) {
-                       if (sc.Match('*', '/')) {
-                               sc.Forward();
-                               sc.ForwardSetState(SCE_V_DEFAULT);
-                       }
-               } else if (sc.state == SCE_V_COMMENTLINE || sc.state == SCE_V_COMMENTLINEBANG) {
-                       if (sc.atLineStart) {
-                               sc.SetState(SCE_V_DEFAULT);
-                       }
-                } else if (sc.state == SCE_V_STRING) {
-                       if (sc.ch == '\\') {
-                               if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
+                               break;
+                       case SCE_V_IDENTIFIER:
+                               if (!isEscapedId &&(!IsAWordChar(sc.ch) || (sc.ch == '.'))) {
+                                       char s[100];
+                                       lineState &= 0xff00;
+                                       sc.GetCurrent(s, sizeof(s));
+                                       if (options.portStyling && (strcmp(s, "input") == 0)) {
+                                               lineState = kwInput;
+                                               sc.ChangeState(SCE_V_INPUT|activitySet);
+                                       } else if (options.portStyling && (strcmp(s, "output") == 0)) {
+                                               lineState = kwOutput;
+                                               sc.ChangeState(SCE_V_OUTPUT|activitySet);
+                                       } else if (options.portStyling && (strcmp(s, "inout") == 0)) {
+                                               lineState = kwInout;
+                                               sc.ChangeState(SCE_V_INOUT|activitySet);
+                                       } else if (lineState == kwInput) {
+                                               sc.ChangeState(SCE_V_INPUT|activitySet);
+                                       } else if (lineState == kwOutput) {
+                                               sc.ChangeState(SCE_V_OUTPUT|activitySet);
+                                       } else if (lineState == kwInout) {
+                                               sc.ChangeState(SCE_V_INOUT|activitySet);
+                                       } else if (lineState == kwDot) {
+                                               lineState = kwOther;
+                                               if (options.portStyling)
+                                                       sc.ChangeState(SCE_V_PORT_CONNECT|activitySet);
+                                       } else if (keywords.InList(s)) {
+                                               sc.ChangeState(SCE_V_WORD|activitySet);
+                                       } else if (keywords2.InList(s)) {
+                                               sc.ChangeState(SCE_V_WORD2|activitySet);
+                                       } else if (keywords3.InList(s)) {
+                                               sc.ChangeState(SCE_V_WORD3|activitySet);
+                                       } else if (keywords4.InList(s)) {
+                                               sc.ChangeState(SCE_V_USER|activitySet);
+                                       } else if (options.allUppercaseDocKeyword && AllUpperCase(s)) {
+                                               sc.ChangeState(SCE_V_USER|activitySet);
+                                       }
+                                       sc.SetState(SCE_V_DEFAULT|activitySet);
+                               }
+                               break;
+                       case SCE_V_PREPROCESSOR:
+                               if (!IsAWordChar(sc.ch) || sc.atLineEnd) {
+                                       sc.SetState(SCE_V_DEFAULT|activitySet);
+                               }
+                               break;
+                       case SCE_V_COMMENT:
+                               if (sc.Match('*', '/')) {
                                        sc.Forward();
+                                       sc.ForwardSetState(SCE_V_DEFAULT|activitySet);
+                               } else if (IsAWordStart(sc.ch)) {
+                                       lineState = sc.state | (lineState & 0xff00);
+                                       sc.SetState(SCE_V_COMMENT_WORD|activitySet);
                                }
-                       } else if (sc.ch == '\"') {
-                               sc.ForwardSetState(SCE_V_DEFAULT);
-                       } else if (sc.atLineEnd) {
-                               sc.ChangeState(SCE_V_STRINGEOL);
-                               sc.ForwardSetState(SCE_V_DEFAULT);
-                       }
+                               break;
+                       case SCE_V_COMMENTLINE:
+                       case SCE_V_COMMENTLINEBANG:
+                               if (sc.atLineStart) {
+                                       sc.SetState(SCE_V_DEFAULT|activitySet);
+                               } else if (IsAWordStart(sc.ch)) {
+                                       lineState = sc.state | (lineState & 0xff00);
+                                       sc.SetState(SCE_V_COMMENT_WORD|activitySet);
+                               }
+                               break;
+                       case SCE_V_STRING:
+                               if (sc.ch == '\\') {
+                                       if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
+                                               sc.Forward();
+                                       }
+                               } else if (sc.ch == '\"') {
+                                       sc.ForwardSetState(SCE_V_DEFAULT|activitySet);
+                               } else if (sc.atLineEnd) {
+                                       sc.ChangeState(SCE_V_STRINGEOL|activitySet);
+                                       sc.ForwardSetState(SCE_V_DEFAULT|activitySet);
+                               }
+                               break;
+               }
+
+               if (sc.atLineEnd && !atLineEndBeforeSwitch) {
+                       // State exit processing consumed characters up to end of line.
+                       curLine++;
+                       lineEndNext = styler.LineEnd(curLine);
+                       vlls.Add(curLine, preproc);
+                       // Update the line state, so it can be seen by next line
+                       styler.SetLineState(curLine, lineState);
+                       isEscapedId = false;    // EOL terminates an escaped Identifier
                }
 
                // Determine if a new state should be entered.
-               if (sc.state == SCE_V_DEFAULT) {
-                       if (IsADigit(sc.ch) || (sc.ch == '\'') || (sc.ch == '.' && IsADigit(sc.chNext))) {
-                               sc.SetState(SCE_V_NUMBER);
-                       } else if (IsAWordStart(sc.ch)) {
-                               sc.SetState(SCE_V_IDENTIFIER);
-                       } else if (sc.Match('/', '*')) {
-                                sc.SetState(SCE_V_COMMENT);
-                               sc.Forward();   // Eat the * so it isn't used for the end of the comment
-                       } else if (sc.Match('/', '/')) {
-                               if (sc.Match("//!"))    // Nice to have a different comment style
-                                       sc.SetState(SCE_V_COMMENTLINEBANG);
-                               else
-                                       sc.SetState(SCE_V_COMMENTLINE);
-                       } else if (sc.ch == '\"') {
-                               sc.SetState(SCE_V_STRING);
-                       } else if (sc.ch == '`') {
-                               sc.SetState(SCE_V_PREPROCESSOR);
+               if (MaskActive(sc.state) == SCE_V_DEFAULT) {
+                       if (sc.ch == '`') {
+                               sc.SetState(SCE_V_PREPROCESSOR|activitySet);
                                // Skip whitespace between ` and preprocessor word
                                do {
                                        sc.Forward();
                                } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
                                if (sc.atLineEnd) {
-                                       sc.SetState(SCE_V_DEFAULT);
+                                       sc.SetState(SCE_V_DEFAULT|activitySet);
+                                       styler.SetLineState(curLine, lineState);
+                               } else {
+                                       if (sc.Match("protected")) {
+                                               isProtected = true;
+                                               lineState |= kwProtected;
+                                               styler.SetLineState(curLine, lineState);
+                                       } else if (sc.Match("endprotected")) {
+                                               isProtected = false;
+                                               lineState &= ~kwProtected;
+                                               styler.SetLineState(curLine, lineState);
+                                       } else if (!isProtected && options.trackPreprocessor) {
+                                               if (sc.Match("ifdef") || sc.Match("ifndef")) {
+                                                       bool isIfDef = sc.Match("ifdef");
+                                                       int i = isIfDef ? 5 : 6;
+                                                       std::string restOfLine = GetRestOfLine(styler, 
sc.currentPos + i + 1, false);
+                                                       bool foundDef = 
preprocessorDefinitions.find(restOfLine) != preprocessorDefinitions.end();
+                                                       preproc.StartSection(isIfDef == foundDef);
+                                               } else if (sc.Match("else")) {
+                                                       if (!preproc.CurrentIfTaken()) {
+                                                               preproc.InvertCurrentLevel();
+                                                               activitySet = preproc.IsInactive() ? 
activeFlag : 0;
+                                                               if (!activitySet) {
+                                                                       
sc.ChangeState(SCE_V_PREPROCESSOR|activitySet);
+                                                               }
+                                                       } else if (!preproc.IsInactive()) {
+                                                               preproc.InvertCurrentLevel();
+                                                               activitySet = preproc.IsInactive() ? 
activeFlag : 0;
+                                                               if (!activitySet) {
+                                                                       
sc.ChangeState(SCE_V_PREPROCESSOR|activitySet);
+                                                               }
+                                                       }
+                                               } else if (sc.Match("elsif")) {
+                                                       // Ensure only one chosen out of `if .. `elsif .. 
`elsif .. `else .. `endif
+                                                       if (!preproc.CurrentIfTaken()) {
+                                                               // Similar to `ifdef
+                                                               std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 6, true);
+                                                               bool ifGood = 
preprocessorDefinitions.find(restOfLine) != preprocessorDefinitions.end();
+                                                               if (ifGood) {
+                                                                       preproc.InvertCurrentLevel();
+                                                                       activitySet = preproc.IsInactive() ? 
activeFlag : 0;
+                                                                       if (!activitySet)
+                                                                               
sc.ChangeState(SCE_V_PREPROCESSOR|activitySet);
+                                                               }
+                                                       } else if (!preproc.IsInactive()) {
+                                                               preproc.InvertCurrentLevel();
+                                                               activitySet = preproc.IsInactive() ? 
activeFlag : 0;
+                                                               if (!activitySet)
+                                                                       
sc.ChangeState(SCE_V_PREPROCESSOR|activitySet);
+                                                       }
+                                               } else if (sc.Match("endif")) {
+                                                       preproc.EndSection();
+                                                       activitySet = preproc.IsInactive() ? activeFlag : 0;
+                                                       sc.ChangeState(SCE_V_PREPROCESSOR|activitySet);
+                                               } else if (sc.Match("define")) {
+                                                       if (options.updatePreprocessor && 
!preproc.IsInactive()) {
+                                                               std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 6, true);
+                                                               size_t startName = 0;
+                                                               while ((startName < restOfLine.length()) && 
IsSpaceOrTab(restOfLine[startName]))
+                                                                       startName++;
+                                                               size_t endName = startName;
+                                                               while ((endName < restOfLine.length()) && 
setWord.Contains(static_cast<unsigned char>(restOfLine[endName])))
+                                                                       endName++;
+                                                               std::string key = 
restOfLine.substr(startName, endName-startName);
+                                                               if ((endName < restOfLine.length()) && 
(restOfLine.at(endName) == '(')) {
+                                                                       // Macro
+                                                                       size_t endArgs = endName;
+                                                                       while ((endArgs < 
restOfLine.length()) && (restOfLine[endArgs] != ')'))
+                                                                               endArgs++;
+                                                                       std::string args = 
restOfLine.substr(endName + 1, endArgs - endName - 1);
+                                                                       size_t startValue = endArgs+1;
+                                                                       while ((startValue < 
restOfLine.length()) && IsSpaceOrTab(restOfLine[startValue]))
+                                                                               startValue++;
+                                                                       std::string value;
+                                                                       if (startValue < restOfLine.length())
+                                                                               value = 
restOfLine.substr(startValue);
+                                                                       preprocessorDefinitions[key] = 
SymbolValue(value, args);
+                                                                       
ppDefineHistory.push_back(PPDefinition(curLine, key, value, false, args));
+                                                                       definitionsChanged = true;
+                                                               } else {
+                                                                       // Value
+                                                                       size_t startValue = endName;
+                                                                       while ((startValue < 
restOfLine.length()) && IsSpaceOrTab(restOfLine[startValue]))
+                                                                               startValue++;
+                                                                       std::string value = 
restOfLine.substr(startValue);
+                                                                       preprocessorDefinitions[key] = value;
+                                                                       
ppDefineHistory.push_back(PPDefinition(curLine, key, value));
+                                                                       definitionsChanged = true;
+                                                               }
+                                                       }
+                                               } else if (sc.Match("undefineall")) {
+                                                       if (options.updatePreprocessor && 
!preproc.IsInactive()) {
+                                                               // remove all preprocessor definitions
+                                                               std::map<std::string, SymbolValue>::iterator 
itDef;
+                                                               for(itDef = preprocessorDefinitions.begin(); 
itDef != preprocessorDefinitions.end(); ++itDef) {
+                                                                       
ppDefineHistory.push_back(PPDefinition(curLine, itDef->first, "", true));
+                                                               }
+                                                               preprocessorDefinitions.clear();
+                                                               definitionsChanged = true;
+                                                       }
+                                               } else if (sc.Match("undef")) {
+                                                       if (options.updatePreprocessor && 
!preproc.IsInactive()) {
+                                                               std::string restOfLine = 
GetRestOfLine(styler, sc.currentPos + 5, true);
+                                                               std::vector<std::string> tokens = 
Tokenize(restOfLine);
+                                                               std::string key;
+                                                               if (tokens.size() >= 1) {
+                                                                       key = tokens[0];
+                                                                       preprocessorDefinitions.erase(key);
+                                                                       
ppDefineHistory.push_back(PPDefinition(curLine, key, "", true));
+                                                                       definitionsChanged = true;
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       } else if (!isProtected) {
+                               if (IsADigit(sc.ch) || (sc.ch == '\'') || (sc.ch == '.' && 
IsADigit(sc.chNext))) {
+                                       sc.SetState(SCE_V_NUMBER|activitySet);
+                               } else if (IsAWordStart(sc.ch)) {
+                                       sc.SetState(SCE_V_IDENTIFIER|activitySet);
+                               } else if (sc.Match('/', '*')) {
+                                       sc.SetState(SCE_V_COMMENT|activitySet);
+                                       sc.Forward();   // Eat the * so it isn't used for the end of the 
comment
+                               } else if (sc.Match('/', '/')) {
+                                       if (sc.Match("//!"))    // Nice to have a different comment style
+                                               sc.SetState(SCE_V_COMMENTLINEBANG|activitySet);
+                                       else
+                                               sc.SetState(SCE_V_COMMENTLINE|activitySet);
+                               } else if (sc.ch == '\"') {
+                                       sc.SetState(SCE_V_STRING|activitySet);
+                               } else if (sc.ch == '\\') {
+                                       // escaped identifier, everything is ok up to whitespace
+                                       isEscapedId = true;
+                                       sc.SetState(SCE_V_IDENTIFIER|activitySet);
+                               } else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == 
'#') {
+                                       sc.SetState(SCE_V_OPERATOR|activitySet);
+                                       if (sc.ch == '.') lineState = kwDot;
+                                       if (sc.ch == ';') lineState = kwOther;
                                }
-                       } else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '#') {
-                               sc.SetState(SCE_V_OPERATOR);
                        }
                }
+               if (isEscapedId && isspacechar(sc.ch)) {
+                       isEscapedId = false;
+               }
+       }
+       if (definitionsChanged) {
+               styler.ChangeLexerState(startPos, startPos + length);
        }
        sc.Complete();
 }
@@ -153,10 +764,10 @@ static bool IsStreamCommentStyle(int style) {
        return style == SCE_V_COMMENT;
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
-       int eolPos = styler.LineStart(line + 1) - 1;
-       for (int i = pos; i < eolPos; i++) {
+static bool IsCommentLine(Sci_Position line, LexAccessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
+       Sci_Position eolPos = styler.LineStart(line + 1) - 1;
+       for (Sci_Position i = pos; i < eolPos; i++) {
                char ch = styler[i];
                char chNext = styler.SafeGetCharAt(i + 1);
                int style = styler.StyleAt(i);
@@ -169,151 +780,247 @@ static bool IsCommentLine(int line, Accessor &styler) {
        }
        return false;
 }
+
 // Store both the current line's fold level and the next lines in the
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
-static void FoldNoBoxVerilogDoc(unsigned int startPos, int length, int initStyle,
-                            Accessor &styler) {
-       bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
-       bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
-       bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
-       bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
-        // Verilog specific folding options:
-        // fold_at_module -
-        //      Generally used methodology in verilog code is
-        //      one module per file, so folding at module definition is useless.
-        // fold_at_brace/parenthese -
-        //      Folding of long port lists can be convenient.
-       bool foldAtModule = styler.GetPropertyInt("fold.verilog.flags", 0) != 0;
+void SCI_METHOD LexerVerilog::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess)
+{
+       LexAccessor styler(pAccess);
        bool foldAtBrace  = 1;
        bool foldAtParenthese  = 1;
 
-       unsigned int endPos = startPos + length;
+       Sci_Position lineCurrent = styler.GetLine(startPos);
+       // Move back one line to be compatible with LexerModule::Fold behavior, fixes problem with 
foldComment behavior
+       if (lineCurrent > 0) {
+               lineCurrent--;
+               Sci_Position newStartPos = styler.LineStart(lineCurrent);
+               length += startPos - newStartPos;
+               startPos = newStartPos;
+               initStyle = 0;
+               if (startPos > 0) {
+                       initStyle = styler.StyleAt(startPos - 1);
+               }
+       }
+       Sci_PositionU endPos = startPos + length;
        int visibleChars = 0;
-       int lineCurrent = styler.GetLine(startPos);
        int levelCurrent = SC_FOLDLEVELBASE;
        if (lineCurrent > 0)
                levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
        int levelMinCurrent = levelCurrent;
        int levelNext = levelCurrent;
        char chNext = styler[startPos];
-       int styleNext = styler.StyleAt(startPos);
-       int style = initStyle;
-       for (unsigned int i = startPos; i < endPos; i++) {
+       int styleNext = MaskActive(styler.StyleAt(startPos));
+       int style = MaskActive(initStyle);
+
+       // restore fold state (if it exists) for prior line
+       int stateCurrent = 0;
+       std::map<Sci_Position,int>::iterator foldStateIterator = foldState.find(lineCurrent-1);
+       if (foldStateIterator != foldState.end()) {
+               stateCurrent = foldStateIterator->second;
+       }
+
+       // remove all foldState entries after lineCurrent-1
+       foldStateIterator = foldState.upper_bound(lineCurrent-1);
+       if (foldStateIterator != foldState.end()) {
+               foldState.erase(foldStateIterator, foldState.end());
+       }
+
+       for (Sci_PositionU i = startPos; i < endPos; i++) {
                char ch = chNext;
                chNext = styler.SafeGetCharAt(i + 1);
                int stylePrev = style;
                style = styleNext;
-               styleNext = styler.StyleAt(i + 1);
+               styleNext = MaskActive(styler.StyleAt(i + 1));
                bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
-               if (foldComment && IsStreamCommentStyle(style)) {
-                       if (!IsStreamCommentStyle(stylePrev)) {
-                               levelNext++;
-                       } else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
-                               // Comments don't end at end of line and the next character may be unstyled.
-                               levelNext--;
+               if (!(stateCurrent & protectedFlag)) {
+                       if (options.foldComment && IsStreamCommentStyle(style)) {
+                               if (!IsStreamCommentStyle(stylePrev)) {
+                                       levelNext++;
+                               } else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
+                                       // Comments don't end at end of line and the next character may be 
unstyled.
+                                       levelNext--;
+                               }
+                       }
+                       if (options.foldComment && atEOL && IsCommentLine(lineCurrent, styler))
+                       {
+                               if (!IsCommentLine(lineCurrent - 1, styler)
+                                       && IsCommentLine(lineCurrent + 1, styler))
+                                       levelNext++;
+                               else if (IsCommentLine(lineCurrent - 1, styler)
+                                                && !IsCommentLine(lineCurrent+1, styler))
+                                       levelNext--;
+                       }
+                       if (options.foldComment && (style == SCE_V_COMMENTLINE)) {
+                               if ((ch == '/') && (chNext == '/')) {
+                                       char chNext2 = styler.SafeGetCharAt(i + 2);
+                                       if (chNext2 == '{') {
+                                               levelNext++;
+                                       } else if (chNext2 == '}') {
+                                               levelNext--;
+                                       }
+                               }
                        }
                }
-               if (foldComment && atEOL && IsCommentLine(lineCurrent, styler))
-               {
-                       if (!IsCommentLine(lineCurrent - 1, styler)
-                           && IsCommentLine(lineCurrent + 1, styler))
+               if (ch == '`') {
+                       Sci_PositionU j = i + 1;
+                       while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
+                               j++;
+                       }
+                       if (styler.Match(j, "protected")) {
+                               stateCurrent |= protectedFlag;
                                levelNext++;
-                       else if (IsCommentLine(lineCurrent - 1, styler)
-                                && !IsCommentLine(lineCurrent+1, styler))
+                       } else if (styler.Match(j, "endprotected")) {
+                               stateCurrent &= ~protectedFlag;
                                levelNext--;
-               }
-               if (foldComment && (style == SCE_V_COMMENTLINE)) {
-                       if ((ch == '/') && (chNext == '/')) {
-                               char chNext2 = styler.SafeGetCharAt(i + 2);
-                               if (chNext2 == '{') {
+                       } else if (!(stateCurrent & protectedFlag) && options.foldPreprocessor && (style == 
SCE_V_PREPROCESSOR)) {
+                               if (styler.Match(j, "if")) {
+                                       if (options.foldPreprocessorElse) {
+                                               // Measure the minimum before a begin to allow
+                                               // folding on "end else begin"
+                                               if (levelMinCurrent > levelNext) {
+                                                       levelMinCurrent = levelNext;
+                                               }
+                                       }
+                                       levelNext++;
+                               } else if (options.foldPreprocessorElse && styler.Match(j, "else")) {
+                                       levelNext--;
+                                       if (levelMinCurrent > levelNext) {
+                                               levelMinCurrent = levelNext;
+                                       }
+                                       levelNext++;
+                               } else if (options.foldPreprocessorElse && styler.Match(j, "elsif")) {
+                                       levelNext--;
+                                       // Measure the minimum before a begin to allow
+                                       // folding on "end else begin"
+                                       if (levelMinCurrent > levelNext) {
+                                               levelMinCurrent = levelNext;
+                                       }
                                        levelNext++;
-                               } else if (chNext2 == '}') {
+                               } else if (styler.Match(j, "endif")) {
                                        levelNext--;
                                }
                        }
                }
-               if (foldPreprocessor && (style == SCE_V_PREPROCESSOR)) {
-                       if (ch == '`') {
-                               unsigned int j = i + 1;
-                               while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
-                                       j++;
-                               }
-                               if (styler.Match(j, "if")) {
+               if (style == SCE_V_OPERATOR) {
+                       if (foldAtParenthese) {
+                               if (ch == '(') {
                                        levelNext++;
-                               } else if (styler.Match(j, "end")) {
+                               } else if (ch == ')') {
                                        levelNext--;
                                }
                        }
-               }
-                if (style == SCE_V_OPERATOR) {
-                    if (foldAtParenthese) {
+                       // semicolons terminate external declarations
+                       if (ch == ';') {
+                               // extern and pure virtual declarations terminated by semicolon
+                               if (stateCurrent & foldExternFlag) {
+                                       levelNext--;
+                                       stateCurrent &= ~foldExternFlag;
+                               }
+                               // wait and disable statements terminated by semicolon
+                               if (stateCurrent & foldWaitDisableFlag) {
+                                       stateCurrent &= ~foldWaitDisableFlag;
+                               }
+                               // typedef statements terminated by semicolon
+                               if (stateCurrent & typedefFlag) {
+                                       stateCurrent &= ~typedefFlag;
+                               }
+                       }
+                       // wait and disable statements containing '(' will not contain "fork" keyword, 
special processing is not needed
                        if (ch == '(') {
-                               levelNext++;
-                       } else if (ch == ')') {
-                               levelNext--;
+                               if (stateCurrent & foldWaitDisableFlag) {
+                                       stateCurrent &= ~foldWaitDisableFlag;
+                               }
+                       }
+               }
+               if (style == SCE_V_OPERATOR) {
+                       if (foldAtBrace) {
+                               if (ch == '{') {
+                                       levelNext++;
+                               } else if (ch == '}') {
+                                       levelNext--;
+                               }
                        }
-                    }
                }
-                if (style == SCE_V_OPERATOR) {
-                    if (foldAtBrace) {
-                       if (ch == '{') {
+               if (style == SCE_V_WORD && stylePrev != SCE_V_WORD) {
+                       Sci_PositionU j = i;
+                       if (styler.Match(j, "case") ||
+                               styler.Match(j, "casex") ||
+                               styler.Match(j, "casez") ||
+                               styler.Match(j, "covergroup") ||
+                               styler.Match(j, "function") ||
+                               styler.Match(j, "generate") ||
+                               styler.Match(j, "interface") ||
+                               styler.Match(j, "package") ||
+                               styler.Match(j, "primitive") ||
+                               styler.Match(j, "program") ||
+                               styler.Match(j, "sequence") ||
+                               styler.Match(j, "specify") ||
+                               styler.Match(j, "table") ||
+                               styler.Match(j, "task") ||
+                               (styler.Match(j, "module") && options.foldAtModule)) {
+                               levelNext++;
+                       } else if (styler.Match(j, "begin")) {
+                               // Measure the minimum before a begin to allow
+                               // folding on "end else begin"
+                               if (levelMinCurrent > levelNext) {
+                                       levelMinCurrent = levelNext;
+                               }
                                levelNext++;
-                       } else if (ch == '}') {
+                       } else if (styler.Match(j, "class")) {
+                               // class does not introduce a block when used in a typedef statement
+                               if (!(stateCurrent & typedefFlag))
+                                       levelNext++;
+                       } else if (styler.Match(j, "fork")) {
+                               // fork does not introduce a block when used in a wait or disable statement
+                               if (stateCurrent & foldWaitDisableFlag) {
+                                       stateCurrent &= ~foldWaitDisableFlag;
+                               } else
+                                       levelNext++;
+                       } else if (styler.Match(j, "endcase") ||
+                               styler.Match(j, "endclass") ||
+                               styler.Match(j, "endfunction") ||
+                               styler.Match(j, "endgenerate") ||
+                               styler.Match(j, "endgroup") ||
+                               styler.Match(j, "endinterface") ||
+                               styler.Match(j, "endpackage") ||
+                               styler.Match(j, "endprimitive") ||
+                               styler.Match(j, "endprogram") ||
+                               styler.Match(j, "endsequence") ||
+                               styler.Match(j, "endspecify") ||
+                               styler.Match(j, "endtable") ||
+                               styler.Match(j, "endtask") ||
+                               styler.Match(j, "join") ||
+                               styler.Match(j, "join_any") ||
+                               styler.Match(j, "join_none") ||
+                               (styler.Match(j, "endmodule") && options.foldAtModule) ||
+                               (styler.Match(j, "end") && !IsAWordChar(styler.SafeGetCharAt(j + 3)))) {
                                levelNext--;
+                       } else if (styler.Match(j, "extern") ||
+                               styler.Match(j, "pure")) {
+                               // extern and pure virtual functions/tasks are terminated by ';' not 
endfunction/endtask
+                               stateCurrent |= foldExternFlag;
+                       } else if (styler.Match(j, "disable") ||
+                               styler.Match(j, "wait")) {
+                               // fork does not introduce a block when used in a wait or disable statement
+                               stateCurrent |= foldWaitDisableFlag;
+                       } else if (styler.Match(j, "typedef")) {
+                               stateCurrent |= typedefFlag;
                        }
-                    }
-               }
-                if (style == SCE_V_WORD && stylePrev != SCE_V_WORD) {
-                        unsigned int j = i;
-                        if (styler.Match(j, "case") ||
-                            styler.Match(j, "casex") ||
-                            styler.Match(j, "casez") ||
-                            styler.Match(j, "class") ||
-                            styler.Match(j, "function") ||
-                            styler.Match(j, "generate") ||
-                            styler.Match(j, "covergroup") ||
-                            styler.Match(j, "package") ||
-                            styler.Match(j, "primitive") ||
-                            styler.Match(j, "program") ||
-                            styler.Match(j, "sequence") ||
-                            styler.Match(j, "specify") ||
-                            styler.Match(j, "table") ||
-                            styler.Match(j, "task") ||
-                            styler.Match(j, "fork") ||
-                            (styler.Match(j, "module") && foldAtModule) ||
-                            styler.Match(j, "begin")) {
-                                levelNext++;
-                        } else if (styler.Match(j, "endcase") ||
-                                   styler.Match(j, "endclass") ||
-                                   styler.Match(j, "endfunction") ||
-                                   styler.Match(j, "endgenerate") ||
-                                   styler.Match(j, "endgroup") ||
-                                   styler.Match(j, "endpackage") ||
-                                   styler.Match(j, "endprimitive") ||
-                                   styler.Match(j, "endprogram") ||
-                                   styler.Match(j, "endsequence") ||
-                                   styler.Match(j, "endspecify") ||
-                                   styler.Match(j, "endtable") ||
-                                   styler.Match(j, "endtask") ||
-                                   styler.Match(j, "join") ||
-                                   styler.Match(j, "join_any") ||
-                                   styler.Match(j, "join_none") ||
-                                   (styler.Match(j, "endmodule") && foldAtModule) ||
-                                   (styler.Match(j, "end") && !IsAWordChar(styler.SafeGetCharAt(j+3)))) {
-                                levelNext--;
-                        }
                }
                if (atEOL) {
                        int levelUse = levelCurrent;
-                       if (foldAtElse) {
+                       if (options.foldAtElse||options.foldPreprocessorElse) {
                                levelUse = levelMinCurrent;
                        }
                        int lev = levelUse | levelNext << 16;
-                       if (visibleChars == 0 && foldCompact)
+                       if (visibleChars == 0 && options.foldCompact)
                                lev |= SC_FOLDLEVELWHITEFLAG;
                        if (levelUse < levelNext)
                                lev |= SC_FOLDLEVELHEADERFLAG;
+                       if (stateCurrent) {
+                               foldState[lineCurrent] = stateCurrent;
+                       }
                        if (lev != styler.LevelAt(lineCurrent)) {
                                styler.SetLevel(lineCurrent, lev);
                        }
@@ -327,9 +1034,31 @@ static void FoldNoBoxVerilogDoc(unsigned int startPos, int length, int initStyle
        }
 }
 
-static void FoldVerilogDoc(unsigned int startPos, int length, int initStyle, WordList *[],
-                       Accessor &styler) {
-       FoldNoBoxVerilogDoc(startPos, length, initStyle, styler);
+std::vector<std::string> LexerVerilog::Tokenize(const std::string &expr) const {
+       // Break into tokens
+       std::vector<std::string> tokens;
+       const char *cp = expr.c_str();
+       while (*cp) {
+               std::string word;
+               if (setWord.Contains(static_cast<unsigned char>(*cp))) {
+                       // Identifiers and numbers
+                       while (setWord.Contains(static_cast<unsigned char>(*cp))) {
+                               word += *cp;
+                               cp++;
+                       }
+               } else if (IsSpaceOrTab(*cp)) {
+                       while (IsSpaceOrTab(*cp)) {
+                               cp++;
+                       }
+                       continue;
+               } else {
+                       // Should handle strings, characters, and comments here
+                       word += *cp;
+                       cp++;
+               }
+               tokens.push_back(word);
+       }
+       return tokens;
 }
 
 static const char * const verilogWordLists[] = {
@@ -337,9 +1066,9 @@ static const char * const verilogWordLists[] = {
             "Secondary keywords and identifiers",
             "System Tasks",
             "User defined tasks and identifiers",
-            "Unused",
+            "Documentation comment keywords",
+            "Preprocessor definitions",
             0,
         };
 
-
-LexerModule lmVerilog(SCLEX_VERILOG, ColouriseVerilogDoc, "verilog", FoldVerilogDoc, verilogWordLists);
+LexerModule lmVerilog(SCLEX_VERILOG, LexerVerilog::LexerFactoryVerilog, "verilog", verilogWordLists);
diff --git a/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx 
b/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx
index 8a7495b..6c61c18 100644
--- a/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx
@@ -7,12 +7,16 @@
 // Copyright 1998-2005 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+// The line state contains:
+// In SCE_VISUALPROLOG_STRING_VERBATIM_EOL (i.e. multiline string literal): The closingQuote.
+// else (for SCE_VISUALPROLOG_COMMENT_BLOCK): The comment nesting level
+
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h>
 #include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <ctype.h>
 
 #ifdef _MSC_VER
 #pragma warning(disable: 4786)
@@ -32,6 +36,7 @@
 #include "Accessor.h"
 #include "StyleContext.h"
 #include "CharacterSet.h"
+#include "CharacterCategory.h"
 #include "LexerModule.h"
 #include "OptionSet.h"
 
@@ -71,30 +76,30 @@ public:
     }
     virtual ~LexerVisualProlog() {
     }
-    void SCI_METHOD Release() {
+    void SCI_METHOD Release() override {
         delete this;
     }
-    int SCI_METHOD Version() const {
+    int SCI_METHOD Version() const override {
         return lvOriginal;
     }
-    const char * SCI_METHOD PropertyNames() {
+    const char * SCI_METHOD PropertyNames() override {
         return osVisualProlog.PropertyNames();
     }
-    int SCI_METHOD PropertyType(const char *name) {
+    int SCI_METHOD PropertyType(const char *name) override {
         return osVisualProlog.PropertyType(name);
     }
-    const char * SCI_METHOD DescribeProperty(const char *name) {
+    const char * SCI_METHOD DescribeProperty(const char *name) override {
         return osVisualProlog.DescribeProperty(name);
     }
-    int SCI_METHOD PropertySet(const char *key, const char *val);
-    const char * SCI_METHOD DescribeWordListSets() {
+    Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
+    const char * SCI_METHOD DescribeWordListSets() override {
         return osVisualProlog.DescribeWordListSets();
     }
-    int SCI_METHOD WordListSet(int n, const char *wl);
-    void SCI_METHOD Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
-    void SCI_METHOD Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess);
+    Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
+    void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
+    void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) 
override;
 
-    void * SCI_METHOD PrivateCall(int, void *) {
+    void * SCI_METHOD PrivateCall(int, void *) override {
         return 0;
     }
 
@@ -103,14 +108,14 @@ public:
     }
 };
 
-int SCI_METHOD LexerVisualProlog::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerVisualProlog::PropertySet(const char *key, const char *val) {
     if (osVisualProlog.PropertySet(&options, key, val)) {
         return 0;
     }
     return -1;
 }
 
-int SCI_METHOD LexerVisualProlog::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerVisualProlog::WordListSet(int n, const char *wl) {
     WordList *wordListN = 0;
     switch (n) {
     case 0:
@@ -126,7 +131,7 @@ int SCI_METHOD LexerVisualProlog::WordListSet(int n, const char *wl) {
         wordListN = &docKeywords;
         break;
     }
-    int firstModification = -1;
+    Sci_Position firstModification = -1;
     if (wordListN) {
         WordList wlNew;
         wlNew.Set(wl);
@@ -140,19 +145,82 @@ int SCI_METHOD LexerVisualProlog::WordListSet(int n, const char *wl) {
 
 // Functor used to truncate history
 struct After {
-    int line;
-    After(int line_) : line(line_) {}
+    Sci_Position line;
+    After(Sci_Position line_) : line(line_) {}
 };
 
+static bool isLowerLetter(int ch){
+    return ccLl == CategoriseCharacter(ch);
+}
+
+static bool isUpperLetter(int ch){
+    return ccLu == CategoriseCharacter(ch);
+}
+
+static bool isAlphaNum(int ch){
+    CharacterCategory cc = CategoriseCharacter(ch);
+    return (ccLu == cc || ccLl == cc || ccLt == cc || ccLm == cc || ccLo == cc || ccNd == cc || ccNl == cc 
|| ccNo == cc);
+}
+
+static bool isStringVerbatimOpenClose(int ch){
+    CharacterCategory cc = CategoriseCharacter(ch);
+    return (ccPc <= cc && cc <= ccSo);
+}
+
+static bool isIdChar(int ch){
+    return ('_') == ch || isAlphaNum(ch);
+}
+
+static bool isOpenStringVerbatim(int next, int &closingQuote){
+    switch (next) {
+    case L'<':
+        closingQuote = L'>';
+        return true;
+    case L'>':
+        closingQuote = L'<';
+        return true;
+    case L'(':
+        closingQuote = L')';
+        return true;
+    case L')':
+        closingQuote = L'(';
+        return true;
+    case L'[':
+        closingQuote = L']';
+        return true;
+    case L']':
+        closingQuote = L'[';
+        return true;
+    case L'{':
+        closingQuote = L'}';
+        return true;
+    case L'}':
+        closingQuote = L'{';
+        return true;
+    case L'_':
+    case L'.':
+    case L',':
+    case L';':
+        return false;
+    default:
+        if (isStringVerbatimOpenClose(next)) {
+            closingQuote = next;
+            return true;
+        } else {
+                       return false;
+        }
+    }
+}
+
 // Look ahead to see which colour "end" should have (takes colour after the following keyword)
-static void endLookAhead(char s[], LexAccessor &styler, int start, CharacterSet &setIdentifier) {
+static void endLookAhead(char s[], LexAccessor &styler, Sci_Position start) {
     char ch = styler.SafeGetCharAt(start, '\n');
     while (' ' == ch) {
         start++;
         ch = styler.SafeGetCharAt(start, '\n');
     }
-    int i = 0;
-    while (i < 100 && setIdentifier.Contains(ch)){
+    Sci_Position i = 0;
+    while (i < 100 && isLowerLetter(ch)){
         s[i] = ch;
         i++;
         ch = styler.SafeGetCharAt(start + i, '\n');
@@ -160,11 +228,11 @@ static void endLookAhead(char s[], LexAccessor &styler, int start, CharacterSet
     s[i] = '\0';
 }
 
-static void forwardEscapeLiteral(StyleContext &sc, int OwnChar, int EscapeState) {
+static void forwardEscapeLiteral(StyleContext &sc, int EscapeState) {
     sc.Forward();
-    if (sc.ch == OwnChar || sc.ch == '\\' || sc.ch == 'n' || sc.ch == 'l' || sc.ch == 'r' || sc.ch == 't') {
+    if (sc.Match('"') || sc.Match('\'') || sc.Match('\\') || sc.Match('n') || sc.Match('l') || sc.Match('r') 
|| sc.Match('t')) {
         sc.ChangeState(EscapeState);
-    } else if (sc.ch == 'u') {
+    } else if (sc.Match('u')) {
         if (IsADigit(sc.chNext, 16)) {
             sc.Forward();
             if (IsADigit(sc.chNext, 16)) {
@@ -181,47 +249,28 @@ static void forwardEscapeLiteral(StyleContext &sc, int OwnChar, int EscapeState)
     }
 }
 
-void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) 
{
+void SCI_METHOD LexerVisualProlog::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument 
*pAccess) {
     LexAccessor styler(pAccess);
+    CharacterSet setDoxygen(CharacterSet::setAlpha, "");
+    CharacterSet setNumber(CharacterSet::setNone, "0123456789abcdefABCDEFxoXO");
 
-    CharacterSet setDoxygen(CharacterSet::setAlpha, "$@\\&<>#{}[]");
-
-    CharacterSet setLowerStart(CharacterSet::setLower);
-    CharacterSet setVariableStart(CharacterSet::setUpper);
-    CharacterSet setIdentifier(CharacterSet::setAlphaNum, "_", 0x80, true);
+    StyleContext sc(startPos, length, initStyle, styler, 0x7f);
 
     int styleBeforeDocKeyword = SCE_VISUALPROLOG_DEFAULT;
+    Sci_Position currentLine = styler.GetLine(startPos);
 
-    int currentLine = styler.GetLine(startPos);
-
+    int closingQuote = '"';
     int nestLevel = 0;
     if (currentLine >= 1)
     {
         nestLevel = styler.GetLineState(currentLine - 1);
+        closingQuote = nestLevel;
     }
 
-    StyleContext sc(startPos, length, initStyle, styler, 0x7f);
-
     // Truncate ppDefineHistory before current line
 
     for (; sc.More(); sc.Forward()) {
 
-        if (sc.atLineEnd) {
-            // Update the line state, so it can be seen by next line
-            styler.SetLineState(currentLine, nestLevel);
-            currentLine++;
-        }
-
-        if (sc.atLineStart) {
-            if ((sc.state == SCE_VISUALPROLOG_STRING) || (sc.state == SCE_VISUALPROLOG_CHARACTER)) {
-                // Prevent SCE_VISUALPROLOG_STRING_EOL from leaking back to previous line which
-                // ends with a line continuation by locking in the state upto this position.
-                sc.SetState(sc.state);
-            }
-        }
-
-        const bool atLineEndBeforeSwitch = sc.atLineEnd;
-
         // Determine if the current state should terminate.
         switch (sc.state) {
         case SCE_VISUALPROLOG_OPERATOR:
@@ -229,16 +278,16 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
             break;
         case SCE_VISUALPROLOG_NUMBER:
             // We accept almost anything because of hex. and number suffixes
-            if (!(setIdentifier.Contains(sc.ch) || (sc.ch == '.') || ((sc.ch == '+' || sc.ch == '-') && 
(sc.chPrev == 'e' || sc.chPrev == 'E')))) {
+            if (!(setNumber.Contains(sc.ch)) || (sc.Match('.') && IsADigit(sc.chNext))) {
                 sc.SetState(SCE_VISUALPROLOG_DEFAULT);
             }
             break;
         case SCE_VISUALPROLOG_IDENTIFIER:
-            if (!setIdentifier.Contains(sc.ch)) {
+            if (!isIdChar(sc.ch)) {
                 char s[1000];
                 sc.GetCurrent(s, sizeof(s));
                 if (0 == strcmp(s, "end")) {
-                    endLookAhead(s, styler, sc.currentPos, setIdentifier);
+                    endLookAhead(s, styler, sc.currentPos);
                 }
                 if (majorKeywords.InList(s)) {
                     sc.ChangeState(SCE_VISUALPROLOG_KEY_MAJOR);
@@ -250,12 +299,12 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
             break;
         case SCE_VISUALPROLOG_VARIABLE:
         case SCE_VISUALPROLOG_ANONYMOUS:
-            if (!setIdentifier.Contains(sc.ch)) {
+            if (!isIdChar(sc.ch)) {
                 sc.SetState(SCE_VISUALPROLOG_DEFAULT);
             }
             break;
         case SCE_VISUALPROLOG_KEY_DIRECTIVE:
-            if (!setLowerStart.Contains(sc.ch)) {
+            if (!isLowerLetter(sc.ch)) {
                 char s[1000];
                 sc.GetCurrent(s, sizeof(s));
                 if (!directiveKeywords.InList(s+1)) {
@@ -273,9 +322,7 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
             } else if (sc.Match('/', '*')) {
                 sc.Forward();
                 nestLevel++;
-            } else if (sc.ch == '%') {
-                sc.SetState(SCE_VISUALPROLOG_COMMENT_LINE);
-            } else if (sc.ch == '@') {
+            } else if (sc.Match('@')) {
                 styleBeforeDocKeyword = sc.state;
                 sc.SetState(SCE_VISUALPROLOG_COMMENT_KEY_ERROR);
             }
@@ -284,24 +331,34 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
             if (sc.atLineEnd) {
                 int nextState = (nestLevel == 0) ? SCE_VISUALPROLOG_DEFAULT : SCE_VISUALPROLOG_COMMENT_BLOCK;
                 sc.SetState(nextState);
-            } else if (sc.ch == '@') {
+            } else if (sc.Match('@')) {
                 styleBeforeDocKeyword = sc.state;
                 sc.SetState(SCE_VISUALPROLOG_COMMENT_KEY_ERROR);
             }
             break;
         case SCE_VISUALPROLOG_COMMENT_KEY_ERROR:
-            if (!setDoxygen.Contains(sc.ch)) {
+            if (!setDoxygen.Contains(sc.ch) || sc.atLineEnd) {
                 char s[1000];
                 sc.GetCurrent(s, sizeof(s));
                 if (docKeywords.InList(s+1)) {
                     sc.ChangeState(SCE_VISUALPROLOG_COMMENT_KEY);
                 }
-                sc.SetState(styleBeforeDocKeyword);
-            }
-            if (SCE_VISUALPROLOG_COMMENT_LINE == styleBeforeDocKeyword && sc.atLineStart) {
-                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
-            } else if (SCE_VISUALPROLOG_COMMENT_BLOCK == styleBeforeDocKeyword && sc.atLineStart) {
-                sc.SetState(SCE_VISUALPROLOG_COMMENT_BLOCK);
+                if (SCE_VISUALPROLOG_COMMENT_LINE == styleBeforeDocKeyword && sc.atLineEnd) {
+                    // end line comment
+                    int nextState = (nestLevel == 0) ? SCE_VISUALPROLOG_DEFAULT : 
SCE_VISUALPROLOG_COMMENT_BLOCK;
+                    sc.SetState(nextState);
+                } else {
+                    sc.SetState(styleBeforeDocKeyword);
+                    if (SCE_VISUALPROLOG_COMMENT_BLOCK == styleBeforeDocKeyword && sc.Match('*', '/')) {
+                        // we have consumed the '*' if it comes immediately after the docKeyword
+                        sc.Forward();
+                        sc.Forward();
+                        nestLevel--;
+                        if (0 == nestLevel) {
+                            sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+                        }
+                    }
+                }
             }
             break;
         case SCE_VISUALPROLOG_STRING_ESCAPE:
@@ -311,38 +368,11 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
         case SCE_VISUALPROLOG_STRING:
             if (sc.atLineEnd) {
                 sc.SetState(SCE_VISUALPROLOG_STRING_EOL_OPEN);
-            } else if (sc.ch == '"') {
+            } else if (sc.Match(closingQuote)) {
                 sc.ForwardSetState(SCE_VISUALPROLOG_DEFAULT);
-            } else if (sc.ch == '\\') {
+            } else if (sc.Match('\\')) {
                 sc.SetState(SCE_VISUALPROLOG_STRING_ESCAPE_ERROR);
-                forwardEscapeLiteral(sc, '"', SCE_VISUALPROLOG_STRING_ESCAPE);
-            }
-            break;
-        case SCE_VISUALPROLOG_CHARACTER_TOO_MANY:
-            if (sc.atLineStart) {
-                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
-            } else if (sc.ch == '\'') {
-                sc.SetState(SCE_VISUALPROLOG_CHARACTER);
-                sc.ForwardSetState(SCE_VISUALPROLOG_DEFAULT);
-            }
-            break;
-        case SCE_VISUALPROLOG_CHARACTER:
-            if (sc.atLineEnd) {
-                sc.SetState(SCE_VISUALPROLOG_STRING_EOL_OPEN);  // reuse STRING_EOL_OPEN for this
-            } else if (sc.ch == '\'') {
-                sc.SetState(SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR);
-                sc.ForwardSetState(SCE_VISUALPROLOG_DEFAULT);
-            } else {
-                if (sc.ch == '\\') {
-                    sc.SetState(SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR);
-                    forwardEscapeLiteral(sc, '\'', SCE_VISUALPROLOG_CHARACTER);
-                } 
-                sc.ForwardSetState(SCE_VISUALPROLOG_CHARACTER);
-                if (sc.ch == '\'') {
-                    sc.ForwardSetState(SCE_VISUALPROLOG_DEFAULT);
-                } else {
-                    sc.SetState(SCE_VISUALPROLOG_CHARACTER_TOO_MANY);
-                }
+                forwardEscapeLiteral(sc, SCE_VISUALPROLOG_STRING_ESCAPE);
             }
             break;
         case SCE_VISUALPROLOG_STRING_EOL_OPEN:
@@ -357,8 +387,8 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
         case SCE_VISUALPROLOG_STRING_VERBATIM:
             if (sc.atLineEnd) {
                 sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM_EOL);
-            } else if (sc.ch == '\"') {
-                if (sc.chNext == '\"') {
+            } else if (sc.Match(closingQuote)) {
+                if (closingQuote == sc.chNext) {
                     sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL);
                     sc.Forward();
                 } else {
@@ -368,37 +398,46 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
             break;
         }
 
-        if (sc.atLineEnd && !atLineEndBeforeSwitch) {
-            // State exit processing consumed characters up to end of line.
+        if (sc.atLineEnd) {
+            // Update the line state, so it can be seen by next line
+            int lineState = 0;
+            if (SCE_VISUALPROLOG_STRING_VERBATIM_EOL == sc.state) {
+                lineState = closingQuote;
+            } else if (SCE_VISUALPROLOG_COMMENT_BLOCK == sc.state) {
+                lineState = nestLevel;
+            }
+            styler.SetLineState(currentLine, lineState);
             currentLine++;
         }
 
         // Determine if a new state should be entered.
         if (sc.state == SCE_VISUALPROLOG_DEFAULT) {
-            if (sc.Match('@', '\"')) {
+            if (sc.Match('@') && isOpenStringVerbatim(sc.chNext, closingQuote)) {
                 sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM);
                 sc.Forward();
-            } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+            } else if (IsADigit(sc.ch) || (sc.Match('.') && IsADigit(sc.chNext))) {
                 sc.SetState(SCE_VISUALPROLOG_NUMBER);
-            } else if (setLowerStart.Contains(sc.ch)) {
+            } else if (isLowerLetter(sc.ch)) {
                 sc.SetState(SCE_VISUALPROLOG_IDENTIFIER);
-            } else if (setVariableStart.Contains(sc.ch)) {
+            } else if (isUpperLetter(sc.ch)) {
                 sc.SetState(SCE_VISUALPROLOG_VARIABLE);
-            } else if (sc.ch == '_') {
+            } else if (sc.Match('_')) {
                 sc.SetState(SCE_VISUALPROLOG_ANONYMOUS);
             } else if (sc.Match('/', '*')) {
                 sc.SetState(SCE_VISUALPROLOG_COMMENT_BLOCK);
                 nestLevel = 1;
                 sc.Forward();  // Eat the * so it isn't used for the end of the comment
-            } else if (sc.ch == '%') {
+            } else if (sc.Match('%')) {
                 sc.SetState(SCE_VISUALPROLOG_COMMENT_LINE);
-            } else if (sc.ch == '\"') {
+            } else if (sc.Match('\'')) {
+                closingQuote = '\'';
+                sc.SetState(SCE_VISUALPROLOG_STRING);
+            } else if (sc.Match('"')) {
+                closingQuote = '"';
                 sc.SetState(SCE_VISUALPROLOG_STRING);
-            } else if (sc.ch == '\'') {
-                sc.SetState(SCE_VISUALPROLOG_CHARACTER);
-            } else if (sc.ch == '#') {
+            } else if (sc.Match('#')) {
                 sc.SetState(SCE_VISUALPROLOG_KEY_DIRECTIVE);
-            } else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '\\') {
+            } else if (isoperator(static_cast<char>(sc.ch)) || sc.Match('\\')) {
                 sc.SetState(SCE_VISUALPROLOG_OPERATOR);
             }
         }
@@ -412,13 +451,13 @@ void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int in
 // level store to make it easy to pick up with each increment
 // and to make it possible to fiddle the current level for "} else {".
 
-void SCI_METHOD LexerVisualProlog::Fold(unsigned int startPos, int length, int initStyle, IDocument 
*pAccess) {
+void SCI_METHOD LexerVisualProlog::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, 
IDocument *pAccess) {
 
     LexAccessor styler(pAccess);
 
-    unsigned int endPos = startPos + length;
+    Sci_PositionU endPos = startPos + length;
     int visibleChars = 0;
-    int currentLine = styler.GetLine(startPos);
+    Sci_Position currentLine = styler.GetLine(startPos);
     int levelCurrent = SC_FOLDLEVELBASE;
     if (currentLine > 0)
         levelCurrent = styler.LevelAt(currentLine-1) >> 16;
@@ -427,7 +466,7 @@ void SCI_METHOD LexerVisualProlog::Fold(unsigned int startPos, int length, int i
     char chNext = styler[startPos];
     int styleNext = styler.StyleAt(startPos);
     int style = initStyle;
-    for (unsigned int i = startPos; i < endPos; i++) {
+    for (Sci_PositionU i = startPos; i < endPos; i++) {
         char ch = chNext;
         chNext = styler.SafeGetCharAt(i + 1);
         style = styleNext;
@@ -458,7 +497,7 @@ void SCI_METHOD LexerVisualProlog::Fold(unsigned int startPos, int length, int i
             currentLine++;
             levelCurrent = levelNext;
             levelMinCurrent = levelCurrent;
-            if (atEOL && (i == static_cast<unsigned int>(styler.Length()-1))) {
+            if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length()-1))) {
                 // There is an empty line at end of file so give it same level and empty
                 styler.SetLevel(currentLine, (levelCurrent | levelCurrent << 16) | SC_FOLDLEVELWHITEFLAG);
             }
diff --git a/plugins/scintilla/scintilla/lexers/LexYAML.cxx b/plugins/scintilla/scintilla/lexers/LexYAML.cxx
index c808d97..3709538 100644
--- a/plugins/scintilla/scintilla/lexers/LexYAML.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexYAML.cxx
@@ -32,7 +32,7 @@ static const char * const yamlWordListDesc[] = {
        0
 };
 
-static inline bool AtEOL(Accessor &styler, unsigned int i) {
+static inline bool AtEOL(Accessor &styler, Sci_PositionU i) {
        return (styler[i] == '\n') ||
                ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n'));
 }
@@ -46,27 +46,42 @@ static unsigned int SpaceCount(char* lineBuffer) {
        while (*headBuffer == ' ')
                headBuffer++;
 
-       return headBuffer - lineBuffer;
+       return static_cast<unsigned int>(headBuffer - lineBuffer);
 }
 
-#define YAML_STATE_BITSIZE 16
+static bool KeywordAtChar(char* lineBuffer, char* startComment, const WordList &keywords) {
+       if (lineBuffer == NULL || startComment <= lineBuffer)
+               return false;
+       char* endValue = startComment - 1;
+       while (endValue >= lineBuffer && *endValue == ' ')
+               endValue--;
+       Sci_PositionU len = static_cast<Sci_PositionU>(endValue - lineBuffer) + 1;
+       char s[100];
+       if (len > (sizeof(s) / sizeof(s[0]) - 1))
+               return false;
+       strncpy(s, lineBuffer, len);
+       s[len] = '\0';
+       return (keywords.InList(s));
+}
+
+#define YAML_STATE_BITSIZE             16
 #define YAML_STATE_MASK                        (0xFFFF0000)
 #define YAML_STATE_DOCUMENT            (1 << YAML_STATE_BITSIZE)
-#define YAML_STATE_VALUE                       (2 << YAML_STATE_BITSIZE)
+#define YAML_STATE_VALUE               (2 << YAML_STATE_BITSIZE)
 #define YAML_STATE_COMMENT             (3 << YAML_STATE_BITSIZE)
 #define YAML_STATE_TEXT_PARENT (4 << YAML_STATE_BITSIZE)
 #define YAML_STATE_TEXT                        (5 << YAML_STATE_BITSIZE)
 
 static void ColouriseYAMLLine(
        char *lineBuffer,
-       unsigned int currentLine,
-       unsigned int lengthLine,
-       unsigned int startLine,
-       unsigned int endPos,
+       Sci_PositionU currentLine,
+       Sci_PositionU lengthLine,
+       Sci_PositionU startLine,
+       Sci_PositionU endPos,
        WordList &keywords,
        Accessor &styler) {
 
-       unsigned int i = 0;
+       Sci_PositionU i = 0;
        bool bInQuotes = false;
        unsigned int indentAmount = SpaceCount(lineBuffer);
 
@@ -83,7 +98,7 @@ static void ColouriseYAMLLine(
                }
        }
        styler.SetLineState(currentLine, 0);
-       if (strncmp(lineBuffer, "---", 3) == 0) {       // Document marker
+       if (strncmp(lineBuffer, "---", 3) == 0 || strncmp(lineBuffer, "...", 3) == 0) { // Document marker
                styler.SetLineState(currentLine, YAML_STATE_DOCUMENT);
                styler.ColourTo(endPos, SCE_YAML_DOCUMENT);
                return;
@@ -104,6 +119,10 @@ static void ColouriseYAMLLine(
        while (i < lengthLine) {
                if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') {
                        bInQuotes = !bInQuotes;
+               } else if (lineBuffer[i] == '#' && isspacechar(lineBuffer[i - 1]) && !bInQuotes) {
+                       styler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT);
+                       styler.ColourTo(endPos, SCE_YAML_COMMENT);
+                       return;
                } else if (lineBuffer[i] == ':' && !bInQuotes) {
                        styler.ColourTo(startLine + i - 1, SCE_YAML_IDENTIFIER);
                        styler.ColourTo(startLine + i, SCE_YAML_OPERATOR);
@@ -111,7 +130,7 @@ static void ColouriseYAMLLine(
                        i++;
                        while ((i < lengthLine) && isspacechar(lineBuffer[i]))
                                i++;
-                       unsigned int endValue = lengthLine - 1;
+                       Sci_PositionU endValue = lengthLine - 1;
                        while ((endValue >= i) && isspacechar(lineBuffer[endValue]))
                                endValue--;
                        lineBuffer[endValue + 1] = '\0';
@@ -139,27 +158,44 @@ static void ColouriseYAMLLine(
                                styler.ColourTo(endPos, SCE_YAML_COMMENT);
                                return;
                        }
+                       Sci_PositionU startComment = i;
+                       bInQuotes = false;
+                       while (startComment < lengthLine) { // Comment must be space padded
+                               if (lineBuffer[startComment] == '\'' || lineBuffer[startComment] == '\"')
+                                       bInQuotes = !bInQuotes;
+                               if (lineBuffer[startComment] == '#' && isspacechar(lineBuffer[startComment - 
1]) && !bInQuotes)
+                                       break;
+                               startComment++;
+                       }
                        styler.SetLineState(currentLine, YAML_STATE_VALUE);
                        if (lineBuffer[i] == '&' || lineBuffer[i] == '*') {
-                               styler.ColourTo(endPos, SCE_YAML_REFERENCE);
+                               styler.ColourTo(startLine + startComment - 1, SCE_YAML_REFERENCE);
+                               if (startComment < lengthLine)
+                                       styler.ColourTo(endPos, SCE_YAML_COMMENT);
                                return;
                        }
-                       if (keywords.InList(&lineBuffer[i])) { // Convertible value (true/false, etc.)
-                               styler.ColourTo(endPos, SCE_YAML_KEYWORD);
+                       if (KeywordAtChar(&lineBuffer[i], &lineBuffer[startComment], keywords)) { // 
Convertible value (true/false, etc.)
+                               styler.ColourTo(startLine + startComment - 1, SCE_YAML_KEYWORD);
+                               if (startComment < lengthLine)
+                                       styler.ColourTo(endPos, SCE_YAML_COMMENT);
                                return;
-                       } else {
-                               unsigned int i2 = i;
-                               while ((i < lengthLine) && lineBuffer[i]) {
-                                       if (!(isascii(lineBuffer[i]) && isdigit(lineBuffer[i])) && 
lineBuffer[i] != '-' && lineBuffer[i] != '.' && lineBuffer[i] != ',') {
-                                               styler.ColourTo(endPos, SCE_YAML_DEFAULT);
-                                               return;
-                                       }
-                                       i++;
-                               }
-                               if (i > i2) {
-                                       styler.ColourTo(endPos, SCE_YAML_NUMBER);
+                       }
+                       Sci_PositionU i2 = i;
+                       while ((i < startComment) && lineBuffer[i]) {
+                               if (!(IsASCII(lineBuffer[i]) && isdigit(lineBuffer[i])) && lineBuffer[i] != 
'-'
+                                       && lineBuffer[i] != '.' && lineBuffer[i] != ',' && lineBuffer[i] != ' 
') {
+                                       styler.ColourTo(startLine + startComment - 1, SCE_YAML_DEFAULT);
+                                       if (startComment < lengthLine)
+                                               styler.ColourTo(endPos, SCE_YAML_COMMENT);
                                        return;
                                }
+                               i++;
+                       }
+                       if (i > i2) {
+                               styler.ColourTo(startLine + startComment - 1, SCE_YAML_NUMBER);
+                               if (startComment < lengthLine)
+                                       styler.ColourTo(endPos, SCE_YAML_COMMENT);
+                               return;
                        }
                        break; // shouldn't get here, but just in case, the rest of the line is coloured the 
default
                }
@@ -168,17 +204,17 @@ static void ColouriseYAMLLine(
        styler.ColourTo(endPos, SCE_YAML_DEFAULT);
 }
 
-static void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor 
&styler) {
+static void ColouriseYAMLDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], 
Accessor &styler) {
        char lineBuffer[1024] = "";
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
-       unsigned int linePos = 0;
-       unsigned int startLine = startPos;
-       unsigned int endPos = startPos + length;
-       unsigned int maxPos = styler.Length();
-       unsigned int lineCurrent = styler.GetLine(startPos);
+       Sci_PositionU linePos = 0;
+       Sci_PositionU startLine = startPos;
+       Sci_PositionU endPos = startPos + length;
+       Sci_PositionU maxPos = styler.Length();
+       Sci_PositionU lineCurrent = styler.GetLine(startPos);
 
-       for (unsigned int i = startPos; i < maxPos && i < endPos; i++) {
+       for (Sci_PositionU i = startPos; i < maxPos && i < endPos; i++) {
                lineBuffer[linePos++] = styler[i];
                if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {
                        // End of line (or of line buffer) met, colourise it
@@ -194,18 +230,18 @@ static void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *k
        }
 }
 
-static bool IsCommentLine(int line, Accessor &styler) {
-       int pos = styler.LineStart(line);
+static bool IsCommentLine(Sci_Position line, Accessor &styler) {
+       Sci_Position pos = styler.LineStart(line);
        if (styler[pos] == '#')
                return true;
        return false;
 }
 
-static void FoldYAMLDoc(unsigned int startPos, int length, int /*initStyle - unused*/,
+static void FoldYAMLDoc(Sci_PositionU startPos, Sci_Position length, int /*initStyle - unused*/,
                       WordList *[], Accessor &styler) {
-       const int maxPos = startPos + length;
-       const int maxLines = styler.GetLine(maxPos - 1);             // Requested last line
-       const int docLines = styler.GetLine(styler.Length() - 1);  // Available last line
+       const Sci_Position maxPos = startPos + length;
+       const Sci_Position maxLines = styler.GetLine(maxPos - 1);             // Requested last line
+       const Sci_Position docLines = styler.GetLine(styler.Length() - 1);  // Available last line
        const bool foldComment = styler.GetPropertyInt("fold.comment.yaml") != 0;
 
        // Backtrack to previous non-blank line so we can determine indent level
@@ -213,7 +249,7 @@ static void FoldYAMLDoc(unsigned int startPos, int length, int /*initStyle - unu
        // and so we can fix any preceding fold level (which is why we go back
        // at least one line in all cases)
        int spaceFlags = 0;
-       int lineCurrent = styler.GetLine(startPos);
+       Sci_Position lineCurrent = styler.GetLine(startPos);
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
        while (lineCurrent > 0) {
                lineCurrent--;
@@ -236,12 +272,12 @@ static void FoldYAMLDoc(unsigned int startPos, int length, int /*initStyle - unu
 
                // Gather info
                int lev = indentCurrent;
-               int lineNext = lineCurrent + 1;
+               Sci_Position lineNext = lineCurrent + 1;
                int indentNext = indentCurrent;
                if (lineNext <= docLines) {
                        // Information about next line is only available if not at end of document
                        indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);
-       }
+               }
                const int comment = foldComment && IsCommentLine(lineCurrent, styler);
                const int comment_start = (comment && !prevComment && (lineNext <= docLines) &&
                                           IsCommentLine(lineNext, styler) && (lev > SC_FOLDLEVELBASE));
@@ -280,7 +316,7 @@ static void FoldYAMLDoc(unsigned int startPos, int length, int /*initStyle - unu
                // which is indented more than the line after the end of
                // the comment-block, use the level of the block before
 
-               int skipLine = lineNext;
+               Sci_Position skipLine = lineNext;
                int skipLevel = levelAfterComments;
 
                while (--skipLine > lineCurrent) {
diff --git a/plugins/scintilla/scintilla/lexlib/Accessor.cxx b/plugins/scintilla/scintilla/lexlib/Accessor.cxx
index f67737d..2e51fa3 100644
--- a/plugins/scintilla/scintilla/lexlib/Accessor.cxx
+++ b/plugins/scintilla/scintilla/lexlib/Accessor.cxx
@@ -1,16 +1,12 @@
 // Scintilla source code edit control
-/** @file KeyWords.cxx
- ** Colourise for particular languages.
+/** @file Accessor.cxx
+ ** Interfaces between Scintilla and lexers.
  **/
 // Copyright 1998-2002 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <ctype.h>
+#include <cstdlib>
+#include <cassert>
 
 #include "ILexer.h"
 #include "Scintilla.h"
@@ -32,8 +28,8 @@ int Accessor::GetPropertyInt(const char *key, int defaultValue) const {
        return pprops->GetInt(key, defaultValue);
 }
 
-int Accessor::IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader) {
-       int end = Length();
+int Accessor::IndentAmount(Sci_Position line, int *flags, PFNIsCommentLeader pfnIsCommentLeader) {
+       const Sci_Position end = Length();
        int spaceFlags = 0;
 
        // Determines the indentation level of the current line and also checks for consistent
@@ -41,14 +37,14 @@ int Accessor::IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsComment
        // Indentation is judged consistent when the indentation whitespace of each line lines
        // the same or the indentation of one line is a prefix of the other.
 
-       int pos = LineStart(line);
+       Sci_Position pos = LineStart(line);
        char ch = (*this)[pos];
        int indent = 0;
        bool inPrevPrefix = line > 0;
-       int posPrev = inPrevPrefix ? LineStart(line-1) : 0;
+       Sci_Position posPrev = inPrevPrefix ? LineStart(line-1) : 0;
        while ((ch == ' ' || ch == '\t') && (pos < end)) {
                if (inPrevPrefix) {
-                       char chPrev = (*this)[posPrev++];
+                       const char chPrev = (*this)[posPrev++];
                        if (chPrev == ' ' || chPrev == '\t') {
                                if (chPrev != ch)
                                        spaceFlags |= wsInconsistent;
diff --git a/plugins/scintilla/scintilla/lexlib/Accessor.h b/plugins/scintilla/scintilla/lexlib/Accessor.h
index 9789f2b..00b2a54 100644
--- a/plugins/scintilla/scintilla/lexlib/Accessor.h
+++ b/plugins/scintilla/scintilla/lexlib/Accessor.h
@@ -12,20 +12,20 @@
 namespace Scintilla {
 #endif
 
-enum { wsSpace = 1, wsTab = 2, wsSpaceTab = 4, wsInconsistent=8};
+enum { wsSpace=1, wsTab=2, wsSpaceTab=4, wsInconsistent=8 };
 
 class Accessor;
 class WordList;
 class PropSetSimple;
 
-typedef bool (*PFNIsCommentLeader)(Accessor &styler, int pos, int len);
+typedef bool (*PFNIsCommentLeader)(Accessor &styler, Sci_Position pos, Sci_Position len);
 
 class Accessor : public LexAccessor {
 public:
        PropSetSimple *pprops;
        Accessor(IDocument *pAccess_, PropSetSimple *pprops_);
        int GetPropertyInt(const char *, int defaultValue=0) const;
-       int IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0);
+       int IndentAmount(Sci_Position line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0);
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/lexlib/CharacterCategory.cxx 
b/plugins/scintilla/scintilla/lexlib/CharacterCategory.cxx
index a837760..c57c8ba 100644
--- a/plugins/scintilla/scintilla/lexlib/CharacterCategory.cxx
+++ b/plugins/scintilla/scintilla/lexlib/CharacterCategory.cxx
@@ -9,6 +9,7 @@
 
 #include <algorithm>
 
+#include "StringCopy.h"
 #include "CharacterCategory.h"
 
 #ifdef SCI_NAMESPACE
@@ -20,7 +21,7 @@ namespace {
 
 const int catRanges[] = {
 //++Autogenerated -- start of section automatically generated
-// Created with Python 3.3.0,  Unicode 6.1.0
+// Created with Python 3.6.1,  Unicode 9.0.0
 25,
 1046,
 1073,
@@ -394,7 +395,8 @@ const int catRanges[] = {
 28483,
 28513,
 28625,
-28669,
+28640,
+28701,
 28820,
 28864,
 28913,
@@ -638,7 +640,15 @@ const int catRanges[] = {
 42145,
 42176,
 42209,
-42269,
+42240,
+42273,
+42304,
+42337,
+42368,
+42401,
+42432,
+42465,
+42525,
 42528,
 43773,
 43811,
@@ -649,6 +659,7 @@ const int catRanges[] = {
 45361,
 45388,
 45437,
+45493,
 45555,
 45597,
 45605,
@@ -667,7 +678,6 @@ const int catRanges[] = {
 48753,
 48829,
 49178,
-49341,
 49362,
 49457,
 49523,
@@ -675,7 +685,8 @@ const int catRanges[] = {
 49621,
 49669,
 50033,
-50077,
+50074,
+50109,
 50129,
 50180,
 51203,
@@ -738,12 +749,12 @@ const int catRanges[] = {
 68561,
 68605,
 70660,
-70717,
-70724,
-71101,
-72837,
-73725,
-73733,
+71357,
+71364,
+71645,
+72325,
+72794,
+72805,
 73830,
 73860,
 75589,
@@ -764,9 +775,6 @@ const int catRanges[] = {
 77329,
 77347,
 77380,
-77597,
-77604,
-77853,
 77861,
 77894,
 77981,
@@ -879,6 +887,8 @@ const int catRanges[] = {
 89617,
 89651,
 89693,
+89892,
+89949,
 90149,
 90182,
 90269,
@@ -959,6 +969,7 @@ const int catRanges[] = {
 98099,
 98133,
 98173,
+98309,
 98342,
 98461,
 98468,
@@ -968,8 +979,6 @@ const int catRanges[] = {
 98884,
 99645,
 99652,
-99997,
-100004,
 100189,
 100260,
 100293,
@@ -982,7 +991,7 @@ const int catRanges[] = {
 101029,
 101117,
 101124,
-101213,
+101245,
 101380,
 101445,
 101533,
@@ -990,7 +999,8 @@ const int catRanges[] = {
 101917,
 102154,
 102389,
-102429,
+102404,
+102437,
 102470,
 102557,
 102564,
@@ -1026,6 +1036,7 @@ const int catRanges[] = {
 106013,
 106020,
 106109,
+106533,
 106566,
 106653,
 106660,
@@ -1043,15 +1054,16 @@ const int catRanges[] = {
 108870,
 108965,
 108996,
-109053,
+109045,
+109085,
+109188,
 109286,
-109341,
-109572,
+109322,
+109540,
 109637,
 109725,
 109768,
 110090,
-110301,
 110389,
 110404,
 110621,
@@ -1076,6 +1088,8 @@ const int catRanges[] = {
 113405,
 113414,
 113693,
+113864,
+114205,
 114246,
 114321,
 114365,
@@ -1259,8 +1273,10 @@ const int catRanges[] = {
 159748,
 160277,
 160605,
-160772,
-163517,
+160768,
+163549,
+163585,
+163805,
 163852,
 163876,
 183729,
@@ -1273,7 +1289,8 @@ const int catRanges[] = {
 185348,
 187761,
 187849,
-187965,
+187940,
+188221,
 188420,
 188861,
 188868,
@@ -1315,7 +1332,7 @@ const int catRanges[] = {
 196812,
 196849,
 196965,
-197078,
+197082,
 197117,
 197128,
 197469,
@@ -1324,13 +1341,15 @@ const int catRanges[] = {
 198788,
 200477,
 200708,
+200869,
+200932,
 202021,
 202052,
 202109,
 202244,
 204509,
 204804,
-205757,
+205821,
 205829,
 205926,
 206053,
@@ -1351,9 +1370,7 @@ const int catRanges[] = {
 208573,
 208900,
 210333,
-210438,
-210980,
-211206,
+210436,
 211293,
 211464,
 211786,
@@ -1362,6 +1379,7 @@ const int catRanges[] = {
 212996,
 213733,
 213798,
+213861,
 213917,
 213969,
 214020,
@@ -1387,6 +1405,9 @@ const int catRanges[] = {
 218339,
 218385,
 218589,
+218629,
+219079,
+219133,
 221189,
 221318,
 221348,
@@ -1415,7 +1436,6 @@ const int catRanges[] = {
 226565,
 226630,
 226661,
-226694,
 226756,
 226824,
 227140,
@@ -1443,7 +1463,8 @@ const int catRanges[] = {
 232260,
 233219,
 233425,
-233501,
+233473,
+233789,
 235537,
 235805,
 236037,
@@ -1458,6 +1479,8 @@ const int catRanges[] = {
 237189,
 237220,
 237309,
+237317,
+237405,
 237569,
 238979,
 240993,
@@ -1465,8 +1488,8 @@ const int catRanges[] = {
 241441,
 242531,
 243717,
-244989,
-245637,
+245469,
+245605,
 245760,
 245793,
 245824,
@@ -1811,7 +1834,7 @@ const int catRanges[] = {
 265206,
 265242,
 265405,
-265562,
+265434,
 265738,
 265763,
 265821,
@@ -1828,7 +1851,7 @@ const int catRanges[] = {
 266755,
 267197,
 267283,
-268125,
+268285,
 268805,
 269223,
 269349,
@@ -1881,7 +1904,8 @@ const int catRanges[] = {
 274561,
 274601,
 274730,
-274781,
+274773,
+274845,
 274962,
 275125,
 275282,
@@ -1902,7 +1926,10 @@ const int catRanges[] = {
 277173,
 278162,
 286741,
-286994,
+286989,
+287022,
+287053,
+287086,
 287125,
 287762,
 287829,
@@ -1915,7 +1942,7 @@ const int catRanges[] = {
 292501,
 293778,
 293973,
-294557,
+294909,
 294933,
 296189,
 296981,
@@ -1932,8 +1959,6 @@ const int catRanges[] = {
 311317,
 314866,
 314901,
-319517,
-319541,
 322829,
 322862,
 322893,
@@ -2002,9 +2027,18 @@ const int catRanges[] = {
 353810,
 354485,
 354546,
-354749,
-354837,
-355165,
+354741,
+355997,
+356053,
+357085,
+357141,
+358237,
+358325,
+358717,
+358741,
+359005,
+359829,
+359965,
 360448,
 361981,
 361985,
@@ -2202,7 +2236,12 @@ const int catRanges[] = {
 378339,
 378385,
 378700,
-378781,
+378769,
+378892,
+378929,
+378957,
+378993,
+379069,
 380949,
 381789,
 381813,
@@ -2294,7 +2333,7 @@ const int catRanges[] = {
 636637,
 636949,
 638980,
-1309117,
+1309405,
 1310724,
 1311395,
 1311428,
@@ -2388,8 +2427,12 @@ const int catRanges[] = {
 1364641,
 1364672,
 1364705,
-1364765,
-1364965,
+1364736,
+1364769,
+1364800,
+1364833,
+1364867,
+1364933,
 1364996,
 1367241,
 1367557,
@@ -2496,12 +2539,21 @@ const int catRanges[] = {
 1372545,
 1372576,
 1372609,
-1372669,
+1372644,
 1372672,
 1372705,
 1372736,
 1372769,
-1372829,
+1372864,
+1372897,
+1372928,
+1372961,
+1372992,
+1373025,
+1373056,
+1373089,
+1373120,
+1373153,
 1373184,
 1373217,
 1373248,
@@ -2513,7 +2565,13 @@ const int catRanges[] = {
 1373440,
 1373473,
 1373504,
-1373565,
+1373693,
+1373696,
+1373857,
+1373888,
+1373921,
+1373981,
+1375972,
 1376003,
 1376065,
 1376100,
@@ -2540,7 +2598,7 @@ const int catRanges[] = {
 1380420,
 1382022,
 1382533,
-1382589,
+1382621,
 1382865,
 1382920,
 1383261,
@@ -2548,7 +2606,9 @@ const int catRanges[] = {
 1384004,
 1384209,
 1384292,
-1384349,
+1384337,
+1384356,
+1384413,
 1384456,
 1384772,
 1385669,
@@ -2575,7 +2635,13 @@ const int catRanges[] = {
 1391112,
 1391453,
 1391569,
-1391645,
+1391620,
+1391781,
+1391811,
+1391844,
+1392136,
+1392452,
+1392637,
 1392644,
 1393957,
 1394150,
@@ -2598,8 +2664,9 @@ const int catRanges[] = {
 1396469,
 1396548,
 1396582,
-1396637,
-1396740,
+1396613,
+1396646,
+1396676,
 1398277,
 1398308,
 1398341,
@@ -2634,6 +2701,12 @@ const int catRanges[] = {
 1402109,
 1402116,
 1402365,
+1402369,
+1403764,
+1403779,
+1403905,
+1404125,
+1404417,
 1406980,
 1408102,
 1408165,
@@ -2680,8 +2753,8 @@ const int catRanges[] = {
 2061908,
 2062429,
 2062948,
-2074573,
-2074606,
+2074574,
+2074605,
 2074653,
 2075140,
 2077213,
@@ -2698,7 +2771,6 @@ const int catRanges[] = {
 2081585,
 2081629,
 2081797,
-2082045,
 2082321,
 2082348,
 2082411,
@@ -2830,9 +2902,12 @@ const int catRanges[] = {
 2109098,
 2109237,
 2109770,
-2109821,
+2109845,
+2109949,
 2109973,
 2110365,
+2110485,
+2110525,
 2112021,
 2113445,
 2113501,
@@ -2840,8 +2915,10 @@ const int catRanges[] = {
 2118589,
 2118660,
 2120253,
+2120709,
+2120746,
+2121629,
 2121732,
-2122749,
 2122762,
 2122909,
 2123268,
@@ -2849,6 +2926,9 @@ const int catRanges[] = {
 2123844,
 2124105,
 2124157,
+2124292,
+2125509,
+2125693,
 2125828,
 2126813,
 2126833,
@@ -2864,6 +2944,22 @@ const int catRanges[] = {
 2135005,
 2135048,
 2135389,
+2135552,
+2136733,
+2136833,
+2138013,
+2138116,
+2139421,
+2139652,
+2141341,
+2141681,
+2141725,
+2146308,
+2156285,
+2156548,
+2157277,
+2157572,
+2157853,
 2162692,
 2162909,
 2162948,
@@ -2878,7 +2974,18 @@ const int catRanges[] = {
 2165469,
 2165489,
 2165514,
-2165789,
+2165764,
+2166517,
+2166570,
+2166788,
+2167805,
+2168042,
+2168349,
+2169860,
+2170493,
+2170500,
+2170589,
+2170730,
 2170884,
 2171594,
 2171805,
@@ -2889,8 +2996,11 @@ const int catRanges[] = {
 2172957,
 2174980,
 2176797,
+2176906,
 2176964,
-2177053,
+2177034,
+2177565,
+2177610,
 2179076,
 2179109,
 2179229,
@@ -2913,7 +3023,17 @@ const int catRanges[] = {
 2182148,
 2183082,
 2183153,
-2183197,
+2183172,
+2184106,
+2184221,
+2185220,
+2185493,
+2185508,
+2186405,
+2186493,
+2186602,
+2186769,
+2187005,
 2187268,
 2189021,
 2189105,
@@ -2923,9 +3043,20 @@ const int catRanges[] = {
 2190340,
 2190973,
 2191114,
-2191389,
+2191364,
+2191965,
+2192177,
+2192317,
+2192682,
+2192925,
 2195460,
 2197821,
+2199552,
+2201213,
+2201601,
+2203261,
+2203466,
+2203677,
 2214922,
 2215933,
 2228230,
@@ -2938,7 +3069,7 @@ const int catRanges[] = {
 2230858,
 2231496,
 2231837,
-2232325,
+2232293,
 2232390,
 2232420,
 2233862,
@@ -2962,6 +3093,11 @@ const int catRanges[] = {
 2238152,
 2238481,
 2238621,
+2238980,
+2240101,
+2240145,
+2240196,
+2240253,
 2240517,
 2240582,
 2240612,
@@ -2970,9 +3106,139 @@ const int catRanges[] = {
 2242534,
 2242596,
 2242737,
-2242877,
+2242885,
+2242993,
+2243037,
 2243080,
-2243421,
+2243396,
+2243441,
+2243460,
+2243505,
+2243613,
+2243626,
+2244285,
+2244612,
+2245213,
+2245220,
+2246022,
+2246117,
+2246214,
+2246277,
+2246310,
+2246341,
+2246417,
+2246597,
+2246653,
+2248708,
+2248957,
+2248964,
+2249021,
+2249028,
+2249181,
+2249188,
+2249693,
+2249700,
+2250033,
+2250077,
+2250244,
+2251749,
+2251782,
+2251877,
+2252157,
+2252296,
+2252637,
+2252805,
+2252870,
+2252957,
+2252964,
+2253245,
+2253284,
+2253373,
+2253412,
+2254141,
+2254148,
+2254397,
+2254404,
+2254493,
+2254500,
+2254685,
+2254725,
+2254756,
+2254790,
+2254853,
+2254886,
+2255037,
+2255078,
+2255165,
+2255206,
+2255325,
+2255364,
+2255421,
+2255590,
+2255645,
+2255780,
+2255942,
+2256029,
+2256069,
+2256317,
+2256389,
+2256573,
+2260996,
+2262694,
+2262789,
+2263046,
+2263109,
+2263206,
+2263237,
+2263268,
+2263409,
+2263560,
+2263901,
+2263921,
+2263965,
+2263985,
+2264029,
+2265092,
+2266630,
+2266725,
+2266918,
+2266949,
+2266982,
+2267109,
+2267174,
+2267205,
+2267268,
+2267345,
+2267364,
+2267421,
+2267656,
+2267997,
+2273284,
+2274790,
+2274885,
+2275037,
+2275078,
+2275205,
+2275270,
+2275301,
+2275377,
+2276100,
+2276229,
+2276317,
+2277380,
+2278918,
+2279013,
+2279270,
+2279333,
+2279366,
+2279397,
+2279473,
+2279556,
+2279613,
+2279944,
+2280285,
+2280465,
+2280893,
 2281476,
 2282853,
 2282886,
@@ -2984,16 +3250,96 @@ const int catRanges[] = {
 2283293,
 2283528,
 2283869,
+2285572,
+2286429,
+2286501,
+2286598,
+2286661,
+2286790,
+2286821,
+2287005,
+2287112,
+2287434,
+2287505,
+2287605,
+2287645,
+2298880,
+2299905,
+2300936,
+2301258,
+2301565,
+2301924,
+2301981,
+2316292,
+2318141,
+2326532,
+2326845,
+2326852,
+2328038,
+2328069,
+2328317,
+2328325,
+2328518,
+2328549,
+2328580,
+2328625,
+2328797,
+2329096,
+2329418,
+2330045,
+2330129,
+2330180,
+2331165,
+2331205,
+2331933,
+2331942,
+2331973,
+2332198,
+2332229,
+2332294,
+2332325,
+2332413,
 2359300,
-2387453,
+2388829,
 2392073,
-2395261,
+2395645,
 2395665,
-2395805,
+2395837,
+2396164,
+2402461,
 2490372,
 2524669,
+2654212,
+2672893,
 2949124,
 2967357,
+2967556,
+2968573,
+2968584,
+2968925,
+2969041,
+2969117,
+2972164,
+2973149,
+2973189,
+2973361,
+2973405,
+2973700,
+2975237,
+2975473,
+2975637,
+2975747,
+2975889,
+2975925,
+2975965,
+2976264,
+2976605,
+2976618,
+2976861,
+2976868,
+2977565,
+2977700,
+2978333,
 3006468,
 3008701,
 3009028,
@@ -3002,8 +3348,27 @@ const int catRanges[] = {
 3011045,
 3011171,
 3011613,
+3013635,
+3013693,
+3014660,
+3210685,
+3211268,
+3235453,
 3538948,
 3539037,
+3637252,
+3640701,
+3640836,
+3641277,
+3641348,
+3641661,
+3641860,
+3642205,
+3642261,
+3642277,
+3642353,
+3642394,
+3642525,
 3801109,
 3808989,
 3809301,
@@ -3020,7 +3385,7 @@ const int catRanges[] = {
 3813781,
 3814725,
 3814869,
-3816413,
+3816765,
 3817493,
 3819589,
 3819701,
@@ -3119,7 +3484,44 @@ const int catRanges[] = {
 3864929,
 3864989,
 3865032,
-3866653,
+3866645,
+3883013,
+3884789,
+3884901,
+3886517,
+3886757,
+3886805,
+3887237,
+3887285,
+3887345,
+3887517,
+3887973,
+3888157,
+3888165,
+3888669,
+3932165,
+3932413,
+3932421,
+3932989,
+3933029,
+3933277,
+3933285,
+3933373,
+3933381,
+3933565,
+3997700,
+4004029,
+4004074,
+4004357,
+4004605,
+4005888,
+4006977,
+4008069,
+4008317,
+4008456,
+4008797,
+4008913,
+4008989,
 4046852,
 4047005,
 4047012,
@@ -3195,69 +3597,73 @@ const int catRanges[] = {
 4068373,
 4068861,
 4068917,
-4069373,
+4069405,
 4069429,
 4069917,
 4069941,
-4070429,
+4071133,
 4071434,
-4071805,
+4071869,
 4071957,
 4072957,
 4072981,
 4074909,
 4075029,
-4076413,
+4076989,
 4078805,
 4079741,
 4080149,
-4081533,
+4081565,
 4081685,
 4081981,
 4082197,
 4082269,
 4087829,
-4088893,
-4089365,
-4089565,
-4089589,
-4091837,
-4091925,
-4092573,
-4092949,
-4094141,
-4094165,
-4094333,
-4094997,
-4095549,
+4095860,
 4096021,
-4098045,
-4098069,
-4098109,
-4098133,
-4103965,
-4103989,
-4104125,
-4104213,
-4106205,
-4106261,
-4106397,
-4106773,
-4107549,
-4112245,
-4114493,
-4114613,
-4114973,
-4116501,
-4118749,
+4119165,
+4119573,
+4119997,
+4120085,
+4120317,
 4120597,
 4124317,
+4124693,
+4127421,
+4128789,
+4129181,
+4129301,
+4131101,
+4131349,
+4131677,
+4131861,
+4133149,
+4133397,
+4134365,
+4137493,
+4137981,
+4138005,
+4138269,
+4138517,
+4138557,
+4138613,
+4139005,
+4139029,
+4139421,
+4139541,
+4140029,
+4141077,
+4141661,
+4143125,
+4143165,
 4194308,
 5561085,
 5562372,
 5695165,
 5695492,
 5702621,
+5702660,
+5887069,
 6225924,
 6243293,
 29360186,
@@ -3275,7 +3681,7 @@ const int catRanges[] = {
 
 const int maxUnicode = 0x10ffff;
 const int maskCategory = 0x1F;
-const int nRanges = sizeof(catRanges) / sizeof(catRanges[0]);
+const int nRanges = ELEMENTS(catRanges);
 
 }
 
@@ -3286,7 +3692,7 @@ const int nRanges = sizeof(catRanges) / sizeof(catRanges[0]);
 // Initial version has 3249 entries and adds about 13K to the executable.
 // The array is in ascending order so can be searched using binary search.
 // Therefore the average call takes log2(3249) = 12 comparisons.
-// For speed, it may be an useful to make a linear table for the common values,
+// For speed, it may be useful to make a linear table for the common values,
 // possibly for 0..0xff for most Western European text or 0..0xfff for most
 // alphabetic languages.
 
@@ -3298,6 +3704,152 @@ CharacterCategory CategoriseCharacter(int character) {
        return static_cast<CharacterCategory>(*(placeAfter-1) & maskCategory);
 }
 
+// Implementation of character sets recommended for identifiers in Unicode Standard Annex #31.
+// http://unicode.org/reports/tr31/
+
+namespace {
+
+enum class OtherID { oidNone, oidStart, oidContinue };
+
+// Some characters are treated as valid for identifiers even
+// though most characters from their category are not.
+// Values copied from http://www.unicode.org/Public/9.0.0/ucd/PropList.txt
+OtherID OtherIDOfCharacter(int character) {
+       if (
+               (character == 0x1885) ||        // MONGOLIAN LETTER ALI GALI BALUDA
+               (character == 0x1886) ||        // MONGOLIAN LETTER ALI GALI THREE BALUDA
+               (character == 0x2118) ||        // SCRIPT CAPITAL P
+               (character == 0x212E) ||        // ESTIMATED SYMBOL
+               (character == 0x309B) ||        // KATAKANA-HIRAGANA VOICED SOUND MARK
+               (character == 0x309C)) {        // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+               return OtherID::oidStart;
+       } else if (
+               (character == 0x00B7) ||        // MIDDLE DOT
+               (character == 0x0387) ||        // GREEK ANO TELEIA
+               ((character >= 0x1369) && (character <= 0x1371)) ||     // ETHIOPIC DIGIT ONE..ETHIOPIC DIGIT 
NINE
+               (character == 0x19DA)) {        // NEW TAI LUE THAM DIGIT ONE
+               return OtherID::oidContinue;
+       } else {
+               return OtherID::oidNone;
+       }
+}
+
+// Determine if a character is in  Ll|Lu|Lt|Lm|Lo|Nl|Mn|Mc|Nd|Pc and has
+// Pattern_Syntax|Pattern_White_Space.
+// As of Unicode 9, only VERTICAL TILDE which is in Lm and has Pattern_Syntax matches.
+// Should really generate from PropList.txt a list of Pattern_Syntax and Pattern_White_Space.
+bool IsIdPattern(int character) {
+       return character == 0x2E2F;
+}
+
+bool OmitXidStart(int character) {
+       switch (character) {
+       case 0x037A:    // GREEK YPOGEGRAMMENI
+       case 0x0E33:    // THAI CHARACTER SARA AM
+       case 0x0EB3:    // LAO VOWEL SIGN AM
+       case 0x309B:    // KATAKANA-HIRAGANA VOICED SOUND MARK
+       case 0x309C:    // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+       case 0xFC5E:    // ARABIC LIGATURE SHADDA WITH DAMMATAN ISOLATED FORM
+       case 0xFC5F:    // ARABIC LIGATURE SHADDA WITH KASRATAN ISOLATED FORM
+       case 0xFC60:    // ARABIC LIGATURE SHADDA WITH FATHA ISOLATED FORM
+       case 0xFC61:    // ARABIC LIGATURE SHADDA WITH DAMMA ISOLATED FORM
+       case 0xFC62:    // ARABIC LIGATURE SHADDA WITH KASRA ISOLATED FORM
+       case 0xFC63:    // ARABIC LIGATURE SHADDA WITH SUPERSCRIPT ALEF ISOLATED FORM
+       case 0xFDFA:    // ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM
+       case 0xFDFB:    // ARABIC LIGATURE JALLAJALALOUHOU
+       case 0xFE70:    // ARABIC FATHATAN ISOLATED FORM
+       case 0xFE72:    // ARABIC DAMMATAN ISOLATED FORM
+       case 0xFE74:    // ARABIC KASRATAN ISOLATED FORM
+       case 0xFE76:    // ARABIC FATHA ISOLATED FORM
+       case 0xFE78:    // ARABIC DAMMA ISOLATED FORM
+       case 0xFE7A:    // ARABIC KASRA ISOLATED FORM
+       case 0xFE7C:    // ARABIC SHADDA ISOLATED FORM
+       case 0xFE7E:    // ARABIC SUKUN ISOLATED FORM
+       case 0xFF9E:    // HALFWIDTH KATAKANA VOICED SOUND MARK
+       case 0xFF9F:    // HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
+               return true;
+       default:
+               return false;
+       }
+}
+
+bool OmitXidContinue(int character) {
+       switch (character) {
+       case 0x037A:    // GREEK YPOGEGRAMMENI
+       case 0x309B:    // KATAKANA-HIRAGANA VOICED SOUND MARK
+       case 0x309C:    // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
+       case 0xFC5E:    // ARABIC LIGATURE SHADDA WITH DAMMATAN ISOLATED FORM
+       case 0xFC5F:    // ARABIC LIGATURE SHADDA WITH KASRATAN ISOLATED FORM
+       case 0xFC60:    // ARABIC LIGATURE SHADDA WITH FATHA ISOLATED FORM
+       case 0xFC61:    // ARABIC LIGATURE SHADDA WITH DAMMA ISOLATED FORM
+       case 0xFC62:    // ARABIC LIGATURE SHADDA WITH KASRA ISOLATED FORM
+       case 0xFC63:    // ARABIC LIGATURE SHADDA WITH SUPERSCRIPT ALEF ISOLATED FORM
+       case 0xFDFA:    // ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM
+       case 0xFDFB:    // ARABIC LIGATURE JALLAJALALOUHOU
+       case 0xFE70:    // ARABIC FATHATAN ISOLATED FORM
+       case 0xFE72:    // ARABIC DAMMATAN ISOLATED FORM
+       case 0xFE74:    // ARABIC KASRATAN ISOLATED FORM
+       case 0xFE76:    // ARABIC FATHA ISOLATED FORM
+       case 0xFE78:    // ARABIC DAMMA ISOLATED FORM
+       case 0xFE7A:    // ARABIC KASRA ISOLATED FORM
+       case 0xFE7C:    // ARABIC SHADDA ISOLATED FORM
+       case 0xFE7E:    // ARABIC SUKUN ISOLATED FORM
+               return true;
+       default:
+               return false;
+       }
+}
+
+}
+
+// UAX #31 defines ID_Start as
+// [[:L:][:Nl:][:Other_ID_Start:]--[:Pattern_Syntax:]--[:Pattern_White_Space:]]
+bool IsIdStart(int character) {
+       if (IsIdPattern(character)) {
+               return false;
+       }
+       const OtherID oid = OtherIDOfCharacter(character);
+       if (oid == OtherID::oidStart) {
+               return true;
+       }
+       const CharacterCategory c = CategoriseCharacter(character);
+       return (c == ccLl || c == ccLu || c == ccLt || c == ccLm || c == ccLo
+               || c == ccNl);
+}
+
+// UAX #31 defines ID_Continue as
+// [[:ID_Start:][:Mn:][:Mc:][:Nd:][:Pc:][:Other_ID_Continue:]--[:Pattern_Syntax:]--[:Pattern_White_Space:]]
+bool IsIdContinue(int character) {
+       if (IsIdPattern(character)) {
+               return false;
+       }
+       const OtherID oid = OtherIDOfCharacter(character);
+       if (oid != OtherID::oidNone) {
+               return true;
+       }
+       const CharacterCategory c = CategoriseCharacter(character);
+       return (c == ccLl || c == ccLu || c == ccLt || c == ccLm || c == ccLo
+               || c == ccNl || c == ccMn || c == ccMc || c == ccNd || c == ccPc);
+}
+
+// XID_Start is ID_Start modified for Normalization Form KC in UAX #31
+bool IsXidStart(int character) {
+       if (OmitXidStart(character)) {
+               return false;
+       } else {
+               return IsIdStart(character);
+       }
+}
+
+// XID_Continue is ID_Continue modified for Normalization Form KC in UAX #31
+bool IsXidContinue(int character) {
+       if (OmitXidContinue(character)) {
+               return false;
+       } else {
+               return IsIdContinue(character);
+       }
+}
+
 #ifdef SCI_NAMESPACE
 }
 #endif
diff --git a/plugins/scintilla/scintilla/lexlib/CharacterCategory.h 
b/plugins/scintilla/scintilla/lexlib/CharacterCategory.h
index c860050..05ea418 100644
--- a/plugins/scintilla/scintilla/lexlib/CharacterCategory.h
+++ b/plugins/scintilla/scintilla/lexlib/CharacterCategory.h
@@ -24,6 +24,12 @@ enum CharacterCategory {
 
 CharacterCategory CategoriseCharacter(int character);
 
+// Common definitions of allowable characters in identifiers from UAX #31.
+bool IsIdStart(int character);
+bool IsIdContinue(int character);
+bool IsXidStart(int character);
+bool IsXidContinue(int character);
+
 #ifdef SCI_NAMESPACE
 }
 #endif
diff --git a/plugins/scintilla/scintilla/lexlib/CharacterSet.cxx 
b/plugins/scintilla/scintilla/lexlib/CharacterSet.cxx
index 35669df..0db3e41 100644
--- a/plugins/scintilla/scintilla/lexlib/CharacterSet.cxx
+++ b/plugins/scintilla/scintilla/lexlib/CharacterSet.cxx
@@ -6,11 +6,8 @@
 // Copyright 1998-2010 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <assert.h>
+#include <cstdlib>
+#include <cassert>
 
 #include "CharacterSet.h"
 
@@ -25,8 +22,8 @@ namespace Scintilla {
 int CompareCaseInsensitive(const char *a, const char *b) {
        while (*a && *b) {
                if (*a != *b) {
-                       char upperA = MakeUpperCase(*a);
-                       char upperB = MakeUpperCase(*b);
+                       const char upperA = static_cast<char>(MakeUpperCase(*a));
+                       const char upperB = static_cast<char>(MakeUpperCase(*b));
                        if (upperA != upperB)
                                return upperA - upperB;
                }
@@ -40,8 +37,8 @@ int CompareCaseInsensitive(const char *a, const char *b) {
 int CompareNCaseInsensitive(const char *a, const char *b, size_t len) {
        while (*a && *b && len) {
                if (*a != *b) {
-                       char upperA = MakeUpperCase(*a);
-                       char upperB = MakeUpperCase(*b);
+                       const char upperA = static_cast<char>(MakeUpperCase(*a));
+                       const char upperB = static_cast<char>(MakeUpperCase(*b));
                        if (upperA != upperB)
                                return upperA - upperB;
                }
diff --git a/plugins/scintilla/scintilla/lexlib/CharacterSet.h 
b/plugins/scintilla/scintilla/lexlib/CharacterSet.h
index a0c45b2..38d84a2 100644
--- a/plugins/scintilla/scintilla/lexlib/CharacterSet.h
+++ b/plugins/scintilla/scintilla/lexlib/CharacterSet.h
@@ -48,6 +48,17 @@ public:
                        bset[i] = other.bset[i];
                }
        }
+       CharacterSet &operator=(CharacterSet &&other) {
+               if (this != &other) {
+                       delete []bset;
+                       size = other.size;
+                       valueAfter = other.valueAfter;
+                       bset = other.bset;
+                       other.size = 0;
+                       other.bset = nullptr;
+               }
+               return *this;
+       }
        ~CharacterSet() {
                delete []bset;
                bset = 0;
@@ -160,13 +171,20 @@ inline bool isoperator(int ch) {
 
 // Simple case functions for ASCII.
 
-inline char MakeUpperCase(char ch) {
+inline int MakeUpperCase(int ch) {
        if (ch < 'a' || ch > 'z')
                return ch;
        else
                return static_cast<char>(ch - 'a' + 'A');
 }
 
+inline int MakeLowerCase(int ch) {
+       if (ch < 'A' || ch > 'Z')
+               return ch;
+       else
+               return ch - 'A' + 'a';
+}
+
 int CompareCaseInsensitive(const char *a, const char *b);
 int CompareNCaseInsensitive(const char *a, const char *b, size_t len);
 
diff --git a/plugins/scintilla/scintilla/lexlib/LexAccessor.h 
b/plugins/scintilla/scintilla/lexlib/LexAccessor.h
index e29bbc9..064a175 100644
--- a/plugins/scintilla/scintilla/lexlib/LexAccessor.h
+++ b/plugins/scintilla/scintilla/lexlib/LexAccessor.h
@@ -24,21 +24,18 @@ private:
         * in case there is some backtracking. */
        enum {bufferSize=4000, slopSize=bufferSize/8};
        char buf[bufferSize+1];
-       int startPos;
-       int endPos;
+       Sci_Position startPos;
+       Sci_Position endPos;
        int codePage;
        enum EncodingType encodingType;
-       int lenDoc;
-       int mask;
+       Sci_Position lenDoc;
        char styleBuf[bufferSize];
-       int validLen;
-       char chFlags;
-       char chWhile;
-       unsigned int startSeg;
-       int startPosStyling;
+       Sci_Position validLen;
+       Sci_PositionU startSeg;
+       Sci_Position startPosStyling;
        int documentVersion;
 
-       void Fill(int position) {
+       void Fill(Sci_Position position) {
                startPos = position - slopSize;
                if (startPos + bufferSize > lenDoc)
                        startPos = lenDoc - bufferSize;
@@ -53,14 +50,17 @@ private:
        }
 
 public:
-       LexAccessor(IDocument *pAccess_) :
+       explicit LexAccessor(IDocument *pAccess_) :
                pAccess(pAccess_), startPos(extremePosition), endPos(0),
-               codePage(pAccess->CodePage()), 
+               codePage(pAccess->CodePage()),
                encodingType(enc8bit),
                lenDoc(pAccess->Length()),
-               mask(127), validLen(0), chFlags(0), chWhile(0),
-               startSeg(0), startPosStyling(0), 
+               validLen(0),
+               startSeg(0), startPosStyling(0),
                documentVersion(pAccess->Version()) {
+               // Prevent warnings by static analyzers about uninitialized buf and styleBuf.
+               buf[0] = 0;
+               styleBuf[0] = 0;
                switch (codePage) {
                case 65001:
                        encodingType = encUnicode;
@@ -73,7 +73,7 @@ public:
                        encodingType = encDBCS;
                }
        }
-       char operator[](int position) {
+       char operator[](Sci_Position position) {
                if (position < startPos || position >= endPos) {
                        Fill(position);
                }
@@ -86,7 +86,7 @@ public:
                return 0;
        }
        /** Safe version of operator[], returning a defined value for invalid position. */
-       char SafeGetCharAt(int position, char chDefault=' ') {
+       char SafeGetCharAt(Sci_Position position, char chDefault=' ') {
                if (position < startPos || position >= endPos) {
                        Fill(position);
                        if (position < startPos || position >= endPos) {
@@ -102,7 +102,7 @@ public:
        EncodingType Encoding() const {
                return encodingType;
        }
-       bool Match(int pos, const char *s) {
+       bool Match(Sci_Position pos, const char *s) {
                for (int i=0; *s; i++) {
                        if (*s != SafeGetCharAt(pos+i))
                                return false;
@@ -110,66 +110,59 @@ public:
                }
                return true;
        }
-       char StyleAt(int position) const {
-               return static_cast<char>(pAccess->StyleAt(position) & mask);
+       char StyleAt(Sci_Position position) const {
+               return static_cast<char>(pAccess->StyleAt(position));
        }
-       int GetLine(int position) const {
+       Sci_Position GetLine(Sci_Position position) const {
                return pAccess->LineFromPosition(position);
        }
-       int LineStart(int line) const {
+       Sci_Position LineStart(Sci_Position line) const {
                return pAccess->LineStart(line);
        }
-       int LineEnd(int line) {
+       Sci_Position LineEnd(Sci_Position line) {
                if (documentVersion >= dvLineEnd) {
                        return (static_cast<IDocumentWithLineEnd *>(pAccess))->LineEnd(line);
                } else {
                        // Old interface means only '\r', '\n' and '\r\n' line ends.
-                       int startNext = pAccess->LineStart(line+1);
-                       char chLineEnd = SafeGetCharAt(startNext-1);
+                       Sci_Position startNext = pAccess->LineStart(line+1);
+                       const char chLineEnd = SafeGetCharAt(startNext-1);
                        if (chLineEnd == '\n' && (SafeGetCharAt(startNext-2)  == '\r'))
                                return startNext - 2;
                        else
                                return startNext - 1;
                }
        }
-       int LevelAt(int line) const {
+       int LevelAt(Sci_Position line) const {
                return pAccess->GetLevel(line);
        }
-       int Length() const {
+       Sci_Position Length() const {
                return lenDoc;
        }
        void Flush() {
-               startPos = extremePosition;
                if (validLen > 0) {
                        pAccess->SetStyles(validLen, styleBuf);
                        startPosStyling += validLen;
                        validLen = 0;
                }
        }
-       int GetLineState(int line) const {
+       int GetLineState(Sci_Position line) const {
                return pAccess->GetLineState(line);
        }
-       int SetLineState(int line, int state) {
+       int SetLineState(Sci_Position line, int state) {
                return pAccess->SetLineState(line, state);
        }
        // Style setting
-       void StartAt(unsigned int start, char chMask=31) {
-               // Store the mask specified for use with StyleAt.
-               mask = chMask;
-               pAccess->StartStyling(start, chMask);
+       void StartAt(Sci_PositionU start) {
+               pAccess->StartStyling(start, '\377');
                startPosStyling = start;
        }
-       void SetFlags(char chFlags_, char chWhile_) {
-               chFlags = chFlags_;
-               chWhile = chWhile_;
-       }
-       unsigned int GetStartSegment() const {
+       Sci_PositionU GetStartSegment() const {
                return startSeg;
        }
-       void StartSegment(unsigned int pos) {
+       void StartSegment(Sci_PositionU pos) {
                startSeg = pos;
        }
-       void ColourTo(unsigned int pos, int chAttr) {
+       void ColourTo(Sci_PositionU pos, int chAttr) {
                // Only perform styling if non empty range
                if (pos != startSeg - 1) {
                        assert(pos >= startSeg);
@@ -183,10 +176,7 @@ public:
                                // Too big for buffer so send directly
                                pAccess->SetStyleFor(pos - startSeg + 1, static_cast<char>(chAttr));
                        } else {
-                               if (chAttr != chWhile)
-                                       chFlags = 0;
-                               chAttr = static_cast<char>(chAttr | chFlags);
-                               for (unsigned int i = startSeg; i <= pos; i++) {
+                               for (Sci_PositionU i = startSeg; i <= pos; i++) {
                                        assert((startPosStyling + validLen) < Length());
                                        styleBuf[validLen++] = static_cast<char>(chAttr);
                                }
@@ -194,15 +184,15 @@ public:
                }
                startSeg = pos+1;
        }
-       void SetLevel(int line, int level) {
+       void SetLevel(Sci_Position line, int level) {
                pAccess->SetLevel(line, level);
        }
-       void IndicatorFill(int start, int end, int indicator, int value) {
+       void IndicatorFill(Sci_Position start, Sci_Position end, int indicator, int value) {
                pAccess->DecorationSetCurrentIndicator(indicator);
                pAccess->DecorationFillRange(start, value, end - start);
        }
 
-       void ChangeLexerState(int start, int end) {
+       void ChangeLexerState(Sci_Position start, Sci_Position end) {
                pAccess->ChangeLexerState(start, end);
        }
 };
diff --git a/plugins/scintilla/scintilla/lexlib/LexerBase.cxx 
b/plugins/scintilla/scintilla/lexlib/LexerBase.cxx
index bbef3f1..71e2601 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerBase.cxx
+++ b/plugins/scintilla/scintilla/lexlib/LexerBase.cxx
@@ -5,12 +5,9 @@
 // Copyright 1998-2010 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <ctype.h>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
 
 #include "ILexer.h"
 #include "Scintilla.h"
@@ -61,7 +58,7 @@ const char * SCI_METHOD LexerBase::DescribeProperty(const char *) {
        return "";
 }
 
-int SCI_METHOD LexerBase::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerBase::PropertySet(const char *key, const char *val) {
        const char *valOld = props.Get(key);
        if (strcmp(val, valOld) != 0) {
                props.Set(key, val);
@@ -75,7 +72,7 @@ const char * SCI_METHOD LexerBase::DescribeWordListSets() {
        return "";
 }
 
-int SCI_METHOD LexerBase::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerBase::WordListSet(int n, const char *wl) {
        if (n < numWordLists) {
                WordList wlNew;
                wlNew.Set(wl);
diff --git a/plugins/scintilla/scintilla/lexlib/LexerBase.h b/plugins/scintilla/scintilla/lexlib/LexerBase.h
index 2998d24..d8849d2 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerBase.h
+++ b/plugins/scintilla/scintilla/lexlib/LexerBase.h
@@ -26,11 +26,11 @@ public:
        const char * SCI_METHOD PropertyNames();
        int SCI_METHOD PropertyType(const char *name);
        const char * SCI_METHOD DescribeProperty(const char *name);
-       int SCI_METHOD PropertySet(const char *key, const char *val);
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val);
        const char * SCI_METHOD DescribeWordListSets();
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess) = 0;
-       void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess) = 0;
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl);
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) = 0;
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) = 0;
        void * SCI_METHOD PrivateCall(int operation, void *pointer);
 };
 
diff --git a/plugins/scintilla/scintilla/lexlib/LexerModule.cxx 
b/plugins/scintilla/scintilla/lexlib/LexerModule.cxx
index b2b0f06..a9fc4f5 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerModule.cxx
+++ b/plugins/scintilla/scintilla/lexlib/LexerModule.cxx
@@ -5,12 +5,8 @@
 // Copyright 1998-2010 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <ctype.h>
+#include <cstdlib>
+#include <cassert>
 
 #include <string>
 
@@ -34,28 +30,24 @@ LexerModule::LexerModule(int language_,
        LexerFunction fnLexer_,
        const char *languageName_,
        LexerFunction fnFolder_,
-        const char *const wordListDescriptions_[],
-       int styleBits_) :
+        const char *const wordListDescriptions_[]) :
        language(language_),
        fnLexer(fnLexer_),
        fnFolder(fnFolder_),
        fnFactory(0),
        wordListDescriptions(wordListDescriptions_),
-       styleBits(styleBits_),
        languageName(languageName_) {
 }
 
 LexerModule::LexerModule(int language_,
        LexerFactoryFunction fnFactory_,
        const char *languageName_,
-       const char * const wordListDescriptions_[],
-       int styleBits_) :
+       const char * const wordListDescriptions_[]) :
        language(language_),
        fnLexer(0),
        fnFolder(0),
        fnFactory(fnFactory_),
        wordListDescriptions(wordListDescriptions_),
-       styleBits(styleBits_),
        languageName(languageName_) {
 }
 
@@ -79,11 +71,7 @@ const char *LexerModule::GetWordListDescription(int index) const {
                return "";
        } else {
                return wordListDescriptions[index];
-       }
-}
-
-int LexerModule::GetStyleBitsNeeded() const {
-       return styleBits;
+       }
 }
 
 ILexer *LexerModule::Create() const {
@@ -93,20 +81,20 @@ ILexer *LexerModule::Create() const {
                return new LexerSimple(this);
 }
 
-void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle,
+void LexerModule::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle,
          WordList *keywordlists[], Accessor &styler) const {
        if (fnLexer)
                fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler);
 }
 
-void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle,
+void LexerModule::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle,
          WordList *keywordlists[], Accessor &styler) const {
        if (fnFolder) {
-               int lineCurrent = styler.GetLine(startPos);
+               Sci_Position lineCurrent = styler.GetLine(startPos);
                // Move back one line in case deletion wrecked current line fold state
                if (lineCurrent > 0) {
                        lineCurrent--;
-                       int newStartPos = styler.LineStart(lineCurrent);
+                       Sci_Position newStartPos = styler.LineStart(lineCurrent);
                        lengthDoc += startPos - newStartPos;
                        startPos = newStartPos;
                        initStyle = 0;
diff --git a/plugins/scintilla/scintilla/lexlib/LexerModule.h 
b/plugins/scintilla/scintilla/lexlib/LexerModule.h
index e502541..ca1d86c 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerModule.h
+++ b/plugins/scintilla/scintilla/lexlib/LexerModule.h
@@ -15,7 +15,7 @@ namespace Scintilla {
 class Accessor;
 class WordList;
 
-typedef void (*LexerFunction)(unsigned int startPos, int lengthDoc, int initStyle,
+typedef void (*LexerFunction)(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle,
                   WordList *keywordlists[], Accessor &styler);
 typedef ILexer *(*LexerFactoryFunction)();
 
@@ -31,7 +31,6 @@ protected:
        LexerFunction fnFolder;
        LexerFactoryFunction fnFactory;
        const char * const * wordListDescriptions;
-       int styleBits;
 
 public:
        const char *languageName;
@@ -39,13 +38,11 @@ public:
                LexerFunction fnLexer_,
                const char *languageName_=0,
                LexerFunction fnFolder_=0,
-               const char * const wordListDescriptions_[] = NULL,
-               int styleBits_=5);
+               const char * const wordListDescriptions_[] = NULL);
        LexerModule(int language_,
                LexerFactoryFunction fnFactory_,
                const char *languageName_,
-               const char * const wordListDescriptions_[] = NULL,
-               int styleBits_=8);
+               const char * const wordListDescriptions_[] = NULL);
        virtual ~LexerModule() {
        }
        int GetLanguage() const { return language; }
@@ -54,13 +51,11 @@ public:
        int GetNumWordLists() const;
        const char *GetWordListDescription(int index) const;
 
-       int GetStyleBitsNeeded() const;
-
        ILexer *Create() const;
 
-       virtual void Lex(unsigned int startPos, int length, int initStyle,
+       virtual void Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle,
                   WordList *keywordlists[], Accessor &styler) const;
-       virtual void Fold(unsigned int startPos, int length, int initStyle,
+       virtual void Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle,
                   WordList *keywordlists[], Accessor &styler) const;
 
        friend class Catalogue;
@@ -72,7 +67,12 @@ inline int Maximum(int a, int b) {
 
 // Shut up annoying Visual C++ warnings:
 #ifdef _MSC_VER
-#pragma warning(disable: 4244 4309 4514 4710)
+#pragma warning(disable: 4244 4456 4457)
+#endif
+
+// Turn off shadow warnings for lexers as may be maintained by others
+#if defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wshadow"
 #endif
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.cxx 
b/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.cxx
index 9ebae2a..96a3a72 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.cxx
+++ b/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.cxx
@@ -5,12 +5,8 @@
 // Copyright 1998-2010 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <ctype.h>
+#include <cstdlib>
+#include <cassert>
 
 #include "ILexer.h"
 #include "Scintilla.h"
@@ -28,7 +24,7 @@
 using namespace Scintilla;
 #endif
 
-int SCI_METHOD LexerNoExceptions::PropertySet(const char *key, const char *val) {
+Sci_Position SCI_METHOD LexerNoExceptions::PropertySet(const char *key, const char *val) {
        try {
                return LexerBase::PropertySet(key, val);
        } catch (...) {
@@ -37,7 +33,7 @@ int SCI_METHOD LexerNoExceptions::PropertySet(const char *key, const char *val)
        return -1;
 }
 
-int SCI_METHOD LexerNoExceptions::WordListSet(int n, const char *wl) {
+Sci_Position SCI_METHOD LexerNoExceptions::WordListSet(int n, const char *wl) {
        try {
                return LexerBase::WordListSet(n, wl);
        } catch (...) {
@@ -46,20 +42,20 @@ int SCI_METHOD LexerNoExceptions::WordListSet(int n, const char *wl) {
        return -1;
 }
 
-void SCI_METHOD LexerNoExceptions::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) 
{
+void SCI_METHOD LexerNoExceptions::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, 
IDocument *pAccess) {
        try {
                Accessor astyler(pAccess, &props);
-               Lexer(startPos, length, initStyle, pAccess, astyler);
+               Lexer(startPos, lengthDoc, initStyle, pAccess, astyler);
                astyler.Flush();
        } catch (...) {
                // Should not throw into caller as may be compiled with different compiler or options
                pAccess->SetErrorStatus(SC_STATUS_FAILURE);
        }
 }
-void SCI_METHOD LexerNoExceptions::Fold(unsigned int startPos, int length, int initStyle, IDocument 
*pAccess) {
+void SCI_METHOD LexerNoExceptions::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, 
IDocument *pAccess) {
        try {
                Accessor astyler(pAccess, &props);
-               Folder(startPos, length, initStyle, pAccess, astyler);
+               Folder(startPos, lengthDoc, initStyle, pAccess, astyler);
                astyler.Flush();
        } catch (...) {
                // Should not throw into caller as may be compiled with different compiler or options
diff --git a/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.h 
b/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.h
index caac61a..ba24a8e 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.h
+++ b/plugins/scintilla/scintilla/lexlib/LexerNoExceptions.h
@@ -5,8 +5,8 @@
 // Copyright 1998-2010 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#ifndef LexerNoExceptions_H
-#define LexerNoExceptions_H
+#ifndef LEXERNOEXCEPTIONS_H
+#define LEXERNOEXCEPTIONS_H
 
 #ifdef SCI_NAMESPACE
 namespace Scintilla {
@@ -16,13 +16,13 @@ namespace Scintilla {
 class LexerNoExceptions : public LexerBase {
 public:
        // TODO Also need to prevent exceptions in constructor and destructor
-       int SCI_METHOD PropertySet(const char *key, const char *val);
-       int SCI_METHOD WordListSet(int n, const char *wl);
-       void SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *);
+       Sci_Position SCI_METHOD PropertySet(const char *key, const char *val);
+       Sci_Position SCI_METHOD WordListSet(int n, const char *wl);
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess);
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *);
 
-       virtual void Lexer(unsigned int startPos, int length, int initStyle, IDocument *pAccess, Accessor 
&styler) = 0;
-       virtual void Folder(unsigned int startPos, int length, int initStyle, IDocument *pAccess, Accessor 
&styler) = 0;
+       virtual void Lexer(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess, 
Accessor &styler) = 0;
+       virtual void Folder(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess, 
Accessor &styler) = 0;
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/lexlib/LexerSimple.cxx 
b/plugins/scintilla/scintilla/lexlib/LexerSimple.cxx
index 4d0e178..f741e0f 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerSimple.cxx
+++ b/plugins/scintilla/scintilla/lexlib/LexerSimple.cxx
@@ -5,12 +5,8 @@
 // Copyright 1998-2010 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <ctype.h>
+#include <cstdlib>
+#include <cassert>
 
 #include <string>
 
@@ -42,13 +38,13 @@ const char * SCI_METHOD LexerSimple::DescribeWordListSets() {
        return wordLists.c_str();
 }
 
-void SCI_METHOD LexerSimple::Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerSimple::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) {
        Accessor astyler(pAccess, &props);
        module->Lex(startPos, lengthDoc, initStyle, keyWordLists, astyler);
        astyler.Flush();
 }
 
-void SCI_METHOD LexerSimple::Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess) {
+void SCI_METHOD LexerSimple::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess) {
        if (props.GetInt("fold")) {
                Accessor astyler(pAccess, &props);
                module->Fold(startPos, lengthDoc, initStyle, keyWordLists, astyler);
diff --git a/plugins/scintilla/scintilla/lexlib/LexerSimple.h 
b/plugins/scintilla/scintilla/lexlib/LexerSimple.h
index 8963193..a88c409 100644
--- a/plugins/scintilla/scintilla/lexlib/LexerSimple.h
+++ b/plugins/scintilla/scintilla/lexlib/LexerSimple.h
@@ -17,10 +17,10 @@ class LexerSimple : public LexerBase {
        const LexerModule *module;
        std::string wordLists;
 public:
-       LexerSimple(const LexerModule *module_);
+       explicit LexerSimple(const LexerModule *module_);
        const char * SCI_METHOD DescribeWordListSets();
-       void SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
-       void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
+       void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess);
+       void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument 
*pAccess);
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/lexlib/PropSetSimple.cxx 
b/plugins/scintilla/scintilla/lexlib/PropSetSimple.cxx
index 9197fb6..a16a225 100644
--- a/plugins/scintilla/scintilla/lexlib/PropSetSimple.cxx
+++ b/plugins/scintilla/scintilla/lexlib/PropSetSimple.cxx
@@ -7,14 +7,8 @@
 
 // Maintain a dictionary of properties
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-
-#ifdef _MSC_VER
-// Visual C++ doesn't like unreachable code in its own headers.
-#pragma warning(disable: 4018 4100 4245 4511 4512 4663 4702)
-#endif
+#include <cstdlib>
+#include <cstring>
 
 #include <string>
 #include <map>
@@ -61,7 +55,7 @@ void PropSetSimple::Set(const char *keyVal) {
                endVal++;
        const char *eqAt = strchr(keyVal, '=');
        if (eqAt) {
-               Set(keyVal, eqAt + 1, static_cast<int>(eqAt-keyVal), 
+               Set(keyVal, eqAt + 1, static_cast<int>(eqAt-keyVal),
                        static_cast<int>(endVal - eqAt - 1));
        } else if (*keyVal) {   // No '=' so assume '=1'
                Set(keyVal, "1", static_cast<int>(endVal-keyVal), 1);
@@ -146,7 +140,7 @@ int PropSetSimple::GetExpanded(const char *key, char *result) const {
        ExpandAllInPlace(*this, val, 100, VarChain(key));
        const int n = static_cast<int>(val.size());
        if (result) {
-               strcpy(result, val.c_str());
+               memcpy(result, val.c_str(), n+1);
        }
        return n;       // Not including NUL
 }
diff --git a/plugins/scintilla/scintilla/lexlib/SparseState.h 
b/plugins/scintilla/scintilla/lexlib/SparseState.h
index 08ff104..e767d67 100644
--- a/plugins/scintilla/scintilla/lexlib/SparseState.h
+++ b/plugins/scintilla/scintilla/lexlib/SparseState.h
@@ -38,7 +38,7 @@ class SparseState {
        }
 
 public:
-       SparseState(int positionFirst_=-1) {
+       explicit SparseState(int positionFirst_=-1) {
                positionFirst = positionFirst_;
        }
        void Set(int position, T value) {
diff --git a/plugins/scintilla/scintilla/lexlib/StringCopy.h b/plugins/scintilla/scintilla/lexlib/StringCopy.h
new file mode 100644
index 0000000..1812b4e
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexlib/StringCopy.h
@@ -0,0 +1,36 @@
+// Scintilla source code edit control
+/** @file StringCopy.h
+ ** Safe string copy function which always NUL terminates.
+ ** ELEMENTS macro for determining array sizes.
+ **/
+// Copyright 2013 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef STRINGCOPY_H
+#define STRINGCOPY_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+// Safer version of string copy functions like strcpy, wcsncpy, etc.
+// Instantiate over fixed length strings of both char and wchar_t.
+// May truncate if source doesn't fit into dest with room for NUL.
+
+template <typename T, size_t count>
+void StringCopy(T (&dest)[count], const T* source) {
+       for (size_t i=0; i<count; i++) {
+               dest[i] = source[i];
+               if (!source[i])
+                       break;
+       }
+       dest[count-1] = 0;
+}
+
+#define ELEMENTS(a) (sizeof(a) / sizeof(a[0]))
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/lexlib/StyleContext.cxx 
b/plugins/scintilla/scintilla/lexlib/StyleContext.cxx
index cf59fdd..9c3057a 100644
--- a/plugins/scintilla/scintilla/lexlib/StyleContext.cxx
+++ b/plugins/scintilla/scintilla/lexlib/StyleContext.cxx
@@ -5,28 +5,43 @@
 // Copyright 1998-2004 by Neil Hodgson <neilh scintilla org>
 // This file is in the public domain.
 
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <assert.h>
+#include <cstdlib>
+#include <cassert>
+#include <cctype>
 
 #include "ILexer.h"
 
 #include "LexAccessor.h"
 #include "Accessor.h"
 #include "StyleContext.h"
+#include "CharacterSet.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
-static void getRange(unsigned int start,
-               unsigned int end,
+bool StyleContext::MatchIgnoreCase(const char *s) {
+       if (MakeLowerCase(ch) != static_cast<unsigned char>(*s))
+               return false;
+       s++;
+       if (MakeLowerCase(chNext) != static_cast<unsigned char>(*s))
+               return false;
+       s++;
+       for (int n = 2; *s; n++) {
+               if (static_cast<unsigned char>(*s) !=
+                       MakeLowerCase(static_cast<unsigned char>(styler.SafeGetCharAt(currentPos + n, 0))))
+                       return false;
+               s++;
+       }
+       return true;
+}
+
+static void getRange(Sci_PositionU start,
+               Sci_PositionU end,
                LexAccessor &styler,
                char *s,
-               unsigned int len) {
-       unsigned int i = 0;
+               Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = styler[start + i];
                i++;
@@ -34,16 +49,16 @@ static void getRange(unsigned int start,
        s[i] = '\0';
 }
 
-void StyleContext::GetCurrent(char *s, unsigned int len) {
+void StyleContext::GetCurrent(char *s, Sci_PositionU len) {
        getRange(styler.GetStartSegment(), currentPos - 1, styler, s, len);
 }
 
-static void getRangeLowered(unsigned int start,
-               unsigned int end,
+static void getRangeLowered(Sci_PositionU start,
+               Sci_PositionU end,
                LexAccessor &styler,
                char *s,
-               unsigned int len) {
-       unsigned int i = 0;
+               Sci_PositionU len) {
+       Sci_PositionU i = 0;
        while ((i < end - start + 1) && (i < len-1)) {
                s[i] = static_cast<char>(tolower(styler[start + i]));
                i++;
@@ -51,6 +66,6 @@ static void getRangeLowered(unsigned int start,
        s[i] = '\0';
 }
 
-void StyleContext::GetCurrentLowered(char *s, unsigned int len) {
+void StyleContext::GetCurrentLowered(char *s, Sci_PositionU len) {
        getRangeLowered(styler.GetStartSegment(), currentPos - 1, styler, s, len);
 }
diff --git a/plugins/scintilla/scintilla/lexlib/StyleContext.h 
b/plugins/scintilla/scintilla/lexlib/StyleContext.h
index 73b7b51..a536822 100644
--- a/plugins/scintilla/scintilla/lexlib/StyleContext.h
+++ b/plugins/scintilla/scintilla/lexlib/StyleContext.h
@@ -12,13 +12,6 @@
 namespace Scintilla {
 #endif
 
-static inline int MakeLowerCase(int ch) {
-       if (ch < 'A' || ch > 'Z')
-               return ch;
-       else
-               return ch - 'A' + 'a';
-}
-
 // All languages handled so far can treat all characters >= 0x80 as one class
 // which just continues the current token or starts an identifier if in default.
 // DBCS treated specially as the second character can be < 0x80 and hence
@@ -26,15 +19,13 @@ static inline int MakeLowerCase(int ch) {
 class StyleContext {
        LexAccessor &styler;
        IDocumentWithLineEnd *multiByteAccess;
-       unsigned int endPos;
-       unsigned int lengthDocument;
-       
-       // Used for optimizing GetRelativeCharacter
-       unsigned int posRelative;
-       unsigned int currentPosLastRelative;
-       int offsetRelative;
+       Sci_PositionU endPos;
+       Sci_PositionU lengthDocument;
 
-       StyleContext &operator=(const StyleContext &);
+       // Used for optimizing GetRelativeCharacter
+       Sci_PositionU posRelative;
+       Sci_PositionU currentPosLastRelative;
+       Sci_Position offsetRelative;
 
        void GetNextChar() {
                if (multiByteAccess) {
@@ -43,30 +34,30 @@ class StyleContext {
                        chNext = static_cast<unsigned char>(styler.SafeGetCharAt(currentPos+width, 0));
                        widthNext = 1;
                }
-               // End of line determined from line end position, allowing CR, LF, 
+               // End of line determined from line end position, allowing CR, LF,
                // CRLF and Unicode line ends as set by document.
                if (currentLine < lineDocEnd)
-                       atLineEnd = static_cast<int>(currentPos) >= (lineStartNext-1);
+                       atLineEnd = static_cast<Sci_Position>(currentPos) >= (lineStartNext-1);
                else // Last line
-                       atLineEnd = static_cast<int>(currentPos) >= lineStartNext;
+                       atLineEnd = static_cast<Sci_Position>(currentPos) >= lineStartNext;
        }
 
 public:
-       unsigned int currentPos;
-       int currentLine;
-       int lineDocEnd;
-       int lineStartNext;
+       Sci_PositionU currentPos;
+       Sci_Position currentLine;
+       Sci_Position lineDocEnd;
+       Sci_Position lineStartNext;
        bool atLineStart;
        bool atLineEnd;
        int state;
        int chPrev;
        int ch;
-       int width;
+       Sci_Position width;
        int chNext;
-       int widthNext;
+       Sci_Position widthNext;
 
-       StyleContext(unsigned int startPos, unsigned int length,
-                        int initStyle, LexAccessor &styler_, char chMask=31) :
+       StyleContext(Sci_PositionU startPos, Sci_PositionU length,
+                        int initStyle, LexAccessor &styler_, char chMask='\377') :
                styler(styler_),
                multiByteAccess(0),
                endPos(startPos + length),
@@ -86,15 +77,15 @@ public:
                if (styler.Encoding() != enc8bit) {
                        multiByteAccess = styler.MultiByteAccess();
                }
-               styler.StartAt(startPos, chMask);
+               styler.StartAt(startPos /*, chMask*/);
                styler.StartSegment(startPos);
                currentLine = styler.GetLine(startPos);
                lineStartNext = styler.LineStart(currentLine+1);
-               lengthDocument = static_cast<unsigned int>(styler.Length());
+               lengthDocument = static_cast<Sci_PositionU>(styler.Length());
                if (endPos == lengthDocument)
                        endPos++;
                lineDocEnd = styler.GetLine(lengthDocument);
-               atLineStart = static_cast<unsigned int>(styler.LineStart(currentLine)) == startPos;
+               atLineStart = static_cast<Sci_PositionU>(styler.LineStart(currentLine)) == startPos;
 
                // Variable width is now 0 so GetNextChar gets the char at currentPos into chNext/widthNext
                width = 0;
@@ -104,6 +95,9 @@ public:
 
                GetNextChar();
        }
+       // Deleted so StyleContext objects can not be copied.
+       StyleContext(const StyleContext &) = delete;
+       StyleContext &operator=(const StyleContext &) = delete;
        void Complete() {
                styler.ColourTo(currentPos - ((currentPos > lengthDocument) ? 2 : 1), state);
                styler.Flush();
@@ -131,13 +125,13 @@ public:
                        atLineEnd = true;
                }
        }
-       void Forward(int nb) {
-               for (int i = 0; i < nb; i++) {
+       void Forward(Sci_Position nb) {
+               for (Sci_Position i = 0; i < nb; i++) {
                        Forward();
                }
        }
-       void ForwardBytes(int nb) {
-               size_t forwardPos = currentPos + nb;
+       void ForwardBytes(Sci_Position nb) {
+               const Sci_PositionU forwardPos = currentPos + nb;
                while (forwardPos > currentPos) {
                        Forward();
                }
@@ -154,13 +148,13 @@ public:
                styler.ColourTo(currentPos - ((currentPos > lengthDocument) ? 2 : 1), state);
                state = state_;
        }
-       int LengthCurrent() const {
+       Sci_Position LengthCurrent() const {
                return currentPos - styler.GetStartSegment();
        }
-       int GetRelative(int n) {
+       int GetRelative(Sci_Position n) {
                return static_cast<unsigned char>(styler.SafeGetCharAt(currentPos+n, 0));
        }
-       int GetRelativeCharacter(int n) {
+       int GetRelativeCharacter(Sci_Position n) {
                if (n == 0)
                        return ch;
                if (multiByteAccess) {
@@ -170,13 +164,13 @@ public:
                                posRelative = currentPos;
                                offsetRelative = 0;
                        }
-                       int diffRelative = n - offsetRelative;
-                       int posNew = multiByteAccess->GetRelativePosition(posRelative, diffRelative);
-                       int ch = multiByteAccess->GetCharacterAndWidth(posNew, 0);
+                       Sci_Position diffRelative = n - offsetRelative;
+                       Sci_Position posNew = multiByteAccess->GetRelativePosition(posRelative, diffRelative);
+                       const int chReturn = multiByteAccess->GetCharacterAndWidth(posNew, 0);
                        posRelative = posNew;
                        currentPosLastRelative = currentPos;
                        offsetRelative = n;
-                       return ch;
+                       return chReturn;
                } else {
                        // fast version for single byte encodings
                        return static_cast<unsigned char>(styler.SafeGetCharAt(currentPos + n, 0));
@@ -204,24 +198,10 @@ public:
                }
                return true;
        }
-       bool MatchIgnoreCase(const char *s) {
-               if (MakeLowerCase(ch) != static_cast<unsigned char>(*s))
-                       return false;
-               s++;
-               if (MakeLowerCase(chNext) != static_cast<unsigned char>(*s))
-                       return false;
-               s++;
-               for (int n=2; *s; n++) {
-                       if (static_cast<unsigned char>(*s) !=
-                               MakeLowerCase(static_cast<unsigned char>(styler.SafeGetCharAt(currentPos+n, 
0))))
-                               return false;
-                       s++;
-               }
-               return true;
-       }
        // Non-inline
-       void GetCurrent(char *s, unsigned int len);
-       void GetCurrentLowered(char *s, unsigned int len);
+       bool MatchIgnoreCase(const char *s);
+       void GetCurrent(char *s, Sci_PositionU len);
+       void GetCurrentLowered(char *s, Sci_PositionU len);
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/lexlib/SubStyles.h b/plugins/scintilla/scintilla/lexlib/SubStyles.h
index e6c34e0..f5b15e9 100644
--- a/plugins/scintilla/scintilla/lexlib/SubStyles.h
+++ b/plugins/scintilla/scintilla/lexlib/SubStyles.h
@@ -13,13 +13,14 @@ namespace Scintilla {
 #endif
 
 class WordClassifier {
+       int baseStyle;
        int firstStyle;
        int lenStyles;
        std::map<std::string, int> wordToStyle;
 
 public:
 
-       WordClassifier() : firstStyle(0), lenStyles(0) {
+       explicit WordClassifier(int baseStyle_) : baseStyle(baseStyle_), firstStyle(0), lenStyles(0) {
        }
 
        void Allocate(int firstStyle_, int lenStyles_) {
@@ -28,6 +29,10 @@ public:
                wordToStyle.clear();
        }
 
+       int Base() const {
+               return baseStyle;
+       }
+
        int Start() const {
                return firstStyle;
        }
@@ -57,10 +62,12 @@ public:
        void SetIdentifiers(int style, const char *identifiers) {
                while (*identifiers) {
                        const char *cpSpace = identifiers;
-                       while (*cpSpace && *cpSpace != ' ')
+                       while (*cpSpace && !(*cpSpace == ' ' || *cpSpace == '\t' || *cpSpace == '\r' || 
*cpSpace == '\n'))
                                cpSpace++;
-                       std::string word(identifiers, cpSpace - identifiers);
-                       wordToStyle[word] = style;
+                       if (cpSpace > identifiers) {
+                               std::string word(identifiers, cpSpace - identifiers);
+                               wordToStyle[word] = style;
+                       }
                        identifiers = cpSpace;
                        if (*identifiers)
                                identifiers++;
@@ -105,8 +112,8 @@ public:
                secondaryDistance(secondaryDistance_),
                allocated(0) {
                while (baseStyles[classifications]) {
+                       classifiers.push_back(WordClassifier(baseStyles[classifications]));
                        classifications++;
-                       classifiers.push_back(WordClassifier());
                }
        }
 
@@ -134,6 +141,14 @@ public:
                return (block >= 0) ? classifiers[block].Length() : 0;
        }
 
+       int BaseStyle(int subStyle) const {
+               int block = BlockFromStyle(subStyle);
+               if (block >= 0)
+                       return classifiers[block].Base();
+               else
+                       return subStyle;
+       }
+
        int DistanceToSecondaryStyles() const {
                return secondaryDistance;
        }
@@ -151,7 +166,8 @@ public:
        }
 
        const WordClassifier &Classifier(int baseStyle) const {
-               return classifiers[BlockFromBaseStyle(baseStyle)];
+               const int block = BlockFromBaseStyle(baseStyle);
+               return classifiers[block >= 0 ? block : 0];
        }
 };
 
diff --git a/plugins/scintilla/scintilla/lexlib/WordList.cxx b/plugins/scintilla/scintilla/lexlib/WordList.cxx
index 049bf6e..1780a1c 100644
--- a/plugins/scintilla/scintilla/lexlib/WordList.cxx
+++ b/plugins/scintilla/scintilla/lexlib/WordList.cxx
@@ -1,18 +1,17 @@
 // Scintilla source code edit control
-/** @file KeyWords.cxx
- ** Colourise for particular languages.
+/** @file WordList.cxx
+ ** Hold a list of words.
  **/
 // Copyright 1998-2002 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <stdarg.h>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
 
 #include <algorithm>
 
+#include "StringCopy.h"
 #include "WordList.h"
 
 #ifdef SCI_NAMESPACE
@@ -28,47 +27,49 @@ static char **ArrayFromWordList(char *wordlist, int *len, bool onlyLineEnds = fa
        int words = 0;
        // For rapid determination of whether a character is a separator, build
        // a look up table.
-       bool wordSeparator[256];
-       for (int i=0; i<256; i++) {
-               wordSeparator[i] = false;
-       }
-       wordSeparator['\r'] = true;
-       wordSeparator['\n'] = true;
+       bool wordSeparator[256] = {};   // Initialise all to false.
+       wordSeparator[static_cast<unsigned int>('\r')] = true;
+       wordSeparator[static_cast<unsigned int>('\n')] = true;
        if (!onlyLineEnds) {
-               wordSeparator[' '] = true;
-               wordSeparator['\t'] = true;
+               wordSeparator[static_cast<unsigned int>(' ')] = true;
+               wordSeparator[static_cast<unsigned int>('\t')] = true;
        }
        for (int j = 0; wordlist[j]; j++) {
-               int curr = static_cast<unsigned char>(wordlist[j]);
+               const int curr = static_cast<unsigned char>(wordlist[j]);
                if (!wordSeparator[curr] && wordSeparator[prev])
                        words++;
                prev = curr;
        }
        char **keywords = new char *[words + 1];
-       words = 0;
-       prev = '\0';
-       size_t slen = strlen(wordlist);
-       for (size_t k = 0; k < slen; k++) {
-               if (!wordSeparator[static_cast<unsigned char>(wordlist[k])]) {
-                       if (!prev) {
-                               keywords[words] = &wordlist[k];
-                               words++;
+       int wordsStore = 0;
+       const size_t slen = strlen(wordlist);
+       if (words) {
+               prev = '\0';
+               for (size_t k = 0; k < slen; k++) {
+                       if (!wordSeparator[static_cast<unsigned char>(wordlist[k])]) {
+                               if (!prev) {
+                                       keywords[wordsStore] = &wordlist[k];
+                                       wordsStore++;
+                               }
+                       } else {
+                               wordlist[k] = '\0';
                        }
-               } else {
-                       wordlist[k] = '\0';
+                       prev = wordlist[k];
                }
-               prev = wordlist[k];
        }
-       keywords[words] = &wordlist[slen];
-       *len = words;
+       assert(wordsStore < (words + 1));
+       keywords[wordsStore] = &wordlist[slen];
+       *len = wordsStore;
        return keywords;
 }
 
 WordList::WordList(bool onlyLineEnds_) :
        words(0), list(0), len(0), onlyLineEnds(onlyLineEnds_) {
+       // Prevent warnings by static analyzers about uninitialized starts.
+       starts[0] = -1;
 }
 
-WordList::~WordList() { 
+WordList::~WordList() {
        Clear();
 }
 
@@ -103,7 +104,7 @@ void WordList::Clear() {
 #ifdef _MSC_VER
 
 static bool cmpWords(const char *a, const char *b) {
-       return strcmp(a, b) == -1;
+       return strcmp(a, b) < 0;
 }
 
 #else
@@ -113,23 +114,23 @@ static int cmpWords(const void *a, const void *b) {
 }
 
 static void SortWordList(char **words, unsigned int len) {
-       qsort(reinterpret_cast<void *>(words), len, sizeof(*words), cmpWords);
+       qsort(static_cast<void *>(words), len, sizeof(*words), cmpWords);
 }
 
 #endif
 
 void WordList::Set(const char *s) {
        Clear();
-       list = new char[strlen(s) + 1];
-       strcpy(list, s);
+       const size_t lenS = strlen(s) + 1;
+       list = new char[lenS];
+       memcpy(list, s, lenS);
        words = ArrayFromWordList(list, &len, onlyLineEnds);
 #ifdef _MSC_VER
        std::sort(words, words + len, cmpWords);
 #else
        SortWordList(words, len);
 #endif
-       for (unsigned int k = 0; k < (sizeof(starts) / sizeof(starts[0])); k++)
-               starts[k] = -1;
+       std::fill(starts, starts + ELEMENTS(starts), -1);
        for (int l = len - 1; l >= 0; l--) {
                unsigned char indexChar = words[l][0];
                starts[indexChar] = l;
@@ -144,7 +145,7 @@ void WordList::Set(const char *s) {
 bool WordList::InList(const char *s) const {
        if (0 == words)
                return false;
-       unsigned char firstChar = s[0];
+       const unsigned char firstChar = s[0];
        int j = starts[firstChar];
        if (j >= 0) {
                while (static_cast<unsigned char>(words[j][0]) == firstChar) {
@@ -161,7 +162,7 @@ bool WordList::InList(const char *s) const {
                        j++;
                }
        }
-       j = starts['^'];
+       j = starts[static_cast<unsigned int>('^')];
        if (j >= 0) {
                while (words[j][0] == '^') {
                        const char *a = words[j] + 1;
@@ -186,7 +187,7 @@ bool WordList::InList(const char *s) const {
 bool WordList::InListAbbreviated(const char *s, const char marker) const {
        if (0 == words)
                return false;
-       unsigned char firstChar = s[0];
+       const unsigned char firstChar = s[0];
        int j = starts[firstChar];
        if (j >= 0) {
                while (static_cast<unsigned char>(words[j][0]) == firstChar) {
@@ -213,7 +214,7 @@ bool WordList::InListAbbreviated(const char *s, const char marker) const {
                        j++;
                }
        }
-       j = starts['^'];
+       j = starts[static_cast<unsigned int>('^')];
        if (j >= 0) {
                while (words[j][0] == '^') {
                        const char *a = words[j] + 1;
@@ -230,6 +231,66 @@ bool WordList::InListAbbreviated(const char *s, const char marker) const {
        return false;
 }
 
+/** similar to InListAbbreviated, but word s can be a abridged version of a keyword.
+* eg. the keyword is defined as "after.~:". This means the word must have a prefix (begins with) of
+* "after." and suffix (ends with) of ":" to be a keyword, Hence "after.field:" , "after.form.item:" are 
valid.
+* Similarly "~.is.valid" keyword is suffix only... hence "field.is.valid" , "form.is.valid" are valid.
+* The marker is ~ in this case.
+* No multiple markers check is done and wont work.
+*/
+bool WordList::InListAbridged(const char *s, const char marker) const {
+       if (0 == words)
+               return false;
+       const unsigned char firstChar = s[0];
+       int j = starts[firstChar];
+       if (j >= 0) {
+               while (static_cast<unsigned char>(words[j][0]) == firstChar) {
+                       const char *a = words[j];
+                       const char *b = s;
+                       while (*a && *a == *b) {
+                               a++;
+                               if (*a == marker) {
+                                       a++;
+                                       const size_t suffixLengthA = strlen(a);
+                                       const size_t suffixLengthB = strlen(b);
+                                       if (suffixLengthA >= suffixLengthB)
+                                               break;
+                                       b = b + suffixLengthB - suffixLengthA - 1;
+                               }
+                               b++;
+                       }
+                       if (!*a  && !*b)
+                               return true;
+                       j++;
+               }
+       }
+
+       j = starts[static_cast<unsigned int>(marker)];
+       if (j >= 0) {
+               while (words[j][0] == marker) {
+                       const char *a = words[j] + 1;
+                       const char *b = s;
+                       const size_t suffixLengthA = strlen(a);
+                       const size_t suffixLengthB = strlen(b);
+                       if (suffixLengthA > suffixLengthB) {
+                               j++;
+                               continue;
+                       }
+                       b = b + suffixLengthB - suffixLengthA;
+
+                       while (*a && *a == *b) {
+                               a++;
+                               b++;
+                       }
+                       if (!*a && !*b)
+                               return true;
+                       j++;
+               }
+       }
+
+       return false;
+}
+
 const char *WordList::WordAt(int n) const {
        return words[n];
 }
diff --git a/plugins/scintilla/scintilla/lexlib/WordList.h b/plugins/scintilla/scintilla/lexlib/WordList.h
index 9c8285e..b1f8c85 100644
--- a/plugins/scintilla/scintilla/lexlib/WordList.h
+++ b/plugins/scintilla/scintilla/lexlib/WordList.h
@@ -22,7 +22,7 @@ class WordList {
        bool onlyLineEnds;      ///< Delimited by any white space or only line ends
        int starts[256];
 public:
-       WordList(bool onlyLineEnds_ = false);
+       explicit WordList(bool onlyLineEnds_ = false);
        ~WordList();
        operator bool() const;
        bool operator!=(const WordList &other) const;
@@ -31,6 +31,7 @@ public:
        void Set(const char *s);
        bool InList(const char *s) const;
        bool InListAbbreviated(const char *s, const char marker) const;
+       bool InListAbridged(const char *s, const char marker) const;
        const char *WordAt(int n) const;
 };
 
diff --git a/plugins/scintilla/scintilla/src/AutoComplete.cxx 
b/plugins/scintilla/scintilla/src/AutoComplete.cxx
index d55af85..1c847ce 100644
--- a/plugins/scintilla/scintilla/src/AutoComplete.cxx
+++ b/plugins/scintilla/scintilla/src/AutoComplete.cxx
@@ -5,20 +5,23 @@
 // Copyright 1998-2003 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <assert.h>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cstdio>
 
-#include <algorithm>
+#include <stdexcept>
 #include <string>
 #include <vector>
+#include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
+#include "Scintilla.h"
 #include "CharacterSet.h"
+#include "Position.h"
 #include "AutoComplete.h"
-#include "Scintilla.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
@@ -30,7 +33,6 @@ AutoComplete::AutoComplete() :
        typesep('?'),
        ignoreCase(false),
        chooseSingle(false),
-       lb(0),
        posStart(0),
        startLen(0),
        cancelAtStartPos(true),
@@ -40,16 +42,12 @@ AutoComplete::AutoComplete() :
        widthLBDefault(100),
        heightLBDefault(100),
        autoSort(SC_ORDER_PRESORTED) {
-       lb = ListBox::Allocate();
-       stopChars[0] = '\0';
-       fillUpChars[0] = '\0';
+       lb.reset(ListBox::Allocate());
 }
 
 AutoComplete::~AutoComplete() {
        if (lb) {
                lb->Destroy();
-               delete lb;
-               lb = 0;
        }
 }
 
@@ -58,7 +56,7 @@ bool AutoComplete::Active() const {
 }
 
 void AutoComplete::Start(Window &parent, int ctrlID,
-       int position, Point location, int startLen_,
+       Sci::Position position, Point location, int startLen_,
        int lineHeight, bool unicodeMode, int technology) {
        if (active) {
                Cancel();
@@ -71,21 +69,19 @@ void AutoComplete::Start(Window &parent, int ctrlID,
 }
 
 void AutoComplete::SetStopChars(const char *stopChars_) {
-       strncpy(stopChars, stopChars_, sizeof(stopChars));
-       stopChars[sizeof(stopChars) - 1] = '\0';
+       stopChars = stopChars_;
 }
 
 bool AutoComplete::IsStopChar(char ch) {
-       return ch && strchr(stopChars, ch);
+       return ch && (stopChars.find(ch) != std::string::npos);
 }
 
 void AutoComplete::SetFillUpChars(const char *fillUpChars_) {
-       strncpy(fillUpChars, fillUpChars_, sizeof(fillUpChars));
-       fillUpChars[sizeof(fillUpChars) - 1] = '\0';
+       fillUpChars = fillUpChars_;
 }
 
 bool AutoComplete::IsFillUpChar(char ch) {
-       return ch && strchr(fillUpChars, ch);
+       return ch && (fillUpChars.find(ch) != std::string::npos);
 }
 
 void AutoComplete::SetSeparator(char separator_) {
@@ -133,9 +129,9 @@ struct Sorter {
        }
 
        bool operator()(int a, int b) {
-               int lenA = indices[a * 2 + 1] - indices[a * 2];
-               int lenB = indices[b * 2 + 1] - indices[b * 2];
-               int len  = std::min(lenA, lenB);
+               const int lenA = indices[a * 2 + 1] - indices[a * 2];
+               const int lenB = indices[b * 2 + 1] - indices[b * 2];
+               const int len  = std::min(lenA, lenB);
                int cmp;
                if (ac->ignoreCase)
                        cmp = CompareNCaseInsensitive(list + indices[a * 2], list + indices[b * 2], len);
@@ -158,7 +154,7 @@ void AutoComplete::SetList(const char *list) {
 
        Sorter IndexSort(this, list);
        sortMatrix.clear();
-       for (int i = 0; i < (int)IndexSort.indices.size() / 2; ++i)
+       for (int i = 0; i < static_cast<int>(IndexSort.indices.size()) / 2; ++i)
                sortMatrix.push_back(i);
        std::sort(sortMatrix.begin(), sortMatrix.end(), IndexSort);
        if (autoSort == SC_ORDER_CUSTOM || sortMatrix.size() < 2) {
@@ -171,7 +167,9 @@ void AutoComplete::SetList(const char *list) {
        char item[maxItemLen];
        for (size_t i = 0; i < sortMatrix.size(); ++i) {
                int wordLen = IndexSort.indices[sortMatrix[i] * 2 + 2] - IndexSort.indices[sortMatrix[i] * 2];
-               strncpy(item, list + IndexSort.indices[sortMatrix[i] * 2], wordLen);
+               if (wordLen > maxItemLen-2)
+                       wordLen = maxItemLen - 2;
+               memcpy(item, list + IndexSort.indices[sortMatrix[i] * 2], wordLen);
                if ((i+1) == sortMatrix.size()) {
                        // Last item so remove separator if present
                        if ((wordLen > 0) && (item[wordLen-1] == separator))
@@ -186,7 +184,7 @@ void AutoComplete::SetList(const char *list) {
                item[wordLen] = '\0';
                sortedList += item;
        }
-       for (int i = 0; i < (int)sortMatrix.size(); ++i)
+       for (int i = 0; i < static_cast<int>(sortMatrix.size()); ++i)
                sortMatrix[i] = i;
        lb->SetList(sortedList.c_str(), separator, typesep);
 }
@@ -217,7 +215,7 @@ void AutoComplete::Cancel() {
 
 
 void AutoComplete::Move(int delta) {
-       int count = lb->Length();
+       const int count = lb->Length();
        int current = lb->GetSelection();
        current += delta;
        if (current >= count)
diff --git a/plugins/scintilla/scintilla/src/AutoComplete.h b/plugins/scintilla/scintilla/src/AutoComplete.h
index 9977196..1799865 100644
--- a/plugins/scintilla/scintilla/src/AutoComplete.h
+++ b/plugins/scintilla/scintilla/src/AutoComplete.h
@@ -16,8 +16,8 @@ namespace Scintilla {
  */
 class AutoComplete {
        bool active;
-       char stopChars[256];
-       char fillUpChars[256];
+       std::string stopChars;
+       std::string fillUpChars;
        char separator;
        char typesep; // Type seperator
        enum { maxItemLen=1000 };
@@ -27,8 +27,8 @@ public:
 
        bool ignoreCase;
        bool chooseSingle;
-       ListBox *lb;
-       int posStart;
+       std::unique_ptr<ListBox> lb;
+       Sci::Position posStart;
        int startLen;
        /// Should autocompletion be canceled if editor's currentPos <= startPos?
        bool cancelAtStartPos;
@@ -50,7 +50,7 @@ public:
        bool Active() const;
 
        /// Display the auto completion list positioned to be near a character position
-       void Start(Window &parent, int ctrlID, int position, Point location,
+       void Start(Window &parent, int ctrlID, Sci::Position position, Point location,
                int startLen_, int lineHeight, bool unicodeMode, int technology);
 
        /// The stop chars are characters which, when typed, cause the auto completion list to disappear
@@ -65,13 +65,13 @@ public:
        void SetSeparator(char separator_);
        char GetSeparator() const;
 
-       /// The typesep character is used for seperating the word from the type
+       /// The typesep character is used for separating the word from the type
        void SetTypesep(char separator_);
        char GetTypesep() const;
 
        /// The list string contains a sequence of words separated by the separator character
        void SetList(const char *list);
-       
+
        /// Return the position of the currently selected list item
        int GetSelection() const;
 
diff --git a/plugins/scintilla/scintilla/src/CallTip.cxx b/plugins/scintilla/scintilla/src/CallTip.cxx
index c12a6e8..de2b37c 100644
--- a/plugins/scintilla/scintilla/src/CallTip.cxx
+++ b/plugins/scintilla/scintilla/src/CallTip.cxx
@@ -5,15 +5,21 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
+#include <cstdlib>
+#include <cstring>
+#include <cstdio>
 
+#include <stdexcept>
 #include <string>
+#include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
+
+#include "StringCopy.h"
+#include "Position.h"
 #include "CallTip.h"
 
 #ifdef SCI_NAMESPACE
@@ -85,7 +91,7 @@ void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
        int posStart, int posEnd, int ytext, PRectangle rcClient,
        bool highlight, bool draw) {
        s += posStart;
-       int len = posEnd - posStart;
+       const int len = posEnd - posStart;
 
        // Divide the text into sections that are all text, or that are
        // single arrows or single tab characters (if tabSize > 0).
@@ -107,13 +113,15 @@ void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
                int endSeg = ends[seg];
                if (endSeg > startSeg) {
                        if (IsArrowCharacter(s[startSeg])) {
-                               bool upArrow = s[startSeg] == '\001';
-                               rcClient.left = x;
-                               rcClient.right = rcClient.left + widthArrow;
+                               xEnd = x + widthArrow;
+                               const bool upArrow = s[startSeg] == '\001';
+                               rcClient.left = static_cast<XYPOSITION>(x);
+                               rcClient.right = static_cast<XYPOSITION>(xEnd);
                                if (draw) {
                                        const int halfWidth = widthArrow / 2 - 3;
-                                       const int centreX = rcClient.left + widthArrow / 2 - 1;
-                                       const int centreY = (rcClient.top + rcClient.bottom) / 2;
+                                       const int quarterWidth = halfWidth / 2;
+                                       const int centreX = x + widthArrow / 2 - 1;
+                                       const int centreY = static_cast<int>(rcClient.top + rcClient.bottom) 
/ 2;
                                        surface->FillRectangle(rcClient, colourBG);
                                        PRectangle rcClientInner(rcClient.left + 1, rcClient.top + 1,
                                                                 rcClient.right - 2, rcClient.bottom - 1);
@@ -121,23 +129,20 @@ void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
 
                                        if (upArrow) {      // Up arrow
                                                Point pts[] = {
-                                               Point(centreX - halfWidth, centreY + halfWidth / 2),
-                                               Point(centreX + halfWidth, centreY + halfWidth / 2),
-                                               Point(centreX, centreY - halfWidth + halfWidth / 2),
+                                               Point::FromInts(centreX - halfWidth, centreY + quarterWidth),
+                                               Point::FromInts(centreX + halfWidth, centreY + quarterWidth),
+                                               Point::FromInts(centreX, centreY - halfWidth + quarterWidth),
                                                };
-                                               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                                                               colourBG, colourBG);
+                                               surface->Polygon(pts, ELEMENTS(pts), colourBG, colourBG);
                                        } else {            // Down arrow
                                                Point pts[] = {
-                                               Point(centreX - halfWidth, centreY - halfWidth / 2),
-                                               Point(centreX + halfWidth, centreY - halfWidth / 2),
-                                               Point(centreX, centreY + halfWidth - halfWidth / 2),
+                                               Point::FromInts(centreX - halfWidth, centreY - quarterWidth),
+                                               Point::FromInts(centreX + halfWidth, centreY - quarterWidth),
+                                               Point::FromInts(centreX, centreY + halfWidth - quarterWidth),
                                                };
-                                               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                                                               colourBG, colourBG);
+                                               surface->Polygon(pts, ELEMENTS(pts), colourBG, colourBG);
                                        }
                                }
-                               xEnd = rcClient.right;
                                offsetMain = xEnd;
                                if (upArrow) {
                                        rectUp = rcClient;
@@ -147,11 +152,11 @@ void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
                        } else if (IsTabCharacter(s[startSeg])) {
                                xEnd = NextTabPos(x);
                        } else {
-                               xEnd = x + surface->WidthText(font, s + startSeg, endSeg - startSeg);
+                               xEnd = x + RoundXYPosition(surface->WidthText(font, s + startSeg, endSeg - 
startSeg));
                                if (draw) {
-                                       rcClient.left = x;
-                                       rcClient.right = xEnd;
-                                       surface->DrawTextTransparent(rcClient, font, ytext,
+                                       rcClient.left = static_cast<XYPOSITION>(x);
+                                       rcClient.right = static_cast<XYPOSITION>(xEnd);
+                                       surface->DrawTextTransparent(rcClient, font, 
static_cast<XYPOSITION>(ytext),
                                                                                s+startSeg, endSeg - startSeg,
                                                                     highlight ? colourSel : colourUnSel);
                                }
@@ -164,16 +169,16 @@ void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
 
 int CallTip::PaintContents(Surface *surfaceWindow, bool draw) {
        PRectangle rcClientPos = wCallTip.GetClientPosition();
-       PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
+       PRectangle rcClientSize(0.0f, 0.0f, rcClientPos.right - rcClientPos.left,
                                rcClientPos.bottom - rcClientPos.top);
-       PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
+       PRectangle rcClient(1.0f, 1.0f, rcClientSize.right - 1, rcClientSize.bottom - 1);
 
        // To make a nice small call tip window, it is only sized to fit most normal characters without 
accents
-       int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font);
+       int ascent = RoundXYPosition(surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font));
 
        // For each line...
        // Draw the definition in three parts: before highlight, highlighted, after highlight
-       int ytext = rcClient.top + ascent + 1;
+       int ytext = static_cast<int>(rcClient.top) + ascent + 1;
        rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1;
        const char *chunkVal = val.c_str();
        bool moreChunks = true;
@@ -185,16 +190,16 @@ int CallTip::PaintContents(Surface *surfaceWindow, bool draw) {
                        chunkEnd = chunkVal + strlen(chunkVal);
                        moreChunks = false;
                }
-               int chunkOffset = chunkVal - val.c_str();
-               int chunkLength = chunkEnd - chunkVal;
-               int chunkEndOffset = chunkOffset + chunkLength;
-               int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset);
-               thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset);
+               const int chunkOffset = static_cast<int>(chunkVal - val.c_str());
+               const int chunkLength = static_cast<int>(chunkEnd - chunkVal);
+               const int chunkEndOffset = chunkOffset + chunkLength;
+               int thisStartHighlight = std::max(startHighlight, chunkOffset);
+               thisStartHighlight = std::min(thisStartHighlight, chunkEndOffset);
                thisStartHighlight -= chunkOffset;
-               int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset);
-               thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset);
+               int thisEndHighlight = std::max(endHighlight, chunkOffset);
+               thisEndHighlight = std::min(thisEndHighlight, chunkEndOffset);
                thisEndHighlight -= chunkOffset;
-               rcClient.top = ytext - ascent - 1;
+               rcClient.top = static_cast<XYPOSITION>(ytext - ascent - 1);
 
                int x = insetX;     // start each line at this inset
 
@@ -208,7 +213,7 @@ int CallTip::PaintContents(Surface *surfaceWindow, bool draw) {
                chunkVal = chunkEnd + 1;
                ytext += lineHeight;
                rcClient.bottom += lineHeight;
-               maxWidth = Platform::Maximum(maxWidth, x);
+               maxWidth = std::max(maxWidth, x);
        }
        return maxWidth;
 }
@@ -217,9 +222,9 @@ void CallTip::PaintCT(Surface *surfaceWindow) {
        if (val.empty())
                return;
        PRectangle rcClientPos = wCallTip.GetClientPosition();
-       PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
+       PRectangle rcClientSize(0.0f, 0.0f, rcClientPos.right - rcClientPos.left,
                                rcClientPos.bottom - rcClientPos.top);
-       PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
+       PRectangle rcClient(1.0f, 1.0f, rcClientSize.right - 1, rcClientSize.bottom - 1);
 
        surfaceWindow->FillRectangle(rcClient, colourBG);
 
@@ -229,13 +234,13 @@ void CallTip::PaintCT(Surface *surfaceWindow) {
 #ifndef __APPLE__
        // OSX doesn't put borders on "help tags"
        // Draw a raised border around the edges of the window
-       surfaceWindow->MoveTo(0, rcClientSize.bottom - 1);
+       surfaceWindow->MoveTo(0, static_cast<int>(rcClientSize.bottom) - 1);
        surfaceWindow->PenColour(colourShade);
-       surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1);
-       surfaceWindow->LineTo(rcClientSize.right - 1, 0);
+       surfaceWindow->LineTo(static_cast<int>(rcClientSize.right) - 1, static_cast<int>(rcClientSize.bottom) 
- 1);
+       surfaceWindow->LineTo(static_cast<int>(rcClientSize.right) - 1, 0);
        surfaceWindow->PenColour(colourLight);
        surfaceWindow->LineTo(0, 0);
-       surfaceWindow->LineTo(0, rcClientSize.bottom - 1);
+       surfaceWindow->LineTo(0, static_cast<int>(rcClientSize.bottom) - 1);
 #endif
 }
 
@@ -247,16 +252,14 @@ void CallTip::MouseClick(Point pt) {
                clickPlace = 2;
 }
 
-PRectangle CallTip::CallTipStart(int pos, Point pt, int textHeight, const char *defn,
+PRectangle CallTip::CallTipStart(Sci::Position pos, Point pt, int textHeight, const char *defn,
                                  const char *faceName, int size,
                                  int codePage_, int characterSet,
                                                                 int technology, Window &wParent) {
        clickPlace = 0;
        val = defn;
        codePage = codePage_;
-       Surface *surfaceMeasure = Surface::Allocate(technology);
-       if (!surfaceMeasure)
-               return PRectangle();
+       std::unique_ptr<Surface> surfaceMeasure(Surface::Allocate(technology));
        surfaceMeasure->Init(wParent.GetID());
        surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage);
        surfaceMeasure->SetDBCSMode(codePage);
@@ -264,7 +267,7 @@ PRectangle CallTip::CallTipStart(int pos, Point pt, int textHeight, const char *
        endHighlight = 0;
        inCallTipMode = true;
        posStartCallTip = pos;
-       int deviceHeight = surfaceMeasure->DeviceHeightFont(size);
+       XYPOSITION deviceHeight = static_cast<XYPOSITION>(surfaceMeasure->DeviceHeightFont(size));
        FontParameters fp(faceName, deviceHeight / SC_FONT_SIZE_MULTIPLIER, SC_WEIGHT_NORMAL, false, 0, 
technology, characterSet);
        font.Create(fp);
        // Look for multiple lines in the text
@@ -275,18 +278,17 @@ PRectangle CallTip::CallTipStart(int pos, Point pt, int textHeight, const char *
        rectUp = PRectangle(0,0,0,0);
        rectDown = PRectangle(0,0,0,0);
        offsetMain = insetX;            // changed to right edge of any arrows
-       int width = PaintContents(surfaceMeasure, false) + insetX;
+       const int width = PaintContents(surfaceMeasure.get(), false) + insetX;
        while ((newline = strchr(look, '\n')) != NULL) {
                look = newline + 1;
                numLines++;
        }
-       lineHeight = surfaceMeasure->Height(font);
+       lineHeight = RoundXYPosition(surfaceMeasure->Height(font));
 
        // The returned
        // rectangle is aligned to the right edge of the last arrow encountered in
        // the tip text, else to the tip text left edge.
-       int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + borderHeight * 2;
-       delete surfaceMeasure;
+       int height = lineHeight * numLines - static_cast<int>(surfaceMeasure->InternalLeading(font)) + 
borderHeight * 2;
        if (above) {
                return PRectangle(pt.x - offsetMain, pt.y - verticalOffset - height, pt.x + width - 
offsetMain, pt.y - verticalOffset);
        } else {
diff --git a/plugins/scintilla/scintilla/src/CallTip.h b/plugins/scintilla/scintilla/src/CallTip.h
index 840aa26..ad669fa 100644
--- a/plugins/scintilla/scintilla/src/CallTip.h
+++ b/plugins/scintilla/scintilla/src/CallTip.h
@@ -27,21 +27,18 @@ class CallTip {
        bool useStyleCallTip;   // if true, STYLE_CALLTIP should be used
        bool above;             // if true, display calltip above text
 
-       // Private so CallTip objects can not be copied
-       CallTip(const CallTip &);
-       CallTip &operator=(const CallTip &);
        void DrawChunk(Surface *surface, int &x, const char *s,
                int posStart, int posEnd, int ytext, PRectangle rcClient,
                bool highlight, bool draw);
        int PaintContents(Surface *surfaceWindow, bool draw);
-       bool IsTabCharacter(char c) const;
+       bool IsTabCharacter(char ch) const;
        int NextTabPos(int x) const;
 
 public:
        Window wCallTip;
        Window wDraw;
        bool inCallTipMode;
-       int posStartCallTip;
+       Sci::Position posStartCallTip;
        ColourDesired colourBG;
        ColourDesired colourUnSel;
        ColourDesired colourSel;
@@ -56,6 +53,9 @@ public:
        int verticalOffset; // pixel offset up or down of the calltip with respect to the line
 
        CallTip();
+       // Deleted so CallTip objects can not be copied.
+       CallTip(const CallTip &) = delete;
+       CallTip &operator=(const CallTip &) = delete;
        ~CallTip();
 
        void PaintCT(Surface *surfaceWindow);
@@ -63,7 +63,7 @@ public:
        void MouseClick(Point pt);
 
        /// Setup the calltip and return a rectangle of the area required.
-       PRectangle CallTipStart(int pos, Point pt, int textHeight, const char *defn,
+       PRectangle CallTipStart(Sci::Position pos, Point pt, int textHeight, const char *defn,
                const char *faceName, int size, int codePage_,
                int characterSet, int technology, Window &wParent);
 
diff --git a/plugins/scintilla/scintilla/src/CaseConvert.cxx b/plugins/scintilla/scintilla/src/CaseConvert.cxx
index 6f43df8..24205dd 100644
--- a/plugins/scintilla/scintilla/src/CaseConvert.cxx
+++ b/plugins/scintilla/scintilla/src/CaseConvert.cxx
@@ -2,7 +2,7 @@
 // Encoding: UTF-8
 /** @file CaseConvert.cxx
  ** Case fold characters and convert them to upper or lower case.
- ** Tables automatically regenerated by scripts/GenerateCharacterCategory.py
+ ** Tables automatically regenerated by scripts/GenerateCaseConvert.py
  ** Should only be rarely regenerated for new versions of Unicode.
  **/
 // Copyright 2013 by Neil Hodgson <neilh scintilla org>
@@ -10,9 +10,12 @@
 
 #include <cstring>
 
+#include <stdexcept>
+#include <string>
 #include <vector>
 #include <algorithm>
 
+#include "StringCopy.h"
 #include "CaseConvert.h"
 #include "UniConversion.h"
 #include "UnicodeFromUTF8.h"
@@ -53,7 +56,7 @@ int symmetricCaseConversionRanges[] = {
 1121,1120,17,2, 
 1163,1162,27,2, 
 1218,1217,7,2, 
-1233,1232,44,2, 
+1233,1232,48,2, 
 1377,1329,38,1, 
 7681,7680,75,2, 
 7841,7840,48,2, 
@@ -69,13 +72,17 @@ int symmetricCaseConversionRanges[] = {
 11393,11392,50,2, 
 11520,4256,38,1, 
 42561,42560,23,2, 
-42625,42624,12,2, 
+42625,42624,14,2, 
 42787,42786,7,2, 
 42803,42802,31,2, 
 42879,42878,5,2, 
-42913,42912,5,2, 
+42903,42902,10,2, 
 65345,65313,26,1, 
 66600,66560,40,1, 
+66776,66736,36,1, 
+68800,68736,51,1, 
+71872,71840,32,1, 
+125218,125184,34,1, 
 
 //--Autogenerated -- end of section automatically generated
 };
@@ -134,13 +141,17 @@ int symmetricCaseConversions[] = {
 599,394, 
 601,399, 
 603,400, 
+604,42923, 
 608,403, 
+609,42924, 
 611,404, 
 613,42893, 
 614,42922, 
 616,407, 
 617,406, 
+618,42926, 
 619,11362, 
+620,42925, 
 623,412, 
 625,11374, 
 626,413, 
@@ -148,12 +159,15 @@ int symmetricCaseConversions[] = {
 637,11364, 
 640,422, 
 643,425, 
+647,42929, 
 648,430, 
 649,580, 
 650,433, 
 651,434, 
 652,581, 
 658,439, 
+669,42930, 
+670,42928, 
 881,880, 
 883,882, 
 887,886, 
@@ -169,6 +183,7 @@ int symmetricCaseConversions[] = {
 974,911, 
 983,975, 
 1010,1017, 
+1011,895, 
 1016,1015, 
 1019,1018, 
 1231,1216, 
@@ -219,6 +234,9 @@ int symmetricCaseConversions[] = {
 42892,42891, 
 42897,42896, 
 42899,42898, 
+42933,42932, 
+42935,42934, 
+43859,42931, 
 
 //--Autogenerated -- end of section automatically generated
 };
@@ -232,132 +250,313 @@ const char *complexCaseConversions =
 // Original | Folded | Upper | Lower |
 //++Autogenerated -- start of section automatically generated
 //**2 \(\*\n\)
-"µ|μ|Μ||"
-"ß|ss|SS||"
-"İ|i̇||i̇|"
-"ı||I||"
-"ʼn|ʼn|ʼN||"
-"ſ|s|S||"
-"Dž|dž|DŽ|dž|"
-"Lj|lj|LJ|lj|"
-"Nj|nj|NJ|nj|"
-"ǰ|ǰ|J̌||"
-"Dz|dz|DZ|dz|"
-"ͅ|ι|Ι||"
-"ΐ|ΐ|Ϊ́||"
-"ΰ|ΰ|Ϋ́||"
-"ς|σ|Σ||"
-"ϐ|β|Β||"
-"ϑ|θ|Θ||"
-"ϕ|φ|Φ||"
-"ϖ|π|Π||"
-"ϰ|κ|Κ||"
-"ϱ|ρ|Ρ||"
-"ϴ|θ||θ|"
-"ϵ|ε|Ε||"
-"և|եւ|ԵՒ||"
-"ẖ|ẖ|H̱||"
-"ẗ|ẗ|T̈||"
-"ẘ|ẘ|W̊||"
-"ẙ|ẙ|Y̊||"
-"ẚ|aʾ|Aʾ||"
-"ẛ|ṡ|Ṡ||"
-"ẞ|ss||ß|"
-"ὐ|ὐ|Υ̓||"
-"ὒ|ὒ|Υ̓̀||"
-"ὔ|ὔ|Υ̓́||"
-"ὖ|ὖ|Υ̓͂||"
-"ᾀ|ἀι|ἈΙ||"
-"ᾁ|ἁι|ἉΙ||"
-"ᾂ|ἂι|ἊΙ||"
-"ᾃ|ἃι|ἋΙ||"
-"ᾄ|ἄι|ἌΙ||"
-"ᾅ|ἅι|ἍΙ||"
-"ᾆ|ἆι|ἎΙ||"
-"ᾇ|ἇι|ἏΙ||"
-"ᾈ|ἀι|ἈΙ|ᾀ|"
-"ᾉ|ἁι|ἉΙ|ᾁ|"
-"ᾊ|ἂι|ἊΙ|ᾂ|"
-"ᾋ|ἃι|ἋΙ|ᾃ|"
-"ᾌ|ἄι|ἌΙ|ᾄ|"
-"ᾍ|ἅι|ἍΙ|ᾅ|"
-"ᾎ|ἆι|ἎΙ|ᾆ|"
-"ᾏ|ἇι|ἏΙ|ᾇ|"
-"ᾐ|ἠι|ἨΙ||"
-"ᾑ|ἡι|ἩΙ||"
-"ᾒ|ἢι|ἪΙ||"
-"ᾓ|ἣι|ἫΙ||"
-"ᾔ|ἤι|ἬΙ||"
-"ᾕ|ἥι|ἭΙ||"
-"ᾖ|ἦι|ἮΙ||"
-"ᾗ|ἧι|ἯΙ||"
-"ᾘ|ἠι|ἨΙ|ᾐ|"
-"ᾙ|ἡι|ἩΙ|ᾑ|"
-"ᾚ|ἢι|ἪΙ|ᾒ|"
-"ᾛ|ἣι|ἫΙ|ᾓ|"
-"ᾜ|ἤι|ἬΙ|ᾔ|"
-"ᾝ|ἥι|ἭΙ|ᾕ|"
-"ᾞ|ἦι|ἮΙ|ᾖ|"
-"ᾟ|ἧι|ἯΙ|ᾗ|"
-"ᾠ|ὠι|ὨΙ||"
-"ᾡ|ὡι|ὩΙ||"
-"ᾢ|ὢι|ὪΙ||"
-"ᾣ|ὣι|ὫΙ||"
-"ᾤ|ὤι|ὬΙ||"
-"ᾥ|ὥι|ὭΙ||"
-"ᾦ|ὦι|ὮΙ||"
-"ᾧ|ὧι|ὯΙ||"
-"ᾨ|ὠι|ὨΙ|ᾠ|"
-"ᾩ|ὡι|ὩΙ|ᾡ|"
-"ᾪ|ὢι|ὪΙ|ᾢ|"
-"ᾫ|ὣι|ὫΙ|ᾣ|"
-"ᾬ|ὤι|ὬΙ|ᾤ|"
-"ᾭ|ὥι|ὭΙ|ᾥ|"
-"ᾮ|ὦι|ὮΙ|ᾦ|"
-"ᾯ|ὧι|ὯΙ|ᾧ|"
-"ᾲ|ὰι|ᾺΙ||"
-"ᾳ|αι|ΑΙ||"
-"ᾴ|άι|ΆΙ||"
-"ᾶ|ᾶ|Α͂||"
-"ᾷ|ᾶι|Α͂Ι||"
-"ᾼ|αι|ΑΙ|ᾳ|"
-"ι|ι|Ι||"
-"ῂ|ὴι|ῊΙ||"
-"ῃ|ηι|ΗΙ||"
-"ῄ|ήι|ΉΙ||"
-"ῆ|ῆ|Η͂||"
-"ῇ|ῆι|Η͂Ι||"
-"ῌ|ηι|ΗΙ|ῃ|"
-"ῒ|ῒ|Ϊ̀||"
-"ΐ|ΐ|Ϊ́||"
-"ῖ|ῖ|Ι͂||"
-"ῗ|ῗ|Ϊ͂||"
-"ῢ|ῢ|Ϋ̀||"
-"ΰ|ΰ|Ϋ́||"
-"ῤ|ῤ|Ρ̓||"
-"ῦ|ῦ|Υ͂||"
-"ῧ|ῧ|Ϋ͂||"
-"ῲ|ὼι|ῺΙ||"
-"ῳ|ωι|ΩΙ||"
-"ῴ|ώι|ΏΙ||"
-"ῶ|ῶ|Ω͂||"
-"ῷ|ῶι|Ω͂Ι||"
-"ῼ|ωι|ΩΙ|ῳ|"
-"Ω|ω||ω|"
-"K|k||k|"
-"Å|å||å|"
-"ff|ff|FF||"
-"fi|fi|FI||"
-"fl|fl|FL||"
-"ffi|ffi|FFI||"
-"ffl|ffl|FFL||"
-"ſt|st|ST||"
-"st|st|ST||"
-"ﬓ|մն|ՄՆ||"
-"ﬔ|մե|ՄԵ||"
-"ﬕ|մի|ՄԻ||"
-"ﬖ|վն|ՎՆ||"
-"ﬗ|մխ|ՄԽ||"
+"\xc2\xb5|\xce\xbc|\xce\x9c||"
+"\xc3\x9f|ss|SS||"
+"\xc4\xb0|i\xcc\x87||i\xcc\x87|"
+"\xc4\xb1||I||"
+"\xc5\x89|\xca\xbcn|\xca\xbcN||"
+"\xc5\xbf|s|S||"
+"\xc7\x85|\xc7\x86|\xc7\x84|\xc7\x86|"
+"\xc7\x88|\xc7\x89|\xc7\x87|\xc7\x89|"
+"\xc7\x8b|\xc7\x8c|\xc7\x8a|\xc7\x8c|"
+"\xc7\xb0|j\xcc\x8c|J\xcc\x8c||"
+"\xc7\xb2|\xc7\xb3|\xc7\xb1|\xc7\xb3|"
+"\xcd\x85|\xce\xb9|\xce\x99||"
+"\xce\x90|\xce\xb9\xcc\x88\xcc\x81|\xce\x99\xcc\x88\xcc\x81||"
+"\xce\xb0|\xcf\x85\xcc\x88\xcc\x81|\xce\xa5\xcc\x88\xcc\x81||"
+"\xcf\x82|\xcf\x83|\xce\xa3||"
+"\xcf\x90|\xce\xb2|\xce\x92||"
+"\xcf\x91|\xce\xb8|\xce\x98||"
+"\xcf\x95|\xcf\x86|\xce\xa6||"
+"\xcf\x96|\xcf\x80|\xce\xa0||"
+"\xcf\xb0|\xce\xba|\xce\x9a||"
+"\xcf\xb1|\xcf\x81|\xce\xa1||"
+"\xcf\xb4|\xce\xb8||\xce\xb8|"
+"\xcf\xb5|\xce\xb5|\xce\x95||"
+"\xd6\x87|\xd5\xa5\xd6\x82|\xd4\xb5\xd5\x92||"
+"\xe1\x8e\xa0|||\xea\xad\xb0|"
+"\xe1\x8e\xa1|||\xea\xad\xb1|"
+"\xe1\x8e\xa2|||\xea\xad\xb2|"
+"\xe1\x8e\xa3|||\xea\xad\xb3|"
+"\xe1\x8e\xa4|||\xea\xad\xb4|"
+"\xe1\x8e\xa5|||\xea\xad\xb5|"
+"\xe1\x8e\xa6|||\xea\xad\xb6|"
+"\xe1\x8e\xa7|||\xea\xad\xb7|"
+"\xe1\x8e\xa8|||\xea\xad\xb8|"
+"\xe1\x8e\xa9|||\xea\xad\xb9|"
+"\xe1\x8e\xaa|||\xea\xad\xba|"
+"\xe1\x8e\xab|||\xea\xad\xbb|"
+"\xe1\x8e\xac|||\xea\xad\xbc|"
+"\xe1\x8e\xad|||\xea\xad\xbd|"
+"\xe1\x8e\xae|||\xea\xad\xbe|"
+"\xe1\x8e\xaf|||\xea\xad\xbf|"
+"\xe1\x8e\xb0|||\xea\xae\x80|"
+"\xe1\x8e\xb1|||\xea\xae\x81|"
+"\xe1\x8e\xb2|||\xea\xae\x82|"
+"\xe1\x8e\xb3|||\xea\xae\x83|"
+"\xe1\x8e\xb4|||\xea\xae\x84|"
+"\xe1\x8e\xb5|||\xea\xae\x85|"
+"\xe1\x8e\xb6|||\xea\xae\x86|"
+"\xe1\x8e\xb7|||\xea\xae\x87|"
+"\xe1\x8e\xb8|||\xea\xae\x88|"
+"\xe1\x8e\xb9|||\xea\xae\x89|"
+"\xe1\x8e\xba|||\xea\xae\x8a|"
+"\xe1\x8e\xbb|||\xea\xae\x8b|"
+"\xe1\x8e\xbc|||\xea\xae\x8c|"
+"\xe1\x8e\xbd|||\xea\xae\x8d|"
+"\xe1\x8e\xbe|||\xea\xae\x8e|"
+"\xe1\x8e\xbf|||\xea\xae\x8f|"
+"\xe1\x8f\x80|||\xea\xae\x90|"
+"\xe1\x8f\x81|||\xea\xae\x91|"
+"\xe1\x8f\x82|||\xea\xae\x92|"
+"\xe1\x8f\x83|||\xea\xae\x93|"
+"\xe1\x8f\x84|||\xea\xae\x94|"
+"\xe1\x8f\x85|||\xea\xae\x95|"
+"\xe1\x8f\x86|||\xea\xae\x96|"
+"\xe1\x8f\x87|||\xea\xae\x97|"
+"\xe1\x8f\x88|||\xea\xae\x98|"
+"\xe1\x8f\x89|||\xea\xae\x99|"
+"\xe1\x8f\x8a|||\xea\xae\x9a|"
+"\xe1\x8f\x8b|||\xea\xae\x9b|"
+"\xe1\x8f\x8c|||\xea\xae\x9c|"
+"\xe1\x8f\x8d|||\xea\xae\x9d|"
+"\xe1\x8f\x8e|||\xea\xae\x9e|"
+"\xe1\x8f\x8f|||\xea\xae\x9f|"
+"\xe1\x8f\x90|||\xea\xae\xa0|"
+"\xe1\x8f\x91|||\xea\xae\xa1|"
+"\xe1\x8f\x92|||\xea\xae\xa2|"
+"\xe1\x8f\x93|||\xea\xae\xa3|"
+"\xe1\x8f\x94|||\xea\xae\xa4|"
+"\xe1\x8f\x95|||\xea\xae\xa5|"
+"\xe1\x8f\x96|||\xea\xae\xa6|"
+"\xe1\x8f\x97|||\xea\xae\xa7|"
+"\xe1\x8f\x98|||\xea\xae\xa8|"
+"\xe1\x8f\x99|||\xea\xae\xa9|"
+"\xe1\x8f\x9a|||\xea\xae\xaa|"
+"\xe1\x8f\x9b|||\xea\xae\xab|"
+"\xe1\x8f\x9c|||\xea\xae\xac|"
+"\xe1\x8f\x9d|||\xea\xae\xad|"
+"\xe1\x8f\x9e|||\xea\xae\xae|"
+"\xe1\x8f\x9f|||\xea\xae\xaf|"
+"\xe1\x8f\xa0|||\xea\xae\xb0|"
+"\xe1\x8f\xa1|||\xea\xae\xb1|"
+"\xe1\x8f\xa2|||\xea\xae\xb2|"
+"\xe1\x8f\xa3|||\xea\xae\xb3|"
+"\xe1\x8f\xa4|||\xea\xae\xb4|"
+"\xe1\x8f\xa5|||\xea\xae\xb5|"
+"\xe1\x8f\xa6|||\xea\xae\xb6|"
+"\xe1\x8f\xa7|||\xea\xae\xb7|"
+"\xe1\x8f\xa8|||\xea\xae\xb8|"
+"\xe1\x8f\xa9|||\xea\xae\xb9|"
+"\xe1\x8f\xaa|||\xea\xae\xba|"
+"\xe1\x8f\xab|||\xea\xae\xbb|"
+"\xe1\x8f\xac|||\xea\xae\xbc|"
+"\xe1\x8f\xad|||\xea\xae\xbd|"
+"\xe1\x8f\xae|||\xea\xae\xbe|"
+"\xe1\x8f\xaf|||\xea\xae\xbf|"
+"\xe1\x8f\xb0|||\xe1\x8f\xb8|"
+"\xe1\x8f\xb1|||\xe1\x8f\xb9|"
+"\xe1\x8f\xb2|||\xe1\x8f\xba|"
+"\xe1\x8f\xb3|||\xe1\x8f\xbb|"
+"\xe1\x8f\xb4|||\xe1\x8f\xbc|"
+"\xe1\x8f\xb5|||\xe1\x8f\xbd|"
+"\xe1\x8f\xb8|\xe1\x8f\xb0|\xe1\x8f\xb0||"
+"\xe1\x8f\xb9|\xe1\x8f\xb1|\xe1\x8f\xb1||"
+"\xe1\x8f\xba|\xe1\x8f\xb2|\xe1\x8f\xb2||"
+"\xe1\x8f\xbb|\xe1\x8f\xb3|\xe1\x8f\xb3||"
+"\xe1\x8f\xbc|\xe1\x8f\xb4|\xe1\x8f\xb4||"
+"\xe1\x8f\xbd|\xe1\x8f\xb5|\xe1\x8f\xb5||"
+"\xe1\xb2\x80|\xd0\xb2|\xd0\x92||"
+"\xe1\xb2\x81|\xd0\xb4|\xd0\x94||"
+"\xe1\xb2\x82|\xd0\xbe|\xd0\x9e||"
+"\xe1\xb2\x83|\xd1\x81|\xd0\xa1||"
+"\xe1\xb2\x84|\xd1\x82|\xd0\xa2||"
+"\xe1\xb2\x85|\xd1\x82|\xd0\xa2||"
+"\xe1\xb2\x86|\xd1\x8a|\xd0\xaa||"
+"\xe1\xb2\x87|\xd1\xa3|\xd1\xa2||"
+"\xe1\xb2\x88|\xea\x99\x8b|\xea\x99\x8a||"
+"\xe1\xba\x96|h\xcc\xb1|H\xcc\xb1||"
+"\xe1\xba\x97|t\xcc\x88|T\xcc\x88||"
+"\xe1\xba\x98|w\xcc\x8a|W\xcc\x8a||"
+"\xe1\xba\x99|y\xcc\x8a|Y\xcc\x8a||"
+"\xe1\xba\x9a|a\xca\xbe|A\xca\xbe||"
+"\xe1\xba\x9b|\xe1\xb9\xa1|\xe1\xb9\xa0||"
+"\xe1\xba\x9e|ss||\xc3\x9f|"
+"\xe1\xbd\x90|\xcf\x85\xcc\x93|\xce\xa5\xcc\x93||"
+"\xe1\xbd\x92|\xcf\x85\xcc\x93\xcc\x80|\xce\xa5\xcc\x93\xcc\x80||"
+"\xe1\xbd\x94|\xcf\x85\xcc\x93\xcc\x81|\xce\xa5\xcc\x93\xcc\x81||"
+"\xe1\xbd\x96|\xcf\x85\xcc\x93\xcd\x82|\xce\xa5\xcc\x93\xcd\x82||"
+"\xe1\xbe\x80|\xe1\xbc\x80\xce\xb9|\xe1\xbc\x88\xce\x99||"
+"\xe1\xbe\x81|\xe1\xbc\x81\xce\xb9|\xe1\xbc\x89\xce\x99||"
+"\xe1\xbe\x82|\xe1\xbc\x82\xce\xb9|\xe1\xbc\x8a\xce\x99||"
+"\xe1\xbe\x83|\xe1\xbc\x83\xce\xb9|\xe1\xbc\x8b\xce\x99||"
+"\xe1\xbe\x84|\xe1\xbc\x84\xce\xb9|\xe1\xbc\x8c\xce\x99||"
+"\xe1\xbe\x85|\xe1\xbc\x85\xce\xb9|\xe1\xbc\x8d\xce\x99||"
+"\xe1\xbe\x86|\xe1\xbc\x86\xce\xb9|\xe1\xbc\x8e\xce\x99||"
+"\xe1\xbe\x87|\xe1\xbc\x87\xce\xb9|\xe1\xbc\x8f\xce\x99||"
+"\xe1\xbe\x88|\xe1\xbc\x80\xce\xb9|\xe1\xbc\x88\xce\x99|\xe1\xbe\x80|"
+"\xe1\xbe\x89|\xe1\xbc\x81\xce\xb9|\xe1\xbc\x89\xce\x99|\xe1\xbe\x81|"
+"\xe1\xbe\x8a|\xe1\xbc\x82\xce\xb9|\xe1\xbc\x8a\xce\x99|\xe1\xbe\x82|"
+"\xe1\xbe\x8b|\xe1\xbc\x83\xce\xb9|\xe1\xbc\x8b\xce\x99|\xe1\xbe\x83|"
+"\xe1\xbe\x8c|\xe1\xbc\x84\xce\xb9|\xe1\xbc\x8c\xce\x99|\xe1\xbe\x84|"
+"\xe1\xbe\x8d|\xe1\xbc\x85\xce\xb9|\xe1\xbc\x8d\xce\x99|\xe1\xbe\x85|"
+"\xe1\xbe\x8e|\xe1\xbc\x86\xce\xb9|\xe1\xbc\x8e\xce\x99|\xe1\xbe\x86|"
+"\xe1\xbe\x8f|\xe1\xbc\x87\xce\xb9|\xe1\xbc\x8f\xce\x99|\xe1\xbe\x87|"
+"\xe1\xbe\x90|\xe1\xbc\xa0\xce\xb9|\xe1\xbc\xa8\xce\x99||"
+"\xe1\xbe\x91|\xe1\xbc\xa1\xce\xb9|\xe1\xbc\xa9\xce\x99||"
+"\xe1\xbe\x92|\xe1\xbc\xa2\xce\xb9|\xe1\xbc\xaa\xce\x99||"
+"\xe1\xbe\x93|\xe1\xbc\xa3\xce\xb9|\xe1\xbc\xab\xce\x99||"
+"\xe1\xbe\x94|\xe1\xbc\xa4\xce\xb9|\xe1\xbc\xac\xce\x99||"
+"\xe1\xbe\x95|\xe1\xbc\xa5\xce\xb9|\xe1\xbc\xad\xce\x99||"
+"\xe1\xbe\x96|\xe1\xbc\xa6\xce\xb9|\xe1\xbc\xae\xce\x99||"
+"\xe1\xbe\x97|\xe1\xbc\xa7\xce\xb9|\xe1\xbc\xaf\xce\x99||"
+"\xe1\xbe\x98|\xe1\xbc\xa0\xce\xb9|\xe1\xbc\xa8\xce\x99|\xe1\xbe\x90|"
+"\xe1\xbe\x99|\xe1\xbc\xa1\xce\xb9|\xe1\xbc\xa9\xce\x99|\xe1\xbe\x91|"
+"\xe1\xbe\x9a|\xe1\xbc\xa2\xce\xb9|\xe1\xbc\xaa\xce\x99|\xe1\xbe\x92|"
+"\xe1\xbe\x9b|\xe1\xbc\xa3\xce\xb9|\xe1\xbc\xab\xce\x99|\xe1\xbe\x93|"
+"\xe1\xbe\x9c|\xe1\xbc\xa4\xce\xb9|\xe1\xbc\xac\xce\x99|\xe1\xbe\x94|"
+"\xe1\xbe\x9d|\xe1\xbc\xa5\xce\xb9|\xe1\xbc\xad\xce\x99|\xe1\xbe\x95|"
+"\xe1\xbe\x9e|\xe1\xbc\xa6\xce\xb9|\xe1\xbc\xae\xce\x99|\xe1\xbe\x96|"
+"\xe1\xbe\x9f|\xe1\xbc\xa7\xce\xb9|\xe1\xbc\xaf\xce\x99|\xe1\xbe\x97|"
+"\xe1\xbe\xa0|\xe1\xbd\xa0\xce\xb9|\xe1\xbd\xa8\xce\x99||"
+"\xe1\xbe\xa1|\xe1\xbd\xa1\xce\xb9|\xe1\xbd\xa9\xce\x99||"
+"\xe1\xbe\xa2|\xe1\xbd\xa2\xce\xb9|\xe1\xbd\xaa\xce\x99||"
+"\xe1\xbe\xa3|\xe1\xbd\xa3\xce\xb9|\xe1\xbd\xab\xce\x99||"
+"\xe1\xbe\xa4|\xe1\xbd\xa4\xce\xb9|\xe1\xbd\xac\xce\x99||"
+"\xe1\xbe\xa5|\xe1\xbd\xa5\xce\xb9|\xe1\xbd\xad\xce\x99||"
+"\xe1\xbe\xa6|\xe1\xbd\xa6\xce\xb9|\xe1\xbd\xae\xce\x99||"
+"\xe1\xbe\xa7|\xe1\xbd\xa7\xce\xb9|\xe1\xbd\xaf\xce\x99||"
+"\xe1\xbe\xa8|\xe1\xbd\xa0\xce\xb9|\xe1\xbd\xa8\xce\x99|\xe1\xbe\xa0|"
+"\xe1\xbe\xa9|\xe1\xbd\xa1\xce\xb9|\xe1\xbd\xa9\xce\x99|\xe1\xbe\xa1|"
+"\xe1\xbe\xaa|\xe1\xbd\xa2\xce\xb9|\xe1\xbd\xaa\xce\x99|\xe1\xbe\xa2|"
+"\xe1\xbe\xab|\xe1\xbd\xa3\xce\xb9|\xe1\xbd\xab\xce\x99|\xe1\xbe\xa3|"
+"\xe1\xbe\xac|\xe1\xbd\xa4\xce\xb9|\xe1\xbd\xac\xce\x99|\xe1\xbe\xa4|"
+"\xe1\xbe\xad|\xe1\xbd\xa5\xce\xb9|\xe1\xbd\xad\xce\x99|\xe1\xbe\xa5|"
+"\xe1\xbe\xae|\xe1\xbd\xa6\xce\xb9|\xe1\xbd\xae\xce\x99|\xe1\xbe\xa6|"
+"\xe1\xbe\xaf|\xe1\xbd\xa7\xce\xb9|\xe1\xbd\xaf\xce\x99|\xe1\xbe\xa7|"
+"\xe1\xbe\xb2|\xe1\xbd\xb0\xce\xb9|\xe1\xbe\xba\xce\x99||"
+"\xe1\xbe\xb3|\xce\xb1\xce\xb9|\xce\x91\xce\x99||"
+"\xe1\xbe\xb4|\xce\xac\xce\xb9|\xce\x86\xce\x99||"
+"\xe1\xbe\xb6|\xce\xb1\xcd\x82|\xce\x91\xcd\x82||"
+"\xe1\xbe\xb7|\xce\xb1\xcd\x82\xce\xb9|\xce\x91\xcd\x82\xce\x99||"
+"\xe1\xbe\xbc|\xce\xb1\xce\xb9|\xce\x91\xce\x99|\xe1\xbe\xb3|"
+"\xe1\xbe\xbe|\xce\xb9|\xce\x99||"
+"\xe1\xbf\x82|\xe1\xbd\xb4\xce\xb9|\xe1\xbf\x8a\xce\x99||"
+"\xe1\xbf\x83|\xce\xb7\xce\xb9|\xce\x97\xce\x99||"
+"\xe1\xbf\x84|\xce\xae\xce\xb9|\xce\x89\xce\x99||"
+"\xe1\xbf\x86|\xce\xb7\xcd\x82|\xce\x97\xcd\x82||"
+"\xe1\xbf\x87|\xce\xb7\xcd\x82\xce\xb9|\xce\x97\xcd\x82\xce\x99||"
+"\xe1\xbf\x8c|\xce\xb7\xce\xb9|\xce\x97\xce\x99|\xe1\xbf\x83|"
+"\xe1\xbf\x92|\xce\xb9\xcc\x88\xcc\x80|\xce\x99\xcc\x88\xcc\x80||"
+"\xe1\xbf\x93|\xce\xb9\xcc\x88\xcc\x81|\xce\x99\xcc\x88\xcc\x81||"
+"\xe1\xbf\x96|\xce\xb9\xcd\x82|\xce\x99\xcd\x82||"
+"\xe1\xbf\x97|\xce\xb9\xcc\x88\xcd\x82|\xce\x99\xcc\x88\xcd\x82||"
+"\xe1\xbf\xa2|\xcf\x85\xcc\x88\xcc\x80|\xce\xa5\xcc\x88\xcc\x80||"
+"\xe1\xbf\xa3|\xcf\x85\xcc\x88\xcc\x81|\xce\xa5\xcc\x88\xcc\x81||"
+"\xe1\xbf\xa4|\xcf\x81\xcc\x93|\xce\xa1\xcc\x93||"
+"\xe1\xbf\xa6|\xcf\x85\xcd\x82|\xce\xa5\xcd\x82||"
+"\xe1\xbf\xa7|\xcf\x85\xcc\x88\xcd\x82|\xce\xa5\xcc\x88\xcd\x82||"
+"\xe1\xbf\xb2|\xe1\xbd\xbc\xce\xb9|\xe1\xbf\xba\xce\x99||"
+"\xe1\xbf\xb3|\xcf\x89\xce\xb9|\xce\xa9\xce\x99||"
+"\xe1\xbf\xb4|\xcf\x8e\xce\xb9|\xce\x8f\xce\x99||"
+"\xe1\xbf\xb6|\xcf\x89\xcd\x82|\xce\xa9\xcd\x82||"
+"\xe1\xbf\xb7|\xcf\x89\xcd\x82\xce\xb9|\xce\xa9\xcd\x82\xce\x99||"
+"\xe1\xbf\xbc|\xcf\x89\xce\xb9|\xce\xa9\xce\x99|\xe1\xbf\xb3|"
+"\xe2\x84\xa6|\xcf\x89||\xcf\x89|"
+"\xe2\x84\xaa|k||k|"
+"\xe2\x84\xab|\xc3\xa5||\xc3\xa5|"
+"\xea\xad\xb0|\xe1\x8e\xa0|\xe1\x8e\xa0||"
+"\xea\xad\xb1|\xe1\x8e\xa1|\xe1\x8e\xa1||"
+"\xea\xad\xb2|\xe1\x8e\xa2|\xe1\x8e\xa2||"
+"\xea\xad\xb3|\xe1\x8e\xa3|\xe1\x8e\xa3||"
+"\xea\xad\xb4|\xe1\x8e\xa4|\xe1\x8e\xa4||"
+"\xea\xad\xb5|\xe1\x8e\xa5|\xe1\x8e\xa5||"
+"\xea\xad\xb6|\xe1\x8e\xa6|\xe1\x8e\xa6||"
+"\xea\xad\xb7|\xe1\x8e\xa7|\xe1\x8e\xa7||"
+"\xea\xad\xb8|\xe1\x8e\xa8|\xe1\x8e\xa8||"
+"\xea\xad\xb9|\xe1\x8e\xa9|\xe1\x8e\xa9||"
+"\xea\xad\xba|\xe1\x8e\xaa|\xe1\x8e\xaa||"
+"\xea\xad\xbb|\xe1\x8e\xab|\xe1\x8e\xab||"
+"\xea\xad\xbc|\xe1\x8e\xac|\xe1\x8e\xac||"
+"\xea\xad\xbd|\xe1\x8e\xad|\xe1\x8e\xad||"
+"\xea\xad\xbe|\xe1\x8e\xae|\xe1\x8e\xae||"
+"\xea\xad\xbf|\xe1\x8e\xaf|\xe1\x8e\xaf||"
+"\xea\xae\x80|\xe1\x8e\xb0|\xe1\x8e\xb0||"
+"\xea\xae\x81|\xe1\x8e\xb1|\xe1\x8e\xb1||"
+"\xea\xae\x82|\xe1\x8e\xb2|\xe1\x8e\xb2||"
+"\xea\xae\x83|\xe1\x8e\xb3|\xe1\x8e\xb3||"
+"\xea\xae\x84|\xe1\x8e\xb4|\xe1\x8e\xb4||"
+"\xea\xae\x85|\xe1\x8e\xb5|\xe1\x8e\xb5||"
+"\xea\xae\x86|\xe1\x8e\xb6|\xe1\x8e\xb6||"
+"\xea\xae\x87|\xe1\x8e\xb7|\xe1\x8e\xb7||"
+"\xea\xae\x88|\xe1\x8e\xb8|\xe1\x8e\xb8||"
+"\xea\xae\x89|\xe1\x8e\xb9|\xe1\x8e\xb9||"
+"\xea\xae\x8a|\xe1\x8e\xba|\xe1\x8e\xba||"
+"\xea\xae\x8b|\xe1\x8e\xbb|\xe1\x8e\xbb||"
+"\xea\xae\x8c|\xe1\x8e\xbc|\xe1\x8e\xbc||"
+"\xea\xae\x8d|\xe1\x8e\xbd|\xe1\x8e\xbd||"
+"\xea\xae\x8e|\xe1\x8e\xbe|\xe1\x8e\xbe||"
+"\xea\xae\x8f|\xe1\x8e\xbf|\xe1\x8e\xbf||"
+"\xea\xae\x90|\xe1\x8f\x80|\xe1\x8f\x80||"
+"\xea\xae\x91|\xe1\x8f\x81|\xe1\x8f\x81||"
+"\xea\xae\x92|\xe1\x8f\x82|\xe1\x8f\x82||"
+"\xea\xae\x93|\xe1\x8f\x83|\xe1\x8f\x83||"
+"\xea\xae\x94|\xe1\x8f\x84|\xe1\x8f\x84||"
+"\xea\xae\x95|\xe1\x8f\x85|\xe1\x8f\x85||"
+"\xea\xae\x96|\xe1\x8f\x86|\xe1\x8f\x86||"
+"\xea\xae\x97|\xe1\x8f\x87|\xe1\x8f\x87||"
+"\xea\xae\x98|\xe1\x8f\x88|\xe1\x8f\x88||"
+"\xea\xae\x99|\xe1\x8f\x89|\xe1\x8f\x89||"
+"\xea\xae\x9a|\xe1\x8f\x8a|\xe1\x8f\x8a||"
+"\xea\xae\x9b|\xe1\x8f\x8b|\xe1\x8f\x8b||"
+"\xea\xae\x9c|\xe1\x8f\x8c|\xe1\x8f\x8c||"
+"\xea\xae\x9d|\xe1\x8f\x8d|\xe1\x8f\x8d||"
+"\xea\xae\x9e|\xe1\x8f\x8e|\xe1\x8f\x8e||"
+"\xea\xae\x9f|\xe1\x8f\x8f|\xe1\x8f\x8f||"
+"\xea\xae\xa0|\xe1\x8f\x90|\xe1\x8f\x90||"
+"\xea\xae\xa1|\xe1\x8f\x91|\xe1\x8f\x91||"
+"\xea\xae\xa2|\xe1\x8f\x92|\xe1\x8f\x92||"
+"\xea\xae\xa3|\xe1\x8f\x93|\xe1\x8f\x93||"
+"\xea\xae\xa4|\xe1\x8f\x94|\xe1\x8f\x94||"
+"\xea\xae\xa5|\xe1\x8f\x95|\xe1\x8f\x95||"
+"\xea\xae\xa6|\xe1\x8f\x96|\xe1\x8f\x96||"
+"\xea\xae\xa7|\xe1\x8f\x97|\xe1\x8f\x97||"
+"\xea\xae\xa8|\xe1\x8f\x98|\xe1\x8f\x98||"
+"\xea\xae\xa9|\xe1\x8f\x99|\xe1\x8f\x99||"
+"\xea\xae\xaa|\xe1\x8f\x9a|\xe1\x8f\x9a||"
+"\xea\xae\xab|\xe1\x8f\x9b|\xe1\x8f\x9b||"
+"\xea\xae\xac|\xe1\x8f\x9c|\xe1\x8f\x9c||"
+"\xea\xae\xad|\xe1\x8f\x9d|\xe1\x8f\x9d||"
+"\xea\xae\xae|\xe1\x8f\x9e|\xe1\x8f\x9e||"
+"\xea\xae\xaf|\xe1\x8f\x9f|\xe1\x8f\x9f||"
+"\xea\xae\xb0|\xe1\x8f\xa0|\xe1\x8f\xa0||"
+"\xea\xae\xb1|\xe1\x8f\xa1|\xe1\x8f\xa1||"
+"\xea\xae\xb2|\xe1\x8f\xa2|\xe1\x8f\xa2||"
+"\xea\xae\xb3|\xe1\x8f\xa3|\xe1\x8f\xa3||"
+"\xea\xae\xb4|\xe1\x8f\xa4|\xe1\x8f\xa4||"
+"\xea\xae\xb5|\xe1\x8f\xa5|\xe1\x8f\xa5||"
+"\xea\xae\xb6|\xe1\x8f\xa6|\xe1\x8f\xa6||"
+"\xea\xae\xb7|\xe1\x8f\xa7|\xe1\x8f\xa7||"
+"\xea\xae\xb8|\xe1\x8f\xa8|\xe1\x8f\xa8||"
+"\xea\xae\xb9|\xe1\x8f\xa9|\xe1\x8f\xa9||"
+"\xea\xae\xba|\xe1\x8f\xaa|\xe1\x8f\xaa||"
+"\xea\xae\xbb|\xe1\x8f\xab|\xe1\x8f\xab||"
+"\xea\xae\xbc|\xe1\x8f\xac|\xe1\x8f\xac||"
+"\xea\xae\xbd|\xe1\x8f\xad|\xe1\x8f\xad||"
+"\xea\xae\xbe|\xe1\x8f\xae|\xe1\x8f\xae||"
+"\xea\xae\xbf|\xe1\x8f\xaf|\xe1\x8f\xaf||"
+"\xef\xac\x80|ff|FF||"
+"\xef\xac\x81|fi|FI||"
+"\xef\xac\x82|fl|FL||"
+"\xef\xac\x83|ffi|FFI||"
+"\xef\xac\x84|ffl|FFL||"
+"\xef\xac\x85|st|ST||"
+"\xef\xac\x86|st|ST||"
+"\xef\xac\x93|\xd5\xb4\xd5\xb6|\xd5\x84\xd5\x86||"
+"\xef\xac\x94|\xd5\xb4\xd5\xa5|\xd5\x84\xd4\xb5||"
+"\xef\xac\x95|\xd5\xb4\xd5\xab|\xd5\x84\xd4\xbb||"
+"\xef\xac\x96|\xd5\xbe\xd5\xb6|\xd5\x8e\xd5\x86||"
+"\xef\xac\x97|\xd5\xb4\xd5\xad|\xd5\x84\xd4\xbd||"
 
 //--Autogenerated -- end of section automatically generated
 ;
@@ -367,6 +566,9 @@ class CaseConverter : public ICaseConverter {
        enum { maxConversionLength=6 };
        struct ConversionString {
                char conversion[maxConversionLength+1];
+               ConversionString() {
+                       conversion[0] = '\0';
+               }
        };
        // Conversions are initially store in a vector of structs but then decomposed into
        // parallel arrays as that is about 10% faster to search.
@@ -374,7 +576,7 @@ class CaseConverter : public ICaseConverter {
                int character;
                ConversionString conversion;
                CharacterConversion(int character_=0, const char *conversion_="") : character(character_) {
-                       strcpy(conversion.conversion, conversion_);
+                       StringCopy(conversion.conversion, conversion_);
                }
                bool operator<(const CharacterConversion &other) const {
                        return character < other.character;
@@ -382,7 +584,7 @@ class CaseConverter : public ICaseConverter {
        };
        typedef std::vector<CharacterConversion> CharacterToConversion;
        CharacterToConversion characterToConversion;
-       // The parallel arrays 
+       // The parallel arrays
        std::vector<int> characters;
        std::vector<ConversionString> conversions;
 
@@ -404,7 +606,7 @@ public:
                else
                        return 0;
        }
-       size_t CaseConvertString(char *converted, size_t sizeConverted, const char *mixed, size_t lenMixed) {
+       size_t CaseConvertString(char *converted, size_t sizeConverted, const char *mixed, size_t lenMixed) 
override {
                size_t lenConverted = 0;
                size_t mixedPos = 0;
                unsigned char bytes[UTF8MaxBytes + 1];
@@ -451,9 +653,9 @@ public:
                std::sort(characterToConversion.begin(), characterToConversion.end());
                characters.reserve(characterToConversion.size());
                conversions.reserve(characterToConversion.size());
-               for (CharacterToConversion::iterator it = characterToConversion.begin(); it != 
characterToConversion.end(); ++it) {
-                       characters.push_back(it->character);
-                       conversions.push_back(it->conversion);
+               for (const CharacterConversion &chConv : characterToConversion) {
+                       characters.push_back(chConv.character);
+                       conversions.push_back(chConv.conversion);
                }
                // Empty the original calculated data completely
                CharacterToConversion().swap(characterToConversion);
@@ -505,19 +707,19 @@ void AddSymmetric(enum CaseConversion conversion, int lower,int upper) {
 
 void SetupConversions(enum CaseConversion conversion) {
        // First initialize for the symmetric ranges
-       for (size_t i=0; i<sizeof(symmetricCaseConversionRanges)/sizeof(symmetricCaseConversionRanges[0]);) {
-               int lower = symmetricCaseConversionRanges[i++];
-               int upper = symmetricCaseConversionRanges[i++];
-               int length = symmetricCaseConversionRanges[i++];
-               int pitch = symmetricCaseConversionRanges[i++];
-               for (int j=0;j<length*pitch;j+=pitch) {
+       for (size_t i=0; i<ELEMENTS(symmetricCaseConversionRanges);) {
+               const int lower = symmetricCaseConversionRanges[i++];
+               const int upper = symmetricCaseConversionRanges[i++];
+               const int length = symmetricCaseConversionRanges[i++];
+               const int pitch = symmetricCaseConversionRanges[i++];
+               for (int j=0; j<length*pitch; j+=pitch) {
                        AddSymmetric(conversion, lower+j, upper+j);
                }
        }
        // Add the symmetric singletons
-       for (size_t i=0; i<sizeof(symmetricCaseConversions)/sizeof(symmetricCaseConversions[0]);) {
-               int lower = symmetricCaseConversions[i++];
-               int upper = symmetricCaseConversions[i++];
+       for (size_t i=0; i<ELEMENTS(symmetricCaseConversions);) {
+               const int lower = symmetricCaseConversions[i++];
+               const int upper = symmetricCaseConversions[i++];
                AddSymmetric(conversion, lower, upper);
        }
        // Add the complex cases
@@ -625,6 +827,14 @@ size_t CaseConvertString(char *converted, size_t sizeConverted, const char *mixe
        return pCaseConv->CaseConvertString(converted, sizeConverted, mixed, lenMixed);
 }
 
+std::string CaseConvertString(const std::string &s, enum CaseConversion conversion) {
+       std::string retMapped(s.length() * maxExpansionCaseConversion, 0);
+       size_t lenMapped = CaseConvertString(&retMapped[0], retMapped.length(), s.c_str(), s.length(),
+               conversion);
+       retMapped.resize(lenMapped);
+       return retMapped;
+}
+
 #ifdef SCI_NAMESPACE
 }
 #endif
diff --git a/plugins/scintilla/scintilla/src/CaseConvert.h b/plugins/scintilla/scintilla/src/CaseConvert.h
index 60de227..7a01003 100644
--- a/plugins/scintilla/scintilla/src/CaseConvert.h
+++ b/plugins/scintilla/scintilla/src/CaseConvert.h
@@ -40,6 +40,9 @@ const int maxExpansionCaseConversion=3;
 // If there is not enough space then 0 is returned.
 size_t CaseConvertString(char *converted, size_t sizeConverted, const char *mixed, size_t lenMixed, enum 
CaseConversion conversion);
 
+// Converts a mixed case string using a particular conversion.
+std::string CaseConvertString(const std::string &s, enum CaseConversion conversion);
+
 #ifdef SCI_NAMESPACE
 }
 #endif
diff --git a/plugins/scintilla/scintilla/src/CaseFolder.cxx b/plugins/scintilla/scintilla/src/CaseFolder.cxx
index 44a94da..4e095df 100644
--- a/plugins/scintilla/scintilla/src/CaseFolder.cxx
+++ b/plugins/scintilla/scintilla/src/CaseFolder.cxx
@@ -5,12 +5,13 @@
 // Copyright 1998-2013 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+#include <stdexcept>
 #include <vector>
 #include <algorithm>
 
+#include "CaseFolder.h"
 #include "CaseConvert.h"
 #include "UniConversion.h"
-#include "CaseFolder.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
diff --git a/plugins/scintilla/scintilla/src/CaseFolder.h b/plugins/scintilla/scintilla/src/CaseFolder.h
index 2d754d4..bdc7d3d 100644
--- a/plugins/scintilla/scintilla/src/CaseFolder.h
+++ b/plugins/scintilla/scintilla/src/CaseFolder.h
@@ -24,7 +24,7 @@ protected:
 public:
        CaseFolderTable();
        virtual ~CaseFolderTable();
-       virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed);
+       size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) override;
        void SetTranslation(char ch, char chTranslation);
        void StandardASCII();
 };
@@ -35,7 +35,7 @@ class CaseFolderUnicode : public CaseFolderTable {
        ICaseConverter *converter;
 public:
        CaseFolderUnicode();
-       virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed);
+       size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) override;
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/Catalogue.cxx b/plugins/scintilla/scintilla/src/Catalogue.cxx
index 1a56304..c4f7a7e 100644
--- a/plugins/scintilla/scintilla/src/Catalogue.cxx
+++ b/plugins/scintilla/scintilla/src/Catalogue.cxx
@@ -1,17 +1,15 @@
 // Scintilla source code edit control
-/** @file KeyWords.cxx
+/** @file Catalogue.cxx
  ** Colourise for particular languages.
  **/
 // Copyright 1998-2002 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
 
+#include <stdexcept>
 #include <vector>
 
 #include "ILexer.h"
@@ -30,10 +28,9 @@ static int nextLanguage = SCLEX_AUTOMATIC+1;
 
 const LexerModule *Catalogue::Find(int language) {
        Scintilla_LinkLexers();
-       for (std::vector<LexerModule *>::iterator it=lexerCatalogue.begin();
-               it != lexerCatalogue.end(); ++it) {
-               if ((*it)->GetLanguage() == language) {
-                       return *it;
+       for (const LexerModule *lm : lexerCatalogue) {
+               if (lm->GetLanguage() == language) {
+                       return lm;
                }
        }
        return 0;
@@ -42,10 +39,9 @@ const LexerModule *Catalogue::Find(int language) {
 const LexerModule *Catalogue::Find(const char *languageName) {
        Scintilla_LinkLexers();
        if (languageName) {
-               for (std::vector<LexerModule *>::iterator it=lexerCatalogue.begin();
-                       it != lexerCatalogue.end(); ++it) {
-                       if ((*it)->languageName && (0 == strcmp((*it)->languageName, languageName))) {
-                               return *it;
+               for (const LexerModule *lm : lexerCatalogue) {
+                       if (lm->languageName && (0 == strcmp(lm->languageName, languageName))) {
+                               return lm;
                        }
                }
        }
@@ -60,11 +56,6 @@ void Catalogue::AddLexerModule(LexerModule *plm) {
        lexerCatalogue.push_back(plm);
 }
 
-// Alternative historical name for Scintilla_LinkLexers
-int wxForceScintillaLexers(void) {
-       return Scintilla_LinkLexers();
-}
-
 // To add or remove a lexer, add or remove its file and run LexGen.py.
 
 // Force a reference to all of the Scintilla lexers so that the linker will
@@ -79,12 +70,13 @@ int Scintilla_LinkLexers() {
 // Shorten the code that declares a lexer and ensures it is linked in by calling a method.
 #define LINK_LEXER(lexer) extern LexerModule lexer; Catalogue::AddLexerModule(&lexer);
 
-//++Autogenerated -- run src/LexGen.py to regenerate
+//++Autogenerated -- run scripts/LexGen.py to regenerate
 //**\(\tLINK_LEXER(\*);\n\)
        LINK_LEXER(lmA68k);
        LINK_LEXER(lmAbaqus);
        LINK_LEXER(lmAda);
        LINK_LEXER(lmAPDL);
+       LINK_LEXER(lmAs);
        LINK_LEXER(lmAsm);
        LINK_LEXER(lmAsn1);
        LINK_LEXER(lmASY);
@@ -94,6 +86,7 @@ int Scintilla_LinkLexers() {
        LINK_LEXER(lmBaan);
        LINK_LEXER(lmBash);
        LINK_LEXER(lmBatch);
+       LINK_LEXER(lmBibTeX);
        LINK_LEXER(lmBlitzBasic);
        LINK_LEXER(lmBullant);
        LINK_LEXER(lmCaml);
@@ -109,7 +102,10 @@ int Scintilla_LinkLexers() {
        LINK_LEXER(lmCss);
        LINK_LEXER(lmD);
        LINK_LEXER(lmDiff);
+       LINK_LEXER(lmDMAP);
+       LINK_LEXER(lmDMIS);
        LINK_LEXER(lmECL);
+       LINK_LEXER(lmEDIFACT);
        LINK_LEXER(lmEiffel);
        LINK_LEXER(lmEiffelkw);
        LINK_LEXER(lmErlang);
@@ -124,8 +120,12 @@ int Scintilla_LinkLexers() {
        LINK_LEXER(lmGui4Cli);
        LINK_LEXER(lmHaskell);
        LINK_LEXER(lmHTML);
+       LINK_LEXER(lmIHex);
+       LINK_LEXER(lmIndent);
        LINK_LEXER(lmInno);
+       LINK_LEXER(lmJSON);
        LINK_LEXER(lmKix);
+       LINK_LEXER(lmKVIrc);
        LINK_LEXER(lmLatex);
        LINK_LEXER(lmLISP);
        LINK_LEXER(lmLiterateHaskell);
@@ -164,7 +164,9 @@ int Scintilla_LinkLexers() {
        LINK_LEXER(lmPython);
        LINK_LEXER(lmR);
        LINK_LEXER(lmREBOL);
+       LINK_LEXER(lmRegistry);
        LINK_LEXER(lmRuby);
+       LINK_LEXER(lmRust);
        LINK_LEXER(lmScriptol);
        LINK_LEXER(lmSmalltalk);
        LINK_LEXER(lmSML);
@@ -172,12 +174,14 @@ int Scintilla_LinkLexers() {
        LINK_LEXER(lmSpecman);
        LINK_LEXER(lmSpice);
        LINK_LEXER(lmSQL);
+       LINK_LEXER(lmSrec);
        LINK_LEXER(lmSTTXT);
        LINK_LEXER(lmTACL);
        LINK_LEXER(lmTADS3);
        LINK_LEXER(lmTAL);
        LINK_LEXER(lmTCL);
        LINK_LEXER(lmTCMD);
+       LINK_LEXER(lmTEHex);
        LINK_LEXER(lmTeX);
        LINK_LEXER(lmTxt2tags);
        LINK_LEXER(lmVB);
diff --git a/plugins/scintilla/scintilla/src/CellBuffer.cxx b/plugins/scintilla/scintilla/src/CellBuffer.cxx
index e88fd63..0cc3b4e 100644
--- a/plugins/scintilla/scintilla/src/CellBuffer.cxx
+++ b/plugins/scintilla/scintilla/src/CellBuffer.cxx
@@ -5,16 +5,21 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stdarg.h>
-
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <cstdio>
+#include <cstdarg>
+
+#include <stdexcept>
+#include <vector>
 #include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
+#include "Position.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "CellBuffer.h"
@@ -43,11 +48,11 @@ void LineVector::SetPerLine(PerLine *pl) {
        perLine = pl;
 }
 
-void LineVector::InsertText(int line, int delta) {
+void LineVector::InsertText(Sci::Line line, Sci::Position delta) {
        starts.InsertText(line, delta);
 }
 
-void LineVector::InsertLine(int line, int position, bool lineStart) {
+void LineVector::InsertLine(Sci::Line line, Sci::Position position, bool lineStart) {
        starts.InsertPartition(line, position);
        if (perLine) {
                if ((line > 0) && lineStart)
@@ -56,66 +61,54 @@ void LineVector::InsertLine(int line, int position, bool lineStart) {
        }
 }
 
-void LineVector::SetLineStart(int line, int position) {
+void LineVector::SetLineStart(Sci::Line line, Sci::Position position) {
        starts.SetPartitionStartPosition(line, position);
 }
 
-void LineVector::RemoveLine(int line) {
+void LineVector::RemoveLine(Sci::Line line) {
        starts.RemovePartition(line);
        if (perLine) {
                perLine->RemoveLine(line);
        }
 }
 
-int LineVector::LineFromPosition(int pos) const {
+Sci::Line LineVector::LineFromPosition(Sci::Position pos) const {
        return starts.PartitionFromPosition(pos);
 }
 
 Action::Action() {
        at = startAction;
        position = 0;
-       data = 0;
        lenData = 0;
        mayCoalesce = false;
 }
 
+Action::Action(Action &&other) {
+       at = other.at;
+       position = other.position;
+       data = std::move(other.data);
+       lenData = other.lenData;
+       mayCoalesce = other.mayCoalesce;
+}
+
 Action::~Action() {
-       Destroy();
 }
 
-void Action::Create(actionType at_, int position_, const char *data_, int lenData_, bool mayCoalesce_) {
-       delete []data;
-       data = NULL;
+void Action::Create(actionType at_, Sci::Position position_, const char *data_, Sci::Position lenData_, bool 
mayCoalesce_) {
+       data = nullptr;
        position = position_;
        at = at_;
        if (lenData_) {
-               data = new char[lenData_];
-               memcpy(data, data_, lenData_);
+               data = std::unique_ptr<char []>(new char[lenData_]);
+               memcpy(&data[0], data_, lenData_);
        }
        lenData = lenData_;
        mayCoalesce = mayCoalesce_;
 }
 
-void Action::Destroy() {
-       delete []data;
-       data = 0;
-}
-
-void Action::Grab(Action *source) {
-       delete []data;
-
-       position = source->position;
-       at = source->at;
-       data = source->data;
-       lenData = source->lenData;
-       mayCoalesce = source->mayCoalesce;
-
-       // Ownership of source data transferred to this
-       source->position = 0;
-       source->at = startAction;
-       source->data = 0;
-       source->lenData = 0;
-       source->mayCoalesce = true;
+void Action::Clear() {
+       data = nullptr;
+       lenData = 0;
 }
 
 // The undo history stores a sequence of user operations that represent the user's view of the
@@ -138,37 +131,29 @@ void Action::Grab(Action *source) {
 
 UndoHistory::UndoHistory() {
 
-       lenActions = 100;
-       actions = new Action[lenActions];
+       actions.resize(3);
        maxAction = 0;
        currentAction = 0;
        undoSequenceDepth = 0;
        savePoint = 0;
+       tentativePoint = -1;
 
        actions[currentAction].Create(startAction);
 }
 
 UndoHistory::~UndoHistory() {
-       delete []actions;
-       actions = 0;
 }
 
 void UndoHistory::EnsureUndoRoom() {
        // Have to test that there is room for 2 more actions in the array
        // as two actions may be created by the calling function
-       if (currentAction >= (lenActions - 2)) {
+       if (static_cast<size_t>(currentAction) >= (actions.size() - 2)) {
                // Run out of undo nodes so extend the array
-               int lenActionsNew = lenActions * 2;
-               Action *actionsNew = new Action[lenActionsNew];
-               for (int act = 0; act <= currentAction; act++)
-                       actionsNew[act].Grab(&actions[act]);
-               delete []actions;
-               lenActions = lenActionsNew;
-               actions = actionsNew;
+               actions.resize(actions.size() * 2);
        }
 }
 
-const char *UndoHistory::AppendAction(actionType at, int position, const char *data, int lengthData,
+const char *UndoHistory::AppendAction(actionType at, Sci::Position position, const char *data, Sci::Position 
lengthData,
        bool &startSequence, bool mayCoalesce) {
        EnsureUndoRoom();
        //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, lengthData, currentAction);
@@ -190,7 +175,7 @@ const char *UndoHistory::AppendAction(actionType at, int position, const char *d
                        }
                        // See if current action can be coalesced into previous action
                        // Will work if both are inserts or deletes and position is same
-                       if (currentAction == savePoint) {
+                       if ((currentAction == savePoint) || (currentAction == tentativePoint)) {
                                currentAction++;
                        } else if (!actions[currentAction].mayCoalesce) {
                                // Not allowed to coalesce if this set
@@ -232,12 +217,12 @@ const char *UndoHistory::AppendAction(actionType at, int position, const char *d
                currentAction++;
        }
        startSequence = oldCurrentAction != currentAction;
-       int actionWithData = currentAction;
+       const int actionWithData = currentAction;
        actions[currentAction].Create(at, position, data, lengthData, mayCoalesce);
        currentAction++;
        actions[currentAction].Create(startAction);
        maxAction = currentAction;
-       return actions[actionWithData].data;
+       return actions[actionWithData].data.get();
 }
 
 void UndoHistory::BeginUndoAction() {
@@ -273,11 +258,12 @@ void UndoHistory::DropUndoSequence() {
 
 void UndoHistory::DeleteUndoHistory() {
        for (int i = 1; i < maxAction; i++)
-               actions[i].Destroy();
+               actions[i].Clear();
        maxAction = 0;
        currentAction = 0;
        actions[currentAction].Create(startAction);
        savePoint = 0;
+       tentativePoint = -1;
 }
 
 void UndoHistory::SetSavePoint() {
@@ -288,6 +274,26 @@ bool UndoHistory::IsSavePoint() const {
        return savePoint == currentAction;
 }
 
+void UndoHistory::TentativeStart() {
+       tentativePoint = currentAction;
+}
+
+void UndoHistory::TentativeCommit() {
+       tentativePoint = -1;
+       // Truncate undo history
+       maxAction = currentAction;
+}
+
+int UndoHistory::TentativeSteps() {
+       // Drop any trailing startAction
+       if (actions[currentAction].at == startAction && currentAction > 0)
+               currentAction--;
+       if (tentativePoint >= 0)
+               return currentAction - tentativePoint;
+       else
+               return -1;
+}
+
 bool UndoHistory::CanUndo() const {
        return (currentAction > 0) && (maxAction > 0);
 }
@@ -319,12 +325,12 @@ bool UndoHistory::CanRedo() const {
 
 int UndoHistory::StartRedo() {
        // Drop any leading startAction
-       if (actions[currentAction].at == startAction && currentAction < maxAction)
+       if (currentAction < maxAction && actions[currentAction].at == startAction)
                currentAction++;
 
        // Count the steps in this action
        int act = currentAction;
-       while (actions[act].at != startAction && act < maxAction) {
+       while (act < maxAction && actions[act].at != startAction) {
                act++;
        }
        return act - currentAction;
@@ -347,12 +353,12 @@ CellBuffer::CellBuffer() {
 CellBuffer::~CellBuffer() {
 }
 
-char CellBuffer::CharAt(int position) const {
+char CellBuffer::CharAt(Sci::Position position) const {
        return substance.ValueAt(position);
 }
 
-void CellBuffer::GetCharRange(char *buffer, int position, int lengthRetrieve) const {
-       if (lengthRetrieve < 0)
+void CellBuffer::GetCharRange(char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const {
+       if (lengthRetrieve <= 0)
                return;
        if (position < 0)
                return;
@@ -364,11 +370,11 @@ void CellBuffer::GetCharRange(char *buffer, int position, int lengthRetrieve) co
        substance.GetRange(buffer, position, lengthRetrieve);
 }
 
-char CellBuffer::StyleAt(int position) const {
+char CellBuffer::StyleAt(Sci::Position position) const {
        return style.ValueAt(position);
 }
 
-void CellBuffer::GetStyleRange(unsigned char *buffer, int position, int lengthRetrieve) const {
+void CellBuffer::GetStyleRange(unsigned char *buffer, Sci::Position position, Sci::Position lengthRetrieve) 
const {
        if (lengthRetrieve < 0)
                return;
        if (position < 0)
@@ -385,16 +391,16 @@ const char *CellBuffer::BufferPointer() {
        return substance.BufferPointer();
 }
 
-const char *CellBuffer::RangePointer(int position, int rangeLength) {
+const char *CellBuffer::RangePointer(Sci::Position position, Sci::Position rangeLength) {
        return substance.RangePointer(position, rangeLength);
 }
 
-int CellBuffer::GapPosition() const {
+Sci::Position CellBuffer::GapPosition() const {
        return substance.GapPosition();
 }
 
 // The char* returned is to an allocation owned by the undo history
-const char *CellBuffer::InsertString(int position, const char *s, int insertLength, bool &startSequence) {
+const char *CellBuffer::InsertString(Sci::Position position, const char *s, Sci::Position insertLength, bool 
&startSequence) {
        // InsertString and DeleteChars are the bottleneck though which all changes occur
        const char *data = s;
        if (!readOnly) {
@@ -409,25 +415,24 @@ const char *CellBuffer::InsertString(int position, const char *s, int insertLeng
        return data;
 }
 
-bool CellBuffer::SetStyleAt(int position, char styleValue, char mask) {
-       styleValue &= mask;
-       char curVal = style.ValueAt(position);
-       if ((curVal & mask) != styleValue) {
-               style.SetValueAt(position, static_cast<char>((curVal & ~mask) | styleValue));
+bool CellBuffer::SetStyleAt(Sci::Position position, char styleValue) {
+       const char curVal = style.ValueAt(position);
+       if (curVal != styleValue) {
+               style.SetValueAt(position, styleValue);
                return true;
        } else {
                return false;
        }
 }
 
-bool CellBuffer::SetStyleFor(int position, int lengthStyle, char styleValue, char mask) {
+bool CellBuffer::SetStyleFor(Sci::Position position, Sci::Position lengthStyle, char styleValue) {
        bool changed = false;
        PLATFORM_ASSERT(lengthStyle == 0 ||
                (lengthStyle > 0 && lengthStyle + position <= style.Length()));
        while (lengthStyle--) {
-               char curVal = style.ValueAt(position);
-               if ((curVal & mask) != styleValue) {
-                       style.SetValueAt(position, static_cast<char>((curVal & ~mask) | styleValue));
+               const char curVal = style.ValueAt(position);
+               if (curVal != styleValue) {
+                       style.SetValueAt(position, styleValue);
                        changed = true;
                }
                position++;
@@ -436,7 +441,7 @@ bool CellBuffer::SetStyleFor(int position, int lengthStyle, char styleValue, cha
 }
 
 // The char* returned is to an allocation owned by the undo history
-const char *CellBuffer::DeleteChars(int position, int deleteLength, bool &startSequence) {
+const char *CellBuffer::DeleteChars(Sci::Position position, Sci::Position deleteLength, bool &startSequence) 
{
        // InsertString and DeleteChars are the bottleneck though which all changes occur
        PLATFORM_ASSERT(deleteLength > 0);
        const char *data = 0;
@@ -453,11 +458,11 @@ const char *CellBuffer::DeleteChars(int position, int deleteLength, bool &startS
        return data;
 }
 
-int CellBuffer::Length() const {
+Sci::Position CellBuffer::Length() const {
        return substance.Length();
 }
 
-void CellBuffer::Allocate(int newSize) {
+void CellBuffer::Allocate(Sci::Position newSize) {
        substance.ReAllocate(newSize);
        style.ReAllocate(newSize);
 }
@@ -469,15 +474,34 @@ void CellBuffer::SetLineEndTypes(int utf8LineEnds_) {
        }
 }
 
+bool CellBuffer::ContainsLineEnd(const char *s, Sci::Position length) const {
+       unsigned char chBeforePrev = 0;
+       unsigned char chPrev = 0;
+       for (Sci::Position i = 0; i < length; i++) {
+               const unsigned char ch = s[i];
+               if ((ch == '\r') || (ch == '\n')) {
+                       return true;
+               } else if (utf8LineEnds) {
+                       const unsigned char back3[3] = { chBeforePrev, chPrev, ch };
+                       if (UTF8IsSeparator(back3) || UTF8IsNEL(back3 + 1)) {
+                               return true;
+                       }
+               }
+               chBeforePrev = chPrev;
+               chPrev = ch;
+       }
+       return false;
+}
+
 void CellBuffer::SetPerLine(PerLine *pl) {
        lv.SetPerLine(pl);
 }
 
-int CellBuffer::Lines() const {
+Sci::Line CellBuffer::Lines() const {
        return lv.Lines();
 }
 
-int CellBuffer::LineStart(int line) const {
+Sci::Position CellBuffer::LineStart(Sci::Line line) const {
        if (line < 0)
                return 0;
        else if (line >= Lines())
@@ -502,18 +526,34 @@ bool CellBuffer::IsSavePoint() const {
        return uh.IsSavePoint();
 }
 
+void CellBuffer::TentativeStart() {
+       uh.TentativeStart();
+}
+
+void CellBuffer::TentativeCommit() {
+       uh.TentativeCommit();
+}
+
+int CellBuffer::TentativeSteps() {
+       return uh.TentativeSteps();
+}
+
+bool CellBuffer::TentativeActive() const {
+       return uh.TentativeActive();
+}
+
 // Without undo
 
-void CellBuffer::InsertLine(int line, int position, bool lineStart) {
+void CellBuffer::InsertLine(Sci::Line line, Sci::Position position, bool lineStart) {
        lv.InsertLine(line, position, lineStart);
 }
 
-void CellBuffer::RemoveLine(int line) {
+void CellBuffer::RemoveLine(Sci::Line line) {
        lv.RemoveLine(line);
 }
 
-bool CellBuffer::UTF8LineEndOverlaps(int position) const {
-       unsigned char bytes[] = {
+bool CellBuffer::UTF8LineEndOverlaps(Sci::Position position) const {
+       const unsigned char bytes[] = {
                static_cast<unsigned char>(substance.ValueAt(position-2)),
                static_cast<unsigned char>(substance.ValueAt(position-1)),
                static_cast<unsigned char>(substance.ValueAt(position)),
@@ -526,15 +566,15 @@ void CellBuffer::ResetLineEnds() {
        // Reinitialize line data -- too much work to preserve
        lv.Init();
 
-       int position = 0;
-       int length = Length();
-       int lineInsert = 1;
+       Sci::Position position = 0;
+       Sci::Position length = Length();
+       Sci::Line lineInsert = 1;
        bool atLineStart = true;
        lv.InsertText(lineInsert-1, length);
        unsigned char chBeforePrev = 0;
        unsigned char chPrev = 0;
-       for (int i = 0; i < length; i++) {
-               unsigned char ch = substance.ValueAt(position + i);
+       for (Sci::Position i = 0; i < length; i++) {
+               const unsigned char ch = substance.ValueAt(position + i);
                if (ch == '\r') {
                        InsertLine(lineInsert, (position + i) + 1, atLineStart);
                        lineInsert++;
@@ -547,7 +587,7 @@ void CellBuffer::ResetLineEnds() {
                                lineInsert++;
                        }
                } else if (utf8LineEnds) {
-                       unsigned char back3[3] = {chBeforePrev, chPrev, ch};
+                       const unsigned char back3[3] = {chBeforePrev, chPrev, ch};
                        if (UTF8IsSeparator(back3) || UTF8IsNEL(back3+1)) {
                                InsertLine(lineInsert, (position + i) + 1, atLineStart);
                                lineInsert++;
@@ -558,12 +598,12 @@ void CellBuffer::ResetLineEnds() {
        }
 }
 
-void CellBuffer::BasicInsertString(int position, const char *s, int insertLength) {
+void CellBuffer::BasicInsertString(Sci::Position position, const char *s, Sci::Position insertLength) {
        if (insertLength == 0)
                return;
        PLATFORM_ASSERT(insertLength > 0);
 
-       unsigned char chAfter = substance.ValueAt(position);
+       const unsigned char chAfter = substance.ValueAt(position);
        bool breakingUTF8LineEnd = false;
        if (utf8LineEnds && UTF8IsTrailByte(chAfter)) {
                breakingUTF8LineEnd = UTF8LineEndOverlaps(position);
@@ -572,7 +612,7 @@ void CellBuffer::BasicInsertString(int position, const char *s, int insertLength
        substance.InsertFromArray(position, s, 0, insertLength);
        style.InsertValue(position, insertLength, 0);
 
-       int lineInsert = lv.LineFromPosition(position) + 1;
+       Sci::Line lineInsert = lv.LineFromPosition(position) + 1;
        bool atLineStart = lv.LineStart(lineInsert-1) == position;
        // Point all the lines after the insertion point further along in the buffer
        lv.InsertText(lineInsert-1, insertLength);
@@ -587,7 +627,7 @@ void CellBuffer::BasicInsertString(int position, const char *s, int insertLength
                RemoveLine(lineInsert);
        }
        unsigned char ch = ' ';
-       for (int i = 0; i < insertLength; i++) {
+       for (Sci::Position i = 0; i < insertLength; i++) {
                ch = s[i];
                if (ch == '\r') {
                        InsertLine(lineInsert, (position + i) + 1, atLineStart);
@@ -601,7 +641,7 @@ void CellBuffer::BasicInsertString(int position, const char *s, int insertLength
                                lineInsert++;
                        }
                } else if (utf8LineEnds) {
-                       unsigned char back3[3] = {chBeforePrev, chPrev, ch};
+                       const unsigned char back3[3] = {chBeforePrev, chPrev, ch};
                        if (UTF8IsSeparator(back3) || UTF8IsNEL(back3+1)) {
                                InsertLine(lineInsert, (position + i) + 1, atLineStart);
                                lineInsert++;
@@ -619,8 +659,8 @@ void CellBuffer::BasicInsertString(int position, const char *s, int insertLength
        } else if (utf8LineEnds && !UTF8IsAscii(chAfter)) {
                // May have end of UTF-8 line end in buffer and start in insertion
                for (int j = 0; j < UTF8SeparatorLength-1; j++) {
-                       unsigned char chAt = substance.ValueAt(position + insertLength + j);
-                       unsigned char back3[3] = {chBeforePrev, chPrev, chAt};
+                       const unsigned char chAt = substance.ValueAt(position + insertLength + j);
+                       const unsigned char back3[3] = {chBeforePrev, chPrev, chAt};
                        if (UTF8IsSeparator(back3)) {
                                InsertLine(lineInsert, (position + insertLength + j) + 1, atLineStart);
                                lineInsert++;
@@ -635,7 +675,7 @@ void CellBuffer::BasicInsertString(int position, const char *s, int insertLength
        }
 }
 
-void CellBuffer::BasicDeleteChars(int position, int deleteLength) {
+void CellBuffer::BasicDeleteChars(Sci::Position position, Sci::Position deleteLength) {
        if (deleteLength == 0)
                return;
 
@@ -647,10 +687,10 @@ void CellBuffer::BasicDeleteChars(int position, int deleteLength) {
                // Have to fix up line positions before doing deletion as looking at text in buffer
                // to work out which lines have been removed
 
-               int lineRemove = lv.LineFromPosition(position) + 1;
+               Sci::Line lineRemove = lv.LineFromPosition(position) + 1;
                lv.InsertText(lineRemove-1, - (deleteLength));
-               unsigned char chPrev = substance.ValueAt(position - 1);
-               unsigned char chBefore = chPrev;
+               const unsigned char chPrev = substance.ValueAt(position - 1);
+               const unsigned char chBefore = chPrev;
                unsigned char chNext = substance.ValueAt(position);
                bool ignoreNL = false;
                if (chPrev == '\r' && chNext == '\n') {
@@ -666,7 +706,7 @@ void CellBuffer::BasicDeleteChars(int position, int deleteLength) {
                }
 
                unsigned char ch = chNext;
-               for (int i = 0; i < deleteLength; i++) {
+               for (Sci::Position i = 0; i < deleteLength; i++) {
                        chNext = substance.ValueAt(position + i + 1);
                        if (ch == '\r') {
                                if (chNext != '\n') {
@@ -680,7 +720,7 @@ void CellBuffer::BasicDeleteChars(int position, int deleteLength) {
                                }
                        } else if (utf8LineEnds) {
                                if (!UTF8IsAscii(ch)) {
-                                       unsigned char next3[3] = {ch, chNext,
+                                       const unsigned char next3[3] = {ch, chNext,
                                                static_cast<unsigned char>(substance.ValueAt(position + i + 
2))};
                                        if (UTF8IsSeparator(next3) || UTF8IsNEL(next3)) {
                                                RemoveLine(lineRemove);
@@ -692,7 +732,7 @@ void CellBuffer::BasicDeleteChars(int position, int deleteLength) {
                }
                // May have to fix up end if last deletion causes cr to be next to lf
                // or removes one of a crlf pair
-               char chAfter = substance.ValueAt(position + deleteLength);
+               const char chAfter = substance.ValueAt(position + deleteLength);
                if (chBefore == '\r' && chAfter == '\n') {
                        // Using lineRemove-1 as cr ended line before start of deletion
                        RemoveLine(lineRemove - 1);
@@ -721,7 +761,7 @@ void CellBuffer::EndUndoAction() {
        uh.EndUndoAction();
 }
 
-void CellBuffer::AddUndoAction(int token, bool mayCoalesce) {
+void CellBuffer::AddUndoAction(Sci::Position token, bool mayCoalesce) {
        bool startSequence;
        uh.AppendAction(containerAction, token, 0, 0, startSequence, mayCoalesce);
 }
@@ -745,9 +785,13 @@ const Action &CellBuffer::GetUndoStep() const {
 void CellBuffer::PerformUndoStep() {
        const Action &actionStep = uh.GetUndoStep();
        if (actionStep.at == insertAction) {
+               if (substance.Length() < actionStep.lenData) {
+                       throw std::runtime_error(
+                               "CellBuffer::PerformUndoStep: deletion must be less than document length.");
+               }
                BasicDeleteChars(actionStep.position, actionStep.lenData);
        } else if (actionStep.at == removeAction) {
-               BasicInsertString(actionStep.position, actionStep.data, actionStep.lenData);
+               BasicInsertString(actionStep.position, actionStep.data.get(), actionStep.lenData);
        }
        uh.CompletedUndoStep();
 }
@@ -767,7 +811,7 @@ const Action &CellBuffer::GetRedoStep() const {
 void CellBuffer::PerformRedoStep() {
        const Action &actionStep = uh.GetRedoStep();
        if (actionStep.at == insertAction) {
-               BasicInsertString(actionStep.position, actionStep.data, actionStep.lenData);
+               BasicInsertString(actionStep.position, actionStep.data.get(), actionStep.lenData);
        } else if (actionStep.at == removeAction) {
                BasicDeleteChars(actionStep.position, actionStep.lenData);
        }
diff --git a/plugins/scintilla/scintilla/src/CellBuffer.h b/plugins/scintilla/scintilla/src/CellBuffer.h
index 82179ac..8e670ac 100644
--- a/plugins/scintilla/scintilla/src/CellBuffer.h
+++ b/plugins/scintilla/scintilla/src/CellBuffer.h
@@ -17,8 +17,8 @@ class PerLine {
 public:
        virtual ~PerLine() {}
        virtual void Init()=0;
-       virtual void InsertLine(int)=0;
-       virtual void RemoveLine(int)=0;
+       virtual void InsertLine(Sci::Line line)=0;
+       virtual void RemoveLine(Sci::Line line)=0;
 };
 
 /**
@@ -32,37 +32,24 @@ class LineVector {
 public:
 
        LineVector();
+       // Deleted so LineVector objects can not be copied.
+       LineVector(const LineVector &) = delete;
+       void operator=(const LineVector &) = delete;
        ~LineVector();
        void Init();
        void SetPerLine(PerLine *pl);
 
-       void InsertText(int line, int delta);
-       void InsertLine(int line, int position, bool lineStart);
-       void SetLineStart(int line, int position);
-       void RemoveLine(int line);
-       int Lines() const {
+       void InsertText(Sci::Line line, Sci::Position delta);
+       void InsertLine(Sci::Line line, Sci::Position position, bool lineStart);
+       void SetLineStart(Sci::Line line, Sci::Position position);
+       void RemoveLine(Sci::Line line);
+       Sci::Line Lines() const {
                return starts.Partitions();
        }
-       int LineFromPosition(int pos) const;
-       int LineStart(int line) const {
+       Sci::Line LineFromPosition(Sci::Position pos) const;
+       Sci::Position LineStart(Sci::Line line) const {
                return starts.PositionFromPartition(line);
        }
-
-       int MarkValue(int line);
-       int AddMark(int line, int marker);
-       void MergeMarkers(int pos);
-       void DeleteMark(int line, int markerNum, bool all);
-       void DeleteMarkFromHandle(int markerHandle);
-       int LineFromHandle(int markerHandle);
-
-       void ClearLevels();
-       int SetLevel(int line, int level);
-       int GetLevel(int line);
-
-       int SetLineState(int line, int state);
-       int GetLineState(int line);
-       int GetMaxLineState();
-
 };
 
 enum actionType { insertAction, removeAction, startAction, containerAction };
@@ -73,39 +60,45 @@ enum actionType { insertAction, removeAction, startAction, containerAction };
 class Action {
 public:
        actionType at;
-       int position;
-       char *data;
-       int lenData;
+       Sci::Position position;
+       std::unique_ptr<char[]> data;
+       Sci::Position lenData;
        bool mayCoalesce;
 
        Action();
+       // Deleted so Action objects can not be copied.
+       Action(const Action &other) = delete;
+       Action &operator=(const Action &other) = delete;
+       Action &operator=(const Action &&other) = delete;
+       // Move constructor allows vector to be resized without reallocating.
+       // Could use =default but MSVC 2013 warns.
+       Action(Action &&other);
        ~Action();
-       void Create(actionType at_, int position_=0, const char *data_=0, int lenData_=0, bool 
mayCoalesce_=true);
-       void Destroy();
-       void Grab(Action *source);
+       void Create(actionType at_, Sci::Position position_=0, const char *data_=0, Sci::Position lenData_=0, 
bool mayCoalesce_=true);
+       void Clear();
 };
 
 /**
  *
  */
 class UndoHistory {
-       Action *actions;
-       int lenActions;
+       std::vector<Action> actions;
        int maxAction;
        int currentAction;
        int undoSequenceDepth;
        int savePoint;
+       int tentativePoint;
 
        void EnsureUndoRoom();
 
-       // Private so UndoHistory objects can not be copied
-       UndoHistory(const UndoHistory &);
-
 public:
        UndoHistory();
+       // Deleted so UndoHistory objects can not be copied.
+       UndoHistory(const UndoHistory &) = delete;
+       void operator=(const UndoHistory &) = delete;
        ~UndoHistory();
 
-       const char *AppendAction(actionType at, int position, const char *data, int length, bool 
&startSequence, bool mayCoalesce=true);
+       const char *AppendAction(actionType at, Sci::Position position, const char *data, Sci::Position 
lengthData, bool &startSequence, bool mayCoalesce=true);
 
        void BeginUndoAction();
        void EndUndoAction();
@@ -117,6 +110,12 @@ public:
        void SetSavePoint();
        bool IsSavePoint() const;
 
+       // Tentative actions are used for input composition so that it can be undone cleanly
+       void TentativeStart();
+       void TentativeCommit();
+       bool TentativeActive() const { return tentativePoint >= 0; }
+       int TentativeSteps();
+
        /// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
        /// called that many times. Similarly for redo.
        bool CanUndo() const;
@@ -146,44 +145,48 @@ private:
 
        LineVector lv;
 
-       bool UTF8LineEndOverlaps(int position) const;
+       bool UTF8LineEndOverlaps(Sci::Position position) const;
        void ResetLineEnds();
        /// Actions without undo
-       void BasicInsertString(int position, const char *s, int insertLength);
-       void BasicDeleteChars(int position, int deleteLength);
+       void BasicInsertString(Sci::Position position, const char *s, Sci::Position insertLength);
+       void BasicDeleteChars(Sci::Position position, Sci::Position deleteLength);
 
 public:
 
        CellBuffer();
+       // Deleted so CellBuffer objects can not be copied.
+       CellBuffer(const CellBuffer &) = delete;
+       void operator=(const CellBuffer &) = delete;
        ~CellBuffer();
 
        /// Retrieving positions outside the range of the buffer works and returns 0
-       char CharAt(int position) const;
-       void GetCharRange(char *buffer, int position, int lengthRetrieve) const;
-       char StyleAt(int position) const;
-       void GetStyleRange(unsigned char *buffer, int position, int lengthRetrieve) const;
+       char CharAt(Sci::Position position) const;
+       void GetCharRange(char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const;
+       char StyleAt(Sci::Position position) const;
+       void GetStyleRange(unsigned char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const;
        const char *BufferPointer();
-       const char *RangePointer(int position, int rangeLength);
-       int GapPosition() const;
+       const char *RangePointer(Sci::Position position, Sci::Position rangeLength);
+       Sci::Position GapPosition() const;
 
-       int Length() const;
-       void Allocate(int newSize);
+       Sci::Position Length() const;
+       void Allocate(Sci::Position newSize);
        int GetLineEndTypes() const { return utf8LineEnds; }
        void SetLineEndTypes(int utf8LineEnds_);
+       bool ContainsLineEnd(const char *s, Sci::Position length) const;
        void SetPerLine(PerLine *pl);
-       int Lines() const;
-       int LineStart(int line) const;
-       int LineFromPosition(int pos) const { return lv.LineFromPosition(pos); }
-       void InsertLine(int line, int position, bool lineStart);
-       void RemoveLine(int line);
-       const char *InsertString(int position, const char *s, int insertLength, bool &startSequence);
+       Sci::Line Lines() const;
+       Sci::Position LineStart(Sci::Line line) const;
+       Sci::Line LineFromPosition(Sci::Position pos) const { return lv.LineFromPosition(pos); }
+       void InsertLine(Sci::Line line, Sci::Position position, bool lineStart);
+       void RemoveLine(Sci::Line line);
+       const char *InsertString(Sci::Position position, const char *s, Sci::Position insertLength, bool 
&startSequence);
 
        /// Setting styles for positions outside the range of the buffer is safe and has no effect.
        /// @return true if the style of a character is changed.
-       bool SetStyleAt(int position, char styleValue, char mask='\377');
-       bool SetStyleFor(int position, int length, char styleValue, char mask);
+       bool SetStyleAt(Sci::Position position, char styleValue);
+       bool SetStyleFor(Sci::Position position, Sci::Position lengthStyle, char styleValue);
 
-       const char *DeleteChars(int position, int deleteLength, bool &startSequence);
+       const char *DeleteChars(Sci::Position position, Sci::Position deleteLength, bool &startSequence);
 
        bool IsReadOnly() const;
        void SetReadOnly(bool set);
@@ -193,11 +196,16 @@ public:
        void SetSavePoint();
        bool IsSavePoint() const;
 
+       void TentativeStart();
+       void TentativeCommit();
+       bool TentativeActive() const;
+       int TentativeSteps();
+
        bool SetUndoCollection(bool collectUndo);
        bool IsCollectingUndo() const;
        void BeginUndoAction();
        void EndUndoAction();
-       void AddUndoAction(int token, bool mayCoalesce);
+       void AddUndoAction(Sci::Position token, bool mayCoalesce);
        void DeleteUndoHistory();
 
        /// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
diff --git a/plugins/scintilla/scintilla/src/CharClassify.cxx 
b/plugins/scintilla/scintilla/src/CharClassify.cxx
index 7e3db73..5d0aa02 100644
--- a/plugins/scintilla/scintilla/src/CharClassify.cxx
+++ b/plugins/scintilla/scintilla/src/CharClassify.cxx
@@ -5,8 +5,10 @@
 // Copyright 2006 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <ctype.h>
+#include <cstdlib>
+#include <cctype>
+
+#include <stdexcept>
 
 #include "CharClassify.h"
 
@@ -14,11 +16,6 @@
 using namespace Scintilla;
 #endif
 
-// Shut up annoying Visual C++ warnings:
-#ifdef _MSC_VER
-#pragma warning(disable: 4514)
-#endif
-
 CharClassify::CharClassify() {
        SetDefaultCharClasses(true);
 }
@@ -47,7 +44,7 @@ void CharClassify::SetCharClasses(const unsigned char *chars, cc newCharClass) {
        }
 }
 
-int CharClassify::GetCharsOfClass(cc characterClass, unsigned char *buffer) {
+int CharClassify::GetCharsOfClass(cc characterClass, unsigned char *buffer) const {
        // Get characters belonging to the given char class; return the number
        // of characters (if the buffer is NULL, don't write to it).
        int count = 0;
diff --git a/plugins/scintilla/scintilla/src/CharClassify.h b/plugins/scintilla/scintilla/src/CharClassify.h
index 5d2734c..26ab546 100644
--- a/plugins/scintilla/scintilla/src/CharClassify.h
+++ b/plugins/scintilla/scintilla/src/CharClassify.h
@@ -19,7 +19,7 @@ public:
        enum cc { ccSpace, ccNewLine, ccWord, ccPunctuation };
        void SetDefaultCharClasses(bool includeWordClass);
        void SetCharClasses(const unsigned char *chars, cc newCharClass);
-       int GetCharsOfClass(cc charClass, unsigned char *buffer);
+       int GetCharsOfClass(cc characterClass, unsigned char *buffer) const;
        cc GetClass(unsigned char ch) const { return static_cast<cc>(charClass[ch]);}
        bool IsWord(unsigned char ch) const { return static_cast<cc>(charClass[ch]) == ccWord;}
 
diff --git a/plugins/scintilla/scintilla/src/ContractionState.cxx 
b/plugins/scintilla/scintilla/src/ContractionState.cxx
index 0636d90..c56c564 100644
--- a/plugins/scintilla/scintilla/src/ContractionState.cxx
+++ b/plugins/scintilla/scintilla/src/ContractionState.cxx
@@ -5,23 +5,30 @@
 // Copyright 1998-2007 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
+#include <cstddef>
+#include <cassert>
+#include <cstring>
 
+#include <stdexcept>
+#include <vector>
 #include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
+#include "Position.h"
+#include "UniqueString.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
+#include "SparseVector.h"
 #include "ContractionState.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
-ContractionState::ContractionState() : visible(0), expanded(0), heights(0), displayLines(0), 
linesInDocument(1) {
-       //InsertLine(0);
+ContractionState::ContractionState() : linesInDocument(1) {
 }
 
 ContractionState::~ContractionState() {
@@ -30,27 +37,25 @@ ContractionState::~ContractionState() {
 
 void ContractionState::EnsureData() {
        if (OneToOne()) {
-               visible = new RunStyles();
-               expanded = new RunStyles();
-               heights = new RunStyles();
-               displayLines = new Partitioning(4);
+               visible.reset(new RunStyles());
+               expanded.reset(new RunStyles());
+               heights.reset(new RunStyles());
+               foldDisplayTexts.reset(new SparseVector<UniqueString>());
+               displayLines.reset(new Partitioning(4));
                InsertLines(0, linesInDocument);
        }
 }
 
 void ContractionState::Clear() {
-       delete visible;
-       visible = 0;
-       delete expanded;
-       expanded = 0;
-       delete heights;
-       heights = 0;
-       delete displayLines;
-       displayLines = 0;
+       visible.reset();
+       expanded.reset();
+       heights.reset();
+       foldDisplayTexts.reset();
+       displayLines.reset();
        linesInDocument = 1;
 }
 
-int ContractionState::LinesInDoc() const {
+Sci::Line ContractionState::LinesInDoc() const {
        if (OneToOne()) {
                return linesInDocument;
        } else {
@@ -58,7 +63,7 @@ int ContractionState::LinesInDoc() const {
        }
 }
 
-int ContractionState::LinesDisplayed() const {
+Sci::Line ContractionState::LinesDisplayed() const {
        if (OneToOne()) {
                return linesInDocument;
        } else {
@@ -66,7 +71,7 @@ int ContractionState::LinesDisplayed() const {
        }
 }
 
-int ContractionState::DisplayFromDoc(int lineDoc) const {
+Sci::Line ContractionState::DisplayFromDoc(Sci::Line lineDoc) const {
        if (OneToOne()) {
                return (lineDoc <= linesInDocument) ? lineDoc : linesInDocument;
        } else {
@@ -76,7 +81,11 @@ int ContractionState::DisplayFromDoc(int lineDoc) const {
        }
 }
 
-int ContractionState::DocFromDisplay(int lineDisplay) const {
+Sci::Line ContractionState::DisplayLastFromDoc(Sci::Line lineDoc) const {
+       return DisplayFromDoc(lineDoc) + GetHeight(lineDoc) - 1;
+}
+
+Sci::Line ContractionState::DocFromDisplay(Sci::Line lineDisplay) const {
        if (OneToOne()) {
                return lineDisplay;
        } else {
@@ -86,13 +95,13 @@ int ContractionState::DocFromDisplay(int lineDisplay) const {
                if (lineDisplay > LinesDisplayed()) {
                        return displayLines->PartitionFromPosition(LinesDisplayed());
                }
-               int lineDoc = displayLines->PartitionFromPosition(lineDisplay);
+               Sci::Line lineDoc = displayLines->PartitionFromPosition(lineDisplay);
                PLATFORM_ASSERT(GetVisible(lineDoc));
                return lineDoc;
        }
 }
 
-void ContractionState::InsertLine(int lineDoc) {
+void ContractionState::InsertLine(Sci::Line lineDoc) {
        if (OneToOne()) {
                linesInDocument++;
        } else {
@@ -102,20 +111,22 @@ void ContractionState::InsertLine(int lineDoc) {
                expanded->SetValueAt(lineDoc, 1);
                heights->InsertSpace(lineDoc, 1);
                heights->SetValueAt(lineDoc, 1);
-               int lineDisplay = DisplayFromDoc(lineDoc);
+               foldDisplayTexts->InsertSpace(lineDoc, 1);
+               foldDisplayTexts->SetValueAt(lineDoc, nullptr);
+               Sci::Line lineDisplay = DisplayFromDoc(lineDoc);
                displayLines->InsertPartition(lineDoc, lineDisplay);
                displayLines->InsertText(lineDoc, 1);
        }
 }
 
-void ContractionState::InsertLines(int lineDoc, int lineCount) {
+void ContractionState::InsertLines(Sci::Line lineDoc, Sci::Line lineCount) {
        for (int l = 0; l < lineCount; l++) {
                InsertLine(lineDoc + l);
        }
        Check();
 }
 
-void ContractionState::DeleteLine(int lineDoc) {
+void ContractionState::DeleteLine(Sci::Line lineDoc) {
        if (OneToOne()) {
                linesInDocument--;
        } else {
@@ -126,17 +137,18 @@ void ContractionState::DeleteLine(int lineDoc) {
                visible->DeleteRange(lineDoc, 1);
                expanded->DeleteRange(lineDoc, 1);
                heights->DeleteRange(lineDoc, 1);
+               foldDisplayTexts->DeletePosition(lineDoc);
        }
 }
 
-void ContractionState::DeleteLines(int lineDoc, int lineCount) {
-       for (int l = 0; l < lineCount; l++) {
+void ContractionState::DeleteLines(Sci::Line lineDoc, Sci::Line lineCount) {
+       for (Sci::Line l = 0; l < lineCount; l++) {
                DeleteLine(lineDoc);
        }
        Check();
 }
 
-bool ContractionState::GetVisible(int lineDoc) const {
+bool ContractionState::GetVisible(Sci::Line lineDoc) const {
        if (OneToOne()) {
                return true;
        } else {
@@ -146,18 +158,18 @@ bool ContractionState::GetVisible(int lineDoc) const {
        }
 }
 
-bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible_) {
-       if (OneToOne() && visible_) {
+bool ContractionState::SetVisible(Sci::Line lineDocStart, Sci::Line lineDocEnd, bool isVisible) {
+       if (OneToOne() && isVisible) {
                return false;
        } else {
                EnsureData();
-               int delta = 0;
+               Sci::Line delta = 0;
                Check();
                if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) {
-                       for (int line = lineDocStart; line <= lineDocEnd; line++) {
-                               if (GetVisible(line) != visible_) {
-                                       int difference = visible_ ? heights->ValueAt(line) : 
-heights->ValueAt(line);
-                                       visible->SetValueAt(line, visible_ ? 1 : 0);
+                       for (Sci::Line line = lineDocStart; line <= lineDocEnd; line++) {
+                               if (GetVisible(line) != isVisible) {
+                                       int difference = isVisible ? heights->ValueAt(line) : 
-heights->ValueAt(line);
+                                       visible->SetValueAt(line, isVisible ? 1 : 0);
                                        displayLines->InsertText(line, difference);
                                        delta += difference;
                                }
@@ -178,7 +190,25 @@ bool ContractionState::HiddenLines() const {
        }
 }
 
-bool ContractionState::GetExpanded(int lineDoc) const {
+const char *ContractionState::GetFoldDisplayText(Sci::Line lineDoc) const {
+       Check();
+       return foldDisplayTexts->ValueAt(lineDoc).get();
+}
+
+bool ContractionState::SetFoldDisplayText(Sci::Line lineDoc, const char *text) {
+       EnsureData();
+       const char *foldText = foldDisplayTexts->ValueAt(lineDoc).get();
+       if (!foldText || !text || 0 != strcmp(text, foldText)) {
+               foldDisplayTexts->SetValueAt(lineDoc, UniqueStringCopy(text));
+               Check();
+               return true;
+       } else {
+               Check();
+               return false;
+       }
+}
+
+bool ContractionState::GetExpanded(Sci::Line lineDoc) const {
        if (OneToOne()) {
                return true;
        } else {
@@ -187,13 +217,13 @@ bool ContractionState::GetExpanded(int lineDoc) const {
        }
 }
 
-bool ContractionState::SetExpanded(int lineDoc, bool expanded_) {
-       if (OneToOne() && expanded_) {
+bool ContractionState::SetExpanded(Sci::Line lineDoc, bool isExpanded) {
+       if (OneToOne() && isExpanded) {
                return false;
        } else {
                EnsureData();
-               if (expanded_ != (expanded->ValueAt(lineDoc) == 1)) {
-                       expanded->SetValueAt(lineDoc, expanded_ ? 1 : 0);
+               if (isExpanded != (expanded->ValueAt(lineDoc) == 1)) {
+                       expanded->SetValueAt(lineDoc, isExpanded ? 1 : 0);
                        Check();
                        return true;
                } else {
@@ -203,7 +233,11 @@ bool ContractionState::SetExpanded(int lineDoc, bool expanded_) {
        }
 }
 
-int ContractionState::ContractedNext(int lineDocStart) const {
+bool ContractionState::GetFoldDisplayTextShown(Sci::Line lineDoc) const {
+       return !GetExpanded(lineDoc) && GetFoldDisplayText(lineDoc);
+}
+
+Sci::Line ContractionState::ContractedNext(Sci::Line lineDocStart) const {
        if (OneToOne()) {
                return -1;
        } else {
@@ -211,7 +245,7 @@ int ContractionState::ContractedNext(int lineDocStart) const {
                if (!expanded->ValueAt(lineDocStart)) {
                        return lineDocStart;
                } else {
-                       int lineDocNextChange = expanded->EndRun(lineDocStart);
+                       Sci::Line lineDocNextChange = expanded->EndRun(lineDocStart);
                        if (lineDocNextChange < LinesInDoc())
                                return lineDocNextChange;
                        else
@@ -220,7 +254,7 @@ int ContractionState::ContractedNext(int lineDocStart) const {
        }
 }
 
-int ContractionState::GetHeight(int lineDoc) const {
+int ContractionState::GetHeight(Sci::Line lineDoc) const {
        if (OneToOne()) {
                return 1;
        } else {
@@ -230,7 +264,7 @@ int ContractionState::GetHeight(int lineDoc) const {
 
 // Set the number of display lines needed for this line.
 // Return true if this is a change.
-bool ContractionState::SetHeight(int lineDoc, int height) {
+bool ContractionState::SetHeight(Sci::Line lineDoc, int height) {
        if (OneToOne() && (height == 1)) {
                return false;
        } else if (lineDoc < LinesInDoc()) {
@@ -252,7 +286,7 @@ bool ContractionState::SetHeight(int lineDoc, int height) {
 }
 
 void ContractionState::ShowAll() {
-       int lines = LinesInDoc();
+       Sci::Line lines = LinesInDoc();
        Clear();
        linesInDocument = lines;
 }
@@ -261,14 +295,14 @@ void ContractionState::ShowAll() {
 
 void ContractionState::Check() const {
 #ifdef CHECK_CORRECTNESS
-       for (int vline = 0; vline < LinesDisplayed(); vline++) {
-               const int lineDoc = DocFromDisplay(vline);
+       for (Sci::Line vline = 0; vline < LinesDisplayed(); vline++) {
+               const Sci::Line lineDoc = DocFromDisplay(vline);
                PLATFORM_ASSERT(GetVisible(lineDoc));
        }
-       for (int lineDoc = 0; lineDoc < LinesInDoc(); lineDoc++) {
-               const int displayThis = DisplayFromDoc(lineDoc);
-               const int displayNext = DisplayFromDoc(lineDoc + 1);
-               const int height = displayNext - displayThis;
+       for (Sci::Line lineDoc = 0; lineDoc < LinesInDoc(); lineDoc++) {
+               const Sci::Line displayThis = DisplayFromDoc(lineDoc);
+               const Sci::Line displayNext = DisplayFromDoc(lineDoc + 1);
+               const Sci::Line height = displayNext - displayThis;
                PLATFORM_ASSERT(height >= 0);
                if (GetVisible(lineDoc)) {
                        PLATFORM_ASSERT(GetHeight(lineDoc) == height);
diff --git a/plugins/scintilla/scintilla/src/ContractionState.h 
b/plugins/scintilla/scintilla/src/ContractionState.h
index 0309fc2..1070fb5 100644
--- a/plugins/scintilla/scintilla/src/ContractionState.h
+++ b/plugins/scintilla/scintilla/src/ContractionState.h
@@ -12,50 +12,62 @@
 namespace Scintilla {
 #endif
 
+template<class T>
+class SparseVector;
+
 /**
  */
 class ContractionState {
        // These contain 1 element for every document line.
-       RunStyles *visible;
-       RunStyles *expanded;
-       RunStyles *heights;
-       Partitioning *displayLines;
-       int linesInDocument;
+       std::unique_ptr<RunStyles> visible;
+       std::unique_ptr<RunStyles> expanded;
+       std::unique_ptr<RunStyles> heights;
+       std::unique_ptr<SparseVector<UniqueString>> foldDisplayTexts;
+       std::unique_ptr<Partitioning> displayLines;
+       Sci::Line linesInDocument;
 
        void EnsureData();
 
        bool OneToOne() const {
                // True when each document line is exactly one display line so need for
                // complex data structures.
-               return visible == 0;
+               return visible == nullptr;
        }
 
 public:
        ContractionState();
+       // Deleted so ContractionState objects can not be copied.
+       ContractionState(const ContractionState &) = delete;
+       void operator=(const ContractionState &) = delete;
        virtual ~ContractionState();
 
        void Clear();
 
-       int LinesInDoc() const;
-       int LinesDisplayed() const;
-       int DisplayFromDoc(int lineDoc) const;
-       int DocFromDisplay(int lineDisplay) const;
+       Sci::Line LinesInDoc() const;
+       Sci::Line LinesDisplayed() const;
+       Sci::Line DisplayFromDoc(Sci::Line lineDoc) const;
+       Sci::Line DisplayLastFromDoc(Sci::Line lineDoc) const;
+       Sci::Line DocFromDisplay(Sci::Line lineDisplay) const;
 
-       void InsertLine(int lineDoc);
-       void InsertLines(int lineDoc, int lineCount);
-       void DeleteLine(int lineDoc);
-       void DeleteLines(int lineDoc, int lineCount);
+       void InsertLine(Sci::Line lineDoc);
+       void InsertLines(Sci::Line lineDoc, Sci::Line lineCount);
+       void DeleteLine(Sci::Line lineDoc);
+       void DeleteLines(Sci::Line lineDoc, Sci::Line lineCount);
 
-       bool GetVisible(int lineDoc) const;
-       bool SetVisible(int lineDocStart, int lineDocEnd, bool visible);
+       bool GetVisible(Sci::Line lineDoc) const;
+       bool SetVisible(Sci::Line lineDocStart, Sci::Line lineDocEnd, bool isVisible);
        bool HiddenLines() const;
 
-       bool GetExpanded(int lineDoc) const;
-       bool SetExpanded(int lineDoc, bool expanded);
-       int ContractedNext(int lineDocStart) const;
+       const char *GetFoldDisplayText(Sci::Line lineDoc) const;
+       bool SetFoldDisplayText(Sci::Line lineDoc, const char *text);
+
+       bool GetExpanded(Sci::Line lineDoc) const;
+       bool SetExpanded(Sci::Line lineDoc, bool isExpanded);
+       bool GetFoldDisplayTextShown(Sci::Line lineDoc) const;
+       Sci::Line ContractedNext(Sci::Line lineDocStart) const;
 
-       int GetHeight(int lineDoc) const;
-       bool SetHeight(int lineDoc, int height);
+       int GetHeight(Sci::Line lineDoc) const;
+       bool SetHeight(Sci::Line lineDoc, int height);
 
        void ShowAll();
        void Check() const;
diff --git a/plugins/scintilla/scintilla/src/Decoration.cxx b/plugins/scintilla/scintilla/src/Decoration.cxx
index cda460a..f5f8283 100644
--- a/plugins/scintilla/scintilla/src/Decoration.cxx
+++ b/plugins/scintilla/scintilla/src/Decoration.cxx
@@ -4,16 +4,21 @@
 // Copyright 1998-2007 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stdarg.h>
-
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <cstdio>
+#include <cstdarg>
+
+#include <stdexcept>
+#include <vector>
 #include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
+#include "Position.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
@@ -23,7 +28,7 @@
 using namespace Scintilla;
 #endif
 
-Decoration::Decoration(int indicator_) : next(0), indicator(indicator_) {
+Decoration::Decoration(int indicator_) : indicator(indicator_) {
 }
 
 Decoration::~Decoration() {
@@ -33,74 +38,48 @@ bool Decoration::Empty() const {
        return (rs.Runs() == 1) && (rs.AllSameAs(0));
 }
 
-DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(0),
-       lengthDocument(0), root(0), clickNotified(false) {
+DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(nullptr),
+       lengthDocument(0), clickNotified(false) {
 }
 
 DecorationList::~DecorationList() {
-       Decoration *deco = root;
-       while (deco) {
-               Decoration *decoNext = deco->next;
-               delete deco;
-               deco = decoNext;
-       }
-       root = 0;
-       current = 0;
+       current = nullptr;
 }
 
 Decoration *DecorationList::DecorationFromIndicator(int indicator) {
-       for (Decoration *deco=root; deco; deco = deco->next) {
-               if (deco->indicator == indicator) {
-                       return deco;
+       for (const std::unique_ptr<Decoration> &deco : decorationList) {
+               if (deco->Indicator() == indicator) {
+                       return deco.get();
                }
        }
-       return 0;
+       return nullptr;
 }
 
 Decoration *DecorationList::Create(int indicator, int length) {
        currentIndicator = indicator;
-       Decoration *decoNew = new Decoration(indicator);
+       std::unique_ptr<Decoration> decoNew(new Decoration(indicator));
        decoNew->rs.InsertSpace(0, length);
 
-       Decoration *decoPrev = 0;
-       Decoration *deco = root;
+       std::vector<std::unique_ptr<Decoration>>::iterator it = std::lower_bound(
+               decorationList.begin(), decorationList.end(), decoNew, 
+               [](const std::unique_ptr<Decoration> &a, const std::unique_ptr<Decoration> &b) {
+               return a->Indicator() < b->Indicator();
+       });
+       std::vector<std::unique_ptr<Decoration>>::iterator itAdded = 
+               decorationList.insert(it, std::move(decoNew));
 
-       while (deco && (deco->indicator < indicator)) {
-               decoPrev = deco;
-               deco = deco->next;
-       }
-       if (decoPrev == 0) {
-               decoNew->next = root;
-               root = decoNew;
-       } else {
-               decoNew->next = deco;
-               decoPrev->next = decoNew;
-       }
-       return decoNew;
+       SetView();
+
+       return itAdded->get();
 }
 
 void DecorationList::Delete(int indicator) {
-       Decoration *decoToDelete = 0;
-       if (root) {
-               if (root->indicator == indicator) {
-                       decoToDelete = root;
-                       root = root->next;
-               } else {
-                       Decoration *deco=root;
-                       while (deco->next && !decoToDelete) {
-                               if (deco->next && deco->next->indicator == indicator) {
-                                       decoToDelete = deco->next;
-                                       deco->next = decoToDelete->next;
-                               } else {
-                                       deco = deco->next;
-                               }
-                       }
-               }
-       }
-       if (decoToDelete) {
-               delete decoToDelete;
-               current = 0;
-       }
+       decorationList.erase(std::remove_if(decorationList.begin(), decorationList.end(),
+               [=](const std::unique_ptr<Decoration> &deco) {
+               return deco->Indicator() == indicator;
+       }), decorationList.end());
+       current = nullptr;
+       SetView();
 }
 
 void DecorationList::SetCurrentIndicator(int indicator) {
@@ -120,7 +99,7 @@ bool DecorationList::FillRange(int &position, int value, int &fillLength) {
                        current = Create(currentIndicator, lengthDocument);
                }
        }
-       bool changed = current->rs.FillRange(position, value, fillLength);
+       const bool changed = current->rs.FillRange(position, value, fillLength);
        if (current->Empty()) {
                Delete(currentIndicator);
        }
@@ -130,7 +109,7 @@ bool DecorationList::FillRange(int &position, int value, int &fillLength) {
 void DecorationList::InsertSpace(int position, int insertLength) {
        const bool atEnd = position == lengthDocument;
        lengthDocument += insertLength;
-       for (Decoration *deco=root; deco; deco = deco->next) {
+       for (const std::unique_ptr<Decoration> &deco : decorationList) {
                deco->rs.InsertSpace(position, insertLength);
                if (atEnd) {
                        deco->rs.FillRange(position, 0, insertLength);
@@ -140,37 +119,58 @@ void DecorationList::InsertSpace(int position, int insertLength) {
 
 void DecorationList::DeleteRange(int position, int deleteLength) {
        lengthDocument -= deleteLength;
-       Decoration *deco;
-       for (deco=root; deco; deco = deco->next) {
+       for (const std::unique_ptr<Decoration> &deco : decorationList) {
                deco->rs.DeleteRange(position, deleteLength);
        }
        DeleteAnyEmpty();
+       if (decorationList.size() != decorationView.size()) {
+               // One or more empty decorations deleted so update view.
+               current = nullptr;
+               SetView();
+       }
+}
+
+void DecorationList::DeleteLexerDecorations() {
+       decorationList.erase(std::remove_if(decorationList.begin(), decorationList.end(),
+               [=](const std::unique_ptr<Decoration> &deco) {
+               return deco->Indicator() < INDIC_CONTAINER;
+       }), decorationList.end());
+       current = nullptr;
+       SetView();
 }
 
 void DecorationList::DeleteAnyEmpty() {
-       Decoration *deco = root;
-       while (deco) {
-               if ((lengthDocument == 0) || deco->Empty()) {
-                       Delete(deco->indicator);
-                       deco = root;
-               } else {
-                       deco = deco->next;
-               }
+       if (lengthDocument == 0) {
+               decorationList.clear();
+       } else {
+               decorationList.erase(std::remove_if(decorationList.begin(), decorationList.end(),
+                       [=](const std::unique_ptr<Decoration> &deco) {
+                       return deco->Empty();
+               }), decorationList.end());
+       }
+}
+
+void DecorationList::SetView() {
+       decorationView.clear();
+       for (const std::unique_ptr<Decoration> &deco : decorationList) {
+               decorationView.push_back(deco.get());
        }
 }
 
 int DecorationList::AllOnFor(int position) const {
        int mask = 0;
-       for (Decoration *deco=root; deco; deco = deco->next) {
+       for (const std::unique_ptr<Decoration> &deco : decorationList) {
                if (deco->rs.ValueAt(position)) {
-                       mask |= 1 << deco->indicator;
+                       if (deco->Indicator() < INDIC_IME) {
+                               mask |= 1 << deco->Indicator();
+                       }
                }
        }
        return mask;
 }
 
 int DecorationList::ValueAt(int indicator, int position) {
-       Decoration *deco = DecorationFromIndicator(indicator);
+       const Decoration *deco = DecorationFromIndicator(indicator);
        if (deco) {
                return deco->rs.ValueAt(position);
        }
@@ -178,7 +178,7 @@ int DecorationList::ValueAt(int indicator, int position) {
 }
 
 int DecorationList::Start(int indicator, int position) {
-       Decoration *deco = DecorationFromIndicator(indicator);
+       const Decoration *deco = DecorationFromIndicator(indicator);
        if (deco) {
                return deco->rs.StartRun(position);
        }
@@ -186,7 +186,7 @@ int DecorationList::Start(int indicator, int position) {
 }
 
 int DecorationList::End(int indicator, int position) {
-       Decoration *deco = DecorationFromIndicator(indicator);
+       const Decoration *deco = DecorationFromIndicator(indicator);
        if (deco) {
                return deco->rs.EndRun(position);
        }
diff --git a/plugins/scintilla/scintilla/src/Decoration.h b/plugins/scintilla/scintilla/src/Decoration.h
index 23d70c7..d096da3 100644
--- a/plugins/scintilla/scintilla/src/Decoration.h
+++ b/plugins/scintilla/scintilla/src/Decoration.h
@@ -12,33 +12,41 @@ namespace Scintilla {
 #endif
 
 class Decoration {
+       int indicator;
 public:
-       Decoration *next;
        RunStyles rs;
-       int indicator;
 
-       Decoration(int indicator_);
+       explicit Decoration(int indicator_);
        ~Decoration();
 
        bool Empty() const;
+       int Indicator() const {
+               return indicator;
+       }
 };
 
 class DecorationList {
        int currentIndicator;
        int currentValue;
-       Decoration *current;
+       Decoration *current;    // Cached so FillRange doesn't have to search for each call.
        int lengthDocument;
+       // Ordered by indicator
+       std::vector<std::unique_ptr<Decoration>> decorationList;
+       std::vector<const Decoration*> decorationView;  // Read-only view of decorationList
+       bool clickNotified;
+
        Decoration *DecorationFromIndicator(int indicator);
        Decoration *Create(int indicator, int length);
        void Delete(int indicator);
        void DeleteAnyEmpty();
+       void SetView();
 public:
-       Decoration *root;
-       bool clickNotified;
 
        DecorationList();
        ~DecorationList();
 
+       const std::vector<const Decoration*> &View() const { return decorationView; }
+
        void SetCurrentIndicator(int indicator);
        int GetCurrentIndicator() const { return currentIndicator; }
 
@@ -51,10 +59,19 @@ public:
        void InsertSpace(int position, int insertLength);
        void DeleteRange(int position, int deleteLength);
 
+       void DeleteLexerDecorations();
+
        int AllOnFor(int position) const;
        int ValueAt(int indicator, int position);
        int Start(int indicator, int position);
        int End(int indicator, int position);
+
+       bool ClickNotified() const {
+               return clickNotified;
+       }
+       void SetClickNotified(bool notified) {
+               clickNotified = notified;
+       }
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/Document.cxx b/plugins/scintilla/scintilla/src/Document.cxx
index 0637c8d..231bc11 100644
--- a/plugins/scintilla/scintilla/src/Document.cxx
+++ b/plugins/scintilla/scintilla/src/Document.cxx
@@ -5,60 +5,74 @@
 // Copyright 1998-2011 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <assert.h>
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cstdio>
 
+#include <stdexcept>
 #include <string>
 #include <vector>
+#include <forward_list>
 #include <algorithm>
+#include <memory>
+
+#define NOEXCEPT
+
+#ifndef NO_CXX11_REGEX
+#include <regex>
+#if defined(__GLIBCXX__)
+// If using the GNU implementation of <regex> then have 'noexcept' so can use
+// when defining regex iterators to keep Clang analyze happy.
+#undef NOEXCEPT
+#define NOEXCEPT noexcept
+#endif
+#endif
 
 #include "Platform.h"
 
 #include "ILexer.h"
 #include "Scintilla.h"
 
+#include "CharacterSet.h"
+#include "CharacterCategory.h"
+#include "Position.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
 #include "CellBuffer.h"
 #include "PerLine.h"
 #include "CharClassify.h"
-#include "CharacterSet.h"
 #include "Decoration.h"
 #include "CaseFolder.h"
 #include "Document.h"
 #include "RESearch.h"
 #include "UniConversion.h"
+#include "UnicodeFromUTF8.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
-static inline bool IsPunctuation(char ch) {
-       return isascii(ch) && ispunct(ch);
-}
-
-void LexInterface::Colourise(int start, int end) {
+void LexInterface::Colourise(Sci::Position start, Sci::Position end) {
        if (pdoc && instance && !performingStyle) {
                // Protect against reentrance, which may occur, for example, when
                // fold points are discovered while performing styling and the folding
                // code looks for child lines which may trigger styling.
                performingStyle = true;
 
-               int lengthDoc = pdoc->Length();
+               Sci::Position lengthDoc = pdoc->Length();
                if (end == -1)
                        end = lengthDoc;
-               int len = end - start;
+               Sci::Position len = end - start;
 
                PLATFORM_ASSERT(len >= 0);
                PLATFORM_ASSERT(start + len <= lengthDoc);
 
                int styleStart = 0;
                if (start > 0)
-                       styleStart = pdoc->StyleAt(start - 1) & pdoc->stylingBitsMask;
+                       styleStart = pdoc->StyleAt(start - 1);
 
                if (len > 0) {
                        instance->Lex(start, len, styleStart, pdoc);
@@ -71,7 +85,7 @@ void LexInterface::Colourise(int start, int end) {
 
 int LexInterface::LineEndTypesSupported() {
        if (instance) {
-               int interfaceVersion = instance->Version();
+               const int interfaceVersion = instance->Version();
                if (interfaceVersion >= lvSubStyles) {
                        ILexerWithSubStyles *ssinstance = static_cast<ILexerWithSubStyles *>(instance);
                        return ssinstance->LineEndTypesSupported();
@@ -82,7 +96,6 @@ int LexInterface::LineEndTypesSupported() {
 
 Document::Document() {
        refCount = 0;
-       pcf = NULL;
 #ifdef _WIN32
        eolMode = SC_EOL_CRLF;
 #else
@@ -90,60 +103,66 @@ Document::Document() {
 #endif
        dbcsCodePage = 0;
        lineEndBitSet = SC_LINE_END_TYPE_DEFAULT;
-       stylingBits = 5;
-       stylingBitsMask = 0x1F;
-       stylingMask = 0;
        endStyled = 0;
        styleClock = 0;
        enteredModification = 0;
        enteredStyling = 0;
        enteredReadOnlyCount = 0;
+       insertionSet = false;
        tabInChars = 8;
        indentInChars = 0;
        actualIndentInChars = 8;
        useTabs = true;
        tabIndents = true;
        backspaceUnindents = false;
+       durationStyleOneLine = 0.00001;
 
        matchesValid = false;
-       regex = 0;
 
        UTF8BytesOfLeadInitialise();
 
-       perLineData[ldMarkers] = new LineMarkers();
-       perLineData[ldLevels] = new LineLevels();
-       perLineData[ldState] = new LineState();
-       perLineData[ldMargin] = new LineAnnotation();
-       perLineData[ldAnnotation] = new LineAnnotation();
+       perLineData[ldMarkers].reset(new LineMarkers());
+       perLineData[ldLevels].reset(new LineLevels());
+       perLineData[ldState].reset(new LineState());
+       perLineData[ldMargin].reset(new LineAnnotation());
+       perLineData[ldAnnotation].reset(new LineAnnotation());
 
        cb.SetPerLine(this);
-
-       pli = 0;
 }
 
 Document::~Document() {
-       for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
-               it->watcher->NotifyDeleted(this, it->userData);
+       for (const WatcherWithUserData &watcher : watchers) {
+               watcher.watcher->NotifyDeleted(this, watcher.userData);
        }
-       for (int j=0; j<ldSize; j++) {
-               delete perLineData[j];
-               perLineData[j] = 0;
-       }
-       delete regex;
-       regex = 0;
-       delete pli;
-       pli = 0;
-       delete pcf;
-       pcf = 0;
 }
 
 void Document::Init() {
-       for (int j=0; j<ldSize; j++) {
-               if (perLineData[j])
-                       perLineData[j]->Init();
+       for (const std::unique_ptr<PerLine> &pl : perLineData) {
+               if (pl)
+                       pl->Init();
        }
 }
 
+LineMarkers *Document::Markers() const {
+       return static_cast<LineMarkers *>(perLineData[ldMarkers].get());
+}
+
+LineLevels *Document::Levels() const {
+       return static_cast<LineLevels *>(perLineData[ldLevels].get());
+}
+
+LineState *Document::States() const {
+       return static_cast<LineState *>(perLineData[ldState].get());
+}
+
+LineAnnotation *Document::Margins() const {
+       return static_cast<LineAnnotation *>(perLineData[ldMargin].get());
+}
+
+LineAnnotation *Document::Annotations() const {
+       return static_cast<LineAnnotation *>(perLineData[ldAnnotation].get());
+}
+
 int Document::LineEndTypesSupported() const {
        if ((SC_CP_UTF8 == dbcsCodePage) && pli)
                return pli->LineEndTypesSupported();
@@ -154,7 +173,7 @@ int Document::LineEndTypesSupported() const {
 bool Document::SetDBCSCodePage(int dbcsCodePage_) {
        if (dbcsCodePage != dbcsCodePage_) {
                dbcsCodePage = dbcsCodePage_;
-               SetCaseFolder(NULL);
+               SetCaseFolder(nullptr);
                cb.SetLineEndTypes(lineEndBitSet & LineEndTypesSupported());
                return true;
        } else {
@@ -178,17 +197,17 @@ bool Document::SetLineEndTypesAllowed(int lineEndBitSet_) {
        }
 }
 
-void Document::InsertLine(int line) {
-       for (int j=0; j<ldSize; j++) {
-               if (perLineData[j])
-                       perLineData[j]->InsertLine(line);
+void Document::InsertLine(Sci::Line line) {
+       for (const std::unique_ptr<PerLine> &pl : perLineData) {
+               if (pl)
+                       pl->InsertLine(line);
        }
 }
 
-void Document::RemoveLine(int line) {
-       for (int j=0; j<ldSize; j++) {
-               if (perLineData[j])
-                       perLineData[j]->RemoveLine(line);
+void Document::RemoveLine(Sci::Line line) {
+       for (const std::unique_ptr<PerLine> &pl : perLineData) {
+               if (pl)
+                       pl->RemoveLine(line);
        }
 }
 
@@ -200,7 +219,7 @@ int Document::AddRef() {
 // Decrease reference count and return its previous value.
 // Delete the document if reference count reaches zero.
 int SCI_METHOD Document::Release() {
-       int curRefCount = --refCount;
+       const int curRefCount = --refCount;
        if (curRefCount == 0)
                delete this;
        return curRefCount;
@@ -211,18 +230,78 @@ void Document::SetSavePoint() {
        NotifySavePoint(true);
 }
 
-int Document::GetMark(int line) {
-       return static_cast<LineMarkers *>(perLineData[ldMarkers])->MarkValue(line);
+void Document::TentativeUndo() {
+       if (!TentativeActive())
+               return;
+       CheckReadOnly();
+       if (enteredModification == 0) {
+               enteredModification++;
+               if (!cb.IsReadOnly()) {
+                       const bool startSavePoint = cb.IsSavePoint();
+                       bool multiLine = false;
+                       const int steps = cb.TentativeSteps();
+                       //Platform::DebugPrintf("Steps=%d\n", steps);
+                       for (int step = 0; step < steps; step++) {
+                               const Sci::Line prevLinesTotal = LinesTotal();
+                               const Action &action = cb.GetUndoStep();
+                               if (action.at == removeAction) {
+                                       NotifyModified(DocModification(
+                                                                       SC_MOD_BEFOREINSERT | 
SC_PERFORMED_UNDO, action));
+                               } else if (action.at == containerAction) {
+                                       DocModification dm(SC_MOD_CONTAINER | SC_PERFORMED_UNDO);
+                                       dm.token = action.position;
+                                       NotifyModified(dm);
+                               } else {
+                                       NotifyModified(DocModification(
+                                                                       SC_MOD_BEFOREDELETE | 
SC_PERFORMED_UNDO, action));
+                               }
+                               cb.PerformUndoStep();
+                               if (action.at != containerAction) {
+                                       ModifiedAt(action.position);
+                               }
+
+                               int modFlags = SC_PERFORMED_UNDO;
+                               // With undo, an insertion action becomes a deletion notification
+                               if (action.at == removeAction) {
+                                       modFlags |= SC_MOD_INSERTTEXT;
+                               } else if (action.at == insertAction) {
+                                       modFlags |= SC_MOD_DELETETEXT;
+                               }
+                               if (steps > 1)
+                                       modFlags |= SC_MULTISTEPUNDOREDO;
+                               const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
+                               if (linesAdded != 0)
+                                       multiLine = true;
+                               if (step == steps - 1) {
+                                       modFlags |= SC_LASTSTEPINUNDOREDO;
+                                       if (multiLine)
+                                               modFlags |= SC_MULTILINEUNDOREDO;
+                               }
+                               NotifyModified(DocModification(modFlags, action.position, action.lenData,
+                                                                                          linesAdded, 
action.data.get()));
+                       }
+
+                       bool endSavePoint = cb.IsSavePoint();
+                       if (startSavePoint != endSavePoint)
+                               NotifySavePoint(endSavePoint);
+
+                       cb.TentativeCommit();
+               }
+               enteredModification--;
+       }
 }
 
-int Document::MarkerNext(int lineStart, int mask) const {
-       return static_cast<LineMarkers *>(perLineData[ldMarkers])->MarkerNext(lineStart, mask);
+int Document::GetMark(Sci::Line line) const {
+       return Markers()->MarkValue(line);
 }
 
-int Document::AddMark(int line, int markerNum) {
+Sci::Line Document::MarkerNext(Sci::Line lineStart, int mask) const {
+       return Markers()->MarkerNext(lineStart, mask);
+}
+
+int Document::AddMark(Sci::Line line, int markerNum) {
        if (line >= 0 && line <= LinesTotal()) {
-               int prev = static_cast<LineMarkers *>(perLineData[ldMarkers])->
-                       AddMark(line, markerNum, LinesTotal());
+               const int prev = Markers()->AddMark(line, markerNum, LinesTotal());
                DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
                NotifyModified(mh);
                return prev;
@@ -231,27 +310,27 @@ int Document::AddMark(int line, int markerNum) {
        }
 }
 
-void Document::AddMarkSet(int line, int valueSet) {
+void Document::AddMarkSet(Sci::Line line, int valueSet) {
        if (line < 0 || line > LinesTotal()) {
                return;
        }
        unsigned int m = valueSet;
-       for (int i = 0; m; i++, m >>= 1)
+       for (int i = 0; m; i++, m >>= 1) {
                if (m & 1)
-                       static_cast<LineMarkers *>(perLineData[ldMarkers])->
-                               AddMark(line, i, LinesTotal());
+                       Markers()->AddMark(line, i, LinesTotal());
+       }
        DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
        NotifyModified(mh);
 }
 
-void Document::DeleteMark(int line, int markerNum) {
-       static_cast<LineMarkers *>(perLineData[ldMarkers])->DeleteMark(line, markerNum, false);
+void Document::DeleteMark(Sci::Line line, int markerNum) {
+       Markers()->DeleteMark(line, markerNum, false);
        DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
        NotifyModified(mh);
 }
 
 void Document::DeleteMarkFromHandle(int markerHandle) {
-       static_cast<LineMarkers *>(perLineData[ldMarkers])->DeleteMarkFromHandle(markerHandle);
+       Markers()->DeleteMarkFromHandle(markerHandle);
        DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
        mh.line = -1;
        NotifyModified(mh);
@@ -259,8 +338,8 @@ void Document::DeleteMarkFromHandle(int markerHandle) {
 
 void Document::DeleteAllMarks(int markerNum) {
        bool someChanges = false;
-       for (int line = 0; line < LinesTotal(); line++) {
-               if (static_cast<LineMarkers *>(perLineData[ldMarkers])->DeleteMark(line, markerNum, true))
+       for (Sci::Line line = 0; line < LinesTotal(); line++) {
+               if (Markers()->DeleteMark(line, markerNum, true))
                        someChanges = true;
        }
        if (someChanges) {
@@ -270,21 +349,25 @@ void Document::DeleteAllMarks(int markerNum) {
        }
 }
 
-int Document::LineFromHandle(int markerHandle) {
-       return static_cast<LineMarkers *>(perLineData[ldMarkers])->LineFromHandle(markerHandle);
+Sci::Line Document::LineFromHandle(int markerHandle) const {
+       return Markers()->LineFromHandle(markerHandle);
 }
 
-int SCI_METHOD Document::LineStart(int line) const {
+Sci_Position SCI_METHOD Document::LineStart(Sci_Position line) const {
        return cb.LineStart(line);
 }
 
-int SCI_METHOD Document::LineEnd(int line) const {
-       if (line == LinesTotal() - 1) {
+bool Document::IsLineStartPosition(Sci::Position position) const {
+       return LineStart(LineFromPosition(position)) == position;
+}
+
+Sci_Position SCI_METHOD Document::LineEnd(Sci_Position line) const {
+       if (line >= LinesTotal() - 1) {
                return LineStart(line + 1);
        } else {
-               int position = LineStart(line + 1);
+               Sci::Position position = LineStart(line + 1);
                if (SC_CP_UTF8 == dbcsCodePage) {
-                       unsigned char bytes[] = {
+                       const unsigned char bytes[] = {
                                static_cast<unsigned char>(cb.CharAt(position-3)),
                                static_cast<unsigned char>(cb.CharAt(position-2)),
                                static_cast<unsigned char>(cb.CharAt(position-1)),
@@ -307,32 +390,32 @@ int SCI_METHOD Document::LineEnd(int line) const {
 
 void SCI_METHOD Document::SetErrorStatus(int status) {
        // Tell the watchers an error has occurred.
-       for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
-               it->watcher->NotifyErrorOccurred(this, it->userData, status);
+       for (const WatcherWithUserData &watcher : watchers) {
+               watcher.watcher->NotifyErrorOccurred(this, watcher.userData, status);
        }
 }
 
-int SCI_METHOD Document::LineFromPosition(int pos) const {
+Sci_Position SCI_METHOD Document::LineFromPosition(Sci_Position pos) const {
        return cb.LineFromPosition(pos);
 }
 
-int Document::LineEndPosition(int position) const {
+Sci::Position Document::LineEndPosition(Sci::Position position) const {
        return LineEnd(LineFromPosition(position));
 }
 
-bool Document::IsLineEndPosition(int position) const {
+bool Document::IsLineEndPosition(Sci::Position position) const {
        return LineEnd(LineFromPosition(position)) == position;
 }
 
-bool Document::IsPositionInLineEnd(int position) const {
+bool Document::IsPositionInLineEnd(Sci::Position position) const {
        return position >= LineEnd(LineFromPosition(position));
 }
 
-int Document::VCHomePosition(int position) const {
-       int line = LineFromPosition(position);
-       int startPosition = LineStart(line);
-       int endLine = LineEnd(line);
-       int startText = startPosition;
+Sci::Position Document::VCHomePosition(Sci::Position position) const {
+       Sci::Line line = LineFromPosition(position);
+       Sci::Position startPosition = LineStart(line);
+       const Sci::Position endLine = LineEnd(line);
+       Sci::Position startText = startPosition;
        while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t'))
                startText++;
        if (position == startText)
@@ -341,8 +424,8 @@ int Document::VCHomePosition(int position) const {
                return startText;
 }
 
-int SCI_METHOD Document::SetLevel(int line, int level) {
-       int prev = static_cast<LineLevels *>(perLineData[ldLevels])->SetLevel(line, level, LinesTotal());
+int SCI_METHOD Document::SetLevel(Sci_Position line, int level) {
+       const int prev = Levels()->SetLevel(line, level, LinesTotal());
        if (prev != level) {
                DocModification mh(SC_MOD_CHANGEFOLD | SC_MOD_CHANGEMARKER,
                                   LineStart(line), 0, 0, 0, line);
@@ -353,27 +436,27 @@ int SCI_METHOD Document::SetLevel(int line, int level) {
        return prev;
 }
 
-int SCI_METHOD Document::GetLevel(int line) const {
-       return static_cast<LineLevels *>(perLineData[ldLevels])->GetLevel(line);
+int SCI_METHOD Document::GetLevel(Sci_Position line) const {
+       return Levels()->GetLevel(line);
 }
 
 void Document::ClearLevels() {
-       static_cast<LineLevels *>(perLineData[ldLevels])->ClearLevels();
+       Levels()->ClearLevels();
 }
 
 static bool IsSubordinate(int levelStart, int levelTry) {
        if (levelTry & SC_FOLDLEVELWHITEFLAG)
                return true;
        else
-               return (levelStart & SC_FOLDLEVELNUMBERMASK) < (levelTry & SC_FOLDLEVELNUMBERMASK);
+               return LevelNumber(levelStart) < LevelNumber(levelTry);
 }
 
-int Document::GetLastChild(int lineParent, int level, int lastLine) {
+Sci::Line Document::GetLastChild(Sci::Line lineParent, int level, Sci::Line lastLine) {
        if (level == -1)
-               level = GetLevel(lineParent) & SC_FOLDLEVELNUMBERMASK;
-       int maxLine = LinesTotal();
-       int lookLastLine = (lastLine != -1) ? Platform::Minimum(LinesTotal() - 1, lastLine) : -1;
-       int lineMaxSubord = lineParent;
+               level = LevelNumber(GetLevel(lineParent));
+       const Sci::Line maxLine = LinesTotal();
+       const Sci::Line lookLastLine = (lastLine != -1) ? std::min(LinesTotal() - 1, lastLine) : -1;
+       Sci::Line lineMaxSubord = lineParent;
        while (lineMaxSubord < maxLine - 1) {
                EnsureStyledTo(LineStart(lineMaxSubord + 2));
                if (!IsSubordinate(level, GetLevel(lineMaxSubord + 1)))
@@ -383,7 +466,7 @@ int Document::GetLastChild(int lineParent, int level, int lastLine) {
                lineMaxSubord++;
        }
        if (lineMaxSubord > lineParent) {
-               if (level > (GetLevel(lineMaxSubord + 1) & SC_FOLDLEVELNUMBERMASK)) {
+               if (level > LevelNumber(GetLevel(lineMaxSubord + 1))) {
                        // Have chewed up some whitespace that belongs to a parent so seek back
                        if (GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG) {
                                lineMaxSubord--;
@@ -393,48 +476,48 @@ int Document::GetLastChild(int lineParent, int level, int lastLine) {
        return lineMaxSubord;
 }
 
-int Document::GetFoldParent(int line) const {
-       int level = GetLevel(line) & SC_FOLDLEVELNUMBERMASK;
-       int lineLook = line - 1;
+Sci::Line Document::GetFoldParent(Sci::Line line) const {
+       const int level = LevelNumber(GetLevel(line));
+       Sci::Line lineLook = line - 1;
        while ((lineLook > 0) && (
                    (!(GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG)) ||
-                   ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) >= level))
+                   (LevelNumber(GetLevel(lineLook)) >= level))
              ) {
                lineLook--;
        }
        if ((GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG) &&
-               ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) < level)) {
+               (LevelNumber(GetLevel(lineLook)) < level)) {
                return lineLook;
        } else {
                return -1;
        }
 }
 
-void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, int line, int lastLine) {
-       int level = GetLevel(line);
-       int lookLastLine = Platform::Maximum(line, lastLine) + 1;
+void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, Sci::Line line, Sci::Line 
lastLine) {
+       const int level = GetLevel(line);
+       Sci::Line lookLastLine = std::max(line, lastLine) + 1;
 
-       int lookLine = line;
+       Sci::Line lookLine = line;
        int lookLineLevel = level;
-       int lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
+       int lookLineLevelNum = LevelNumber(lookLineLevel);
        while ((lookLine > 0) && ((lookLineLevel & SC_FOLDLEVELWHITEFLAG) ||
-               ((lookLineLevel & SC_FOLDLEVELHEADERFLAG) && (lookLineLevelNum >= (GetLevel(lookLine + 1) & 
SC_FOLDLEVELNUMBERMASK))))) {
+               ((lookLineLevel & SC_FOLDLEVELHEADERFLAG) && (lookLineLevelNum >= 
LevelNumber(GetLevel(lookLine + 1)))))) {
                lookLineLevel = GetLevel(--lookLine);
-               lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
+               lookLineLevelNum = LevelNumber(lookLineLevel);
        }
 
-       int beginFoldBlock = (lookLineLevel & SC_FOLDLEVELHEADERFLAG) ? lookLine : GetFoldParent(lookLine);
+       Sci::Line beginFoldBlock = (lookLineLevel & SC_FOLDLEVELHEADERFLAG) ? lookLine : 
GetFoldParent(lookLine);
        if (beginFoldBlock == -1) {
                highlightDelimiter.Clear();
                return;
        }
 
-       int endFoldBlock = GetLastChild(beginFoldBlock, -1, lookLastLine);
-       int firstChangeableLineBefore = -1;
+       Sci::Line endFoldBlock = GetLastChild(beginFoldBlock, -1, lookLastLine);
+       Sci::Line firstChangeableLineBefore = -1;
        if (endFoldBlock < line) {
                lookLine = beginFoldBlock - 1;
                lookLineLevel = GetLevel(lookLine);
-               lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
+               lookLineLevelNum = LevelNumber(lookLineLevel);
                while ((lookLine >= 0) && (lookLineLevelNum >= SC_FOLDLEVELBASE)) {
                        if (lookLineLevel & SC_FOLDLEVELHEADERFLAG) {
                                if (GetLastChild(lookLine, -1, lookLastLine) == line) {
@@ -443,17 +526,17 @@ void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, in
                                        firstChangeableLineBefore = line - 1;
                                }
                        }
-                       if ((lookLine > 0) && (lookLineLevelNum == SC_FOLDLEVELBASE) && ((GetLevel(lookLine - 
1) & SC_FOLDLEVELNUMBERMASK) > lookLineLevelNum))
+                       if ((lookLine > 0) && (lookLineLevelNum == SC_FOLDLEVELBASE) && 
(LevelNumber(GetLevel(lookLine - 1)) > lookLineLevelNum))
                                break;
                        lookLineLevel = GetLevel(--lookLine);
-                       lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
+                       lookLineLevelNum = LevelNumber(lookLineLevel);
                }
        }
        if (firstChangeableLineBefore == -1) {
-               for (lookLine = line - 1, lookLineLevel = GetLevel(lookLine), lookLineLevelNum = 
lookLineLevel & SC_FOLDLEVELNUMBERMASK;
+               for (lookLine = line - 1, lookLineLevel = GetLevel(lookLine), lookLineLevelNum = 
LevelNumber(lookLineLevel);
                        lookLine >= beginFoldBlock;
-                       lookLineLevel = GetLevel(--lookLine), lookLineLevelNum = lookLineLevel & 
SC_FOLDLEVELNUMBERMASK) {
-                       if ((lookLineLevel & SC_FOLDLEVELWHITEFLAG) || (lookLineLevelNum > (level & 
SC_FOLDLEVELNUMBERMASK))) {
+                       lookLineLevel = GetLevel(--lookLine), lookLineLevelNum = LevelNumber(lookLineLevel)) {
+                       if ((lookLineLevel & SC_FOLDLEVELWHITEFLAG) || (lookLineLevelNum > 
LevelNumber(level))) {
                                firstChangeableLineBefore = lookLine;
                                break;
                        }
@@ -462,11 +545,11 @@ void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, in
        if (firstChangeableLineBefore == -1)
                firstChangeableLineBefore = beginFoldBlock - 1;
 
-       int firstChangeableLineAfter = -1;
-       for (lookLine = line + 1, lookLineLevel = GetLevel(lookLine), lookLineLevelNum = lookLineLevel & 
SC_FOLDLEVELNUMBERMASK;
+       Sci::Line firstChangeableLineAfter = -1;
+       for (lookLine = line + 1, lookLineLevel = GetLevel(lookLine), lookLineLevelNum = 
LevelNumber(lookLineLevel);
                lookLine <= endFoldBlock;
-               lookLineLevel = GetLevel(++lookLine), lookLineLevelNum = lookLineLevel & 
SC_FOLDLEVELNUMBERMASK) {
-               if ((lookLineLevel & SC_FOLDLEVELHEADERFLAG) && (lookLineLevelNum < (GetLevel(lookLine + 1) & 
SC_FOLDLEVELNUMBERMASK))) {
+               lookLineLevel = GetLevel(++lookLine), lookLineLevelNum = LevelNumber(lookLineLevel)) {
+               if ((lookLineLevel & SC_FOLDLEVELHEADERFLAG) && (lookLineLevelNum < 
LevelNumber(GetLevel(lookLine + 1)))) {
                        firstChangeableLineAfter = lookLine;
                        break;
                }
@@ -480,11 +563,11 @@ void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, in
        highlightDelimiter.firstChangeableLineAfter = firstChangeableLineAfter;
 }
 
-int Document::ClampPositionIntoDocument(int pos) const {
+Sci::Position Document::ClampPositionIntoDocument(Sci::Position pos) const {
        return Platform::Clamp(pos, 0, Length());
 }
 
-bool Document::IsCrLf(int pos) const {
+bool Document::IsCrLf(Sci::Position pos) const {
        if (pos < 0)
                return false;
        if (pos >= (Length() - 1))
@@ -492,7 +575,7 @@ bool Document::IsCrLf(int pos) const {
        return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n');
 }
 
-int Document::LenChar(int pos) {
+int Document::LenChar(Sci::Position pos) {
        if (pos < 0) {
                return 1;
        } else if (IsCrLf(pos)) {
@@ -500,7 +583,7 @@ int Document::LenChar(int pos) {
        } else if (SC_CP_UTF8 == dbcsCodePage) {
                const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(pos));
                const int widthCharBytes = UTF8BytesOfLead[leadByte];
-               int lengthDoc = Length();
+               Sci::Position lengthDoc = Length();
                if ((pos + widthCharBytes) > lengthDoc)
                        return lengthDoc - pos;
                else
@@ -512,8 +595,8 @@ int Document::LenChar(int pos) {
        }
 }
 
-bool Document::InGoodUTF8(int pos, int &start, int &end) const {
-       int trail = pos;
+bool Document::InGoodUTF8(Sci::Position pos, Sci::Position &start, Sci::Position &end) const {
+       Sci::Position trail = pos;
        while ((trail>0) && (pos-trail < UTF8MaxBytes) && UTF8IsTrailByte(static_cast<unsigned 
char>(cb.CharAt(trail-1))))
                trail--;
        start = (trail > 0) ? trail-1 : trail;
@@ -523,15 +606,15 @@ bool Document::InGoodUTF8(int pos, int &start, int &end) const {
        if (widthCharBytes == 1) {
                return false;
        } else {
-               int trailBytes = widthCharBytes - 1;
-               int len = pos - start;
+               const int trailBytes = widthCharBytes - 1;
+               const Sci::Position len = pos - start;
                if (len > trailBytes)
                        // pos too far from lead
                        return false;
                char charBytes[UTF8MaxBytes] = {static_cast<char>(leadByte),0,0,0};
                for (int b=1; b<widthCharBytes && ((start+b) < Length()); b++)
-                       charBytes[b] = cb.CharAt(static_cast<int>(start+b));
-               int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(charBytes), 
widthCharBytes);
+                       charBytes[b] = cb.CharAt(static_cast<Sci::Position>(start+b));
+               const int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(charBytes), 
widthCharBytes);
                if (utf8status & UTF8MaskInvalid)
                        return false;
                end = start + widthCharBytes;
@@ -544,7 +627,7 @@ bool Document::InGoodUTF8(int pos, int &start, int &end) const {
 // When lines are terminated with \r\n pairs which should be treated as one character.
 // When displaying DBCS text such as Japanese.
 // If moving, move the position in the indicated direction.
-int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) {
+Sci::Position Document::MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool checkLineEnd) 
const {
        //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
        // If out of range, just return minimum/maximum value.
        if (pos <= 0)
@@ -562,11 +645,11 @@ int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) {
 
        if (dbcsCodePage) {
                if (SC_CP_UTF8 == dbcsCodePage) {
-                       unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
+                       const unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
                        // If ch is not a trail byte then pos is valid intercharacter position
                        if (UTF8IsTrailByte(ch)) {
-                               int startUTF = pos;
-                               int endUTF = pos;
+                               Sci::Position startUTF = pos;
+                               Sci::Position endUTF = pos;
                                if (InGoodUTF8(pos, startUTF, endUTF)) {
                                        // ch is a trail byte within a UTF-8 character
                                        if (moveDir > 0)
@@ -579,12 +662,12 @@ int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) {
                } else {
                        // Anchor DBCS calculations at start of line because start of line can
                        // not be a DBCS trail byte.
-                       int posStartLine = LineStart(LineFromPosition(pos));
+                       const Sci::Position posStartLine = LineStart(LineFromPosition(pos));
                        if (pos == posStartLine)
                                return pos;
 
                        // Step back until a non-lead-byte is found.
-                       int posCheck = pos;
+                       Sci::Position posCheck = pos;
                        while ((posCheck > posStartLine) && IsDBCSLeadByte(cb.CharAt(posCheck-1)))
                                posCheck--;
 
@@ -611,7 +694,7 @@ int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) {
 // NextPosition moves between valid positions - it can not handle a position in the middle of a
 // multi-byte character. It is used to iterate through text more efficiently than MovePositionOutsideChar.
 // A \r\n pair is treated as two characters.
-int Document::NextPosition(int pos, int moveDir) const {
+Sci::Position Document::NextPosition(Sci::Position pos, int moveDir) const {
        // If out of range, just return minimum/maximum value.
        int increment = (moveDir > 0) ? 1 : -1;
        if (pos + increment <= 0)
@@ -641,12 +724,12 @@ int Document::NextPosition(int pos, int moveDir) const {
                        } else {
                                // Examine byte before position
                                pos--;
-                               unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
+                               const unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
                                // If ch is not a trail byte then pos is valid intercharacter position
                                if (UTF8IsTrailByte(ch)) {
                                        // If ch is a trail byte in a valid UTF-8 character then return start 
of character
-                                       int startUTF = pos;
-                                       int endUTF = pos;
+                                       Sci::Position startUTF = pos;
+                                       Sci::Position endUTF = pos;
                                        if (InGoodUTF8(pos, startUTF, endUTF)) {
                                                pos = startUTF;
                                        }
@@ -662,7 +745,7 @@ int Document::NextPosition(int pos, int moveDir) const {
                        } else {
                                // Anchor DBCS calculations at start of line because start of line can
                                // not be a DBCS trail byte.
-                               int posStartLine = LineStart(LineFromPosition(pos));
+                               const Sci::Position posStartLine = LineStart(LineFromPosition(pos));
                                // See http://msdn.microsoft.com/en-us/library/cc194792%28v=MSDN.10%29.aspx
                                // http://msdn.microsoft.com/en-us/library/cc194790.aspx
                                if ((pos - 1) <= posStartLine) {
@@ -672,7 +755,7 @@ int Document::NextPosition(int pos, int moveDir) const {
                                        return pos - 2;
                                } else {
                                        // Otherwise, step back until a non-lead-byte is found.
-                                       int posTemp = pos - 1;
+                                       Sci::Position posTemp = pos - 1;
                                        while (posStartLine <= --posTemp && 
IsDBCSLeadByte(cb.CharAt(posTemp)))
                                                ;
                                        // Now posTemp+1 must point to the beginning of a character,
@@ -689,9 +772,9 @@ int Document::NextPosition(int pos, int moveDir) const {
        return pos;
 }
 
-bool Document::NextCharacter(int &pos, int moveDir) const {
+bool Document::NextCharacter(Sci::Position &pos, int moveDir) const {
        // Returns true if pos changed
-       int posNext = NextPosition(pos, moveDir);
+       Sci::Position posNext = NextPosition(pos, moveDir);
        if (posNext == pos) {
                return false;
        } else {
@@ -700,28 +783,107 @@ bool Document::NextCharacter(int &pos, int moveDir) const {
        }
 }
 
-static inline int UnicodeFromBytes(const unsigned char *us) {
-       if (us[0] < 0xC2) {
-               return us[0];
-       } else if (us[0] < 0xE0) {
-               return ((us[0] & 0x1F) << 6) + (us[1] & 0x3F);
-       } else if (us[0] < 0xF0) {
-               return ((us[0] & 0xF) << 12) + ((us[1] & 0x3F) << 6) + (us[2] & 0x3F);
-       } else if (us[0] < 0xF5) {
-               return ((us[0] & 0x7) << 18) + ((us[1] & 0x3F) << 12) + ((us[2] & 0x3F) << 6) + (us[3] & 
0x3F);
+Document::CharacterExtracted Document::CharacterAfter(Sci::Position position) const {
+       if (position >= Length()) {
+               return CharacterExtracted(unicodeReplacementChar, 0);
+       }
+       const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(position));
+       if (!dbcsCodePage || UTF8IsAscii(leadByte)) {
+               // Common case: ASCII character
+               return CharacterExtracted(leadByte, 1);
+       }
+       if (SC_CP_UTF8 == dbcsCodePage) {
+               const int widthCharBytes = UTF8BytesOfLead[leadByte];
+               unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
+               for (int b = 1; b<widthCharBytes; b++)
+                       charBytes[b] = static_cast<unsigned char>(cb.CharAt(position + b));
+               int utf8status = UTF8Classify(charBytes, widthCharBytes);
+               if (utf8status & UTF8MaskInvalid) {
+                       // Treat as invalid and use up just one byte
+                       return CharacterExtracted(unicodeReplacementChar, 1);
+               } else {
+                       return CharacterExtracted(UnicodeFromUTF8(charBytes), utf8status & UTF8MaskWidth);
+               }
+       } else {
+               if (IsDBCSLeadByte(leadByte) && ((position + 1) < Length())) {
+                       return CharacterExtracted::DBCS(leadByte, static_cast<unsigned 
char>(cb.CharAt(position + 1)));
+               } else {
+                       return CharacterExtracted(leadByte, 1);
+               }
+       }
+}
+
+Document::CharacterExtracted Document::CharacterBefore(Sci::Position position) const {
+       if (position <= 0) {
+               return CharacterExtracted(unicodeReplacementChar, 0);
+       }
+       const unsigned char previousByte = static_cast<unsigned char>(cb.CharAt(position - 1));
+       if (0 == dbcsCodePage) {
+               return CharacterExtracted(previousByte, 1);
+       }
+       if (SC_CP_UTF8 == dbcsCodePage) {
+               if (UTF8IsAscii(previousByte)) {
+                       return CharacterExtracted(previousByte, 1);
+               }
+               position--;
+               // If previousByte is not a trail byte then its invalid
+               if (UTF8IsTrailByte(previousByte)) {
+                       // If previousByte is a trail byte in a valid UTF-8 character then find start of 
character
+                       Sci::Position startUTF = position;
+                       Sci::Position endUTF = position;
+                       if (InGoodUTF8(position, startUTF, endUTF)) {
+                               const int widthCharBytes = endUTF - startUTF;
+                               unsigned char charBytes[UTF8MaxBytes] = { 0, 0, 0, 0 };
+                               for (int b = 0; b<widthCharBytes; b++)
+                                       charBytes[b] = static_cast<unsigned char>(cb.CharAt(startUTF + b));
+                               int utf8status = UTF8Classify(charBytes, widthCharBytes);
+                               if (utf8status & UTF8MaskInvalid) {
+                                       // Treat as invalid and use up just one byte
+                                       return CharacterExtracted(unicodeReplacementChar, 1);
+                               } else {
+                                       return CharacterExtracted(UnicodeFromUTF8(charBytes), utf8status & 
UTF8MaskWidth);
+                               }
+                       }
+                       // Else invalid UTF-8 so return position of isolated trail byte
+               }
+               return CharacterExtracted(unicodeReplacementChar, 1);
+       } else {
+               // Moving backwards in DBCS is complex so use NextPosition
+               const Sci::Position posStartCharacter = NextPosition(position, -1);
+               return CharacterAfter(posStartCharacter);
        }
-       return us[0];
 }
 
 // Return -1  on out-of-bounds
-int SCI_METHOD Document::GetRelativePosition(int positionStart, int characterOffset) const {
-       int pos = positionStart;
+Sci_Position SCI_METHOD Document::GetRelativePosition(Sci_Position positionStart, Sci_Position 
characterOffset) const {
+       Sci::Position pos = positionStart;
+       if (dbcsCodePage) {
+               const int increment = (characterOffset > 0) ? 1 : -1;
+               while (characterOffset != 0) {
+                       const Sci::Position posNext = NextPosition(pos, increment);
+                       if (posNext == pos)
+                               return INVALID_POSITION;
+                       pos = posNext;
+                       characterOffset -= increment;
+               }
+       } else {
+               pos = positionStart + characterOffset;
+               if ((pos < 0) || (pos > Length()))
+                       return INVALID_POSITION;
+       }
+       return pos;
+}
+
+Sci::Position Document::GetRelativePositionUTF16(Sci::Position positionStart, Sci::Position characterOffset) 
const {
+       Sci::Position pos = positionStart;
        if (dbcsCodePage) {
                const int increment = (characterOffset > 0) ? 1 : -1;
                while (characterOffset != 0) {
-                       const int posNext = NextPosition(pos, increment);
+                       const Sci::Position posNext = NextPosition(pos, increment);
                        if (posNext == pos)
                                return INVALID_POSITION;
+                       if (abs(pos-posNext) > 3)       // 4 byte character = 2*UTF16.
+                               characterOffset -= increment;
                        pos = posNext;
                        characterOffset -= increment;
                }
@@ -733,7 +895,7 @@ int SCI_METHOD Document::GetRelativePosition(int positionStart, int characterOff
        return pos;
 }
 
-int SCI_METHOD Document::GetCharacterAndWidth(int position, int *pWidth) const {
+int SCI_METHOD Document::GetCharacterAndWidth(Sci_Position position, Sci_Position *pWidth) const {
        int character;
        int bytesInCharacter = 1;
        if (dbcsCodePage) {
@@ -747,13 +909,13 @@ int SCI_METHOD Document::GetCharacterAndWidth(int position, int *pWidth) const {
                                unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
                                for (int b=1; b<widthCharBytes; b++)
                                        charBytes[b] = static_cast<unsigned char>(cb.CharAt(position+b));
-                               int utf8status = UTF8Classify(charBytes, widthCharBytes);
+                               const int utf8status = UTF8Classify(charBytes, widthCharBytes);
                                if (utf8status & UTF8MaskInvalid) {
                                        // Report as singleton surrogate values which are invalid Unicode
                                        character =  0xDC80 + leadByte;
                                } else {
                                        bytesInCharacter = utf8status & UTF8MaskWidth;
-                                       character = UnicodeFromBytes(charBytes);
+                                       character = UnicodeFromUTF8(charBytes);
                                }
                        }
                } else {
@@ -779,7 +941,7 @@ int SCI_METHOD Document::CodePage() const {
 
 bool SCI_METHOD Document::IsDBCSLeadByte(char ch) const {
        // Byte ranges found in Wikipedia articles with relevant search strings in each case
-       unsigned char uch = static_cast<unsigned char>(ch);
+       const unsigned char uch = static_cast<unsigned char>(ch);
        switch (dbcsCodePage) {
                case 932:
                        // Shift_jis
@@ -825,9 +987,9 @@ int Document::SafeSegment(const char *text, int length, int lengthSegment) const
                return length;
        int lastSpaceBreak = -1;
        int lastPunctuationBreak = -1;
-       int lastEncodingAllowedBreak = -1;
+       int lastEncodingAllowedBreak = 0;
        for (int j=0; j < lengthSegment;) {
-               unsigned char ch = static_cast<unsigned char>(text[j]);
+               const unsigned char ch = static_cast<unsigned char>(text[j]);
                if (j > 0) {
                        if (IsSpaceOrTab(text[j - 1]) && !IsSpaceOrTab(text[j])) {
                                lastSpaceBreak = j;
@@ -854,7 +1016,16 @@ int Document::SafeSegment(const char *text, int length, int lengthSegment) const
        return lastEncodingAllowedBreak;
 }
 
-void Document::ModifiedAt(int pos) {
+EncodingFamily Document::CodePageFamily() const {
+       if (SC_CP_UTF8 == dbcsCodePage)
+               return efUnicode;
+       else if (dbcsCodePage)
+               return efDBCS;
+       else
+               return efEightBit;
+}
+
+void Document::ModifiedAt(Sci::Position pos) {
        if (endStyled > pos)
                endStyled = pos;
 }
@@ -870,7 +1041,9 @@ void Document::CheckReadOnly() {
 // Document only modified by gateways DeleteChars, InsertString, Undo, Redo, and SetStyleAt.
 // SetStyleAt does not change the persistent state of a document
 
-bool Document::DeleteChars(int pos, int len) {
+bool Document::DeleteChars(Sci::Position pos, Sci::Position len) {
+       if (pos < 0)
+               return false;
        if (len <= 0)
                return false;
        if ((pos + len) > Length())
@@ -886,7 +1059,7 @@ bool Document::DeleteChars(int pos, int len) {
                                SC_MOD_BEFOREDELETE | SC_PERFORMED_USER,
                                pos, len,
                                0, 0));
-                       int prevLinesTotal = LinesTotal();
+                       Sci::Line prevLinesTotal = LinesTotal();
                        bool startSavePoint = cb.IsSavePoint();
                        bool startSequence = false;
                        const char *text = cb.DeleteChars(pos, len, startSequence);
@@ -910,43 +1083,62 @@ bool Document::DeleteChars(int pos, int len) {
 /**
  * Insert a string with a length.
  */
-bool Document::InsertString(int position, const char *s, int insertLength) {
+Sci::Position Document::InsertString(Sci::Position position, const char *s, Sci::Position insertLength) {
        if (insertLength <= 0) {
-               return false;
+               return 0;
+       }
+       CheckReadOnly();        // Application may change read only state here
+       if (cb.IsReadOnly()) {
+               return 0;
        }
-       CheckReadOnly();
        if (enteredModification != 0) {
-               return false;
-       } else {
-               enteredModification++;
-               if (!cb.IsReadOnly()) {
-                       NotifyModified(
-                           DocModification(
-                               SC_MOD_BEFOREINSERT | SC_PERFORMED_USER,
-                               position, insertLength,
-                               0, s));
-                       int prevLinesTotal = LinesTotal();
-                       bool startSavePoint = cb.IsSavePoint();
-                       bool startSequence = false;
-                       const char *text = cb.InsertString(position, s, insertLength, startSequence);
-                       if (startSavePoint && cb.IsCollectingUndo())
-                               NotifySavePoint(!startSavePoint);
-                       ModifiedAt(position);
-                       NotifyModified(
-                           DocModification(
-                               SC_MOD_INSERTTEXT | SC_PERFORMED_USER | (startSequence?SC_STARTACTION:0),
-                               position, insertLength,
-                               LinesTotal() - prevLinesTotal, text));
-               }
-               enteredModification--;
+               return 0;
        }
-       return !cb.IsReadOnly();
-}
-
-int SCI_METHOD Document::AddData(char *data, int length) {
+       enteredModification++;
+       insertionSet = false;
+       insertion.clear();
+       NotifyModified(
+               DocModification(
+                       SC_MOD_INSERTCHECK,
+                       position, insertLength,
+                       0, s));
+       if (insertionSet) {
+               s = insertion.c_str();
+               insertLength = static_cast<int>(insertion.length());
+       }
+       NotifyModified(
+               DocModification(
+                       SC_MOD_BEFOREINSERT | SC_PERFORMED_USER,
+                       position, insertLength,
+                       0, s));
+       Sci::Line prevLinesTotal = LinesTotal();
+       bool startSavePoint = cb.IsSavePoint();
+       bool startSequence = false;
+       const char *text = cb.InsertString(position, s, insertLength, startSequence);
+       if (startSavePoint && cb.IsCollectingUndo())
+               NotifySavePoint(!startSavePoint);
+       ModifiedAt(position);
+       NotifyModified(
+               DocModification(
+                       SC_MOD_INSERTTEXT | SC_PERFORMED_USER | (startSequence?SC_STARTACTION:0),
+                       position, insertLength,
+                       LinesTotal() - prevLinesTotal, text));
+       if (insertionSet) {     // Free memory as could be large
+               std::string().swap(insertion);
+       }
+       enteredModification--;
+       return insertLength;
+}
+
+void Document::ChangeInsertion(const char *s, Sci::Position length) {
+       insertionSet = true;
+       insertion.assign(s, length);
+}
+
+int SCI_METHOD Document::AddData(char *data, Sci_Position length) {
        try {
-               int position = Length();
-               InsertString(position,data, length);
+               Sci::Position position = Length();
+               InsertString(position, data, length);
        } catch (std::bad_alloc &) {
                return SC_STATUS_BADALLOC;
        } catch (...) {
@@ -959,22 +1151,22 @@ void * SCI_METHOD Document::ConvertToDocument() {
        return this;
 }
 
-int Document::Undo() {
-       int newPos = -1;
+Sci::Position Document::Undo() {
+       Sci::Position newPos = -1;
        CheckReadOnly();
        if ((enteredModification == 0) && (cb.IsCollectingUndo())) {
                enteredModification++;
                if (!cb.IsReadOnly()) {
-                       bool startSavePoint = cb.IsSavePoint();
+                       const bool startSavePoint = cb.IsSavePoint();
                        bool multiLine = false;
-                       int steps = cb.StartUndo();
+                       const int steps = cb.StartUndo();
                        //Platform::DebugPrintf("Steps=%d\n", steps);
-                       int coalescedRemovePos = -1;
-                       int coalescedRemoveLen = 0;
-                       int prevRemoveActionPos = -1;
-                       int prevRemoveActionLen = 0;
+                       Sci::Position coalescedRemovePos = -1;
+                       Sci::Position coalescedRemoveLen = 0;
+                       Sci::Position prevRemoveActionPos = -1;
+                       Sci::Position prevRemoveActionLen = 0;
                        for (int step = 0; step < steps; step++) {
-                               const int prevLinesTotal = LinesTotal();
+                               const Sci::Line prevLinesTotal = LinesTotal();
                                const Action &action = cb.GetUndoStep();
                                if (action.at == removeAction) {
                                        NotifyModified(DocModification(
@@ -1023,7 +1215,7 @@ int Document::Undo() {
                                }
                                if (steps > 1)
                                        modFlags |= SC_MULTISTEPUNDOREDO;
-                               const int linesAdded = LinesTotal() - prevLinesTotal;
+                               const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
                                if (linesAdded != 0)
                                        multiLine = true;
                                if (step == steps - 1) {
@@ -1032,7 +1224,7 @@ int Document::Undo() {
                                                modFlags |= SC_MULTILINEUNDOREDO;
                                }
                                NotifyModified(DocModification(modFlags, action.position, action.lenData,
-                                                                                          linesAdded, 
action.data));
+                                                                                          linesAdded, 
action.data.get()));
                        }
 
                        bool endSavePoint = cb.IsSavePoint();
@@ -1044,17 +1236,17 @@ int Document::Undo() {
        return newPos;
 }
 
-int Document::Redo() {
-       int newPos = -1;
+Sci::Position Document::Redo() {
+       Sci::Position newPos = -1;
        CheckReadOnly();
        if ((enteredModification == 0) && (cb.IsCollectingUndo())) {
                enteredModification++;
                if (!cb.IsReadOnly()) {
-                       bool startSavePoint = cb.IsSavePoint();
+                       const bool startSavePoint = cb.IsSavePoint();
                        bool multiLine = false;
-                       int steps = cb.StartRedo();
+                       const int steps = cb.StartRedo();
                        for (int step = 0; step < steps; step++) {
-                               const int prevLinesTotal = LinesTotal();
+                               const Sci::Line prevLinesTotal = LinesTotal();
                                const Action &action = cb.GetRedoStep();
                                if (action.at == insertAction) {
                                        NotifyModified(DocModification(
@@ -1082,7 +1274,7 @@ int Document::Redo() {
                                }
                                if (steps > 1)
                                        modFlags |= SC_MULTISTEPUNDOREDO;
-                               const int linesAdded = LinesTotal() - prevLinesTotal;
+                               const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
                                if (linesAdded != 0)
                                        multiLine = true;
                                if (step == steps - 1) {
@@ -1092,7 +1284,7 @@ int Document::Redo() {
                                }
                                NotifyModified(
                                        DocModification(modFlags, action.position, action.lenData,
-                                                                       linesAdded, action.data));
+                                                                       linesAdded, action.data.get()));
                        }
 
                        bool endSavePoint = cb.IsSavePoint();
@@ -1104,44 +1296,28 @@ int Document::Redo() {
        return newPos;
 }
 
-/**
- * Insert a single character.
- */
-bool Document::InsertChar(int pos, char ch) {
-       char chs[1];
-       chs[0] = ch;
-       return InsertString(pos, chs, 1);
-}
-
-/**
- * Insert a null terminated string.
- */
-bool Document::InsertCString(int position, const char *s) {
-       return InsertString(position, s, static_cast<int>(s ? strlen(s) : 0));
-}
-
-void Document::DelChar(int pos) {
+void Document::DelChar(Sci::Position pos) {
        DeleteChars(pos, LenChar(pos));
 }
 
-void Document::DelCharBack(int pos) {
+void Document::DelCharBack(Sci::Position pos) {
        if (pos <= 0) {
                return;
        } else if (IsCrLf(pos - 2)) {
                DeleteChars(pos - 2, 2);
        } else if (dbcsCodePage) {
-               int startChar = NextPosition(pos, -1);
+               Sci::Position startChar = NextPosition(pos, -1);
                DeleteChars(startChar, pos - startChar);
        } else {
                DeleteChars(pos - 1, 1);
        }
 }
 
-static int NextTab(int pos, int tabSize) {
+static Sci::Position NextTab(Sci::Position pos, Sci::Position tabSize) {
        return ((pos / tabSize) + 1) * tabSize;
 }
 
-static std::string CreateIndentation(int indent, int tabSize, bool insertSpaces) {
+static std::string CreateIndentation(Sci::Position indent, int tabSize, bool insertSpaces) {
        std::string indentation;
        if (!insertSpaces) {
                while (indent >= tabSize) {
@@ -1156,13 +1332,13 @@ static std::string CreateIndentation(int indent, int tabSize, bool insertSpaces)
        return indentation;
 }
 
-int SCI_METHOD Document::GetLineIndentation(int line) {
+int SCI_METHOD Document::GetLineIndentation(Sci_Position line) {
        int indent = 0;
        if ((line >= 0) && (line < LinesTotal())) {
-               int lineStart = LineStart(line);
-               int length = Length();
-               for (int i = lineStart; i < length; i++) {
-                       char ch = cb.CharAt(i);
+               const Sci::Position lineStart = LineStart(line);
+               const Sci::Position length = Length();
+               for (Sci::Position i = lineStart; i < length; i++) {
+                       const char ch = cb.CharAt(i);
                        if (ch == ' ')
                                indent++;
                        else if (ch == '\t')
@@ -1174,37 +1350,40 @@ int SCI_METHOD Document::GetLineIndentation(int line) {
        return indent;
 }
 
-void Document::SetLineIndentation(int line, int indent) {
-       int indentOfLine = GetLineIndentation(line);
+Sci::Position Document::SetLineIndentation(Sci::Line line, Sci::Position indent) {
+       const int indentOfLine = GetLineIndentation(line);
        if (indent < 0)
                indent = 0;
        if (indent != indentOfLine) {
                std::string linebuf = CreateIndentation(indent, tabInChars, !useTabs);
-               int thisLineStart = LineStart(line);
-               int indentPos = GetLineIndentPosition(line);
+               Sci::Position thisLineStart = LineStart(line);
+               Sci::Position indentPos = GetLineIndentPosition(line);
                UndoGroup ug(this);
                DeleteChars(thisLineStart, indentPos - thisLineStart);
-               InsertCString(thisLineStart, linebuf.c_str());
+               return thisLineStart + InsertString(thisLineStart, linebuf.c_str(),
+                       static_cast<Sci::Position>(linebuf.length()));
+       } else {
+               return GetLineIndentPosition(line);
        }
 }
 
-int Document::GetLineIndentPosition(int line) const {
+Sci::Position Document::GetLineIndentPosition(Sci::Line line) const {
        if (line < 0)
                return 0;
-       int pos = LineStart(line);
-       int length = Length();
+       Sci::Position pos = LineStart(line);
+       const Sci::Position length = Length();
        while ((pos < length) && IsSpaceOrTab(cb.CharAt(pos))) {
                pos++;
        }
        return pos;
 }
 
-int Document::GetColumn(int pos) {
-       int column = 0;
-       int line = LineFromPosition(pos);
+Sci::Position Document::GetColumn(Sci::Position pos) {
+       Sci::Position column = 0;
+       Sci::Line line = LineFromPosition(pos);
        if ((line >= 0) && (line < LinesTotal())) {
-               for (int i = LineStart(line); i < pos;) {
-                       char ch = cb.CharAt(i);
+               for (Sci::Position i = LineStart(line); i < pos;) {
+                       const char ch = cb.CharAt(i);
                        if (ch == '\t') {
                                column = NextTab(column, tabInChars);
                                i++;
@@ -1223,26 +1402,39 @@ int Document::GetColumn(int pos) {
        return column;
 }
 
-int Document::CountCharacters(int startPos, int endPos) {
+Sci::Position Document::CountCharacters(Sci::Position startPos, Sci::Position endPos) const {
        startPos = MovePositionOutsideChar(startPos, 1, false);
        endPos = MovePositionOutsideChar(endPos, -1, false);
-       int count = 0;
-       int i = startPos;
+       Sci::Position count = 0;
+       Sci::Position i = startPos;
        while (i < endPos) {
                count++;
-               if (IsCrLf(i))
-                       i++;
                i = NextPosition(i, 1);
        }
        return count;
 }
 
-int Document::FindColumn(int line, int column) {
-       int position = LineStart(line);
+Sci::Position Document::CountUTF16(Sci::Position startPos, Sci::Position endPos) const {
+       startPos = MovePositionOutsideChar(startPos, 1, false);
+       endPos = MovePositionOutsideChar(endPos, -1, false);
+       Sci::Position count = 0;
+       Sci::Position i = startPos;
+       while (i < endPos) {
+               count++;
+               const Sci::Position next = NextPosition(i, 1);
+               if ((next - i) > 3)
+                       count++;
+               i = next;
+       }
+       return count;
+}
+
+Sci::Position Document::FindColumn(Sci::Line line, Sci::Position column) {
+       Sci::Position position = LineStart(line);
        if ((line >= 0) && (line < LinesTotal())) {
-               int columnCurrent = 0;
+               Sci::Position columnCurrent = 0;
                while ((columnCurrent < column) && (position < Length())) {
-                       char ch = cb.CharAt(position);
+                       const char ch = cb.CharAt(position);
                        if (ch == '\t') {
                                columnCurrent = NextTab(columnCurrent, tabInChars);
                                if (columnCurrent > column)
@@ -1261,10 +1453,10 @@ int Document::FindColumn(int line, int column) {
        return position;
 }
 
-void Document::Indent(bool forwards, int lineBottom, int lineTop) {
+void Document::Indent(bool forwards, Sci::Line lineBottom, Sci::Line lineTop) {
        // Dedent - suck white space off the front of the line to dedent by equivalent of a tab
-       for (int line = lineBottom; line >= lineTop; line--) {
-               int indentOfLine = GetLineIndentation(line);
+       for (Sci::Line line = lineBottom; line >= lineTop; line--) {
+               Sci::Position indentOfLine = GetLineIndentation(line);
                if (forwards) {
                        if (LineStart(line) < LineEnd(line)) {
                                SetLineIndentation(line, indentOfLine + IndentSize());
@@ -1302,7 +1494,7 @@ std::string Document::TransformLineEnds(const char *s, size_t len, int eolModeWa
 void Document::ConvertLineEnds(int eolModeSet) {
        UndoGroup ug(this);
 
-       for (int pos = 0; pos < Length(); pos++) {
+       for (Sci::Position pos = 0; pos < Length(); pos++) {
                if (cb.CharAt(pos) == '\r') {
                        if (cb.CharAt(pos + 1) == '\n') {
                                // CRLF
@@ -1316,30 +1508,30 @@ void Document::ConvertLineEnds(int eolModeSet) {
                        } else {
                                // CR
                                if (eolModeSet == SC_EOL_CRLF) {
-                                       InsertString(pos + 1, "\n", 1); // Insert LF
-                                       pos++;
+                                       pos += InsertString(pos + 1, "\n", 1); // Insert LF
                                } else if (eolModeSet == SC_EOL_LF) {
-                                       InsertString(pos, "\n", 1); // Insert LF
-                                       DeleteChars(pos + 1, 1); // Delete CR
+                                       pos += InsertString(pos, "\n", 1); // Insert LF
+                                       DeleteChars(pos, 1); // Delete CR
+                                       pos--;
                                }
                        }
                } else if (cb.CharAt(pos) == '\n') {
                        // LF
                        if (eolModeSet == SC_EOL_CRLF) {
-                               InsertString(pos, "\r", 1); // Insert CR
-                               pos++;
+                               pos += InsertString(pos, "\r", 1); // Insert CR
                        } else if (eolModeSet == SC_EOL_CR) {
-                               InsertString(pos, "\r", 1); // Insert CR
-                               DeleteChars(pos + 1, 1); // Delete LF
+                               pos += InsertString(pos, "\r", 1); // Insert CR
+                               DeleteChars(pos, 1); // Delete LF
+                               pos--;
                        }
                }
        }
 
 }
 
-bool Document::IsWhiteLine(int line) const {
-       int currentChar = LineStart(line);
-       int endLine = LineEnd(line);
+bool Document::IsWhiteLine(Sci::Line line) const {
+       Sci::Position currentChar = LineStart(line);
+       const Sci::Position endLine = LineEnd(line);
        while (currentChar < endLine) {
                if (cb.CharAt(currentChar) != ' ' && cb.CharAt(currentChar) != '\t') {
                        return false;
@@ -1349,8 +1541,8 @@ bool Document::IsWhiteLine(int line) const {
        return true;
 }
 
-int Document::ParaUp(int pos) const {
-       int line = LineFromPosition(pos);
+Sci::Position Document::ParaUp(Sci::Position pos) const {
+       Sci::Line line = LineFromPosition(pos);
        line--;
        while (line >= 0 && IsWhiteLine(line)) { // skip empty lines
                line--;
@@ -1362,8 +1554,8 @@ int Document::ParaUp(int pos) const {
        return LineStart(line);
 }
 
-int Document::ParaDown(int pos) const {
-       int line = LineFromPosition(pos);
+Sci::Position Document::ParaDown(Sci::Position pos) const {
+       Sci::Line line = LineFromPosition(pos);
        while (line < LinesTotal() && !IsWhiteLine(line)) { // skip non-empty lines
                line++;
        }
@@ -1376,28 +1568,104 @@ int Document::ParaDown(int pos) const {
                return LineEnd(line-1);
 }
 
-CharClassify::cc Document::WordCharClass(unsigned char ch) const {
-       if ((SC_CP_UTF8 == dbcsCodePage) && (!UTF8IsAscii(ch)))
-               return CharClassify::ccWord;
-       return charClass.GetClass(ch);
+bool Document::IsASCIIWordByte(unsigned char ch) const {
+       if (IsASCII(ch)) {
+               return charClass.GetClass(ch) == CharClassify::ccWord;
+       } else {
+               return false;
+       }
+}
+
+CharClassify::cc Document::WordCharacterClass(unsigned int ch) const {
+       if (dbcsCodePage && (!UTF8IsAscii(ch))) {
+               if (SC_CP_UTF8 == dbcsCodePage) {
+                       // Use hard coded Unicode class
+                       const CharacterCategory cc = CategoriseCharacter(ch);
+                       switch (cc) {
+
+                               // Separator, Line/Paragraph
+                       case ccZl:
+                       case ccZp:
+                               return CharClassify::ccNewLine;
+
+                               // Separator, Space
+                       case ccZs:
+                               // Other
+                       case ccCc:
+                       case ccCf:
+                       case ccCs:
+                       case ccCo:
+                       case ccCn:
+                               return CharClassify::ccSpace;
+
+                               // Letter
+                       case ccLu:
+                       case ccLl:
+                       case ccLt:
+                       case ccLm:
+                       case ccLo:
+                               // Number
+                       case ccNd:
+                       case ccNl:
+                       case ccNo:
+                               // Mark - includes combining diacritics
+                       case ccMn:
+                       case ccMc:
+                       case ccMe:
+                               return CharClassify::ccWord;
+
+                               // Punctuation
+                       case ccPc:
+                       case ccPd:
+                       case ccPs:
+                       case ccPe:
+                       case ccPi:
+                       case ccPf:
+                       case ccPo:
+                               // Symbol
+                       case ccSm:
+                       case ccSc:
+                       case ccSk:
+                       case ccSo:
+                               return CharClassify::ccPunctuation;
+
+                       }
+               } else {
+                       // Asian DBCS
+                       return CharClassify::ccWord;
+               }
+       }
+       return charClass.GetClass(static_cast<unsigned char>(ch));
 }
 
 /**
  * Used by commmands that want to select whole words.
  * Finds the start of word at pos when delta < 0 or the end of the word when delta >= 0.
  */
-int Document::ExtendWordSelect(int pos, int delta, bool onlyWordCharacters) {
+Sci::Position Document::ExtendWordSelect(Sci::Position pos, int delta, bool onlyWordCharacters) const {
        CharClassify::cc ccStart = CharClassify::ccWord;
        if (delta < 0) {
-               if (!onlyWordCharacters)
-                       ccStart = WordCharClass(cb.CharAt(pos-1));
-               while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart))
-                       pos--;
+               if (!onlyWordCharacters) {
+                       const CharacterExtracted ce = CharacterBefore(pos);
+                       ccStart = WordCharacterClass(ce.character);
+               }
+               while (pos > 0) {
+                       const CharacterExtracted ce = CharacterBefore(pos);
+                       if (WordCharacterClass(ce.character) != ccStart)
+                               break;
+                       pos -= ce.widthBytes;
+               }
        } else {
-               if (!onlyWordCharacters && pos < Length())
-                       ccStart = WordCharClass(cb.CharAt(pos));
-               while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart))
-                       pos++;
+               if (!onlyWordCharacters && pos < Length()) {
+                       const CharacterExtracted ce = CharacterAfter(pos);
+                       ccStart = WordCharacterClass(ce.character);
+               }
+               while (pos < Length()) {
+                       const CharacterExtracted ce = CharacterAfter(pos);
+                       if (WordCharacterClass(ce.character) != ccStart)
+                               break;
+                       pos += ce.widthBytes;
+               }
        }
        return MovePositionOutsideChar(pos, delta, true);
 }
@@ -1409,22 +1677,39 @@ int Document::ExtendWordSelect(int pos, int delta, bool onlyWordCharacters) {
  * additional movement to transit white space.
  * Used by cursor movement by word commands.
  */
-int Document::NextWordStart(int pos, int delta) {
+Sci::Position Document::NextWordStart(Sci::Position pos, int delta) const {
        if (delta < 0) {
-               while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace))
-                       pos--;
+               while (pos > 0) {
+                       const CharacterExtracted ce = CharacterBefore(pos);
+                       if (WordCharacterClass(ce.character) != CharClassify::ccSpace)
+                               break;
+                       pos -= ce.widthBytes;
+               }
                if (pos > 0) {
-                       CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1));
-                       while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart)) {
-                               pos--;
+                       CharacterExtracted ce = CharacterBefore(pos);
+                       const CharClassify::cc ccStart = WordCharacterClass(ce.character);
+                       while (pos > 0) {
+                               ce = CharacterBefore(pos);
+                               if (WordCharacterClass(ce.character) != ccStart)
+                                       break;
+                               pos -= ce.widthBytes;
                        }
                }
        } else {
-               CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos));
-               while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart))
-                       pos++;
-               while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace))
-                       pos++;
+               CharacterExtracted ce = CharacterAfter(pos);
+               const CharClassify::cc ccStart = WordCharacterClass(ce.character);
+               while (pos < Length()) {
+                       ce = CharacterAfter(pos);
+                       if (WordCharacterClass(ce.character) != ccStart)
+                               break;
+                       pos += ce.widthBytes;
+               }
+               while (pos < Length()) {
+                       ce = CharacterAfter(pos);
+                       if (WordCharacterClass(ce.character) != CharClassify::ccSpace)
+                               break;
+                       pos += ce.widthBytes;
+               }
        }
        return pos;
 }
@@ -1436,27 +1721,41 @@ int Document::NextWordStart(int pos, int delta) {
  * additional movement to transit white space.
  * Used by cursor movement by word commands.
  */
-int Document::NextWordEnd(int pos, int delta) {
+Sci::Position Document::NextWordEnd(Sci::Position pos, int delta) const {
        if (delta < 0) {
                if (pos > 0) {
-                       CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1));
+                       CharacterExtracted ce = CharacterBefore(pos);
+                       const CharClassify::cc ccStart = WordCharacterClass(ce.character);
                        if (ccStart != CharClassify::ccSpace) {
-                               while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == ccStart) {
-                                       pos--;
+                               while (pos > 0) {
+                                       ce = CharacterBefore(pos);
+                                       if (WordCharacterClass(ce.character) != ccStart)
+                                               break;
+                                       pos -= ce.widthBytes;
                                }
                        }
-                       while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace) {
-                               pos--;
+                       while (pos > 0) {
+                               ce = CharacterBefore(pos);
+                               if (WordCharacterClass(ce.character) != CharClassify::ccSpace)
+                                       break;
+                               pos -= ce.widthBytes;
                        }
                }
        } else {
-               while (pos < Length() && WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace) {
-                       pos++;
+               while (pos < Length()) {
+                       CharacterExtracted ce = CharacterAfter(pos);
+                       if (WordCharacterClass(ce.character) != CharClassify::ccSpace)
+                               break;
+                       pos += ce.widthBytes;
                }
                if (pos < Length()) {
-                       CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos));
-                       while (pos < Length() && WordCharClass(cb.CharAt(pos)) == ccStart) {
-                               pos++;
+                       CharacterExtracted ce = CharacterAfter(pos);
+                       const CharClassify::cc ccStart = WordCharacterClass(ce.character);
+                       while (pos < Length()) {
+                               ce = CharacterAfter(pos);
+                               if (WordCharacterClass(ce.character) != ccStart)
+                                       break;
+                               pos += ce.widthBytes;
                        }
                }
        }
@@ -1467,11 +1766,16 @@ int Document::NextWordEnd(int pos, int delta) {
  * Check that the character at the given position is a word or punctuation character and that
  * the previous character is of a different character class.
  */
-bool Document::IsWordStartAt(int pos) const {
+bool Document::IsWordStartAt(Sci::Position pos) const {
+       if (pos >= Length())
+               return false;
        if (pos > 0) {
-               CharClassify::cc ccPos = WordCharClass(CharAt(pos));
+               const CharacterExtracted cePos = CharacterAfter(pos);
+               const CharClassify::cc ccPos = WordCharacterClass(cePos.character);
+               const CharacterExtracted cePrev = CharacterBefore(pos);
+               const CharClassify::cc ccPrev = WordCharacterClass(cePrev.character);
                return (ccPos == CharClassify::ccWord || ccPos == CharClassify::ccPunctuation) &&
-                       (ccPos != WordCharClass(CharAt(pos - 1)));
+                       (ccPos != ccPrev);
        }
        return true;
 }
@@ -1480,11 +1784,16 @@ bool Document::IsWordStartAt(int pos) const {
  * Check that the character at the given position is a word or punctuation character and that
  * the next character is of a different character class.
  */
-bool Document::IsWordEndAt(int pos) const {
+bool Document::IsWordEndAt(Sci::Position pos) const {
+       if (pos <= 0)
+               return false;
        if (pos < Length()) {
-               CharClassify::cc ccPrev = WordCharClass(CharAt(pos-1));
+               const CharacterExtracted cePos = CharacterAfter(pos);
+               const CharClassify::cc ccPos = WordCharacterClass(cePos.character);
+               const CharacterExtracted cePrev = CharacterBefore(pos);
+               const CharClassify::cc ccPrev = WordCharacterClass(cePrev.character);
                return (ccPrev == CharClassify::ccWord || ccPrev == CharClassify::ccPunctuation) &&
-                       (ccPrev != WordCharClass(CharAt(pos)));
+                       (ccPrev != ccPos);
        }
        return true;
 }
@@ -1493,23 +1802,41 @@ bool Document::IsWordEndAt(int pos) const {
  * Check that the given range is has transitions between character classes at both
  * ends and where the characters on the inside are word or punctuation characters.
  */
-bool Document::IsWordAt(int start, int end) const {
-       return IsWordStartAt(start) && IsWordEndAt(end);
+bool Document::IsWordAt(Sci::Position start, Sci::Position end) const {
+       return (start < end) && IsWordStartAt(start) && IsWordEndAt(end);
 }
 
-bool Document::MatchesWordOptions(bool word, bool wordStart, int pos, int length) const {
+bool Document::MatchesWordOptions(bool word, bool wordStart, Sci::Position pos, Sci::Position length) const {
        return (!word && !wordStart) ||
                        (word && IsWordAt(pos, pos + length)) ||
                        (wordStart && IsWordStartAt(pos));
 }
 
-bool Document::HasCaseFolder(void) const {
-       return pcf != 0;
+bool Document::HasCaseFolder() const {
+       return pcf != nullptr;
 }
 
 void Document::SetCaseFolder(CaseFolder *pcf_) {
-       delete pcf;
-       pcf = pcf_;
+       pcf.reset(pcf_);
+}
+
+Document::CharacterExtracted Document::ExtractCharacter(Sci::Position position) const {
+       const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(position));
+       if (UTF8IsAscii(leadByte)) {
+               // Common case: ASCII character
+               return CharacterExtracted(leadByte, 1);
+       }
+       const int widthCharBytes = UTF8BytesOfLead[leadByte];
+       unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
+       for (int b=1; b<widthCharBytes; b++)
+               charBytes[b] = static_cast<unsigned char>(cb.CharAt(position + b));
+       int utf8status = UTF8Classify(charBytes, widthCharBytes);
+       if (utf8status & UTF8MaskInvalid) {
+               // Treat as invalid and use up just one byte
+               return CharacterExtracted(unicodeReplacementChar, 1);
+       } else {
+               return CharacterExtracted(UnicodeFromUTF8(charBytes), utf8status & UTF8MaskWidth);
+       }
 }
 
 /**
@@ -1517,14 +1844,17 @@ void Document::SetCaseFolder(CaseFolder *pcf_) {
  * searches (just pass minPos > maxPos to do a backward search)
  * Has not been tested with backwards DBCS searches yet.
  */
-long Document::FindText(int minPos, int maxPos, const char *search,
-                        bool caseSensitive, bool word, bool wordStart, bool regExp, int flags,
-                        int *length) {
+long Document::FindText(Sci::Position minPos, Sci::Position maxPos, const char *search,
+                        int flags, Sci::Position *length) {
        if (*length <= 0)
                return minPos;
+       const bool caseSensitive = (flags & SCFIND_MATCHCASE) != 0;
+       const bool word = (flags & SCFIND_WHOLEWORD) != 0;
+       const bool wordStart = (flags & SCFIND_WORDSTART) != 0;
+       const bool regExp = (flags & SCFIND_REGEXP) != 0;
        if (regExp) {
                if (!regex)
-                       regex = CreateRegexSearch(&charClass);
+                       regex = std::unique_ptr<RegexSearchBase>(CreateRegexSearch(&charClass));
                return regex->FindText(this, minPos, maxPos, search, caseSensitive, word, wordStart, flags, 
length);
        } else {
 
@@ -1532,21 +1862,21 @@ long Document::FindText(int minPos, int maxPos, const char *search,
                const int increment = forward ? 1 : -1;
 
                // Range endpoints should not be inside DBCS characters, but just in case, move them.
-               const int startPos = MovePositionOutsideChar(minPos, increment, false);
-               const int endPos = MovePositionOutsideChar(maxPos, increment, false);
+               const Sci::Position startPos = MovePositionOutsideChar(minPos, increment, false);
+               const Sci::Position endPos = MovePositionOutsideChar(maxPos, increment, false);
 
                // Compute actual search ranges needed
-               const int lengthFind = *length;
+               const Sci::Position lengthFind = *length;
 
                //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind);
-               const int limitPos = Platform::Maximum(startPos, endPos);
-               int pos = startPos;
+               const Sci::Position limitPos = std::max(startPos, endPos);
+               Sci::Position pos = startPos;
                if (!forward) {
                        // Back all of a character
                        pos = NextPosition(pos, increment);
                }
                if (caseSensitive) {
-                       const int endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
+                       const Sci::Position endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : 
endPos;
                        const char charStartSearch =  search[0];
                        while (forward ? (pos < endSearch) : (pos >= endSearch)) {
                                if (CharAt(pos) == charStartSearch) {
@@ -1563,14 +1893,14 @@ long Document::FindText(int minPos, int maxPos, const char *search,
                        }
                } else if (SC_CP_UTF8 == dbcsCodePage) {
                        const size_t maxFoldingExpansion = 4;
-                       std::vector<char> searchThing(lengthFind * UTF8MaxBytes * maxFoldingExpansion + 1);
+                       std::vector<char> searchThing((lengthFind+1) * UTF8MaxBytes * maxFoldingExpansion + 
1);
                        const int lenSearch = static_cast<int>(
                                pcf->Fold(&searchThing[0], searchThing.size(), search, lengthFind));
                        char bytes[UTF8MaxBytes + 1];
                        char folded[UTF8MaxBytes * maxFoldingExpansion + 1];
                        while (forward ? (pos < endPos) : (pos >= endPos)) {
                                int widthFirstCharacter = 0;
-                               int posIndexDocument = pos;
+                               Sci::Position posIndexDocument = pos;
                                int indexSearch = 0;
                                bool characterMatches = true;
                                for (;;) {
@@ -1590,6 +1920,8 @@ long Document::FindText(int minPos, int maxPos, const char *search,
                                                break;
                                        const int lenFlat = static_cast<int>(pcf->Fold(folded, 
sizeof(folded), bytes, widthChar));
                                        folded[lenFlat] = 0;
+                                       // memcmp may examine lenFlat bytes in both arguments so assert it 
doesn't read past end of searchThing
+                                       assert(static_cast<size_t>(indexSearch + lenFlat) <= 
searchThing.size());
                                        // Does folded match the buffer
                                        characterMatches = 0 == memcmp(folded, &searchThing[0] + indexSearch, 
lenFlat);
                                        if (!characterMatches)
@@ -1615,7 +1947,7 @@ long Document::FindText(int minPos, int maxPos, const char *search,
                } else if (dbcsCodePage) {
                        const size_t maxBytesCharacter = 2;
                        const size_t maxFoldingExpansion = 4;
-                       std::vector<char> searchThing(lengthFind * maxBytesCharacter * maxFoldingExpansion + 
1);
+                       std::vector<char> searchThing((lengthFind+1) * maxBytesCharacter * 
maxFoldingExpansion + 1);
                        const int lenSearch = static_cast<int>(
                                pcf->Fold(&searchThing[0], searchThing.size(), search, lengthFind));
                        while (forward ? (pos < endPos) : (pos >= endPos)) {
@@ -1635,6 +1967,8 @@ long Document::FindText(int minPos, int maxPos, const char *search,
                                        char folded[maxBytesCharacter * maxFoldingExpansion + 1];
                                        const int lenFlat = static_cast<int>(pcf->Fold(folded, 
sizeof(folded), bytes, widthChar));
                                        folded[lenFlat] = 0;
+                                       // memcmp may examine lenFlat bytes in both arguments so assert it 
doesn't read past end of searchThing
+                                       assert(static_cast<size_t>(indexSearch + lenFlat) <= 
searchThing.size());
                                        // Does folded match the buffer
                                        characterMatches = 0 == memcmp(folded, &searchThing[0] + indexSearch, 
lenFlat);
                                        indexDocument += widthChar;
@@ -1650,7 +1984,7 @@ long Document::FindText(int minPos, int maxPos, const char *search,
                                        break;
                        }
                } else {
-                       const int endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
+                       const Sci::Position endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : 
endPos;
                        std::vector<char> searchThing(lengthFind + 1);
                        pcf->Fold(&searchThing[0], searchThing.size(), search, lengthFind);
                        while (forward ? (pos < endSearch) : (pos >= endSearch)) {
@@ -1673,14 +2007,14 @@ long Document::FindText(int minPos, int maxPos, const char *search,
        return -1;
 }
 
-const char *Document::SubstituteByPosition(const char *text, int *length) {
+const char *Document::SubstituteByPosition(const char *text, Sci::Position *length) {
        if (regex)
                return regex->SubstituteByPosition(this, text, length);
        else
                return 0;
 }
 
-int Document::LinesTotal() const {
+Sci::Line Document::LinesTotal() const {
        return cb.Lines();
 }
 
@@ -1692,28 +2026,21 @@ void Document::SetCharClasses(const unsigned char *chars, CharClassify::cc newCh
     charClass.SetCharClasses(chars, newCharClass);
 }
 
-int Document::GetCharsOfClass(CharClassify::cc characterClass, unsigned char *buffer) {
+int Document::GetCharsOfClass(CharClassify::cc characterClass, unsigned char *buffer) const {
     return charClass.GetCharsOfClass(characterClass, buffer);
 }
 
-void Document::SetStylingBits(int bits) {
-       stylingBits = bits;
-       stylingBitsMask = (1 << stylingBits) - 1;
-}
-
-void SCI_METHOD Document::StartStyling(int position, char mask) {
-       stylingMask = mask;
+void SCI_METHOD Document::StartStyling(Sci_Position position, char) {
        endStyled = position;
 }
 
-bool SCI_METHOD Document::SetStyleFor(int length, char style) {
+bool SCI_METHOD Document::SetStyleFor(Sci_Position length, char style) {
        if (enteredStyling != 0) {
                return false;
        } else {
                enteredStyling++;
-               style &= stylingMask;
-               int prevEndStyled = endStyled;
-               if (cb.SetStyleFor(endStyled, length, style, stylingMask)) {
+               Sci::Position prevEndStyled = endStyled;
+               if (cb.SetStyleFor(endStyled, length, style)) {
                        DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
                                           prevEndStyled, length);
                        NotifyModified(mh);
@@ -1724,17 +2051,17 @@ bool SCI_METHOD Document::SetStyleFor(int length, char style) {
        }
 }
 
-bool SCI_METHOD Document::SetStyles(int length, const char *styles) {
+bool SCI_METHOD Document::SetStyles(Sci_Position length, const char *styles) {
        if (enteredStyling != 0) {
                return false;
        } else {
                enteredStyling++;
                bool didChange = false;
-               int startMod = 0;
-               int endMod = 0;
+               Sci::Position startMod = 0;
+               Sci::Position endMod = 0;
                for (int iPos = 0; iPos < length; iPos++, endStyled++) {
                        PLATFORM_ASSERT(endStyled < Length());
-                       if (cb.SetStyleAt(endStyled, styles[iPos], stylingMask)) {
+                       if (cb.SetStyleAt(endStyled, styles[iPos])) {
                                if (!didChange) {
                                        startMod = endStyled;
                                }
@@ -1752,12 +2079,12 @@ bool SCI_METHOD Document::SetStyles(int length, const char *styles) {
        }
 }
 
-void Document::EnsureStyledTo(int pos) {
+void Document::EnsureStyledTo(Sci::Position pos) {
        if ((enteredStyling == 0) && (pos > GetEndStyled())) {
                IncrementStyleClock();
                if (pli && !pli->UseContainerLexing()) {
-                       int lineEndStyled = LineFromPosition(GetEndStyled());
-                       int endStyledTo = LineStart(lineEndStyled);
+                       Sci::Line lineEndStyled = LineFromPosition(GetEndStyled());
+                       Sci::Position endStyledTo = LineStart(lineEndStyled);
                        pli->Colourise(endStyledTo, pos);
                } else {
                        // Ask the watchers to style, and stop as soon as one responds.
@@ -1769,15 +2096,50 @@ void Document::EnsureStyledTo(int pos) {
        }
 }
 
+void Document::StyleToAdjustingLineDuration(Sci::Position pos) {
+       // Place bounds on the duration used to avoid glitches spiking it
+       // and so causing slow styling or non-responsive scrolling
+       const double minDurationOneLine = 0.000001;
+       const double maxDurationOneLine = 0.0001;
+
+       // Alpha value for exponential smoothing.
+       // Most recent value contributes 25% to smoothed value.
+       const double alpha = 0.25;
+
+       const Sci::Line lineFirst = LineFromPosition(GetEndStyled());
+       ElapsedTime etStyling;
+       EnsureStyledTo(pos);
+       const double durationStyling = etStyling.Duration();
+       const Sci::Line lineLast = LineFromPosition(GetEndStyled());
+       if (lineLast >= lineFirst + 8) {
+               // Only adjust for styling multiple lines to avoid instability
+               const double durationOneLine = durationStyling / (lineLast - lineFirst);
+               durationStyleOneLine = alpha * durationOneLine + (1.0 - alpha) * durationStyleOneLine;
+               if (durationStyleOneLine < minDurationOneLine) {
+                       durationStyleOneLine = minDurationOneLine;
+               } else if (durationStyleOneLine > maxDurationOneLine) {
+                       durationStyleOneLine = maxDurationOneLine;
+               }
+       }
+}
+
 void Document::LexerChanged() {
        // Tell the watchers the lexer has changed.
-       for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
-               it->watcher->NotifyLexerChanged(this, it->userData);
+       for (const WatcherWithUserData &watcher : watchers) {
+               watcher.watcher->NotifyLexerChanged(this, watcher.userData);
        }
 }
 
-int SCI_METHOD Document::SetLineState(int line, int state) {
-       int statePrevious = static_cast<LineState *>(perLineData[ldState])->SetLineState(line, state);
+LexInterface *Document::GetLexInterface() const {
+       return pli.get();
+}
+
+void Document::SetLexInterface(LexInterface *pLexInterface) {
+       pli.reset(pLexInterface);
+}
+
+int SCI_METHOD Document::SetLineState(Sci_Position line, int state) {
+       const int statePrevious = States()->SetLineState(line, state);
        if (state != statePrevious) {
                DocModification mh(SC_MOD_CHANGELINESTATE, LineStart(line), 0, 0, 0, line);
                NotifyModified(mh);
@@ -1785,59 +2147,59 @@ int SCI_METHOD Document::SetLineState(int line, int state) {
        return statePrevious;
 }
 
-int SCI_METHOD Document::GetLineState(int line) const {
-       return static_cast<LineState *>(perLineData[ldState])->GetLineState(line);
+int SCI_METHOD Document::GetLineState(Sci_Position line) const {
+       return States()->GetLineState(line);
 }
 
-int Document::GetMaxLineState() {
-       return static_cast<LineState *>(perLineData[ldState])->GetMaxLineState();
+Sci::Line Document::GetMaxLineState() const {
+       return States()->GetMaxLineState();
 }
 
-void SCI_METHOD Document::ChangeLexerState(int start, int end) {
+void SCI_METHOD Document::ChangeLexerState(Sci_Position start, Sci_Position end) {
        DocModification mh(SC_MOD_LEXERSTATE, start, end-start, 0, 0, 0);
        NotifyModified(mh);
 }
 
-StyledText Document::MarginStyledText(int line) const {
-       LineAnnotation *pla = static_cast<LineAnnotation *>(perLineData[ldMargin]);
+StyledText Document::MarginStyledText(Sci::Line line) const {
+       const LineAnnotation *pla = Margins();
        return StyledText(pla->Length(line), pla->Text(line),
                pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
 }
 
-void Document::MarginSetText(int line, const char *text) {
-       static_cast<LineAnnotation *>(perLineData[ldMargin])->SetText(line, text);
+void Document::MarginSetText(Sci::Line line, const char *text) {
+       Margins()->SetText(line, text);
        DocModification mh(SC_MOD_CHANGEMARGIN, LineStart(line), 0, 0, 0, line);
        NotifyModified(mh);
 }
 
-void Document::MarginSetStyle(int line, int style) {
-       static_cast<LineAnnotation *>(perLineData[ldMargin])->SetStyle(line, style);
+void Document::MarginSetStyle(Sci::Line line, int style) {
+       Margins()->SetStyle(line, style);
        NotifyModified(DocModification(SC_MOD_CHANGEMARGIN, LineStart(line), 0, 0, 0, line));
 }
 
-void Document::MarginSetStyles(int line, const unsigned char *styles) {
-       static_cast<LineAnnotation *>(perLineData[ldMargin])->SetStyles(line, styles);
+void Document::MarginSetStyles(Sci::Line line, const unsigned char *styles) {
+       Margins()->SetStyles(line, styles);
        NotifyModified(DocModification(SC_MOD_CHANGEMARGIN, LineStart(line), 0, 0, 0, line));
 }
 
 void Document::MarginClearAll() {
-       int maxEditorLine = LinesTotal();
-       for (int l=0; l<maxEditorLine; l++)
+       const Sci::Line maxEditorLine = LinesTotal();
+       for (Sci::Line l=0; l<maxEditorLine; l++)
                MarginSetText(l, 0);
        // Free remaining data
-       static_cast<LineAnnotation *>(perLineData[ldMargin])->ClearAll();
+       Margins()->ClearAll();
 }
 
-StyledText Document::AnnotationStyledText(int line) const {
-       LineAnnotation *pla = static_cast<LineAnnotation *>(perLineData[ldAnnotation]);
+StyledText Document::AnnotationStyledText(Sci::Line line) const {
+       const LineAnnotation *pla = Annotations();
        return StyledText(pla->Length(line), pla->Text(line),
                pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
 }
 
-void Document::AnnotationSetText(int line, const char *text) {
+void Document::AnnotationSetText(Sci::Line line, const char *text) {
        if (line >= 0 && line < LinesTotal()) {
-               const int linesBefore = AnnotationLines(line);
-               static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetText(line, text);
+               const Sci::Line linesBefore = AnnotationLines(line);
+               Annotations()->SetText(line, text);
                const int linesAfter = AnnotationLines(line);
                DocModification mh(SC_MOD_CHANGEANNOTATION, LineStart(line), 0, 0, 0, line);
                mh.annotationLinesAdded = linesAfter - linesBefore;
@@ -1845,35 +2207,39 @@ void Document::AnnotationSetText(int line, const char *text) {
        }
 }
 
-void Document::AnnotationSetStyle(int line, int style) {
-       static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetStyle(line, style);
+void Document::AnnotationSetStyle(Sci::Line line, int style) {
+       Annotations()->SetStyle(line, style);
        DocModification mh(SC_MOD_CHANGEANNOTATION, LineStart(line), 0, 0, 0, line);
        NotifyModified(mh);
 }
 
-void Document::AnnotationSetStyles(int line, const unsigned char *styles) {
+void Document::AnnotationSetStyles(Sci::Line line, const unsigned char *styles) {
        if (line >= 0 && line < LinesTotal()) {
-               static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetStyles(line, styles);
+               Annotations()->SetStyles(line, styles);
        }
 }
 
-int Document::AnnotationLines(int line) const {
-       return static_cast<LineAnnotation *>(perLineData[ldAnnotation])->Lines(line);
+int Document::AnnotationLines(Sci::Line line) const {
+       return Annotations()->Lines(line);
 }
 
 void Document::AnnotationClearAll() {
-       int maxEditorLine = LinesTotal();
-       for (int l=0; l<maxEditorLine; l++)
+       const Sci::Line maxEditorLine = LinesTotal();
+       for (Sci::Line l=0; l<maxEditorLine; l++)
                AnnotationSetText(l, 0);
        // Free remaining data
-       static_cast<LineAnnotation *>(perLineData[ldAnnotation])->ClearAll();
+       Annotations()->ClearAll();
 }
 
 void Document::IncrementStyleClock() {
        styleClock = (styleClock + 1) % 0x100000;
 }
 
-void SCI_METHOD Document::DecorationFillRange(int position, int value, int fillLength) {
+void SCI_METHOD Document::DecorationSetCurrentIndicator(int indicator) {
+       decorations.SetCurrentIndicator(indicator);
+}
+
+void SCI_METHOD Document::DecorationFillRange(Sci_Position position, int value, Sci_Position fillLength) {
        if (decorations.FillRange(position, value, fillLength)) {
                DocModification mh(SC_MOD_CHANGEINDICATOR | SC_PERFORMED_USER,
                                                        position, fillLength);
@@ -1883,7 +2249,7 @@ void SCI_METHOD Document::DecorationFillRange(int position, int value, int fillL
 
 bool Document::AddWatcher(DocWatcher *watcher, void *userData) {
        WatcherWithUserData wwud(watcher, userData);
-       std::vector<WatcherWithUserData>::iterator it = 
+       std::vector<WatcherWithUserData>::iterator it =
                std::find(watchers.begin(), watchers.end(), wwud);
        if (it != watchers.end())
                return false;
@@ -1892,7 +2258,7 @@ bool Document::AddWatcher(DocWatcher *watcher, void *userData) {
 }
 
 bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) {
-       std::vector<WatcherWithUserData>::iterator it = 
+       std::vector<WatcherWithUserData>::iterator it =
                std::find(watchers.begin(), watchers.end(), WatcherWithUserData(watcher, userData));
        if (it != watchers.end()) {
                watchers.erase(it);
@@ -1902,14 +2268,14 @@ bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) {
 }
 
 void Document::NotifyModifyAttempt() {
-       for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
-               it->watcher->NotifyModifyAttempt(this, it->userData);
+       for (const WatcherWithUserData &watcher : watchers) {
+               watcher.watcher->NotifyModifyAttempt(this, watcher.userData);
        }
 }
 
 void Document::NotifySavePoint(bool atSavePoint) {
-       for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
-               it->watcher->NotifySavePoint(this, it->userData, atSavePoint);
+       for (const WatcherWithUserData &watcher : watchers) {
+               watcher.watcher->NotifySavePoint(this, watcher.userData, atSavePoint);
        }
 }
 
@@ -1919,111 +2285,152 @@ void Document::NotifyModified(DocModification mh) {
        } else if (mh.modificationType & SC_MOD_DELETETEXT) {
                decorations.DeleteRange(mh.position, mh.length);
        }
-       for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
-               it->watcher->NotifyModified(this, mh, it->userData);
+       for (const WatcherWithUserData &watcher : watchers) {
+               watcher.watcher->NotifyModified(this, mh, watcher.userData);
        }
 }
 
-bool Document::IsWordPartSeparator(char ch) const {
-       return (WordCharClass(ch) == CharClassify::ccWord) && IsPunctuation(ch);
+// Used for word part navigation.
+static bool IsASCIIPunctuationCharacter(unsigned int ch) {
+       switch (ch) {
+       case '!':
+       case '"':
+       case '#':
+       case '$':
+       case '%':
+       case '&':
+       case '\'':
+       case '(':
+       case ')':
+       case '*':
+       case '+':
+       case ',':
+       case '-':
+       case '.':
+       case '/':
+       case ':':
+       case ';':
+       case '<':
+       case '=':
+       case '>':
+       case '?':
+       case '@':
+       case '[':
+       case '\\':
+       case ']':
+       case '^':
+       case '_':
+       case '`':
+       case '{':
+       case '|':
+       case '}':
+       case '~':
+               return true;
+       default:
+               return false;
+       }
+}
+
+bool Document::IsWordPartSeparator(unsigned int ch) const {
+       return (WordCharacterClass(ch) == CharClassify::ccWord) && IsASCIIPunctuationCharacter(ch);
 }
 
-int Document::WordPartLeft(int pos) {
+Sci::Position Document::WordPartLeft(Sci::Position pos) const {
        if (pos > 0) {
-               --pos;
-               char startChar = cb.CharAt(pos);
-               if (IsWordPartSeparator(startChar)) {
-                       while (pos > 0 && IsWordPartSeparator(cb.CharAt(pos))) {
-                               --pos;
+               pos -= CharacterBefore(pos).widthBytes;
+               CharacterExtracted ceStart = CharacterAfter(pos);
+               if (IsWordPartSeparator(ceStart.character)) {
+                       while (pos > 0 && IsWordPartSeparator(CharacterAfter(pos).character)) {
+                               pos -= CharacterBefore(pos).widthBytes;
                        }
                }
                if (pos > 0) {
-                       startChar = cb.CharAt(pos);
-                       --pos;
-                       if (IsLowerCase(startChar)) {
-                               while (pos > 0 && IsLowerCase(cb.CharAt(pos)))
-                                       --pos;
-                               if (!IsUpperCase(cb.CharAt(pos)) && !IsLowerCase(cb.CharAt(pos)))
-                                       ++pos;
-                       } else if (IsUpperCase(startChar)) {
-                               while (pos > 0 && IsUpperCase(cb.CharAt(pos)))
-                                       --pos;
-                               if (!IsUpperCase(cb.CharAt(pos)))
-                                       ++pos;
-                       } else if (IsADigit(startChar)) {
-                               while (pos > 0 && IsADigit(cb.CharAt(pos)))
-                                       --pos;
-                               if (!IsADigit(cb.CharAt(pos)))
-                                       ++pos;
-                       } else if (IsPunctuation(startChar)) {
-                               while (pos > 0 && IsPunctuation(cb.CharAt(pos)))
-                                       --pos;
-                               if (!IsPunctuation(cb.CharAt(pos)))
-                                       ++pos;
-                       } else if (isspacechar(startChar)) {
-                               while (pos > 0 && isspacechar(cb.CharAt(pos)))
-                                       --pos;
-                               if (!isspacechar(cb.CharAt(pos)))
-                                       ++pos;
-                       } else if (!isascii(startChar)) {
-                               while (pos > 0 && !isascii(cb.CharAt(pos)))
-                                       --pos;
-                               if (isascii(cb.CharAt(pos)))
-                                       ++pos;
+                       ceStart = CharacterAfter(pos);
+                       pos -= CharacterBefore(pos).widthBytes;
+                       if (IsLowerCase(ceStart.character)) {
+                               while (pos > 0 && IsLowerCase(CharacterAfter(pos).character))
+                                       pos -= CharacterBefore(pos).widthBytes;
+                               if (!IsUpperCase(CharacterAfter(pos).character) && 
!IsLowerCase(CharacterAfter(pos).character))
+                                       pos += CharacterAfter(pos).widthBytes;
+                       } else if (IsUpperCase(ceStart.character)) {
+                               while (pos > 0 && IsUpperCase(CharacterAfter(pos).character))
+                                       pos -= CharacterBefore(pos).widthBytes;
+                               if (!IsUpperCase(CharacterAfter(pos).character))
+                                       pos += CharacterAfter(pos).widthBytes;
+                       } else if (IsADigit(ceStart.character)) {
+                               while (pos > 0 && IsADigit(CharacterAfter(pos).character))
+                                       pos -= CharacterBefore(pos).widthBytes;
+                               if (!IsADigit(CharacterAfter(pos).character))
+                                       pos += CharacterAfter(pos).widthBytes;
+                       } else if (IsASCIIPunctuationCharacter(ceStart.character)) {
+                               while (pos > 0 && IsASCIIPunctuationCharacter(CharacterAfter(pos).character))
+                                       pos -= CharacterBefore(pos).widthBytes;
+                               if (!IsASCIIPunctuationCharacter(CharacterAfter(pos).character))
+                                       pos += CharacterAfter(pos).widthBytes;
+                       } else if (isspacechar(ceStart.character)) {
+                               while (pos > 0 && isspacechar(CharacterAfter(pos).character))
+                                       pos -= CharacterBefore(pos).widthBytes;
+                               if (!isspacechar(CharacterAfter(pos).character))
+                                       pos += CharacterAfter(pos).widthBytes;
+                       } else if (!IsASCII(ceStart.character)) {
+                               while (pos > 0 && !IsASCII(CharacterAfter(pos).character))
+                                       pos -= CharacterBefore(pos).widthBytes;
+                               if (IsASCII(CharacterAfter(pos).character))
+                                       pos += CharacterAfter(pos).widthBytes;
                        } else {
-                               ++pos;
+                               pos += CharacterAfter(pos).widthBytes;
                        }
                }
        }
        return pos;
 }
 
-int Document::WordPartRight(int pos) {
-       char startChar = cb.CharAt(pos);
-       int length = Length();
-       if (IsWordPartSeparator(startChar)) {
-               while (pos < length && IsWordPartSeparator(cb.CharAt(pos)))
-                       ++pos;
-               startChar = cb.CharAt(pos);
-       }
-       if (!isascii(startChar)) {
-               while (pos < length && !isascii(cb.CharAt(pos)))
-                       ++pos;
-       } else if (IsLowerCase(startChar)) {
-               while (pos < length && IsLowerCase(cb.CharAt(pos)))
-                       ++pos;
-       } else if (IsUpperCase(startChar)) {
-               if (IsLowerCase(cb.CharAt(pos + 1))) {
-                       ++pos;
-                       while (pos < length && IsLowerCase(cb.CharAt(pos)))
-                               ++pos;
+Sci::Position Document::WordPartRight(Sci::Position pos) const {
+       CharacterExtracted ceStart = CharacterAfter(pos);
+       const Sci::Position length = Length();
+       if (IsWordPartSeparator(ceStart.character)) {
+               while (pos < length && IsWordPartSeparator(CharacterAfter(pos).character))
+                       pos += CharacterAfter(pos).widthBytes;
+               ceStart = CharacterAfter(pos);
+       }
+       if (!IsASCII(ceStart.character)) {
+               while (pos < length && !IsASCII(CharacterAfter(pos).character))
+                       pos += CharacterAfter(pos).widthBytes;
+       } else if (IsLowerCase(ceStart.character)) {
+               while (pos < length && IsLowerCase(CharacterAfter(pos).character))
+                       pos += CharacterAfter(pos).widthBytes;
+       } else if (IsUpperCase(ceStart.character)) {
+               if (IsLowerCase(CharacterAfter(pos + ceStart.widthBytes).character)) {
+                       pos += CharacterAfter(pos).widthBytes;
+                       while (pos < length && IsLowerCase(CharacterAfter(pos).character))
+                               pos += CharacterAfter(pos).widthBytes;
                } else {
-                       while (pos < length && IsUpperCase(cb.CharAt(pos)))
-                               ++pos;
-               }
-               if (IsLowerCase(cb.CharAt(pos)) && IsUpperCase(cb.CharAt(pos - 1)))
-                       --pos;
-       } else if (IsADigit(startChar)) {
-               while (pos < length && IsADigit(cb.CharAt(pos)))
-                       ++pos;
-       } else if (IsPunctuation(startChar)) {
-               while (pos < length && IsPunctuation(cb.CharAt(pos)))
-                       ++pos;
-       } else if (isspacechar(startChar)) {
-               while (pos < length && isspacechar(cb.CharAt(pos)))
-                       ++pos;
+                       while (pos < length && IsUpperCase(CharacterAfter(pos).character))
+                               pos += CharacterAfter(pos).widthBytes;
+               }
+               if (IsLowerCase(CharacterAfter(pos).character) && IsUpperCase(CharacterBefore(pos).character))
+                       pos -= CharacterBefore(pos).widthBytes;
+       } else if (IsADigit(ceStart.character)) {
+               while (pos < length && IsADigit(CharacterAfter(pos).character))
+                       pos += CharacterAfter(pos).widthBytes;
+       } else if (IsASCIIPunctuationCharacter(ceStart.character)) {
+               while (pos < length && IsASCIIPunctuationCharacter(CharacterAfter(pos).character))
+                       pos += CharacterAfter(pos).widthBytes;
+       } else if (isspacechar(ceStart.character)) {
+               while (pos < length && isspacechar(CharacterAfter(pos).character))
+                       pos += CharacterAfter(pos).widthBytes;
        } else {
-               ++pos;
+               pos += CharacterAfter(pos).widthBytes;
        }
        return pos;
 }
 
-bool IsLineEndChar(char c) {
+static bool IsLineEndChar(char c) {
        return (c == '\n' || c == '\r');
 }
 
-int Document::ExtendStyleRange(int pos, int delta, bool singleLine) {
-       int sStart = cb.StyleAt(pos);
+Sci::Position Document::ExtendStyleRange(Sci::Position pos, int delta, bool singleLine) {
+       const int sStart = cb.StyleAt(pos);
        if (delta < 0) {
                while (pos > 0 && (cb.StyleAt(pos) == sStart) && (!singleLine || 
!IsLineEndChar(cb.CharAt(pos))))
                        pos--;
@@ -2059,20 +2466,20 @@ static char BraceOpposite(char ch) {
 }
 
 // TODO: should be able to extend styled region to find matching brace
-int Document::BraceMatch(int position, int /*maxReStyle*/) {
-       char chBrace = CharAt(position);
-       char chSeek = BraceOpposite(chBrace);
+Sci::Position Document::BraceMatch(Sci::Position position, Sci::Position /*maxReStyle*/) {
+       const char chBrace = CharAt(position);
+       const char chSeek = BraceOpposite(chBrace);
        if (chSeek == '\0')
                return - 1;
-       char styBrace = static_cast<char>(StyleAt(position) & stylingBitsMask);
+       const int styBrace = StyleIndexAt(position);
        int direction = -1;
        if (chBrace == '(' || chBrace == '[' || chBrace == '{' || chBrace == '<')
                direction = 1;
        int depth = 1;
        position = NextPosition(position, direction);
        while ((position >= 0) && (position < Length())) {
-               char chAtPos = CharAt(position);
-               char styAtPos = static_cast<char>(StyleAt(position) & stylingBitsMask);
+               const char chAtPos = CharAt(position);
+               const int styAtPos = StyleIndexAt(position);
                if ((position > GetEndStyled()) || (styAtPos == styBrace)) {
                        if (chAtPos == chBrace)
                                depth++;
@@ -2081,7 +2488,7 @@ int Document::BraceMatch(int position, int /*maxReStyle*/) {
                        if (depth == 0)
                                return position;
                }
-               int positionBeforeMove = position;
+               const Sci::Position positionBeforeMove = position;
                position = NextPosition(position, direction);
                if (position == positionBeforeMove)
                        break;
@@ -2094,35 +2501,90 @@ int Document::BraceMatch(int position, int /*maxReStyle*/) {
  */
 class BuiltinRegex : public RegexSearchBase {
 public:
-       BuiltinRegex(CharClassify *charClassTable) : search(charClassTable) {}
+       explicit BuiltinRegex(CharClassify *charClassTable) : search(charClassTable) {}
 
-       virtual ~BuiltinRegex() {
+       ~BuiltinRegex() override {
        }
 
-       virtual long FindText(Document *doc, int minPos, int maxPos, const char *s,
+       long FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
                         bool caseSensitive, bool word, bool wordStart, int flags,
-                        int *length);
+                        Sci::Position *length) override;
 
-       virtual const char *SubstituteByPosition(Document *doc, const char *text, int *length);
+       const char *SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) override;
 
 private:
        RESearch search;
        std::string substituted;
 };
 
+namespace {
+
+/**
+* RESearchRange keeps track of search range.
+*/
+class RESearchRange {
+public:
+       const Document *doc;
+       int increment;
+       Sci::Position startPos;
+       Sci::Position endPos;
+       Sci::Line lineRangeStart;
+       Sci::Line lineRangeEnd;
+       Sci::Line lineRangeBreak;
+       RESearchRange(const Document *doc_, Sci::Position minPos, Sci::Position maxPos) : doc(doc_) {
+               increment = (minPos <= maxPos) ? 1 : -1;
+
+               // Range endpoints should not be inside DBCS characters, but just in case, move them.
+               startPos = doc->MovePositionOutsideChar(minPos, 1, false);
+               endPos = doc->MovePositionOutsideChar(maxPos, 1, false);
+
+               lineRangeStart = doc->LineFromPosition(startPos);
+               lineRangeEnd = doc->LineFromPosition(endPos);
+               if ((increment == 1) &&
+                       (startPos >= doc->LineEnd(lineRangeStart)) &&
+                       (lineRangeStart < lineRangeEnd)) {
+                       // the start position is at end of line or between line end characters.
+                       lineRangeStart++;
+                       startPos = doc->LineStart(lineRangeStart);
+               } else if ((increment == -1) &&
+                       (startPos <= doc->LineStart(lineRangeStart)) &&
+                       (lineRangeStart > lineRangeEnd)) {
+                       // the start position is at beginning of line.
+                       lineRangeStart--;
+                       startPos = doc->LineEnd(lineRangeStart);
+               }
+               lineRangeBreak = lineRangeEnd + increment;
+       }
+       Range LineRange(Sci::Line line) const {
+               Range range(doc->LineStart(line), doc->LineEnd(line));
+               if (increment == 1) {
+                       if (line == lineRangeStart)
+                               range.start = startPos;
+                       if (line == lineRangeEnd)
+                               range.end = endPos;
+               } else {
+                       if (line == lineRangeEnd)
+                               range.start = endPos;
+                       if (line == lineRangeStart)
+                               range.end = startPos;
+               }
+               return range;
+       }
+};
+
 // Define a way for the Regular Expression code to access the document
 class DocumentIndexer : public CharacterIndexer {
        Document *pdoc;
-       int end;
+       Sci::Position end;
 public:
-       DocumentIndexer(Document *pdoc_, int end_) :
+       DocumentIndexer(Document *pdoc_, Sci::Position end_) :
                pdoc(pdoc_), end(end_) {
        }
 
-       virtual ~DocumentIndexer() {
+       ~DocumentIndexer() override {
        }
 
-       virtual char CharAt(int index) {
+       char CharAt(Sci::Position index) override {
                if (index < 0 || index >= end)
                        return 0;
                else
@@ -2130,18 +2592,376 @@ public:
        }
 };
 
-long BuiltinRegex::FindText(Document *doc, int minPos, int maxPos, const char *s,
+#ifndef NO_CXX11_REGEX
+
+class ByteIterator : public std::iterator<std::bidirectional_iterator_tag, char> {
+public:
+       const Document *doc;
+       Sci::Position position;
+       ByteIterator(const Document *doc_ = 0, Sci::Position position_ = 0) : doc(doc_), position(position_) {
+       }
+       ByteIterator(const ByteIterator &other) NOEXCEPT {
+               doc = other.doc;
+               position = other.position;
+       }
+       ByteIterator &operator=(const ByteIterator &other) {
+               if (this != &other) {
+                       doc = other.doc;
+                       position = other.position;
+               }
+               return *this;
+       }
+       char operator*() const {
+               return doc->CharAt(position);
+       }
+       ByteIterator &operator++() {
+               position++;
+               return *this;
+       }
+       ByteIterator operator++(int) {
+               ByteIterator retVal(*this);
+               position++;
+               return retVal;
+       }
+       ByteIterator &operator--() {
+               position--;
+               return *this;
+       }
+       bool operator==(const ByteIterator &other) const {
+               return doc == other.doc && position == other.position;
+       }
+       bool operator!=(const ByteIterator &other) const {
+               return doc != other.doc || position != other.position;
+       }
+       Sci::Position Pos() const {
+               return position;
+       }
+       Sci::Position PosRoundUp() const {
+               return position;
+       }
+};
+
+// On Windows, wchar_t is 16 bits wide and on Unix it is 32 bits wide.
+// Would be better to use sizeof(wchar_t) or similar to differentiate
+// but easier for now to hard-code platforms.
+// C++11 has char16_t and char32_t but neither Clang nor Visual C++
+// appear to allow specializing basic_regex over these.
+
+#ifdef _WIN32
+#define WCHAR_T_IS_16 1
+#else
+#define WCHAR_T_IS_16 0
+#endif
+
+#if WCHAR_T_IS_16
+
+// On Windows, report non-BMP characters as 2 separate surrogates as that
+// matches wregex since it is based on wchar_t.
+class UTF8Iterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> {
+       // These 3 fields determine the iterator position and are used for comparisons
+       const Document *doc;
+       Sci::Position position;
+       size_t characterIndex;
+       // Remaining fields are derived from the determining fields so are excluded in comparisons
+       unsigned int lenBytes;
+       size_t lenCharacters;
+       wchar_t buffered[2];
+public:
+       UTF8Iterator(const Document *doc_ = 0, Sci::Position position_ = 0) :
+               doc(doc_), position(position_), characterIndex(0), lenBytes(0), lenCharacters(0) {
+               buffered[0] = 0;
+               buffered[1] = 0;
+               if (doc) {
+                       ReadCharacter();
+               }
+       }
+       UTF8Iterator(const UTF8Iterator &other) {
+               doc = other.doc;
+               position = other.position;
+               characterIndex = other.characterIndex;
+               lenBytes = other.lenBytes;
+               lenCharacters = other.lenCharacters;
+               buffered[0] = other.buffered[0];
+               buffered[1] = other.buffered[1];
+       }
+       UTF8Iterator &operator=(const UTF8Iterator &other) {
+               if (this != &other) {
+                       doc = other.doc;
+                       position = other.position;
+                       characterIndex = other.characterIndex;
+                       lenBytes = other.lenBytes;
+                       lenCharacters = other.lenCharacters;
+                       buffered[0] = other.buffered[0];
+                       buffered[1] = other.buffered[1];
+               }
+               return *this;
+       }
+       wchar_t operator*() const {
+               assert(lenCharacters != 0);
+               return buffered[characterIndex];
+       }
+       UTF8Iterator &operator++() {
+               if ((characterIndex + 1) < (lenCharacters)) {
+                       characterIndex++;
+               } else {
+                       position += lenBytes;
+                       ReadCharacter();
+                       characterIndex = 0;
+               }
+               return *this;
+       }
+       UTF8Iterator operator++(int) {
+               UTF8Iterator retVal(*this);
+               if ((characterIndex + 1) < (lenCharacters)) {
+                       characterIndex++;
+               } else {
+                       position += lenBytes;
+                       ReadCharacter();
+                       characterIndex = 0;
+               }
+               return retVal;
+       }
+       UTF8Iterator &operator--() {
+               if (characterIndex) {
+                       characterIndex--;
+               } else {
+                       position = doc->NextPosition(position, -1);
+                       ReadCharacter();
+                       characterIndex = lenCharacters - 1;
+               }
+               return *this;
+       }
+       bool operator==(const UTF8Iterator &other) const {
+               // Only test the determining fields, not the character widths and values derived from this
+               return doc == other.doc &&
+                       position == other.position &&
+                       characterIndex == other.characterIndex;
+       }
+       bool operator!=(const UTF8Iterator &other) const {
+               // Only test the determining fields, not the character widths and values derived from this
+               return doc != other.doc ||
+                       position != other.position ||
+                       characterIndex != other.characterIndex;
+       }
+       Sci::Position Pos() const {
+               return position;
+       }
+       Sci::Position PosRoundUp() const {
+               if (characterIndex)
+                       return position + lenBytes;     // Force to end of character
+               else
+                       return position;
+       }
+private:
+       void ReadCharacter() {
+               const Document::CharacterExtracted charExtracted = doc->ExtractCharacter(position);
+               lenBytes = charExtracted.widthBytes;
+               if (charExtracted.character == unicodeReplacementChar) {
+                       lenCharacters = 1;
+                       buffered[0] = static_cast<wchar_t>(charExtracted.character);
+               } else {
+                       lenCharacters = UTF16FromUTF32Character(charExtracted.character, buffered);
+               }
+       }
+};
+
+#else
+
+// On Unix, report non-BMP characters as single characters
+
+class UTF8Iterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> {
+       const Document *doc;
+       Sci::Position position;
+public:
+       UTF8Iterator(const Document *doc_=0, Sci::Position position_=0) : doc(doc_), position(position_) {
+       }
+       UTF8Iterator(const UTF8Iterator &other) NOEXCEPT {
+               doc = other.doc;
+               position = other.position;
+       }
+       UTF8Iterator &operator=(const UTF8Iterator &other) {
+               if (this != &other) {
+                       doc = other.doc;
+                       position = other.position;
+               }
+               return *this;
+       }
+       wchar_t operator*() const {
+               Document::CharacterExtracted charExtracted = doc->ExtractCharacter(position);
+               return charExtracted.character;
+       }
+       UTF8Iterator &operator++() {
+               position = doc->NextPosition(position, 1);
+               return *this;
+       }
+       UTF8Iterator operator++(int) {
+               UTF8Iterator retVal(*this);
+               position = doc->NextPosition(position, 1);
+               return retVal;
+       }
+       UTF8Iterator &operator--() {
+               position = doc->NextPosition(position, -1);
+               return *this;
+       }
+       bool operator==(const UTF8Iterator &other) const {
+               return doc == other.doc && position == other.position;
+       }
+       bool operator!=(const UTF8Iterator &other) const {
+               return doc != other.doc || position != other.position;
+       }
+       Sci::Position Pos() const {
+               return position;
+       }
+       Sci::Position PosRoundUp() const {
+               return position;
+       }
+};
+
+#endif
+
+std::regex_constants::match_flag_type MatchFlags(const Document *doc, Sci::Position startPos, Sci::Position 
endPos) {
+       std::regex_constants::match_flag_type flagsMatch = std::regex_constants::match_default;
+       if (!doc->IsLineStartPosition(startPos))
+               flagsMatch |= std::regex_constants::match_not_bol;
+       if (!doc->IsLineEndPosition(endPos))
+               flagsMatch |= std::regex_constants::match_not_eol;
+       return flagsMatch;
+}
+
+template<typename Iterator, typename Regex>
+bool MatchOnLines(const Document *doc, const Regex &regexp, const RESearchRange &resr, RESearch &search) {
+       bool matched = false;
+       std::match_results<Iterator> match;
+
+       // MSVC and libc++ have problems with ^ and $ matching line ends inside a range
+       // If they didn't then the line by line iteration could be removed for the forwards
+       // case and replaced with the following 4 lines:
+       //      Iterator uiStart(doc, startPos);
+       //      Iterator uiEnd(doc, endPos);
+       //      flagsMatch = MatchFlags(doc, startPos, endPos);
+       //      matched = std::regex_search(uiStart, uiEnd, match, regexp, flagsMatch);
+
+       // Line by line.
+       for (Sci::Line line = resr.lineRangeStart; line != resr.lineRangeBreak; line += resr.increment) {
+               const Range lineRange = resr.LineRange(line);
+               Iterator itStart(doc, lineRange.start);
+               Iterator itEnd(doc, lineRange.end);
+               std::regex_constants::match_flag_type flagsMatch = MatchFlags(doc, lineRange.start, 
lineRange.end);
+               matched = std::regex_search(itStart, itEnd, match, regexp, flagsMatch);
+               // Check for the last match on this line.
+               if (matched) {
+                       if (resr.increment == -1) {
+                               while (matched) {
+                                       Iterator itNext(doc, match[0].second.PosRoundUp());
+                                       flagsMatch = MatchFlags(doc, itNext.Pos(), lineRange.end);
+                                       std::match_results<Iterator> matchNext;
+                                       matched = std::regex_search(itNext, itEnd, matchNext, regexp, 
flagsMatch);
+                                       if (matched) {
+                                               if (match[0].first == match[0].second) {
+                                                       // Empty match means failure so exit
+                                                       return false;
+                                               }
+                                               match = matchNext;
+                                       }
+                               }
+                               matched = true;
+                       }
+                       break;
+               }
+       }
+       if (matched) {
+               for (size_t co = 0; co < match.size(); co++) {
+                       search.bopat[co] = match[co].first.Pos();
+                       search.eopat[co] = match[co].second.PosRoundUp();
+                       Sci::Position lenMatch = search.eopat[co] - search.bopat[co];
+                       search.pat[co].resize(lenMatch);
+                       for (Sci::Position iPos = 0; iPos < lenMatch; iPos++) {
+                               search.pat[co][iPos] = doc->CharAt(iPos + search.bopat[co]);
+                       }
+               }
+       }
+       return matched;
+}
+
+Sci::Position Cxx11RegexFindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
+       bool caseSensitive, Sci::Position *length, RESearch &search) {
+       const RESearchRange resr(doc, minPos, maxPos);
+       try {
+               //ElapsedTime et;
+               std::regex::flag_type flagsRe = std::regex::ECMAScript;
+               // Flags that apper to have no effect:
+               // | std::regex::collate | std::regex::extended;
+               if (!caseSensitive)
+                       flagsRe = flagsRe | std::regex::icase;
+
+               // Clear the RESearch so can fill in matches
+               search.Clear();
+
+               bool matched = false;
+               if (SC_CP_UTF8 == doc->dbcsCodePage) {
+                       size_t lenS = strlen(s);
+                       std::vector<wchar_t> ws(lenS + 1);
+#if WCHAR_T_IS_16
+                       size_t outLen = UTF16FromUTF8(s, lenS, &ws[0], lenS);
+#else
+                       size_t outLen = UTF32FromUTF8(s, lenS, reinterpret_cast<unsigned int *>(&ws[0]), 
lenS);
+#endif
+                       ws[outLen] = 0;
+                       std::wregex regexp;
+#if defined(__APPLE__)
+                       // Using a UTF-8 locale doesn't change to Unicode over a byte buffer so '.'
+                       // is one byte not one character.
+                       // However, on OS X this makes wregex act as Unicode
+                       std::locale localeU("en_US.UTF-8");
+                       regexp.imbue(localeU);
+#endif
+                       regexp.assign(&ws[0], flagsRe);
+                       matched = MatchOnLines<UTF8Iterator>(doc, regexp, resr, search);
+
+               } else {
+                       std::regex regexp;
+                       regexp.assign(s, flagsRe);
+                       matched = MatchOnLines<ByteIterator>(doc, regexp, resr, search);
+               }
+
+               Sci::Position posMatch = -1;
+               if (matched) {
+                       posMatch = search.bopat[0];
+                       *length = search.eopat[0] - search.bopat[0];
+               }
+               // Example - search in doc/ScintillaHistory.html for
+               // [[:upper:]]eta[[:space:]]
+               // On MacBook, normally around 1 second but with locale imbued -> 14 seconds.
+               //double durSearch = et.Duration(true);
+               //Platform::DebugPrintf("Search:%9.6g \n", durSearch);
+               return posMatch;
+       } catch (std::regex_error &) {
+               // Failed to create regular expression
+               throw RegexError();
+       } catch (...) {
+               // Failed in some other way
+               return -1;
+       }
+}
+
+#endif
+
+}
+
+long BuiltinRegex::FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
                         bool caseSensitive, bool, bool, int flags,
-                        int *length) {
-       bool posix = (flags & SCFIND_POSIX) != 0;
-       int increment = (minPos <= maxPos) ? 1 : -1;
+                        Sci::Position *length) {
 
-       int startPos = minPos;
-       int endPos = maxPos;
+#ifndef NO_CXX11_REGEX
+       if (flags & SCFIND_CXX11REGEX) {
+                       return Cxx11RegexFindText(doc, minPos, maxPos, s,
+                       caseSensitive, length, search);
+       }
+#endif
 
-       // Range endpoints should not be inside DBCS characters, but just in case, move them.
-       startPos = doc->MovePositionOutsideChar(startPos, 1, false);
-       endPos = doc->MovePositionOutsideChar(endPos, 1, false);
+       const RESearchRange resr(doc, minPos, maxPos);
+
+       const bool posix = (flags & SCFIND_POSIX) != 0;
 
        const char *errmsg = search.Compile(s, *length, caseSensitive, posix);
        if (errmsg) {
@@ -2151,50 +2971,34 @@ long BuiltinRegex::FindText(Document *doc, int minPos, int maxPos, const char *s
        // Replace first '.' with '-' in each property file variable reference:
        //     Search: \$(\([A-Za-z0-9_-]+\)\.\([A-Za-z0-9_.]+\))
        //     Replace: $(\1-\2)
-       int lineRangeStart = doc->LineFromPosition(startPos);
-       int lineRangeEnd = doc->LineFromPosition(endPos);
-       if ((increment == 1) &&
-               (startPos >= doc->LineEnd(lineRangeStart)) &&
-               (lineRangeStart < lineRangeEnd)) {
-               // the start position is at end of line or between line end characters.
-               lineRangeStart++;
-               startPos = doc->LineStart(lineRangeStart);
-       } else if ((increment == -1) &&
-                  (startPos <= doc->LineStart(lineRangeStart)) &&
-                  (lineRangeStart > lineRangeEnd)) {
-               // the start position is at beginning of line.
-               lineRangeStart--;
-               startPos = doc->LineEnd(lineRangeStart);
-       }
-       int pos = -1;
-       int lenRet = 0;
-       char searchEnd = s[*length - 1];
-       char searchEndPrev = (*length > 1) ? s[*length - 2] : '\0';
-       int lineRangeBreak = lineRangeEnd + increment;
-       for (int line = lineRangeStart; line != lineRangeBreak; line += increment) {
-               int startOfLine = doc->LineStart(line);
-               int endOfLine = doc->LineEnd(line);
-               if (increment == 1) {
-                       if (line == lineRangeStart) {
-                               if ((startPos != startOfLine) && (s[0] == '^'))
+       Sci::Position pos = -1;
+       Sci::Position lenRet = 0;
+       const char searchEnd = s[*length - 1];
+       const char searchEndPrev = (*length > 1) ? s[*length - 2] : '\0';
+       for (Sci::Line line = resr.lineRangeStart; line != resr.lineRangeBreak; line += resr.increment) {
+               Sci::Position startOfLine = doc->LineStart(line);
+               Sci::Position endOfLine = doc->LineEnd(line);
+               if (resr.increment == 1) {
+                       if (line == resr.lineRangeStart) {
+                               if ((resr.startPos != startOfLine) && (s[0] == '^'))
                                        continue;       // Can't match start of line if start position after 
start of line
-                               startOfLine = startPos;
+                               startOfLine = resr.startPos;
                        }
-                       if (line == lineRangeEnd) {
-                               if ((endPos != endOfLine) && (searchEnd == '$') && (searchEndPrev != '\\'))
+                       if (line == resr.lineRangeEnd) {
+                               if ((resr.endPos != endOfLine) && (searchEnd == '$') && (searchEndPrev != 
'\\'))
                                        continue;       // Can't match end of line if end position before end 
of line
-                               endOfLine = endPos;
+                               endOfLine = resr.endPos;
                        }
                } else {
-                       if (line == lineRangeEnd) {
-                               if ((endPos != startOfLine) && (s[0] == '^'))
+                       if (line == resr.lineRangeEnd) {
+                               if ((resr.endPos != startOfLine) && (s[0] == '^'))
                                        continue;       // Can't match start of line if end position after 
start of line
-                               startOfLine = endPos;
+                               startOfLine = resr.endPos;
                        }
-                       if (line == lineRangeStart) {
-                               if ((startPos != endOfLine) && (searchEnd == '$') && (searchEndPrev != '\\'))
+                       if (line == resr.lineRangeStart) {
+                               if ((resr.startPos != endOfLine) && (searchEnd == '$') && (searchEndPrev != 
'\\'))
                                        continue;       // Can't match end of line if start position before 
end of line
-                               endOfLine = startPos;
+                               endOfLine = resr.startPos;
                        }
                }
 
@@ -2206,7 +3010,7 @@ long BuiltinRegex::FindText(Document *doc, int minPos, int maxPos, const char *s
                        search.eopat[0] = doc->MovePositionOutsideChar(search.eopat[0], 1, false);
                        lenRet = search.eopat[0] - search.bopat[0];
                        // There can be only one start of a line, so no need to look for last match in line
-                       if ((increment == -1) && (s[0] != '^')) {
+                       if ((resr.increment == -1) && (s[0] != '^')) {
                                // Check for the last match on this line.
                                int repetitions = 1000; // Break out of infinite loop
                                while (success && (search.eopat[0] <= endOfLine) && (repetitions--)) {
@@ -2228,7 +3032,7 @@ long BuiltinRegex::FindText(Document *doc, int minPos, int maxPos, const char *s
        return pos;
 }
 
-const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text, int *length) {
+const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) {
        substituted.clear();
        DocumentIndexer di(doc, doc->Length());
        search.GrabMatches(di);
@@ -2236,7 +3040,7 @@ const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text,
                if (text[j] == '\\') {
                        if (text[j + 1] >= '0' && text[j + 1] <= '9') {
                                unsigned int patNum = text[j + 1] - '0';
-                               unsigned int len = search.eopat[patNum] - search.bopat[patNum];
+                               Sci::Position len = search.eopat[patNum] - search.bopat[patNum];
                                if (!search.pat[patNum].empty())        // Will be null if try for a match 
that did not occur
                                        substituted.append(search.pat[patNum].c_str(), len);
                                j++;
diff --git a/plugins/scintilla/scintilla/src/Document.h b/plugins/scintilla/scintilla/src/Document.h
index 5147875..025b010 100644
--- a/plugins/scintilla/scintilla/src/Document.h
+++ b/plugins/scintilla/scintilla/src/Document.h
@@ -12,12 +12,7 @@
 namespace Scintilla {
 #endif
 
-/**
- * A Position is a position within a document between two characters or at the beginning or end.
- * Sometimes used as a character index where it identifies the character after the position.
- */
-typedef int Position;
-const Position invalidPosition = -1;
+enum EncodingFamily { efEightBit, efUnicode, efDBCS };
 
 /**
  * The range class represents a range of text in a document.
@@ -27,22 +22,34 @@ const Position invalidPosition = -1;
  */
 class Range {
 public:
-       Position start;
-       Position end;
+       Sci::Position start;
+       Sci::Position end;
 
-       Range(Position pos=0) :
+       explicit Range(Sci::Position pos=0) :
                start(pos), end(pos) {
        }
-       Range(Position start_, Position end_) :
+       Range(Sci::Position start_, Sci::Position end_) :
                start(start_), end(end_) {
        }
 
+       bool operator==(const Range &other) const {
+               return (start == other.start) && (end == other.end);
+       }
+
        bool Valid() const {
-               return (start != invalidPosition) && (end != invalidPosition);
+               return (start != Sci::invalidPosition) && (end != Sci::invalidPosition);
+       }
+
+       Sci::Position First() const {
+               return (start <= end) ? start : end;
+       }
+
+       Sci::Position Last() const {
+               return (start > end) ? start : end;
        }
 
        // Is the position within the range?
-       bool Contains(Position pos) const {
+       bool Contains(Sci::Position pos) const {
                if (start < end) {
                        return (pos >= start && pos <= end);
                } else {
@@ -51,7 +58,7 @@ public:
        }
 
        // Is the character after pos within the range?
-       bool ContainsCharacter(Position pos) const {
+       bool ContainsCharacter(Sci::Position pos) const {
                if (start < end) {
                        return (pos >= start && pos < end);
                } else {
@@ -83,11 +90,11 @@ class RegexSearchBase {
 public:
        virtual ~RegexSearchBase() {}
 
-       virtual long FindText(Document *doc, int minPos, int maxPos, const char *s,
-                        bool caseSensitive, bool word, bool wordStart, int flags, int *length) = 0;
+       virtual long FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
+                        bool caseSensitive, bool word, bool wordStart, int flags, Sci::Position *length) = 0;
 
        ///@return String with the substitutions, must remain valid until the next call or destruction
-       virtual const char *SubstituteByPosition(Document *doc, const char *text, int *length) = 0;
+       virtual const char *SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) = 0;
 };
 
 /// Factory function for RegexSearchBase
@@ -128,34 +135,42 @@ public:
                firstChangeableLineAfter = -1;
        }
 
-       bool NeedsDrawing(int line) const {
+       bool NeedsDrawing(Sci::Line line) const {
                return isEnabled && (line <= firstChangeableLineBefore || line >= firstChangeableLineAfter);
        }
 
-       bool IsFoldBlockHighlighted(int line) const {
+       bool IsFoldBlockHighlighted(Sci::Line line) const {
                return isEnabled && beginFoldBlock != -1 && beginFoldBlock <= line && line <= endFoldBlock;
        }
 
-       bool IsHeadOfFoldBlock(int line) const {
+       bool IsHeadOfFoldBlock(Sci::Line line) const {
                return beginFoldBlock == line && line < endFoldBlock;
        }
 
-       bool IsBodyOfFoldBlock(int line) const {
+       bool IsBodyOfFoldBlock(Sci::Line line) const {
                return beginFoldBlock != -1 && beginFoldBlock < line && line < endFoldBlock;
        }
 
-       bool IsTailOfFoldBlock(int line) const {
+       bool IsTailOfFoldBlock(Sci::Line line) const {
                return beginFoldBlock != -1 && beginFoldBlock < line && line == endFoldBlock;
        }
 
-       int beginFoldBlock;     // Begin of current fold block
-       int endFoldBlock;       // End of current fold block
-       int firstChangeableLineBefore;  // First line that triggers repaint before starting line that 
determined current fold block
-       int firstChangeableLineAfter;   // First line that triggers repaint after starting line that 
determined current fold block
+       Sci::Line beginFoldBlock;       // Begin of current fold block
+       Sci::Line endFoldBlock; // End of current fold block
+       Sci::Line firstChangeableLineBefore;    // First line that triggers repaint before starting line that 
determined current fold block
+       Sci::Line firstChangeableLineAfter;     // First line that triggers repaint after starting line that 
determined current fold block
        bool isEnabled;
 };
 
 class Document;
+class LineMarkers;
+class LineLevels;
+class LineState;
+class LineAnnotation;
+
+inline int LevelNumber(int level) {
+       return level & SC_FOLDLEVELNUMBERMASK;
+}
 
 class LexInterface {
 protected:
@@ -163,17 +178,21 @@ protected:
        ILexer *instance;
        bool performingStyle;   ///< Prevent reentrance
 public:
-       LexInterface(Document *pdoc_) : pdoc(pdoc_), instance(0), performingStyle(false) {
+       explicit LexInterface(Document *pdoc_) : pdoc(pdoc_), instance(0), performingStyle(false) {
        }
        virtual ~LexInterface() {
        }
-       void Colourise(int start, int end);
+       void Colourise(Sci::Position start, Sci::Position end);
        int LineEndTypesSupported();
        bool UseContainerLexing() const {
                return instance == 0;
        }
 };
 
+struct RegexError : public std::runtime_error {
+       RegexError() : std::runtime_error("regex failure") {}
+};
+
 /**
  */
 class Document : PerLine, public IDocumentWithLineEnd, public ILoader {
@@ -195,29 +214,44 @@ private:
        int refCount;
        CellBuffer cb;
        CharClassify charClass;
-       CaseFolder *pcf;
-       char stylingMask;
-       int endStyled;
+       std::unique_ptr<CaseFolder> pcf;
+       Sci::Position endStyled;
        int styleClock;
        int enteredModification;
        int enteredStyling;
        int enteredReadOnlyCount;
 
+       bool insertionSet;
+       std::string insertion;
+
        std::vector<WatcherWithUserData> watchers;
 
        // ldSize is not real data - it is for dimensions and loops
        enum lineData { ldMarkers, ldLevels, ldState, ldMargin, ldAnnotation, ldSize };
-       PerLine *perLineData[ldSize];
+       std::unique_ptr<PerLine> perLineData[ldSize];
+       LineMarkers *Markers() const;
+       LineLevels *Levels() const;
+       LineState *States() const;
+       LineAnnotation *Margins() const;
+       LineAnnotation *Annotations() const;
 
        bool matchesValid;
-       RegexSearchBase *regex;
+       std::unique_ptr<RegexSearchBase> regex;
+       std::unique_ptr<LexInterface> pli;
 
 public:
 
-       LexInterface *pli;
-
-       int stylingBits;
-       int stylingBitsMask;
+       struct CharacterExtracted {
+               unsigned int character;
+               unsigned int widthBytes;
+               CharacterExtracted(unsigned int character_, unsigned int widthBytes_) :
+                       character(character_), widthBytes(widthBytes_) {
+               }
+               // For DBCS characters turn 2 bytes into an int
+               static CharacterExtracted DBCS(unsigned char lead, unsigned char trail) {
+                       return CharacterExtracted((lead << 8) | trail, 2);
+               }
+       };
 
        int eolMode;
        /// Can also be SC_CP_UTF8 to enable UTF-8 mode
@@ -229,10 +263,14 @@ public:
        bool useTabs;
        bool tabIndents;
        bool backspaceUnindents;
+       double durationStyleOneLine;
 
        DecorationList decorations;
 
        Document();
+       // Deleted so Document objects can not be copied.
+       Document(const Document &) = delete;
+       void operator=(const Document &) = delete;
        virtual ~Document();
 
        int AddRef();
@@ -244,8 +282,8 @@ public:
        int GetLineEndTypesAllowed() const { return cb.GetLineEndTypes(); }
        bool SetLineEndTypesAllowed(int lineEndBitSet_);
        int GetLineEndTypesActive() const { return cb.GetLineEndTypes(); }
-       virtual void InsertLine(int line);
-       virtual void RemoveLine(int line);
+       virtual void InsertLine(Sci::Line line);
+       virtual void RemoveLine(Sci::Line line);
 
        int SCI_METHOD Version() const {
                return dvLineEnd;
@@ -253,29 +291,35 @@ public:
 
        void SCI_METHOD SetErrorStatus(int status);
 
-       int SCI_METHOD LineFromPosition(int pos) const;
-       int ClampPositionIntoDocument(int pos) const;
-       bool IsCrLf(int pos) const;
-       int LenChar(int pos);
-       bool InGoodUTF8(int pos, int &start, int &end) const;
-       int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true);
-       int NextPosition(int pos, int moveDir) const;
-       bool NextCharacter(int &pos, int moveDir) const;        // Returns true if pos changed
-       int SCI_METHOD GetRelativePosition(int positionStart, int characterOffset) const;
-       int SCI_METHOD GetCharacterAndWidth(int position, int *pWidth) const;
+       Sci_Position SCI_METHOD LineFromPosition(Sci_Position pos) const;
+       Sci::Position ClampPositionIntoDocument(Sci::Position pos) const;
+       bool ContainsLineEnd(const char *s, Sci::Position length) const { return cb.ContainsLineEnd(s, 
length); }
+       bool IsCrLf(Sci::Position pos) const;
+       int LenChar(Sci::Position pos);
+       bool InGoodUTF8(Sci::Position pos, Sci::Position &start, Sci::Position &end) const;
+       Sci::Position MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool 
checkLineEnd=true) const;
+       Sci::Position NextPosition(Sci::Position pos, int moveDir) const;
+       bool NextCharacter(Sci::Position &pos, int moveDir) const;      // Returns true if pos changed
+       Document::CharacterExtracted CharacterAfter(Sci::Position position) const;
+       Document::CharacterExtracted CharacterBefore(Sci::Position position) const;
+       Sci_Position SCI_METHOD GetRelativePosition(Sci_Position positionStart, Sci_Position characterOffset) 
const;
+       Sci::Position GetRelativePositionUTF16(Sci::Position positionStart, Sci::Position characterOffset) 
const;
+       int SCI_METHOD GetCharacterAndWidth(Sci_Position position, Sci_Position *pWidth) const;
        int SCI_METHOD CodePage() const;
        bool SCI_METHOD IsDBCSLeadByte(char ch) const;
        int SafeSegment(const char *text, int length, int lengthSegment) const;
+       EncodingFamily CodePageFamily() const;
 
        // Gateways to modifying document
-       void ModifiedAt(int pos);
+       void ModifiedAt(Sci::Position pos);
        void CheckReadOnly();
-       bool DeleteChars(int pos, int len);
-       bool InsertString(int position, const char *s, int insertLength);
-       int SCI_METHOD AddData(char *data, int length);
+       bool DeleteChars(Sci::Position pos, Sci::Position len);
+       Sci::Position InsertString(Sci::Position position, const char *s, Sci::Position insertLength);
+       void ChangeInsertion(const char *s, Sci::Position length);
+       int SCI_METHOD AddData(char *data, Sci_Position length);
        void * SCI_METHOD ConvertToDocument();
-       int Undo();
-       int Redo();
+       Sci::Position Undo();
+       Sci::Position Redo();
        bool CanUndo() const { return cb.CanUndo(); }
        bool CanRedo() const { return cb.CanRedo(); }
        void DeleteUndoHistory() { cb.DeleteUndoHistory(); }
@@ -285,128 +329,137 @@ public:
        bool IsCollectingUndo() const { return cb.IsCollectingUndo(); }
        void BeginUndoAction() { cb.BeginUndoAction(); }
        void EndUndoAction() { cb.EndUndoAction(); }
-       void AddUndoAction(int token, bool mayCoalesce) { cb.AddUndoAction(token, mayCoalesce); }
+       void AddUndoAction(Sci::Position token, bool mayCoalesce) { cb.AddUndoAction(token, mayCoalesce); }
        void SetSavePoint();
        bool IsSavePoint() const { return cb.IsSavePoint(); }
+
+       void TentativeStart() { cb.TentativeStart(); }
+       void TentativeCommit() { cb.TentativeCommit(); }
+       void TentativeUndo();
+       bool TentativeActive() const { return cb.TentativeActive(); }
+
        const char * SCI_METHOD BufferPointer() { return cb.BufferPointer(); }
-       const char *RangePointer(int position, int rangeLength) { return cb.RangePointer(position, 
rangeLength); }
-       int GapPosition() const { return cb.GapPosition(); }
-
-       int SCI_METHOD GetLineIndentation(int line);
-       void SetLineIndentation(int line, int indent);
-       int GetLineIndentPosition(int line) const;
-       int GetColumn(int position);
-       int CountCharacters(int startPos, int endPos);
-       int FindColumn(int line, int column);
-       void Indent(bool forwards, int lineBottom, int lineTop);
+       const char *RangePointer(Sci::Position position, Sci::Position rangeLength) { return 
cb.RangePointer(position, rangeLength); }
+       Sci::Position GapPosition() const { return cb.GapPosition(); }
+
+       int SCI_METHOD GetLineIndentation(Sci_Position line);
+       Sci::Position SetLineIndentation(Sci::Line line, Sci::Position indent);
+       Sci::Position GetLineIndentPosition(Sci::Line line) const;
+       Sci::Position GetColumn(Sci::Position pos);
+       Sci::Position CountCharacters(Sci::Position startPos, Sci::Position endPos) const;
+       Sci::Position CountUTF16(Sci::Position startPos, Sci::Position endPos) const;
+       Sci::Position FindColumn(Sci::Line line, Sci::Position column);
+       void Indent(bool forwards, Sci::Line lineBottom, Sci::Line lineTop);
        static std::string TransformLineEnds(const char *s, size_t len, int eolModeWanted);
        void ConvertLineEnds(int eolModeSet);
        void SetReadOnly(bool set) { cb.SetReadOnly(set); }
        bool IsReadOnly() const { return cb.IsReadOnly(); }
 
-       bool InsertChar(int pos, char ch);
-       bool InsertCString(int position, const char *s);
-       void DelChar(int pos);
-       void DelCharBack(int pos);
+       void DelChar(Sci::Position pos);
+       void DelCharBack(Sci::Position pos);
 
-       char CharAt(int position) const { return cb.CharAt(position); }
-       void SCI_METHOD GetCharRange(char *buffer, int position, int lengthRetrieve) const {
+       char CharAt(Sci::Position position) const { return cb.CharAt(position); }
+       void SCI_METHOD GetCharRange(char *buffer, Sci_Position position, Sci_Position lengthRetrieve) const {
                cb.GetCharRange(buffer, position, lengthRetrieve);
        }
-       char SCI_METHOD StyleAt(int position) const { return cb.StyleAt(position); }
-       void GetStyleRange(unsigned char *buffer, int position, int lengthRetrieve) const {
+       char SCI_METHOD StyleAt(Sci_Position position) const { return cb.StyleAt(position); }
+       int StyleIndexAt(Sci_Position position) const { return static_cast<unsigned 
char>(cb.StyleAt(position)); }
+       void GetStyleRange(unsigned char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const 
{
                cb.GetStyleRange(buffer, position, lengthRetrieve);
        }
-       int GetMark(int line);
-       int MarkerNext(int lineStart, int mask) const;
-       int AddMark(int line, int markerNum);
-       void AddMarkSet(int line, int valueSet);
-       void DeleteMark(int line, int markerNum);
+       int GetMark(Sci::Line line) const;
+       Sci::Line MarkerNext(Sci::Line lineStart, int mask) const;
+       int AddMark(Sci::Line line, int markerNum);
+       void AddMarkSet(Sci::Line line, int valueSet);
+       void DeleteMark(Sci::Line line, int markerNum);
        void DeleteMarkFromHandle(int markerHandle);
        void DeleteAllMarks(int markerNum);
-       int LineFromHandle(int markerHandle);
-       int SCI_METHOD LineStart(int line) const;
-       int SCI_METHOD LineEnd(int line) const;
-       int LineEndPosition(int position) const;
-       bool IsLineEndPosition(int position) const;
-       bool IsPositionInLineEnd(int position) const;
-       int VCHomePosition(int position) const;
-
-       int SCI_METHOD SetLevel(int line, int level);
-       int SCI_METHOD GetLevel(int line) const;
+       Sci::Line LineFromHandle(int markerHandle) const;
+       Sci_Position SCI_METHOD LineStart(Sci_Position line) const;
+       bool IsLineStartPosition(Sci::Position position) const;
+       Sci_Position SCI_METHOD LineEnd(Sci_Position line) const;
+       Sci::Position LineEndPosition(Sci::Position position) const;
+       bool IsLineEndPosition(Sci::Position position) const;
+       bool IsPositionInLineEnd(Sci::Position position) const;
+       Sci::Position VCHomePosition(Sci::Position position) const;
+
+       int SCI_METHOD SetLevel(Sci_Position line, int level);
+       int SCI_METHOD GetLevel(Sci_Position line) const;
        void ClearLevels();
-       int GetLastChild(int lineParent, int level=-1, int lastLine=-1);
-       int GetFoldParent(int line) const;
-       void GetHighlightDelimiters(HighlightDelimiter &hDelimiter, int line, int lastLine);
-
-       void Indent(bool forwards);
-       int ExtendWordSelect(int pos, int delta, bool onlyWordCharacters=false);
-       int NextWordStart(int pos, int delta);
-       int NextWordEnd(int pos, int delta);
-       int SCI_METHOD Length() const { return cb.Length(); }
-       void Allocate(int newSize) { cb.Allocate(newSize); }
-       bool MatchesWordOptions(bool word, bool wordStart, int pos, int length) const;
-       bool HasCaseFolder(void) const;
+       Sci::Line GetLastChild(Sci::Line lineParent, int level=-1, Sci::Line lastLine=-1);
+       Sci::Line GetFoldParent(Sci::Line line) const;
+       void GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, Sci::Line line, Sci::Line 
lastLine);
+
+       Sci::Position ExtendWordSelect(Sci::Position pos, int delta, bool onlyWordCharacters=false) const;
+       Sci::Position NextWordStart(Sci::Position pos, int delta) const;
+       Sci::Position NextWordEnd(Sci::Position pos, int delta) const;
+       Sci_Position SCI_METHOD Length() const { return cb.Length(); }
+       void Allocate(Sci::Position newSize) { cb.Allocate(newSize); }
+
+       CharacterExtracted ExtractCharacter(Sci::Position position) const;
+
+       bool IsWordStartAt(Sci::Position pos) const;
+       bool IsWordEndAt(Sci::Position pos) const;
+       bool IsWordAt(Sci::Position start, Sci::Position end) const;
+
+       bool MatchesWordOptions(bool word, bool wordStart, Sci::Position pos, Sci::Position length) const;
+       bool HasCaseFolder() const;
        void SetCaseFolder(CaseFolder *pcf_);
-       long FindText(int minPos, int maxPos, const char *search, bool caseSensitive, bool word,
-               bool wordStart, bool regExp, int flags, int *length);
-       const char *SubstituteByPosition(const char *text, int *length);
-       int LinesTotal() const;
+       long FindText(Sci::Position minPos, Sci::Position maxPos, const char *search, int flags, 
Sci::Position *length);
+       const char *SubstituteByPosition(const char *text, Sci::Position *length);
+       Sci::Line LinesTotal() const;
 
        void SetDefaultCharClasses(bool includeWordClass);
        void SetCharClasses(const unsigned char *chars, CharClassify::cc newCharClass);
-       int GetCharsOfClass(CharClassify::cc charClass, unsigned char *buffer);
-       void SetStylingBits(int bits);
-       void SCI_METHOD StartStyling(int position, char mask);
-       bool SCI_METHOD SetStyleFor(int length, char style);
-       bool SCI_METHOD SetStyles(int length, const char *styles);
-       int GetEndStyled() const { return endStyled; }
-       void EnsureStyledTo(int pos);
+       int GetCharsOfClass(CharClassify::cc characterClass, unsigned char *buffer) const;
+       void SCI_METHOD StartStyling(Sci_Position position, char mask);
+       bool SCI_METHOD SetStyleFor(Sci_Position length, char style);
+       bool SCI_METHOD SetStyles(Sci_Position length, const char *styles);
+       Sci::Position GetEndStyled() const { return endStyled; }
+       void EnsureStyledTo(Sci::Position pos);
+       void StyleToAdjustingLineDuration(Sci::Position pos);
        void LexerChanged();
        int GetStyleClock() const { return styleClock; }
        void IncrementStyleClock();
-       void SCI_METHOD DecorationSetCurrentIndicator(int indicator) {
-               decorations.SetCurrentIndicator(indicator);
-       }
-       void SCI_METHOD DecorationFillRange(int position, int value, int fillLength);
-
-       int SCI_METHOD SetLineState(int line, int state);
-       int SCI_METHOD GetLineState(int line) const;
-       int GetMaxLineState();
-       void SCI_METHOD ChangeLexerState(int start, int end);
-
-       StyledText MarginStyledText(int line) const;
-       void MarginSetStyle(int line, int style);
-       void MarginSetStyles(int line, const unsigned char *styles);
-       void MarginSetText(int line, const char *text);
+       void SCI_METHOD DecorationSetCurrentIndicator(int indicator);
+       void SCI_METHOD DecorationFillRange(Sci_Position position, int value, Sci_Position fillLength);
+       LexInterface *GetLexInterface() const;
+       void SetLexInterface(LexInterface *pLexInterface);
+
+       int SCI_METHOD SetLineState(Sci_Position line, int state);
+       int SCI_METHOD GetLineState(Sci_Position line) const;
+       Sci::Line GetMaxLineState() const;
+       void SCI_METHOD ChangeLexerState(Sci_Position start, Sci_Position end);
+
+       StyledText MarginStyledText(Sci::Line line) const;
+       void MarginSetStyle(Sci::Line line, int style);
+       void MarginSetStyles(Sci::Line line, const unsigned char *styles);
+       void MarginSetText(Sci::Line line, const char *text);
        void MarginClearAll();
 
-       StyledText AnnotationStyledText(int line) const;
-       void AnnotationSetText(int line, const char *text);
-       void AnnotationSetStyle(int line, int style);
-       void AnnotationSetStyles(int line, const unsigned char *styles);
-       int AnnotationLines(int line) const;
+       StyledText AnnotationStyledText(Sci::Line line) const;
+       void AnnotationSetText(Sci::Line line, const char *text);
+       void AnnotationSetStyle(Sci::Line line, int style);
+       void AnnotationSetStyles(Sci::Line line, const unsigned char *styles);
+       int AnnotationLines(Sci::Line line) const;
        void AnnotationClearAll();
 
        bool AddWatcher(DocWatcher *watcher, void *userData);
        bool RemoveWatcher(DocWatcher *watcher, void *userData);
 
-       CharClassify::cc WordCharClass(unsigned char ch) const;
-       bool IsWordPartSeparator(char ch) const;
-       int WordPartLeft(int pos);
-       int WordPartRight(int pos);
-       int ExtendStyleRange(int pos, int delta, bool singleLine = false);
-       bool IsWhiteLine(int line) const;
-       int ParaUp(int pos) const;
-       int ParaDown(int pos) const;
+       bool IsASCIIWordByte(unsigned char ch) const;
+       CharClassify::cc WordCharacterClass(unsigned int ch) const;
+       bool IsWordPartSeparator(unsigned int ch) const;
+       Sci::Position WordPartLeft(Sci::Position pos) const;
+       Sci::Position WordPartRight(Sci::Position pos) const;
+       Sci::Position ExtendStyleRange(Sci::Position pos, int delta, bool singleLine = false);
+       bool IsWhiteLine(Sci::Line line) const;
+       Sci::Position ParaUp(Sci::Position pos) const;
+       Sci::Position ParaDown(Sci::Position pos) const;
        int IndentSize() const { return actualIndentInChars; }
-       int BraceMatch(int position, int maxReStyle);
+       Sci::Position BraceMatch(Sci::Position position, Sci::Position maxReStyle);
 
 private:
-       bool IsWordStartAt(int pos) const;
-       bool IsWordEndAt(int pos) const;
-       bool IsWordAt(int start, int end) const;
-
        void NotifyModifyAttempt();
        void NotifySavePoint(bool atSavePoint);
        void NotifyModified(DocModification mh);
@@ -440,19 +493,19 @@ public:
  */
 class DocModification {
 public:
-       int modificationType;
-       int position;
-       int length;
-       int linesAdded; /**< Negative if lines deleted. */
-       const char *text;       /**< Only valid for changes to text, not for changes to style. */
-       int line;
+       int modificationType;
+       Sci::Position position;
+       Sci::Position length;
+       Sci::Line linesAdded;   /**< Negative if lines deleted. */
+       const char *text;       /**< Only valid for changes to text, not for changes to style. */
+       Sci::Line line;
        int foldLevelNow;
        int foldLevelPrev;
-       int annotationLinesAdded;
-       int token;
+       Sci::Line annotationLinesAdded;
+       Sci::Position token;
 
-       DocModification(int modificationType_, int position_=0, int length_=0,
-               int linesAdded_=0, const char *text_=0, int line_=0) :
+       DocModification(int modificationType_, Sci::Position position_=0, Sci::Position length_=0,
+               Sci::Line linesAdded_=0, const char *text_=0, Sci::Line line_=0) :
                modificationType(modificationType_),
                position(position_),
                length(length_),
@@ -464,12 +517,12 @@ public:
                annotationLinesAdded(0),
                token(0) {}
 
-       DocModification(int modificationType_, const Action &act, int linesAdded_=0) :
+       DocModification(int modificationType_, const Action &act, Sci::Line linesAdded_=0) :
                modificationType(modificationType_),
                position(act.position),
                length(act.lenData),
                linesAdded(linesAdded_),
-               text(act.data),
+               text(act.data.get()),
                line(0),
                foldLevelNow(0),
                foldLevelPrev(0),
@@ -489,7 +542,7 @@ public:
        virtual void NotifySavePoint(Document *doc, void *userData, bool atSavePoint) = 0;
        virtual void NotifyModified(Document *doc, DocModification mh, void *userData) = 0;
        virtual void NotifyDeleted(Document *doc, void *userData) = 0;
-       virtual void NotifyStyleNeeded(Document *doc, void *userData, int endPos) = 0;
+       virtual void NotifyStyleNeeded(Document *doc, void *userData, Sci::Position endPos) = 0;
        virtual void NotifyLexerChanged(Document *doc, void *userData) = 0;
        virtual void NotifyErrorOccurred(Document *doc, void *userData, int status) = 0;
 };
diff --git a/plugins/scintilla/scintilla/src/EditModel.cxx b/plugins/scintilla/scintilla/src/EditModel.cxx
new file mode 100644
index 0000000..faf2162
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/EditModel.cxx
@@ -0,0 +1,79 @@
+// Scintilla source code edit control
+/** @file EditModel.cxx
+ ** Defines the editor state that must be visible to EditorView.
+ **/
+// Copyright 1998-2014 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cmath>
+
+#include <stdexcept>
+#include <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+#include <memory>
+
+#include "Platform.h"
+
+#include "ILexer.h"
+#include "Scintilla.h"
+
+#include "StringCopy.h"
+#include "Position.h"
+#include "UniqueString.h"
+#include "SplitVector.h"
+#include "Partitioning.h"
+#include "RunStyles.h"
+#include "ContractionState.h"
+#include "CellBuffer.h"
+#include "KeyMap.h"
+#include "Indicator.h"
+#include "XPM.h"
+#include "LineMarker.h"
+#include "Style.h"
+#include "ViewStyle.h"
+#include "CharClassify.h"
+#include "Decoration.h"
+#include "CaseFolder.h"
+#include "Document.h"
+#include "UniConversion.h"
+#include "Selection.h"
+#include "PositionCache.h"
+#include "EditModel.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+Caret::Caret() :
+       active(false), on(false), period(500) {}
+
+EditModel::EditModel() {
+       inOverstrike = false;
+       xOffset = 0;
+       trackLineWidth = false;
+       posDrag = SelectionPosition(Sci::invalidPosition);
+       braces[0] = Sci::invalidPosition;
+       braces[1] = Sci::invalidPosition;
+       bracesMatchStyle = STYLE_BRACEBAD;
+       highlightGuideColumn = 0;
+       primarySelection = true;
+       imeInteraction = imeWindowed;
+       foldFlags = 0;
+       foldDisplayTextStyle = SC_FOLDDISPLAYTEXT_HIDDEN;
+       hotspot = Range(Sci::invalidPosition);
+       hoverIndicatorPos = Sci::invalidPosition;
+       wrapWidth = LineLayout::wrapWidthInfinite;
+       pdoc = new Document();
+       pdoc->AddRef();
+}
+
+EditModel::~EditModel() {
+       pdoc->Release();
+       pdoc = 0;
+}
diff --git a/plugins/scintilla/scintilla/src/EditModel.h b/plugins/scintilla/scintilla/src/EditModel.h
new file mode 100644
index 0000000..087cf49
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/EditModel.h
@@ -0,0 +1,70 @@
+// Scintilla source code edit control
+/** @file EditModel.h
+ ** Defines the editor state that must be visible to EditorView.
+ **/
+// Copyright 1998-2014 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef EDITMODEL_H
+#define EDITMODEL_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+/**
+*/
+class Caret {
+public:
+       bool active;
+       bool on;
+       int period;
+
+       Caret();
+};
+
+class EditModel {
+public:
+       bool inOverstrike;
+       int xOffset;            ///< Horizontal scrolled amount in pixels
+       bool trackLineWidth;
+
+       SpecialRepresentations reprs;
+       Caret caret;
+       SelectionPosition posDrag;
+       Sci::Position braces[2];
+       int bracesMatchStyle;
+       int highlightGuideColumn;
+       Selection sel;
+       bool primarySelection;
+
+       enum IMEInteraction { imeWindowed, imeInline } imeInteraction;
+
+       int foldFlags;
+       int foldDisplayTextStyle;
+       ContractionState cs;
+       // Hotspot support
+       Range hotspot;
+       Sci::Position hoverIndicatorPos;
+
+       // Wrapping support
+       int wrapWidth;
+
+       Document *pdoc;
+
+       EditModel();
+       // Deleted so EditModel objects can not be copied.
+       explicit EditModel(const EditModel &) = delete;
+       EditModel &operator=(const EditModel &) = delete;
+       virtual ~EditModel();
+       virtual Sci::Line TopLineOfMain() const = 0;
+       virtual Point GetVisibleOriginInMain() const = 0;
+       virtual Sci::Line LinesOnScreen() const = 0;
+       virtual Range GetHotSpotRange() const = 0;
+};
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/EditView.cxx b/plugins/scintilla/scintilla/src/EditView.cxx
new file mode 100644
index 0000000..b3815ff
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/EditView.cxx
@@ -0,0 +1,2371 @@
+// Scintilla source code edit control
+/** @file EditView.cxx
+ ** Defines the appearance of the main text area of the editor window.
+ **/
+// Copyright 1998-2014 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cctype>
+#include <cstdio>
+#include <cmath>
+
+#include <stdexcept>
+#include <string>
+#include <vector>
+#include <map>
+#include <forward_list>
+#include <algorithm>
+#include <memory>
+
+#include "Platform.h"
+
+#include "ILexer.h"
+#include "Scintilla.h"
+
+#include "StringCopy.h"
+#include "CharacterSet.h"
+#include "Position.h"
+#include "UniqueString.h"
+#include "SplitVector.h"
+#include "Partitioning.h"
+#include "RunStyles.h"
+#include "ContractionState.h"
+#include "CellBuffer.h"
+#include "PerLine.h"
+#include "KeyMap.h"
+#include "Indicator.h"
+#include "XPM.h"
+#include "LineMarker.h"
+#include "Style.h"
+#include "ViewStyle.h"
+#include "CharClassify.h"
+#include "Decoration.h"
+#include "CaseFolder.h"
+#include "Document.h"
+#include "UniConversion.h"
+#include "Selection.h"
+#include "PositionCache.h"
+#include "EditModel.h"
+#include "MarginView.h"
+#include "EditView.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static inline bool IsControlCharacter(int ch) {
+       // iscntrl returns true for lots of chars > 127 which are displayable
+       return ch >= 0 && ch < ' ';
+}
+
+PrintParameters::PrintParameters() {
+       magnification = 0;
+       colourMode = SC_PRINT_NORMAL;
+       wrapState = eWrapWord;
+}
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+bool ValidStyledText(const ViewStyle &vs, size_t styleOffset, const StyledText &st) {
+       if (st.multipleStyles) {
+               for (size_t iStyle = 0; iStyle<st.length; iStyle++) {
+                       if (!vs.ValidStyle(styleOffset + st.styles[iStyle]))
+                               return false;
+               }
+       } else {
+               if (!vs.ValidStyle(styleOffset + st.style))
+                       return false;
+       }
+       return true;
+}
+
+static int WidthStyledText(Surface *surface, const ViewStyle &vs, int styleOffset,
+       const char *text, const unsigned char *styles, size_t len) {
+       int width = 0;
+       size_t start = 0;
+       while (start < len) {
+               size_t style = styles[start];
+               size_t endSegment = start;
+               while ((endSegment + 1 < len) && (static_cast<size_t>(styles[endSegment + 1]) == style))
+                       endSegment++;
+               FontAlias fontText = vs.styles[style + styleOffset].font;
+               width += static_cast<int>(surface->WidthText(fontText, text + start,
+                       static_cast<int>(endSegment - start + 1)));
+               start = endSegment + 1;
+       }
+       return width;
+}
+
+int WidestLineWidth(Surface *surface, const ViewStyle &vs, int styleOffset, const StyledText &st) {
+       int widthMax = 0;
+       size_t start = 0;
+       while (start < st.length) {
+               size_t lenLine = st.LineLength(start);
+               int widthSubLine;
+               if (st.multipleStyles) {
+                       widthSubLine = WidthStyledText(surface, vs, styleOffset, st.text + start, st.styles + 
start, lenLine);
+               } else {
+                       FontAlias fontText = vs.styles[styleOffset + st.style].font;
+                       widthSubLine = static_cast<int>(surface->WidthText(fontText,
+                               st.text + start, static_cast<int>(lenLine)));
+               }
+               if (widthSubLine > widthMax)
+                       widthMax = widthSubLine;
+               start += lenLine + 1;
+       }
+       return widthMax;
+}
+
+void DrawTextNoClipPhase(Surface *surface, PRectangle rc, const Style &style, XYPOSITION ybase,
+       const char *s, int len, DrawPhase phase) {
+       FontAlias fontText = style.font;
+       if (phase & drawBack) {
+               if (phase & drawText) {
+                       // Drawing both
+                       surface->DrawTextNoClip(rc, fontText, ybase, s, len,
+                               style.fore, style.back);
+               } else {
+                       surface->FillRectangle(rc, style.back);
+               }
+       } else if (phase & drawText) {
+               surface->DrawTextTransparent(rc, fontText, ybase, s, len, style.fore);
+       }
+}
+
+void DrawStyledText(Surface *surface, const ViewStyle &vs, int styleOffset, PRectangle rcText,
+       const StyledText &st, size_t start, size_t length, DrawPhase phase) {
+
+       if (st.multipleStyles) {
+               int x = static_cast<int>(rcText.left);
+               size_t i = 0;
+               while (i < length) {
+                       size_t end = i;
+                       size_t style = st.styles[i + start];
+                       while (end < length - 1 && st.styles[start + end + 1] == style)
+                               end++;
+                       style += styleOffset;
+                       FontAlias fontText = vs.styles[style].font;
+                       const int width = static_cast<int>(surface->WidthText(fontText,
+                               st.text + start + i, static_cast<int>(end - i + 1)));
+                       PRectangle rcSegment = rcText;
+                       rcSegment.left = static_cast<XYPOSITION>(x);
+                       rcSegment.right = static_cast<XYPOSITION>(x + width + 1);
+                       DrawTextNoClipPhase(surface, rcSegment, vs.styles[style],
+                               rcText.top + vs.maxAscent, st.text + start + i,
+                               static_cast<int>(end - i + 1), phase);
+                       x += width;
+                       i = end + 1;
+               }
+       } else {
+               const size_t style = st.style + styleOffset;
+               DrawTextNoClipPhase(surface, rcText, vs.styles[style],
+                       rcText.top + vs.maxAscent, st.text + start,
+                       static_cast<int>(length), phase);
+       }
+}
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+const XYPOSITION epsilon = 0.0001f;    // A small nudge to avoid floating point precision issues
+
+EditView::EditView() {
+       tabWidthMinimumPixels = 2; // needed for calculating tab stops for fractional proportional fonts
+       hideSelection = false;
+       drawOverstrikeCaret = true;
+       bufferedDraw = true;
+       phasesDraw = phasesTwo;
+       lineWidthMaxSeen = 0;
+       additionalCaretsBlink = true;
+       additionalCaretsVisible = true;
+       imeCaretBlockOverride = false;
+       llc.SetLevel(LineLayoutCache::llcCaret);
+       posCache.SetSize(0x400);
+       tabArrowHeight = 4;
+       customDrawTabArrow = NULL;
+       customDrawWrapMarker = NULL;
+}
+
+EditView::~EditView() {
+}
+
+bool EditView::SetTwoPhaseDraw(bool twoPhaseDraw) {
+       const PhasesDraw phasesDrawNew = twoPhaseDraw ? phasesTwo : phasesOne;
+       const bool redraw = phasesDraw != phasesDrawNew;
+       phasesDraw = phasesDrawNew;
+       return redraw;
+}
+
+bool EditView::SetPhasesDraw(int phases) {
+       const PhasesDraw phasesDrawNew = static_cast<PhasesDraw>(phases);
+       const bool redraw = phasesDraw != phasesDrawNew;
+       phasesDraw = phasesDrawNew;
+       return redraw;
+}
+
+bool EditView::LinesOverlap() const {
+       return phasesDraw == phasesMultiple;
+}
+
+void EditView::ClearAllTabstops() {
+       ldTabstops.reset();
+}
+
+XYPOSITION EditView::NextTabstopPos(Sci::Line line, XYPOSITION x, XYPOSITION tabWidth) const {
+       int next = GetNextTabstop(line, static_cast<int>(x + tabWidthMinimumPixels));
+       if (next > 0)
+               return static_cast<XYPOSITION>(next);
+       return (static_cast<int>((x + tabWidthMinimumPixels) / tabWidth) + 1) * tabWidth;
+}
+
+bool EditView::ClearTabstops(Sci::Line line) {
+       LineTabstops *lt = static_cast<LineTabstops *>(ldTabstops.get());
+       return lt && lt->ClearTabstops(line);
+}
+
+bool EditView::AddTabstop(Sci::Line line, int x) {
+       if (!ldTabstops) {
+               ldTabstops.reset(new LineTabstops());
+       }
+       LineTabstops *lt = static_cast<LineTabstops *>(ldTabstops.get());
+       return lt && lt->AddTabstop(line, x);
+}
+
+int EditView::GetNextTabstop(Sci::Line line, int x) const {
+       const LineTabstops *lt = static_cast<LineTabstops *>(ldTabstops.get());
+       if (lt) {
+               return lt->GetNextTabstop(line, x);
+       } else {
+               return 0;
+       }
+}
+
+void EditView::LinesAddedOrRemoved(Sci::Line lineOfPos, Sci::Line linesAdded) {
+       if (ldTabstops) {
+               if (linesAdded > 0) {
+                       for (Sci::Line line = lineOfPos; line < lineOfPos + linesAdded; line++) {
+                               ldTabstops->InsertLine(line);
+                       }
+               } else {
+                       for (Sci::Line line = (lineOfPos + -linesAdded) - 1; line >= lineOfPos; line--) {
+                               ldTabstops->RemoveLine(line);
+                       }
+               }
+       }
+}
+
+void EditView::DropGraphics(bool freeObjects) {
+       if (freeObjects) {
+               pixmapLine.reset();
+               pixmapIndentGuide.reset();
+               pixmapIndentGuideHighlight.reset();
+       } else {
+               if (pixmapLine)
+                       pixmapLine->Release();
+               if (pixmapIndentGuide)
+                       pixmapIndentGuide->Release();
+               if (pixmapIndentGuideHighlight)
+                       pixmapIndentGuideHighlight->Release();
+       }
+}
+
+void EditView::AllocateGraphics(const ViewStyle &vsDraw) {
+       if (!pixmapLine)
+               pixmapLine.reset(Surface::Allocate(vsDraw.technology));
+       if (!pixmapIndentGuide)
+               pixmapIndentGuide.reset(Surface::Allocate(vsDraw.technology));
+       if (!pixmapIndentGuideHighlight)
+               pixmapIndentGuideHighlight.reset(Surface::Allocate(vsDraw.technology));
+}
+
+static const char *ControlCharacterString(unsigned char ch) {
+       const char *reps[] = {
+               "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
+               "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
+               "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
+               "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US"
+       };
+       if (ch < ELEMENTS(reps)) {
+               return reps[ch];
+       } else {
+               return "BAD";
+       }
+}
+
+static void DrawTabArrow(Surface *surface, PRectangle rcTab, int ymid, const ViewStyle &vsDraw) {
+       if ((rcTab.left + 2) < (rcTab.right - 1))
+               surface->MoveTo(static_cast<int>(rcTab.left) + 2, ymid);
+       else
+               surface->MoveTo(static_cast<int>(rcTab.right) - 1, ymid);
+       surface->LineTo(static_cast<int>(rcTab.right) - 1, ymid);
+
+       // Draw the arrow head if needed
+       if (vsDraw.tabDrawMode == tdLongArrow) {
+               int ydiff = static_cast<int>(rcTab.bottom - rcTab.top) / 2;
+               int xhead = static_cast<int>(rcTab.right) - 1 - ydiff;
+               if (xhead <= rcTab.left) {
+                       ydiff -= static_cast<int>(rcTab.left) - xhead - 1;
+                       xhead = static_cast<int>(rcTab.left) - 1;
+               }
+               surface->LineTo(xhead, ymid - ydiff);
+               surface->MoveTo(static_cast<int>(rcTab.right) - 1, ymid);
+               surface->LineTo(xhead, ymid + ydiff);
+       }
+}
+
+void EditView::RefreshPixMaps(Surface *surfaceWindow, WindowID wid, const ViewStyle &vsDraw) {
+       if (!pixmapIndentGuide->Initialised()) {
+               // 1 extra pixel in height so can handle odd/even positions and so produce a continuous line
+               pixmapIndentGuide->InitPixMap(1, vsDraw.lineHeight + 1, surfaceWindow, wid);
+               pixmapIndentGuideHighlight->InitPixMap(1, vsDraw.lineHeight + 1, surfaceWindow, wid);
+               PRectangle rcIG = PRectangle::FromInts(0, 0, 1, vsDraw.lineHeight);
+               pixmapIndentGuide->FillRectangle(rcIG, vsDraw.styles[STYLE_INDENTGUIDE].back);
+               pixmapIndentGuide->PenColour(vsDraw.styles[STYLE_INDENTGUIDE].fore);
+               pixmapIndentGuideHighlight->FillRectangle(rcIG, vsDraw.styles[STYLE_BRACELIGHT].back);
+               pixmapIndentGuideHighlight->PenColour(vsDraw.styles[STYLE_BRACELIGHT].fore);
+               for (int stripe = 1; stripe < vsDraw.lineHeight + 1; stripe += 2) {
+                       PRectangle rcPixel = PRectangle::FromInts(0, stripe, 1, stripe + 1);
+                       pixmapIndentGuide->FillRectangle(rcPixel, vsDraw.styles[STYLE_INDENTGUIDE].fore);
+                       pixmapIndentGuideHighlight->FillRectangle(rcPixel, 
vsDraw.styles[STYLE_BRACELIGHT].fore);
+               }
+       }
+}
+
+LineLayout *EditView::RetrieveLineLayout(Sci::Line lineNumber, const EditModel &model) {
+       Sci::Position posLineStart = model.pdoc->LineStart(lineNumber);
+       Sci::Position posLineEnd = model.pdoc->LineStart(lineNumber + 1);
+       PLATFORM_ASSERT(posLineEnd >= posLineStart);
+       Sci::Line lineCaret = model.pdoc->LineFromPosition(model.sel.MainCaret());
+       return llc.Retrieve(lineNumber, lineCaret,
+               posLineEnd - posLineStart, model.pdoc->GetStyleClock(),
+               model.LinesOnScreen() + 1, model.pdoc->LinesTotal());
+}
+
+/**
+* Fill in the LineLayout data for the given line.
+* Copy the given @a line and its styles from the document into local arrays.
+* Also determine the x position at which each character starts.
+*/
+void EditView::LayoutLine(const EditModel &model, Sci::Line line, Surface *surface, const ViewStyle &vstyle, 
LineLayout *ll, int width) {
+       if (!ll)
+               return;
+
+       PLATFORM_ASSERT(line < model.pdoc->LinesTotal());
+       PLATFORM_ASSERT(ll->chars != NULL);
+       Sci::Position posLineStart = model.pdoc->LineStart(line);
+       Sci::Position posLineEnd = model.pdoc->LineStart(line + 1);
+       // If the line is very long, limit the treatment to a length that should fit in the viewport
+       if (posLineEnd >(posLineStart + ll->maxLineLength)) {
+               posLineEnd = posLineStart + ll->maxLineLength;
+       }
+       if (ll->validity == LineLayout::llCheckTextAndStyle) {
+               Sci::Position lineLength = posLineEnd - posLineStart;
+               if (!vstyle.viewEOL) {
+                       lineLength = model.pdoc->LineEnd(line) - posLineStart;
+               }
+               if (lineLength == ll->numCharsInLine) {
+                       // See if chars, styles, indicators, are all the same
+                       bool allSame = true;
+                       // Check base line layout
+                       int styleByte = 0;
+                       int numCharsInLine = 0;
+                       while (numCharsInLine < lineLength) {
+                               Sci::Position charInDoc = numCharsInLine + posLineStart;
+                               const char chDoc = model.pdoc->CharAt(charInDoc);
+                               styleByte = model.pdoc->StyleIndexAt(charInDoc);
+                               allSame = allSame &&
+                                       (ll->styles[numCharsInLine] == styleByte);
+                               if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseMixed)
+                                       allSame = allSame &&
+                                       (ll->chars[numCharsInLine] == chDoc);
+                               else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == 
Style::caseLower)
+                                       allSame = allSame &&
+                                       (ll->chars[numCharsInLine] == MakeLowerCase(chDoc));
+                               else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == 
Style::caseUpper)
+                                       allSame = allSame &&
+                                       (ll->chars[numCharsInLine] == MakeUpperCase(chDoc));
+                               else    { // Style::caseCamel
+                                       if ((model.pdoc->IsASCIIWordByte(ll->chars[numCharsInLine])) &&
+                                         ((numCharsInLine == 0) || 
(!model.pdoc->IsASCIIWordByte(ll->chars[numCharsInLine - 1])))) {
+                                               allSame = allSame && (ll->chars[numCharsInLine] == 
MakeUpperCase(chDoc));
+                                       } else {
+                                               allSame = allSame && (ll->chars[numCharsInLine] == 
MakeLowerCase(chDoc));
+                                       }
+                               }
+                               numCharsInLine++;
+                       }
+                       allSame = allSame && (ll->styles[numCharsInLine] == styleByte); // For eolFilled
+                       if (allSame) {
+                               ll->validity = LineLayout::llPositions;
+                       } else {
+                               ll->validity = LineLayout::llInvalid;
+                       }
+               } else {
+                       ll->validity = LineLayout::llInvalid;
+               }
+       }
+       if (ll->validity == LineLayout::llInvalid) {
+               ll->widthLine = LineLayout::wrapWidthInfinite;
+               ll->lines = 1;
+               if (vstyle.edgeState == EDGE_BACKGROUND) {
+                       ll->edgeColumn = model.pdoc->FindColumn(line, vstyle.theEdge.column);
+                       if (ll->edgeColumn >= posLineStart) {
+                               ll->edgeColumn -= posLineStart;
+                       }
+               } else {
+                       ll->edgeColumn = -1;
+               }
+
+               // Fill base line layout
+               const int lineLength = posLineEnd - posLineStart;
+               model.pdoc->GetCharRange(ll->chars.get(), posLineStart, lineLength);
+               model.pdoc->GetStyleRange(ll->styles.get(), posLineStart, lineLength);
+               const int numCharsBeforeEOL = model.pdoc->LineEnd(line) - posLineStart;
+               const int numCharsInLine = (vstyle.viewEOL) ? lineLength : numCharsBeforeEOL;
+               for (Sci::Position styleInLine = 0; styleInLine < numCharsInLine; styleInLine++) {
+                       const unsigned char styleByte = ll->styles[styleInLine];
+                       ll->styles[styleInLine] = styleByte;
+               }
+               const unsigned char styleByteLast = (lineLength > 0) ? ll->styles[lineLength - 1] : 0;
+               if (vstyle.someStylesForceCase) {
+                       for (int charInLine = 0; charInLine<lineLength; charInLine++) {
+                               const char chDoc = ll->chars[charInLine];
+                               if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseUpper)
+                                       ll->chars[charInLine] = static_cast<char>(MakeUpperCase(chDoc));
+                               else if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseLower)
+                                       ll->chars[charInLine] = static_cast<char>(MakeLowerCase(chDoc));
+                               else if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseCamel) 
{
+                                       if ((model.pdoc->IsASCIIWordByte(ll->chars[charInLine])) &&
+                                         ((charInLine == 0) || 
(!model.pdoc->IsASCIIWordByte(ll->chars[charInLine - 1])))) {
+                                               ll->chars[charInLine] = 
static_cast<char>(MakeUpperCase(chDoc));
+                                       } else {
+                                               ll->chars[charInLine] = 
static_cast<char>(MakeLowerCase(chDoc));
+                                       }
+                               }
+                       }
+               }
+               ll->xHighlightGuide = 0;
+               // Extra element at the end of the line to hold end x position and act as
+               ll->chars[numCharsInLine] = 0;   // Also triggers processing in the loops as this is a 
control character
+               ll->styles[numCharsInLine] = styleByteLast;     // For eolFilled
+
+               // Layout the line, determining the position of each character,
+               // with an extra element at the end for the end of the line.
+               ll->positions[0] = 0;
+               bool lastSegItalics = false;
+
+               BreakFinder bfLayout(ll, NULL, Range(0, numCharsInLine), posLineStart, 0, false, model.pdoc, 
&model.reprs, NULL);
+               while (bfLayout.More()) {
+
+                       const TextSegment ts = bfLayout.Next();
+
+                       std::fill(&ll->positions[ts.start + 1], &ll->positions[ts.end() + 1], 0.0f);
+                       if (vstyle.styles[ll->styles[ts.start]].visible) {
+                               if (ts.representation) {
+                                       XYPOSITION representationWidth = vstyle.controlCharWidth;
+                                       if (ll->chars[ts.start] == '\t') {
+                                               // Tab is a special case of representation, taking a variable 
amount of space
+                                               const XYPOSITION x = ll->positions[ts.start];
+                                               representationWidth = NextTabstopPos(line, x, 
vstyle.tabWidth) - ll->positions[ts.start];
+                                       } else {
+                                               if (representationWidth <= 0.0) {
+                                                       XYPOSITION positionsRepr[256];  // Should expand when 
needed
+                                                       posCache.MeasureWidths(surface, vstyle, 
STYLE_CONTROLCHAR, ts.representation->stringRep.c_str(),
+                                                               static_cast<unsigned 
int>(ts.representation->stringRep.length()), positionsRepr, model.pdoc);
+                                                       representationWidth = 
positionsRepr[ts.representation->stringRep.length() - 1] + vstyle.ctrlCharPadding;
+                                               }
+                                       }
+                                       for (int ii = 0; ii < ts.length; ii++)
+                                               ll->positions[ts.start + 1 + ii] = representationWidth;
+                               } else {
+                                       if ((ts.length == 1) && (' ' == ll->chars[ts.start])) {
+                                               // Over half the segments are single characters and of these 
about half are space characters.
+                                               ll->positions[ts.start + 1] = 
vstyle.styles[ll->styles[ts.start]].spaceWidth;
+                                       } else {
+                                               posCache.MeasureWidths(surface, vstyle, ll->styles[ts.start], 
&ll->chars[ts.start],
+                                                       ts.length, &ll->positions[ts.start + 1], model.pdoc);
+                                       }
+                               }
+                               lastSegItalics = (!ts.representation) && ((ll->chars[ts.end() - 1] != ' ') && 
vstyle.styles[ll->styles[ts.start]].italic);
+                       }
+
+                       for (Sci::Position posToIncrease = ts.start + 1; posToIncrease <= ts.end(); 
posToIncrease++) {
+                               ll->positions[posToIncrease] += ll->positions[ts.start];
+                       }
+               }
+
+               // Small hack to make lines that end with italics not cut off the edge of the last character
+               if (lastSegItalics) {
+                       ll->positions[numCharsInLine] += vstyle.lastSegItalicsOffset;
+               }
+               ll->numCharsInLine = numCharsInLine;
+               ll->numCharsBeforeEOL = numCharsBeforeEOL;
+               ll->validity = LineLayout::llPositions;
+       }
+       // Hard to cope when too narrow, so just assume there is space
+       if (width < 20) {
+               width = 20;
+       }
+       if ((ll->validity == LineLayout::llPositions) || (ll->widthLine != width)) {
+               ll->widthLine = width;
+               if (width == LineLayout::wrapWidthInfinite) {
+                       ll->lines = 1;
+               } else if (width > ll->positions[ll->numCharsInLine]) {
+                       // Simple common case where line does not need wrapping.
+                       ll->lines = 1;
+               } else {
+                       if (vstyle.wrapVisualFlags & SC_WRAPVISUALFLAG_END) {
+                               width -= static_cast<int>(vstyle.aveCharWidth); // take into account the 
space for end wrap mark
+                       }
+                       XYPOSITION wrapAddIndent = 0; // This will be added to initial indent of line
+                       if (vstyle.wrapIndentMode == SC_WRAPINDENT_INDENT) {
+                               wrapAddIndent = model.pdoc->IndentSize() * vstyle.spaceWidth;
+                       } else if (vstyle.wrapIndentMode == SC_WRAPINDENT_FIXED) {
+                               wrapAddIndent = vstyle.wrapVisualStartIndent * vstyle.aveCharWidth;
+                       }
+                       ll->wrapIndent = wrapAddIndent;
+                       if (vstyle.wrapIndentMode != SC_WRAPINDENT_FIXED)
+                       for (int i = 0; i < ll->numCharsInLine; i++) {
+                               if (!IsSpaceOrTab(ll->chars[i])) {
+                                       ll->wrapIndent += ll->positions[i]; // Add line indent
+                                       break;
+                               }
+                       }
+                       // Check for text width minimum
+                       if (ll->wrapIndent > width - static_cast<int>(vstyle.aveCharWidth) * 15)
+                               ll->wrapIndent = wrapAddIndent;
+                       // Check for wrapIndent minimum
+                       if ((vstyle.wrapVisualFlags & SC_WRAPVISUALFLAG_START) && (ll->wrapIndent < 
vstyle.aveCharWidth))
+                               ll->wrapIndent = vstyle.aveCharWidth; // Indent to show start visual
+                       ll->lines = 0;
+                       // Calculate line start positions based upon width.
+                       int lastGoodBreak = 0;
+                       int lastLineStart = 0;
+                       XYACCUMULATOR startOffset = 0;
+                       int p = 0;
+                       while (p < ll->numCharsInLine) {
+                               if ((ll->positions[p + 1] - startOffset) >= width) {
+                                       if (lastGoodBreak == lastLineStart) {
+                                               // Try moving to start of last character
+                                               if (p > 0) {
+                                                       lastGoodBreak = model.pdoc->MovePositionOutsideChar(p 
+ posLineStart, -1)
+                                                               - posLineStart;
+                                               }
+                                               if (lastGoodBreak == lastLineStart) {
+                                                       // Ensure at least one character on line.
+                                                       lastGoodBreak = 
model.pdoc->MovePositionOutsideChar(lastGoodBreak + posLineStart + 1, 1)
+                                                               - posLineStart;
+                                               }
+                                       }
+                                       lastLineStart = lastGoodBreak;
+                                       ll->lines++;
+                                       ll->SetLineStart(ll->lines, lastGoodBreak);
+                                       startOffset = ll->positions[lastGoodBreak];
+                                       // take into account the space for start wrap mark and indent
+                                       startOffset -= ll->wrapIndent;
+                                       p = lastGoodBreak + 1;
+                                       continue;
+                               }
+                               if (p > 0) {
+                                       if (vstyle.wrapState == eWrapChar) {
+                                               lastGoodBreak = model.pdoc->MovePositionOutsideChar(p + 
posLineStart, -1)
+                                                       - posLineStart;
+                                               p = model.pdoc->MovePositionOutsideChar(p + 1 + posLineStart, 
1) - posLineStart;
+                                               continue;
+                                       } else if ((vstyle.wrapState == eWrapWord) && (ll->styles[p] != 
ll->styles[p - 1])) {
+                                               lastGoodBreak = p;
+                                       } else if (IsSpaceOrTab(ll->chars[p - 1]) && 
!IsSpaceOrTab(ll->chars[p])) {
+                                               lastGoodBreak = p;
+                                       }
+                               }
+                               p++;
+                       }
+                       ll->lines++;
+               }
+               ll->validity = LineLayout::llLines;
+       }
+}
+
+Point EditView::LocationFromPosition(Surface *surface, const EditModel &model, SelectionPosition pos, 
Sci::Line topLine,
+                                    const ViewStyle &vs, PointEnd pe) {
+       Point pt;
+       if (pos.Position() == INVALID_POSITION)
+               return pt;
+       Sci::Line lineDoc = model.pdoc->LineFromPosition(pos.Position());
+       Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
+       if ((pe & peLineEnd) && (lineDoc > 0) && (pos.Position() == posLineStart)) {
+               // Want point at end of first line
+               lineDoc--;
+               posLineStart = model.pdoc->LineStart(lineDoc);
+       }
+       const Sci::Line lineVisible = model.cs.DisplayFromDoc(lineDoc);
+       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
+       if (surface && ll) {
+               LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
+               const int posInLine = pos.Position() - posLineStart;
+               pt = ll->PointFromPosition(posInLine, vs.lineHeight, pe);
+               pt.y += (lineVisible - topLine) * vs.lineHeight;
+               pt.x += vs.textStart - model.xOffset;
+       }
+       pt.x += pos.VirtualSpace() * vs.styles[ll->EndLineStyle()].spaceWidth;
+       return pt;
+}
+
+Range EditView::RangeDisplayLine(Surface *surface, const EditModel &model, Sci::Line lineVisible, const 
ViewStyle &vs) {
+       Range rangeSubLine = Range(0,0);
+       if (lineVisible < 0) {
+               return rangeSubLine;
+       }
+       const Sci::Line lineDoc = model.cs.DocFromDisplay(lineVisible);
+       const Sci::Position positionLineStart = model.pdoc->LineStart(lineDoc);
+       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
+       if (surface && ll) {
+               LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
+               const Sci::Line lineStartSet = model.cs.DisplayFromDoc(lineDoc);
+               const int subLine = lineVisible - lineStartSet;
+               if (subLine < ll->lines) {
+                       rangeSubLine = ll->SubLineRange(subLine);
+                       if (subLine == ll->lines-1) {
+                               rangeSubLine.end = model.pdoc->LineStart(lineDoc + 1) -
+                                       positionLineStart;
+                       }
+               }
+       }
+       rangeSubLine.start += positionLineStart;
+       rangeSubLine.end += positionLineStart;
+       return rangeSubLine;
+}
+
+SelectionPosition EditView::SPositionFromLocation(Surface *surface, const EditModel &model, PointDocument 
pt, bool canReturnInvalid, bool charPosition, bool virtualSpace, const ViewStyle &vs) {
+       pt.x = pt.x - vs.textStart;
+       Sci::Line visibleLine = static_cast<int>(floor(pt.y / vs.lineHeight));
+       if (!canReturnInvalid && (visibleLine < 0))
+               visibleLine = 0;
+       const Sci::Line lineDoc = model.cs.DocFromDisplay(visibleLine);
+       if (canReturnInvalid && (lineDoc < 0))
+               return SelectionPosition(INVALID_POSITION);
+       if (lineDoc >= model.pdoc->LinesTotal())
+               return SelectionPosition(canReturnInvalid ? INVALID_POSITION : model.pdoc->Length());
+       const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
+       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
+       if (surface && ll) {
+               LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
+               const Sci::Line lineStartSet = model.cs.DisplayFromDoc(lineDoc);
+               const int subLine = visibleLine - lineStartSet;
+               if (subLine < ll->lines) {
+                       const Range rangeSubLine = ll->SubLineRange(subLine);
+                       const XYPOSITION subLineStart = ll->positions[rangeSubLine.start];
+                       if (subLine > 0)        // Wrapped
+                               pt.x -= ll->wrapIndent;
+                       const Sci::Position positionInLine = 
ll->FindPositionFromX(static_cast<XYPOSITION>(pt.x + subLineStart),
+                               rangeSubLine, charPosition);
+                       if (positionInLine < rangeSubLine.end) {
+                               return SelectionPosition(model.pdoc->MovePositionOutsideChar(positionInLine + 
posLineStart, 1));
+                       }
+                       if (virtualSpace) {
+                               const XYPOSITION spaceWidth = vs.styles[ll->EndLineStyle()].spaceWidth;
+                               const int spaceOffset = static_cast<int>(
+                                       (pt.x + subLineStart - ll->positions[rangeSubLine.end] + spaceWidth / 
2) / spaceWidth);
+                               return SelectionPosition(rangeSubLine.end + posLineStart, spaceOffset);
+                       } else if (canReturnInvalid) {
+                               if (pt.x < (ll->positions[rangeSubLine.end] - subLineStart)) {
+                                       return 
SelectionPosition(model.pdoc->MovePositionOutsideChar(rangeSubLine.end + posLineStart, 1));
+                               }
+                       } else {
+                               return SelectionPosition(rangeSubLine.end + posLineStart);
+                       }
+               }
+               if (!canReturnInvalid)
+                       return SelectionPosition(ll->numCharsInLine + posLineStart);
+       }
+       return SelectionPosition(canReturnInvalid ? INVALID_POSITION : posLineStart);
+}
+
+/**
+* Find the document position corresponding to an x coordinate on a particular document line.
+* Ensure is between whole characters when document is in multi-byte or UTF-8 mode.
+* This method is used for rectangular selections and does not work on wrapped lines.
+*/
+SelectionPosition EditView::SPositionFromLineX(Surface *surface, const EditModel &model, Sci::Line lineDoc, 
int x, const ViewStyle &vs) {
+       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
+       if (surface && ll) {
+               const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
+               LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
+               const Range rangeSubLine = ll->SubLineRange(0);
+               const XYPOSITION subLineStart = ll->positions[rangeSubLine.start];
+               const Sci::Position positionInLine = ll->FindPositionFromX(x + subLineStart, rangeSubLine, 
false);
+               if (positionInLine < rangeSubLine.end) {
+                       return SelectionPosition(model.pdoc->MovePositionOutsideChar(positionInLine + 
posLineStart, 1));
+               }
+               const XYPOSITION spaceWidth = vs.styles[ll->EndLineStyle()].spaceWidth;
+               const int spaceOffset = static_cast<int>(
+                       (x + subLineStart - ll->positions[rangeSubLine.end] + spaceWidth / 2) / spaceWidth);
+               return SelectionPosition(rangeSubLine.end + posLineStart, spaceOffset);
+       }
+       return SelectionPosition(0);
+}
+
+Sci::Line EditView::DisplayFromPosition(Surface *surface, const EditModel &model, Sci::Position pos, const 
ViewStyle &vs) {
+       const Sci::Line lineDoc = model.pdoc->LineFromPosition(pos);
+       Sci::Line lineDisplay = model.cs.DisplayFromDoc(lineDoc);
+       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
+       if (surface && ll) {
+               LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
+               const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
+               const Sci::Position posInLine = pos - posLineStart;
+               lineDisplay--; // To make up for first increment ahead.
+               for (int subLine = 0; subLine < ll->lines; subLine++) {
+                       if (posInLine >= ll->LineStart(subLine)) {
+                               lineDisplay++;
+                       }
+               }
+       }
+       return lineDisplay;
+}
+
+Sci::Position EditView::StartEndDisplayLine(Surface *surface, const EditModel &model, Sci::Position pos, 
bool start, const ViewStyle &vs) {
+       const Sci::Line line = model.pdoc->LineFromPosition(pos);
+       AutoLineLayout ll(llc, RetrieveLineLayout(line, model));
+       Sci::Position posRet = INVALID_POSITION;
+       if (surface && ll) {
+               const Sci::Position posLineStart = model.pdoc->LineStart(line);
+               LayoutLine(model, line, surface, vs, ll, model.wrapWidth);
+               const Sci::Position posInLine = pos - posLineStart;
+               if (posInLine <= ll->maxLineLength) {
+                       for (int subLine = 0; subLine < ll->lines; subLine++) {
+                               if ((posInLine >= ll->LineStart(subLine)) &&
+                                   (posInLine <= ll->LineStart(subLine + 1)) &&
+                                   (posInLine <= ll->numCharsBeforeEOL)) {
+                                       if (start) {
+                                               posRet = ll->LineStart(subLine) + posLineStart;
+                                       } else {
+                                               if (subLine == ll->lines - 1)
+                                                       posRet = ll->numCharsBeforeEOL + posLineStart;
+                                               else
+                                                       posRet = ll->LineStart(subLine + 1) + posLineStart - 
1;
+                                       }
+                               }
+                       }
+               }
+       }
+       return posRet;
+}
+
+static ColourDesired SelectionBackground(const ViewStyle &vsDraw, bool main, bool primarySelection) {
+       return main ?
+               (primarySelection ? vsDraw.selColours.back : vsDraw.selBackground2) :
+               vsDraw.selAdditionalBackground;
+}
+
+static ColourDesired TextBackground(const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
+       ColourOptional background, int inSelection, bool inHotspot, int styleMain, Sci::Position i) {
+       if (inSelection == 1) {
+               if (vsDraw.selColours.back.isSet && (vsDraw.selAlpha == SC_ALPHA_NOALPHA)) {
+                       return SelectionBackground(vsDraw, true, model.primarySelection);
+               }
+       } else if (inSelection == 2) {
+               if (vsDraw.selColours.back.isSet && (vsDraw.selAdditionalAlpha == SC_ALPHA_NOALPHA)) {
+                       return SelectionBackground(vsDraw, false, model.primarySelection);
+               }
+       } else {
+               if ((vsDraw.edgeState == EDGE_BACKGROUND) &&
+                       (i >= ll->edgeColumn) &&
+                       (i < ll->numCharsBeforeEOL))
+                       return vsDraw.theEdge.colour;
+               if (inHotspot && vsDraw.hotspotColours.back.isSet)
+                       return vsDraw.hotspotColours.back;
+       }
+       if (background.isSet && (styleMain != STYLE_BRACELIGHT) && (styleMain != STYLE_BRACEBAD)) {
+               return background;
+       } else {
+               return vsDraw.styles[styleMain].back;
+       }
+}
+
+void EditView::DrawIndentGuide(Surface *surface, Sci::Line lineVisible, int lineHeight, Sci::Position start, 
PRectangle rcSegment, bool highlight) {
+       Point from = Point::FromInts(0, ((lineVisible & 1) && (lineHeight & 1)) ? 1 : 0);
+       PRectangle rcCopyArea = PRectangle::FromInts(start + 1, static_cast<int>(rcSegment.top), start + 2, 
static_cast<int>(rcSegment.bottom));
+       surface->Copy(rcCopyArea, from,
+               highlight ? *pixmapIndentGuideHighlight : *pixmapIndentGuide);
+}
+
+static void SimpleAlphaRectangle(Surface *surface, PRectangle rc, ColourDesired fill, int alpha) {
+       if (alpha != SC_ALPHA_NOALPHA) {
+               surface->AlphaRectangle(rc, 0, fill, alpha, fill, alpha, 0);
+       }
+}
+
+static void DrawTextBlob(Surface *surface, const ViewStyle &vsDraw, PRectangle rcSegment,
+       const char *s, ColourDesired textBack, ColourDesired textFore, bool fillBackground) {
+       if (rcSegment.Empty())
+               return;
+       if (fillBackground) {
+               surface->FillRectangle(rcSegment, textBack);
+       }
+       FontAlias ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font;
+       const int normalCharHeight = static_cast<int>(ceil(vsDraw.styles[STYLE_CONTROLCHAR].capitalHeight));
+       PRectangle rcCChar = rcSegment;
+       rcCChar.left = rcCChar.left + 1;
+       rcCChar.top = rcSegment.top + vsDraw.maxAscent - normalCharHeight;
+       rcCChar.bottom = rcSegment.top + vsDraw.maxAscent + 1;
+       PRectangle rcCentral = rcCChar;
+       rcCentral.top++;
+       rcCentral.bottom--;
+       surface->FillRectangle(rcCentral, textFore);
+       PRectangle rcChar = rcCChar;
+       rcChar.left++;
+       rcChar.right--;
+       surface->DrawTextClipped(rcChar, ctrlCharsFont,
+               rcSegment.top + vsDraw.maxAscent, s, static_cast<int>(s ? strlen(s) : 0),
+               textBack, textFore);
+}
+
+static void DrawFrame(Surface *surface, ColourDesired colour, int alpha, PRectangle rcFrame) {
+       if (alpha != SC_ALPHA_NOALPHA)
+               surface->AlphaRectangle(rcFrame, 0, colour, alpha, colour, alpha, 0);
+       else
+               surface->FillRectangle(rcFrame, colour);
+}
+
+static void DrawCaretLineFramed(Surface *surface, const ViewStyle &vsDraw, const LineLayout *ll, PRectangle 
rcLine, int subLine) {
+       const int width = vsDraw.GetFrameWidth();
+       if (subLine == 0 || ll->wrapIndent == 0 || vsDraw.caretLineAlpha != SC_ALPHA_NOALPHA) {
+               // Left
+               DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
+                       PRectangle(rcLine.left, rcLine.top, rcLine.left + width, rcLine.bottom));
+       }
+       if (subLine == 0) {
+               // Top
+               DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
+                       PRectangle(rcLine.left + width, rcLine.top, rcLine.right - width, rcLine.top + 
width));
+       }
+       if (subLine == ll->lines - 1 || vsDraw.caretLineAlpha != SC_ALPHA_NOALPHA) {
+               // Right
+               DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
+                       PRectangle(rcLine.right - width, rcLine.top, rcLine.right, rcLine.bottom));
+       }
+       if (subLine == ll->lines - 1) {
+               // Bottom
+               DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
+                       PRectangle(rcLine.left + width, rcLine.bottom - width, rcLine.right - width, 
rcLine.bottom));
+       }
+}
+
+void EditView::DrawEOL(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout 
*ll,
+       PRectangle rcLine, Sci::Line line, Sci::Position lineEnd, int xStart, int subLine, XYACCUMULATOR 
subLineStart,
+       ColourOptional background) {
+
+       const Sci::Position posLineStart = model.pdoc->LineStart(line);
+       PRectangle rcSegment = rcLine;
+
+       const bool lastSubLine = subLine == (ll->lines - 1);
+       XYPOSITION virtualSpace = 0;
+       if (lastSubLine) {
+               const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
+               virtualSpace = model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line)) * spaceWidth;
+       }
+       const XYPOSITION xEol = static_cast<XYPOSITION>(ll->positions[lineEnd] - subLineStart);
+
+       // Fill the virtual space and show selections within it
+       if (virtualSpace > 0.0f) {
+               rcSegment.left = xEol + xStart;
+               rcSegment.right = xEol + xStart + virtualSpace;
+               surface->FillRectangle(rcSegment, background.isSet ? background : 
vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
+               if (!hideSelection && ((vsDraw.selAlpha == SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha == 
SC_ALPHA_NOALPHA))) {
+                       SelectionSegment virtualSpaceRange(SelectionPosition(model.pdoc->LineEnd(line)), 
SelectionPosition(model.pdoc->LineEnd(line), model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line))));
+                       for (size_t r = 0; r<model.sel.Count(); r++) {
+                               const int alpha = (r == model.sel.Main()) ? vsDraw.selAlpha : 
vsDraw.selAdditionalAlpha;
+                               if (alpha == SC_ALPHA_NOALPHA) {
+                                       const SelectionSegment portion = 
model.sel.Range(r).Intersect(virtualSpaceRange);
+                                       if (!portion.Empty()) {
+                                               const XYPOSITION spaceWidth = 
vsDraw.styles[ll->EndLineStyle()].spaceWidth;
+                                               rcSegment.left = xStart + 
ll->positions[portion.start.Position() - posLineStart] -
+                                                       
static_cast<XYPOSITION>(subLineStart)+portion.start.VirtualSpace() * spaceWidth;
+                                               rcSegment.right = xStart + 
ll->positions[portion.end.Position() - posLineStart] -
+                                                       
static_cast<XYPOSITION>(subLineStart)+portion.end.VirtualSpace() * spaceWidth;
+                                               rcSegment.left = (rcSegment.left > rcLine.left) ? 
rcSegment.left : rcLine.left;
+                                               rcSegment.right = (rcSegment.right < rcLine.right) ? 
rcSegment.right : rcLine.right;
+                                               surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, 
r == model.sel.Main(), model.primarySelection));
+                                       }
+                               }
+                       }
+               }
+       }
+
+       int eolInSelection = 0;
+       int alpha = SC_ALPHA_NOALPHA;
+       if (!hideSelection) {
+               Sci::Position posAfterLineEnd = model.pdoc->LineStart(line + 1);
+               eolInSelection = (lastSubLine == true) ? model.sel.InSelectionForEOL(posAfterLineEnd) : 0;
+               alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
+       }
+
+       // Draw the [CR], [LF], or [CR][LF] blobs if visible line ends are on
+       XYPOSITION blobsWidth = 0;
+       if (lastSubLine) {
+               for (Sci::Position eolPos = ll->numCharsBeforeEOL; eolPos<ll->numCharsInLine; eolPos++) {
+                       rcSegment.left = xStart + ll->positions[eolPos] - 
static_cast<XYPOSITION>(subLineStart)+virtualSpace;
+                       rcSegment.right = xStart + ll->positions[eolPos + 1] - 
static_cast<XYPOSITION>(subLineStart)+virtualSpace;
+                       blobsWidth += rcSegment.Width();
+                       char hexits[4];
+                       const char *ctrlChar;
+                       const unsigned char chEOL = ll->chars[eolPos];
+                       int styleMain = ll->styles[eolPos];
+                       ColourDesired textBack = TextBackground(model, vsDraw, ll, background, 
eolInSelection, false, styleMain, eolPos);
+                       if (UTF8IsAscii(chEOL)) {
+                               ctrlChar = ControlCharacterString(chEOL);
+                       } else {
+                               const Representation *repr = 
model.reprs.RepresentationFromCharacter(&ll->chars[eolPos], ll->numCharsInLine - eolPos);
+                               if (repr) {
+                                       ctrlChar = repr->stringRep.c_str();
+                                       eolPos = ll->numCharsInLine;
+                               } else {
+                                       sprintf(hexits, "x%2X", chEOL);
+                                       ctrlChar = hexits;
+                               }
+                       }
+                       ColourDesired textFore = vsDraw.styles[styleMain].fore;
+                       if (eolInSelection && vsDraw.selColours.fore.isSet) {
+                               textFore = (eolInSelection == 1) ? vsDraw.selColours.fore : 
vsDraw.selAdditionalForeground;
+                       }
+                       if (eolInSelection && vsDraw.selColours.back.isSet && (line < 
model.pdoc->LinesTotal() - 1)) {
+                               if (alpha == SC_ALPHA_NOALPHA) {
+                                       surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, 
eolInSelection == 1, model.primarySelection));
+                               } else {
+                                       surface->FillRectangle(rcSegment, textBack);
+                               }
+                       } else {
+                               surface->FillRectangle(rcSegment, textBack);
+                       }
+                       DrawTextBlob(surface, vsDraw, rcSegment, ctrlChar, textBack, textFore, phasesDraw == 
phasesOne);
+                       if (eolInSelection && vsDraw.selColours.back.isSet && (line < 
model.pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
+                               SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, 
eolInSelection == 1, model.primarySelection), alpha);
+                       }
+               }
+       }
+
+       // Draw the eol-is-selected rectangle
+       rcSegment.left = xEol + xStart + virtualSpace + blobsWidth;
+       rcSegment.right = rcSegment.left + vsDraw.aveCharWidth;
+
+       if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && (alpha 
== SC_ALPHA_NOALPHA)) {
+               surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1, 
model.primarySelection));
+       } else {
+               if (background.isSet) {
+                       surface->FillRectangle(rcSegment, background);
+               } else if (line < model.pdoc->LinesTotal() - 1) {
+                       surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
+               } else if (vsDraw.styles[ll->styles[ll->numCharsInLine]].eolFilled) {
+                       surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
+               } else {
+                       surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back);
+               }
+               if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) 
&& (alpha != SC_ALPHA_NOALPHA)) {
+                       SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection 
== 1, model.primarySelection), alpha);
+               }
+       }
+
+       rcSegment.left = rcSegment.right;
+       if (rcSegment.left < rcLine.left)
+               rcSegment.left = rcLine.left;
+       rcSegment.right = rcLine.right;
+
+       const bool fillRemainder = !lastSubLine || model.foldDisplayTextStyle == SC_FOLDDISPLAYTEXT_HIDDEN || 
!model.cs.GetFoldDisplayTextShown(line);
+       if (fillRemainder) {
+               // Fill the remainder of the line
+               FillLineRemainder(surface, model, vsDraw, ll, line, rcSegment, subLine);
+       }
+
+       bool drawWrapMarkEnd = false;
+
+       if (subLine + 1 < ll->lines) {
+               if (vsDraw.wrapVisualFlags & SC_WRAPVISUALFLAG_END) {
+                       drawWrapMarkEnd = ll->LineStart(subLine + 1) != 0;
+               }
+               if (vsDraw.IsLineFrameOpaque(model.caret.active, ll->containsCaret)) {
+                       const int width = vsDraw.GetFrameWidth();
+                       // Draw right of frame under marker
+                       DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
+                               PRectangle(rcLine.right - width, rcLine.top, rcLine.right, rcLine.bottom));
+               }
+       }
+
+       if (drawWrapMarkEnd) {
+               PRectangle rcPlace = rcSegment;
+
+               if (vsDraw.wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_END_BY_TEXT) {
+                       rcPlace.left = xEol + xStart + virtualSpace;
+                       rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
+               } else {
+                       // rcLine is clipped to text area
+                       rcPlace.right = rcLine.right;
+                       rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
+               }
+               if (customDrawWrapMarker == NULL) {
+                       DrawWrapMarker(surface, rcPlace, true, vsDraw.WrapColour());
+               } else {
+                       customDrawWrapMarker(surface, rcPlace, true, vsDraw.WrapColour());
+               }
+       }
+}
+
+static void DrawIndicator(int indicNum, Sci::Position startPos, Sci::Position endPos, Surface *surface, 
const ViewStyle &vsDraw,
+       const LineLayout *ll, int xStart, PRectangle rcLine, Sci::Position secondCharacter, int subLine, 
Indicator::DrawState drawState, int value) {
+       const XYPOSITION subLineStart = ll->positions[ll->LineStart(subLine)];
+       PRectangle rcIndic(
+               ll->positions[startPos] + xStart - subLineStart,
+               rcLine.top + vsDraw.maxAscent,
+               ll->positions[endPos] + xStart - subLineStart,
+               rcLine.top + vsDraw.maxAscent + 3);
+       PRectangle rcFirstCharacter = rcIndic;
+       // Allow full descent space for character indicators
+       rcFirstCharacter.bottom = rcLine.top + vsDraw.maxAscent + vsDraw.maxDescent;
+       if (secondCharacter >= 0) {
+               rcFirstCharacter.right = ll->positions[secondCharacter] + xStart - subLineStart;
+       } else {
+               // Indicator continued from earlier line so make an empty box and don't draw
+               rcFirstCharacter.right = rcFirstCharacter.left;
+       }
+       vsDraw.indicators[indicNum].Draw(surface, rcIndic, rcLine, rcFirstCharacter, drawState, value);
+}
+
+static void DrawIndicators(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       Sci::Line line, int xStart, PRectangle rcLine, int subLine, Sci::Position lineEnd, bool under, 
Sci::Position hoverIndicatorPos) {
+       // Draw decorators
+       const Sci::Position posLineStart = model.pdoc->LineStart(line);
+       const Sci::Position lineStart = ll->LineStart(subLine);
+       const Sci::Position posLineEnd = posLineStart + lineEnd;
+
+       for (const Decoration *deco : model.pdoc->decorations.View()) {
+               if (under == vsDraw.indicators[deco->Indicator()].under) {
+                       Sci::Position startPos = posLineStart + lineStart;
+                       if (!deco->rs.ValueAt(startPos)) {
+                               startPos = deco->rs.EndRun(startPos);
+                       }
+                       while ((startPos < posLineEnd) && (deco->rs.ValueAt(startPos))) {
+                               const Range rangeRun(deco->rs.StartRun(startPos), deco->rs.EndRun(startPos));
+                               const Sci::Position endPos = std::min(rangeRun.end, posLineEnd);
+                               const bool hover = vsDraw.indicators[deco->Indicator()].IsDynamic() &&
+                                       rangeRun.ContainsCharacter(hoverIndicatorPos);
+                               const int value = deco->rs.ValueAt(startPos);
+                               const Indicator::DrawState drawState = hover ? Indicator::drawHover : 
Indicator::drawNormal;
+                               const Sci::Position posSecond = 
model.pdoc->MovePositionOutsideChar(rangeRun.First() + 1, 1);
+                               DrawIndicator(deco->Indicator(), startPos - posLineStart, endPos - 
posLineStart,
+                                       surface, vsDraw, ll, xStart, rcLine, posSecond - posLineStart, 
subLine, drawState, value);
+                               startPos = endPos;
+                               if (!deco->rs.ValueAt(startPos)) {
+                                       startPos = deco->rs.EndRun(startPos);
+                               }
+                       }
+               }
+       }
+
+       // Use indicators to highlight matching braces
+       if ((vsDraw.braceHighlightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACELIGHT)) ||
+               (vsDraw.braceBadLightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACEBAD))) {
+               const int braceIndicator = (model.bracesMatchStyle == STYLE_BRACELIGHT) ? 
vsDraw.braceHighlightIndicator : vsDraw.braceBadLightIndicator;
+               if (under == vsDraw.indicators[braceIndicator].under) {
+                       Range rangeLine(posLineStart + lineStart, posLineEnd);
+                       if (rangeLine.ContainsCharacter(model.braces[0])) {
+                               Sci::Position braceOffset = model.braces[0] - posLineStart;
+                               if (braceOffset < ll->numCharsInLine) {
+                                       const Sci::Position secondOffset = 
model.pdoc->MovePositionOutsideChar(model.braces[0] + 1, 1) - posLineStart;
+                                       DrawIndicator(braceIndicator, braceOffset, braceOffset + 1, surface, 
vsDraw, ll, xStart, rcLine, secondOffset, subLine, Indicator::drawNormal, 1);
+                               }
+                       }
+                       if (rangeLine.ContainsCharacter(model.braces[1])) {
+                               Sci::Position braceOffset = model.braces[1] - posLineStart;
+                               if (braceOffset < ll->numCharsInLine) {
+                                       const Sci::Position secondOffset = 
model.pdoc->MovePositionOutsideChar(model.braces[1] + 1, 1) - posLineStart;
+                                       DrawIndicator(braceIndicator, braceOffset, braceOffset + 1, surface, 
vsDraw, ll, xStart, rcLine, secondOffset, subLine, Indicator::drawNormal, 1);
+                               }
+                       }
+               }
+       }
+}
+
+void EditView::DrawFoldDisplayText(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+                                                         Sci::Line line, int xStart, PRectangle rcLine, int 
subLine, XYACCUMULATOR subLineStart, DrawPhase phase) {
+       const bool lastSubLine = subLine == (ll->lines - 1);
+       if (!lastSubLine)
+               return;
+
+       if ((model.foldDisplayTextStyle == SC_FOLDDISPLAYTEXT_HIDDEN) || 
!model.cs.GetFoldDisplayTextShown(line))
+               return;
+
+       PRectangle rcSegment = rcLine;
+       const char *foldDisplayText = model.cs.GetFoldDisplayText(line);
+       const int lengthFoldDisplayText = static_cast<int>(strlen(foldDisplayText));
+       FontAlias fontText = vsDraw.styles[STYLE_FOLDDISPLAYTEXT].font;
+       const int widthFoldDisplayText = static_cast<int>(surface->WidthText(fontText, foldDisplayText, 
lengthFoldDisplayText));
+
+       int eolInSelection = 0;
+       int alpha = SC_ALPHA_NOALPHA;
+       if (!hideSelection) {
+               Sci::Position posAfterLineEnd = model.pdoc->LineStart(line + 1);
+               eolInSelection = (subLine == (ll->lines - 1)) ? model.sel.InSelectionForEOL(posAfterLineEnd) 
: 0;
+               alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
+       }
+
+       const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
+       XYPOSITION virtualSpace = model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line)) * spaceWidth;
+       rcSegment.left = xStart + static_cast<XYPOSITION>(ll->positions[ll->numCharsInLine] - subLineStart) + 
virtualSpace + vsDraw.aveCharWidth;
+       rcSegment.right = rcSegment.left + static_cast<XYPOSITION>(widthFoldDisplayText);
+
+       const ColourOptional background = vsDraw.Background(model.pdoc->GetMark(line), model.caret.active, 
ll->containsCaret);
+       FontAlias textFont = vsDraw.styles[STYLE_FOLDDISPLAYTEXT].font;
+       ColourDesired textFore = vsDraw.styles[STYLE_FOLDDISPLAYTEXT].fore;
+       if (eolInSelection && (vsDraw.selColours.fore.isSet)) {
+               textFore = (eolInSelection == 1) ? vsDraw.selColours.fore : vsDraw.selAdditionalForeground;
+       }
+       const ColourDesired textBack = TextBackground(model, vsDraw, ll, background, eolInSelection,
+                                                                                       false, 
STYLE_FOLDDISPLAYTEXT, -1);
+
+       if (model.trackLineWidth) {
+               if (rcSegment.right + 1> lineWidthMaxSeen) {
+                       // Fold display text border drawn on rcSegment.right with width 1 is the last visble 
object of the line
+                       lineWidthMaxSeen = static_cast<int>(rcSegment.right + 1);
+               }
+       }
+
+       if (phase & drawBack) {
+               surface->FillRectangle(rcSegment, textBack);
+
+               // Fill Remainder of the line
+               PRectangle rcRemainder = rcSegment;
+               rcRemainder.left = rcRemainder.right;
+               if (rcRemainder.left < rcLine.left)
+                       rcRemainder.left = rcLine.left;
+               rcRemainder.right = rcLine.right;
+               FillLineRemainder(surface, model, vsDraw, ll, line, rcRemainder, subLine);
+       }
+
+       if (phase & drawText) {
+               if (phasesDraw != phasesOne) {
+                       surface->DrawTextTransparent(rcSegment, textFont,
+                               rcSegment.top + vsDraw.maxAscent, foldDisplayText,
+                               lengthFoldDisplayText, textFore);
+               } else {
+                       surface->DrawTextNoClip(rcSegment, textFont,
+                               rcSegment.top + vsDraw.maxAscent, foldDisplayText,
+                               lengthFoldDisplayText, textFore, textBack);
+               }
+       }
+
+       if (phase & drawIndicatorsFore) {
+               if (model.foldDisplayTextStyle == SC_FOLDDISPLAYTEXT_BOXED) {
+                       surface->PenColour(textFore);
+                       PRectangle rcBox = rcSegment;
+                       rcBox.left = static_cast<XYPOSITION>(RoundXYPosition(rcSegment.left));
+                       rcBox.right = static_cast<XYPOSITION>(RoundXYPosition(rcSegment.right));
+                       surface->MoveTo(static_cast<int>(rcBox.left), static_cast<int>(rcBox.top));
+                       surface->LineTo(static_cast<int>(rcBox.left), static_cast<int>(rcBox.bottom));
+                       surface->MoveTo(static_cast<int>(rcBox.right), static_cast<int>(rcBox.top));
+                       surface->LineTo(static_cast<int>(rcBox.right), static_cast<int>(rcBox.bottom));
+                       surface->MoveTo(static_cast<int>(rcBox.left), static_cast<int>(rcBox.top));
+                       surface->LineTo(static_cast<int>(rcBox.right), static_cast<int>(rcBox.top));
+                       surface->MoveTo(static_cast<int>(rcBox.left), static_cast<int>(rcBox.bottom - 1));
+                       surface->LineTo(static_cast<int>(rcBox.right), static_cast<int>(rcBox.bottom - 1));
+               }
+       }
+
+       if (phase & drawSelectionTranslucent) {
+               if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) 
&& alpha != SC_ALPHA_NOALPHA) {
+                       SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection 
== 1, model.primarySelection), alpha);
+               }
+       }
+}
+
+static bool AnnotationBoxedOrIndented(int annotationVisible) {
+       return annotationVisible == ANNOTATION_BOXED || annotationVisible == ANNOTATION_INDENTED;
+}
+
+void EditView::DrawAnnotation(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       Sci::Line line, int xStart, PRectangle rcLine, int subLine, DrawPhase phase) {
+       const int indent = static_cast<int>(model.pdoc->GetLineIndentation(line) * vsDraw.spaceWidth);
+       PRectangle rcSegment = rcLine;
+       const int annotationLine = subLine - ll->lines;
+       const StyledText stAnnotation = model.pdoc->AnnotationStyledText(line);
+       if (stAnnotation.text && ValidStyledText(vsDraw, vsDraw.annotationStyleOffset, stAnnotation)) {
+               if (phase & drawBack) {
+                       surface->FillRectangle(rcSegment, vsDraw.styles[0].back);
+               }
+               rcSegment.left = static_cast<XYPOSITION>(xStart);
+               if (model.trackLineWidth || AnnotationBoxedOrIndented(vsDraw.annotationVisible)) {
+                       // Only care about calculating width if tracking or need to draw indented box
+                       int widthAnnotation = WidestLineWidth(surface, vsDraw, vsDraw.annotationStyleOffset, 
stAnnotation);
+                       if (AnnotationBoxedOrIndented(vsDraw.annotationVisible)) {
+                               widthAnnotation += static_cast<int>(vsDraw.spaceWidth * 2); // Margins
+                               rcSegment.left = static_cast<XYPOSITION>(xStart + indent);
+                               rcSegment.right = rcSegment.left + widthAnnotation;
+                       }
+                       if (widthAnnotation > lineWidthMaxSeen)
+                               lineWidthMaxSeen = widthAnnotation;
+               }
+               const int annotationLines = model.pdoc->AnnotationLines(line);
+               size_t start = 0;
+               size_t lengthAnnotation = stAnnotation.LineLength(start);
+               int lineInAnnotation = 0;
+               while ((lineInAnnotation < annotationLine) && (start < stAnnotation.length)) {
+                       start += lengthAnnotation + 1;
+                       lengthAnnotation = stAnnotation.LineLength(start);
+                       lineInAnnotation++;
+               }
+               PRectangle rcText = rcSegment;
+               if ((phase & drawBack) && AnnotationBoxedOrIndented(vsDraw.annotationVisible)) {
+                       surface->FillRectangle(rcText,
+                               vsDraw.styles[stAnnotation.StyleAt(start) + 
vsDraw.annotationStyleOffset].back);
+                       rcText.left += vsDraw.spaceWidth;
+               }
+               DrawStyledText(surface, vsDraw, vsDraw.annotationStyleOffset, rcText,
+                       stAnnotation, start, lengthAnnotation, phase);
+               if ((phase & drawBack) && (vsDraw.annotationVisible == ANNOTATION_BOXED)) {
+                       surface->PenColour(vsDraw.styles[vsDraw.annotationStyleOffset].fore);
+                       surface->MoveTo(static_cast<int>(rcSegment.left), static_cast<int>(rcSegment.top));
+                       surface->LineTo(static_cast<int>(rcSegment.left), static_cast<int>(rcSegment.bottom));
+                       surface->MoveTo(static_cast<int>(rcSegment.right), static_cast<int>(rcSegment.top));
+                       surface->LineTo(static_cast<int>(rcSegment.right), 
static_cast<int>(rcSegment.bottom));
+                       if (subLine == ll->lines) {
+                               surface->MoveTo(static_cast<int>(rcSegment.left), 
static_cast<int>(rcSegment.top));
+                               surface->LineTo(static_cast<int>(rcSegment.right), 
static_cast<int>(rcSegment.top));
+                       }
+                       if (subLine == ll->lines + annotationLines - 1) {
+                               surface->MoveTo(static_cast<int>(rcSegment.left), 
static_cast<int>(rcSegment.bottom - 1));
+                               surface->LineTo(static_cast<int>(rcSegment.right), 
static_cast<int>(rcSegment.bottom - 1));
+                       }
+               }
+       }
+}
+
+static void DrawBlockCaret(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       int subLine, int xStart, Sci::Position offset, Sci::Position posCaret, PRectangle rcCaret, 
ColourDesired caretColour) {
+
+       Sci::Position lineStart = ll->LineStart(subLine);
+       Sci::Position posBefore = posCaret;
+       Sci::Position posAfter = model.pdoc->MovePositionOutsideChar(posCaret + 1, 1);
+       Sci::Position numCharsToDraw = posAfter - posCaret;
+
+       // Work out where the starting and ending offsets are. We need to
+       // see if the previous character shares horizontal space, such as a
+       // glyph / combining character. If so we'll need to draw that too.
+       Sci::Position offsetFirstChar = offset;
+       Sci::Position offsetLastChar = offset + (posAfter - posCaret);
+       while ((posBefore > 0) && ((offsetLastChar - numCharsToDraw) >= lineStart)) {
+               if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - numCharsToDraw]) > 0) {
+                       // The char does not share horizontal space
+                       break;
+               }
+               // Char shares horizontal space, update the numChars to draw
+               // Update posBefore to point to the prev char
+               posBefore = model.pdoc->MovePositionOutsideChar(posBefore - 1, -1);
+               numCharsToDraw = posAfter - posBefore;
+               offsetFirstChar = offset - (posCaret - posBefore);
+       }
+
+       // See if the next character shares horizontal space, if so we'll
+       // need to draw that too.
+       if (offsetFirstChar < 0)
+               offsetFirstChar = 0;
+       numCharsToDraw = offsetLastChar - offsetFirstChar;
+       while ((offsetLastChar < ll->LineStart(subLine + 1)) && (offsetLastChar <= ll->numCharsInLine)) {
+               // Update posAfter to point to the 2nd next char, this is where
+               // the next character ends, and 2nd next begins. We'll need
+               // to compare these two
+               posBefore = posAfter;
+               posAfter = model.pdoc->MovePositionOutsideChar(posAfter + 1, 1);
+               offsetLastChar = offset + (posAfter - posCaret);
+               if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - (posAfter - posBefore)]) 
0) {
+                       // The char does not share horizontal space
+                       break;
+               }
+               // Char shares horizontal space, update the numChars to draw
+               numCharsToDraw = offsetLastChar - offsetFirstChar;
+       }
+
+       // We now know what to draw, update the caret drawing rectangle
+       rcCaret.left = ll->positions[offsetFirstChar] - ll->positions[lineStart] + xStart;
+       rcCaret.right = ll->positions[offsetFirstChar + numCharsToDraw] - ll->positions[lineStart] + xStart;
+
+       // Adjust caret position to take into account any word wrapping symbols.
+       if ((ll->wrapIndent != 0) && (lineStart != 0)) {
+               XYPOSITION wordWrapCharWidth = ll->wrapIndent;
+               rcCaret.left += wordWrapCharWidth;
+               rcCaret.right += wordWrapCharWidth;
+       }
+
+       // This character is where the caret block is, we override the colours
+       // (inversed) for drawing the caret here.
+       int styleMain = ll->styles[offsetFirstChar];
+       FontAlias fontText = vsDraw.styles[styleMain].font;
+       surface->DrawTextClipped(rcCaret, fontText,
+               rcCaret.top + vsDraw.maxAscent, &ll->chars[offsetFirstChar],
+               numCharsToDraw, vsDraw.styles[styleMain].back,
+               caretColour);
+}
+
+void EditView::DrawCarets(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       Sci::Line lineDoc, int xStart, PRectangle rcLine, int subLine) const {
+       // When drag is active it is the only caret drawn
+       const bool drawDrag = model.posDrag.IsValid();
+       if (hideSelection && !drawDrag)
+               return;
+       const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
+       // For each selection draw
+       for (size_t r = 0; (r<model.sel.Count()) || drawDrag; r++) {
+               const bool mainCaret = r == model.sel.Main();
+               SelectionPosition posCaret = (drawDrag ? model.posDrag : model.sel.Range(r).caret);
+               if (vsDraw.caretStyle == CARETSTYLE_BLOCK && !drawDrag && posCaret > 
model.sel.Range(r).anchor) {
+                       if (posCaret.VirtualSpace() > 0)
+                               posCaret.SetVirtualSpace(posCaret.VirtualSpace() - 1);
+                       else
+                               
posCaret.SetPosition(model.pdoc->MovePositionOutsideChar(posCaret.Position()-1, -1));
+               }
+               const int offset = posCaret.Position() - posLineStart;
+               const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
+               const XYPOSITION virtualOffset = posCaret.VirtualSpace() * spaceWidth;
+               if (ll->InLine(offset, subLine) && offset <= ll->numCharsBeforeEOL) {
+                       XYPOSITION xposCaret = ll->positions[offset] + virtualOffset - 
ll->positions[ll->LineStart(subLine)];
+                       if (ll->wrapIndent != 0) {
+                               const Sci::Position lineStart = ll->LineStart(subLine);
+                               if (lineStart != 0)     // Wrapped
+                                       xposCaret += ll->wrapIndent;
+                       }
+                       const bool caretBlinkState = (model.caret.active && model.caret.on) || 
(!additionalCaretsBlink && !mainCaret);
+                       const bool caretVisibleState = additionalCaretsVisible || mainCaret;
+                       if ((xposCaret >= 0) && (vsDraw.caretWidth > 0) && (vsDraw.caretStyle != 
CARETSTYLE_INVISIBLE) &&
+                               ((model.posDrag.IsValid()) || (caretBlinkState && caretVisibleState))) {
+                               bool caretAtEOF = false;
+                               bool caretAtEOL = false;
+                               bool drawBlockCaret = false;
+                               XYPOSITION widthOverstrikeCaret;
+                               XYPOSITION caretWidthOffset = 0;
+                               PRectangle rcCaret = rcLine;
+
+                               if (posCaret.Position() == model.pdoc->Length()) {   // At end of document
+                                       caretAtEOF = true;
+                                       widthOverstrikeCaret = vsDraw.aveCharWidth;
+                               } else if ((posCaret.Position() - posLineStart) >= ll->numCharsInLine) {      
  // At end of line
+                                       caretAtEOL = true;
+                                       widthOverstrikeCaret = vsDraw.aveCharWidth;
+                               } else {
+                                       const int widthChar = model.pdoc->LenChar(posCaret.Position());
+                                       widthOverstrikeCaret = ll->positions[offset + widthChar] - 
ll->positions[offset];
+                               }
+                               if (widthOverstrikeCaret < 3)   // Make sure its visible
+                                       widthOverstrikeCaret = 3;
+
+                               if (xposCaret > 0)
+                                       caretWidthOffset = 0.51f;       // Move back so overlaps both 
character cells.
+                               xposCaret += xStart;
+                               if (model.posDrag.IsValid()) {
+                                       /* Dragging text, use a line caret */
+                                       rcCaret.left = static_cast<XYPOSITION>(RoundXYPosition(xposCaret - 
caretWidthOffset));
+                                       rcCaret.right = rcCaret.left + vsDraw.caretWidth;
+                               } else if (model.inOverstrike && drawOverstrikeCaret) {
+                                       /* Overstrike (insert mode), use a modified bar caret */
+                                       rcCaret.top = rcCaret.bottom - 2;
+                                       rcCaret.left = xposCaret + 1;
+                                       rcCaret.right = rcCaret.left + widthOverstrikeCaret - 1;
+                               } else if ((vsDraw.caretStyle == CARETSTYLE_BLOCK) || imeCaretBlockOverride) {
+                                       /* Block caret */
+                                       rcCaret.left = xposCaret;
+                                       if (!caretAtEOL && !caretAtEOF && (ll->chars[offset] != '\t') && 
!(IsControlCharacter(ll->chars[offset]))) {
+                                               drawBlockCaret = true;
+                                               rcCaret.right = xposCaret + widthOverstrikeCaret;
+                                       } else {
+                                               rcCaret.right = xposCaret + vsDraw.aveCharWidth;
+                                       }
+                               } else {
+                                       /* Line caret */
+                                       rcCaret.left = static_cast<XYPOSITION>(RoundXYPosition(xposCaret - 
caretWidthOffset));
+                                       rcCaret.right = rcCaret.left + vsDraw.caretWidth;
+                               }
+                               ColourDesired caretColour = mainCaret ? vsDraw.caretcolour : 
vsDraw.additionalCaretColour;
+                               if (drawBlockCaret) {
+                                       DrawBlockCaret(surface, model, vsDraw, ll, subLine, xStart, offset, 
posCaret.Position(), rcCaret, caretColour);
+                               } else {
+                                       surface->FillRectangle(rcCaret, caretColour);
+                               }
+                       }
+               }
+               if (drawDrag)
+                       break;
+       }
+}
+
+static void DrawWrapIndentAndMarker(Surface *surface, const ViewStyle &vsDraw, const LineLayout *ll,
+       int xStart, PRectangle rcLine, ColourOptional background, DrawWrapMarkerFn customDrawWrapMarker,
+       bool caretActive) {
+       // default bgnd here..
+       surface->FillRectangle(rcLine, background.isSet ? background :
+               vsDraw.styles[STYLE_DEFAULT].back);
+
+       if (vsDraw.IsLineFrameOpaque(caretActive, ll->containsCaret)) {
+               const int width = vsDraw.GetFrameWidth();
+               // Draw left of frame under marker
+               DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
+                       PRectangle(rcLine.left, rcLine.top, rcLine.left + width, rcLine.bottom));
+       }
+
+       if (vsDraw.wrapVisualFlags & SC_WRAPVISUALFLAG_START) {
+
+               // draw continuation rect
+               PRectangle rcPlace = rcLine;
+
+               rcPlace.left = static_cast<XYPOSITION>(xStart);
+               rcPlace.right = rcPlace.left + ll->wrapIndent;
+
+               if (vsDraw.wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_START_BY_TEXT)
+                       rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
+               else
+                       rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
+
+               if (customDrawWrapMarker == NULL) {
+                       DrawWrapMarker(surface, rcPlace, false, vsDraw.WrapColour());
+               } else {
+                       customDrawWrapMarker(surface, rcPlace, false, vsDraw.WrapColour());
+               }
+       }
+}
+
+void EditView::DrawBackground(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       PRectangle rcLine, Range lineRange, Sci::Position posLineStart, int xStart,
+       int subLine, ColourOptional background) const {
+
+       const bool selBackDrawn = vsDraw.SelectionBackgroundDrawn();
+       bool inIndentation = subLine == 0;      // Do not handle indentation except on first subline.
+       const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
+       // Does not take margin into account but not significant
+       const int xStartVisible = static_cast<int>(subLineStart)-xStart;
+
+       BreakFinder bfBack(ll, &model.sel, lineRange, posLineStart, xStartVisible, selBackDrawn, model.pdoc, 
&model.reprs, NULL);
+
+       const bool drawWhitespaceBackground = vsDraw.WhitespaceBackgroundDrawn() && !background.isSet;
+
+       // Background drawing loop
+       while (bfBack.More()) {
+
+               const TextSegment ts = bfBack.Next();
+               const Sci::Position i = ts.end() - 1;
+               const Sci::Position iDoc = i + posLineStart;
+
+               PRectangle rcSegment = rcLine;
+               rcSegment.left = ll->positions[ts.start] + xStart - static_cast<XYPOSITION>(subLineStart);
+               rcSegment.right = ll->positions[ts.end()] + xStart - static_cast<XYPOSITION>(subLineStart);
+               // Only try to draw if really visible - enhances performance by not calling environment to
+               // draw strings that are completely past the right side of the window.
+               if (!rcSegment.Empty() && rcSegment.Intersects(rcLine)) {
+                       // Clip to line rectangle, since may have a huge position which will not work with 
some platforms
+                       if (rcSegment.left < rcLine.left)
+                               rcSegment.left = rcLine.left;
+                       if (rcSegment.right > rcLine.right)
+                               rcSegment.right = rcLine.right;
+
+                       const int inSelection = hideSelection ? 0 : model.sel.CharacterInSelection(iDoc);
+                       const bool inHotspot = (ll->hotspot.Valid()) && ll->hotspot.ContainsCharacter(iDoc);
+                       ColourDesired textBack = TextBackground(model, vsDraw, ll, background, inSelection,
+                               inHotspot, ll->styles[i], i);
+                       if (ts.representation) {
+                               if (ll->chars[i] == '\t') {
+                                       // Tab display
+                                       if (drawWhitespaceBackground && 
vsDraw.WhiteSpaceVisible(inIndentation))
+                                               textBack = vsDraw.whitespaceColours.back;
+                               } else {
+                                       // Blob display
+                                       inIndentation = false;
+                               }
+                               surface->FillRectangle(rcSegment, textBack);
+                       } else {
+                               // Normal text display
+                               surface->FillRectangle(rcSegment, textBack);
+                               if (vsDraw.viewWhitespace != wsInvisible) {
+                                       for (int cpos = 0; cpos <= i - ts.start; cpos++) {
+                                               if (ll->chars[cpos + ts.start] == ' ') {
+                                                       if (drawWhitespaceBackground && 
vsDraw.WhiteSpaceVisible(inIndentation)) {
+                                                               PRectangle rcSpace(
+                                                                       ll->positions[cpos + ts.start] + 
xStart - static_cast<XYPOSITION>(subLineStart),
+                                                                       rcSegment.top,
+                                                                       ll->positions[cpos + ts.start + 1] + 
xStart - static_cast<XYPOSITION>(subLineStart),
+                                                                       rcSegment.bottom);
+                                                               surface->FillRectangle(rcSpace, 
vsDraw.whitespaceColours.back);
+                                                       }
+                                               } else {
+                                                       inIndentation = false;
+                                               }
+                                       }
+                               }
+                       }
+               } else if (rcSegment.left > rcLine.right) {
+                       break;
+               }
+       }
+}
+
+static void DrawEdgeLine(Surface *surface, const ViewStyle &vsDraw, const LineLayout *ll, PRectangle rcLine,
+       Range lineRange, int xStart) {
+       if (vsDraw.edgeState == EDGE_LINE) {
+               PRectangle rcSegment = rcLine;
+               int edgeX = static_cast<int>(vsDraw.theEdge.column * vsDraw.spaceWidth);
+               rcSegment.left = static_cast<XYPOSITION>(edgeX + xStart);
+               if ((ll->wrapIndent != 0) && (lineRange.start != 0))
+                       rcSegment.left -= ll->wrapIndent;
+               rcSegment.right = rcSegment.left + 1;
+               surface->FillRectangle(rcSegment, vsDraw.theEdge.colour);
+       } else if (vsDraw.edgeState == EDGE_MULTILINE) {
+               for (size_t edge = 0; edge < vsDraw.theMultiEdge.size(); edge++) {
+                       if (vsDraw.theMultiEdge[edge].column >= 0) {
+                               PRectangle rcSegment = rcLine;
+                               int edgeX = static_cast<int>(vsDraw.theMultiEdge[edge].column * 
vsDraw.spaceWidth);
+                               rcSegment.left = static_cast<XYPOSITION>(edgeX + xStart);
+                               if ((ll->wrapIndent != 0) && (lineRange.start != 0))
+                                       rcSegment.left -= ll->wrapIndent;
+                               rcSegment.right = rcSegment.left + 1;
+                               surface->FillRectangle(rcSegment, vsDraw.theMultiEdge[edge].colour);
+                       }
+               }
+       }
+}
+
+// Draw underline mark as part of background if not transparent
+static void DrawMarkUnderline(Surface *surface, const EditModel &model, const ViewStyle &vsDraw,
+       Sci::Line line, PRectangle rcLine) {
+       int marks = model.pdoc->GetMark(line);
+       for (int markBit = 0; (markBit < 32) && marks; markBit++) {
+               if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_UNDERLINE) &&
+                       (vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
+                       PRectangle rcUnderline = rcLine;
+                       rcUnderline.top = rcUnderline.bottom - 2;
+                       surface->FillRectangle(rcUnderline, vsDraw.markers[markBit].back);
+               }
+               marks >>= 1;
+       }
+}
+static void DrawTranslucentSelection(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, 
const LineLayout *ll,
+       Sci::Line line, PRectangle rcLine, int subLine, Range lineRange, int xStart) {
+       if ((vsDraw.selAlpha != SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha != SC_ALPHA_NOALPHA)) {
+               const Sci::Position posLineStart = model.pdoc->LineStart(line);
+               const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
+               // For each selection draw
+               Sci::Position virtualSpaces = 0;
+               if (subLine == (ll->lines - 1)) {
+                       virtualSpaces = model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line));
+               }
+               const SelectionPosition posStart(posLineStart + lineRange.start);
+               const SelectionPosition posEnd(posLineStart + lineRange.end, virtualSpaces);
+               const SelectionSegment virtualSpaceRange(posStart, posEnd);
+               for (size_t r = 0; r < model.sel.Count(); r++) {
+                       const int alpha = (r == model.sel.Main()) ? vsDraw.selAlpha : 
vsDraw.selAdditionalAlpha;
+                       if (alpha != SC_ALPHA_NOALPHA) {
+                               const SelectionSegment portion = 
model.sel.Range(r).Intersect(virtualSpaceRange);
+                               if (!portion.Empty()) {
+                                       const XYPOSITION spaceWidth = 
vsDraw.styles[ll->EndLineStyle()].spaceWidth;
+                                       PRectangle rcSegment = rcLine;
+                                       rcSegment.left = xStart + ll->positions[portion.start.Position() - 
posLineStart] -
+                                               
static_cast<XYPOSITION>(subLineStart)+portion.start.VirtualSpace() * spaceWidth;
+                                       rcSegment.right = xStart + ll->positions[portion.end.Position() - 
posLineStart] -
+                                               
static_cast<XYPOSITION>(subLineStart)+portion.end.VirtualSpace() * spaceWidth;
+                                       if ((ll->wrapIndent != 0) && (lineRange.start != 0)) {
+                                               if ((portion.start.Position() - posLineStart) == 
lineRange.start && model.sel.Range(r).ContainsCharacter(portion.start.Position() - 1))
+                                                       rcSegment.left -= static_cast<int>(ll->wrapIndent); 
// indentation added to xStart was truncated to int, so we do the same here
+                                       }
+                                       rcSegment.left = (rcSegment.left > rcLine.left) ? rcSegment.left : 
rcLine.left;
+                                       rcSegment.right = (rcSegment.right < rcLine.right) ? rcSegment.right 
: rcLine.right;
+                                       if (rcSegment.right > rcLine.left)
+                                               SimpleAlphaRectangle(surface, rcSegment, 
SelectionBackground(vsDraw, r == model.sel.Main(), model.primarySelection), alpha);
+                               }
+                       }
+               }
+       }
+}
+
+// Draw any translucent whole line states
+static void DrawTranslucentLineState(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, 
const LineLayout *ll,
+       Sci::Line line, PRectangle rcLine, int subLine) {
+       if ((model.caret.active || vsDraw.alwaysShowCaretLineBackground) && vsDraw.showCaretLineBackground && 
ll->containsCaret &&
+               vsDraw.caretLineAlpha != SC_ALPHA_NOALPHA) {
+               if (vsDraw.caretLineFrame) {
+                       DrawCaretLineFramed(surface, vsDraw, ll, rcLine, subLine);
+               } else {
+                       SimpleAlphaRectangle(surface, rcLine, vsDraw.caretLineBackground, 
vsDraw.caretLineAlpha);
+               }
+       }
+       const int marksOfLine = model.pdoc->GetMark(line);
+       int marksDrawnInText = marksOfLine & vsDraw.maskDrawInText;
+       for (int markBit = 0; (markBit < 32) && marksDrawnInText; markBit++) {
+               if (marksDrawnInText & 1) {
+                       if (vsDraw.markers[markBit].markType == SC_MARK_BACKGROUND) {
+                               SimpleAlphaRectangle(surface, rcLine, vsDraw.markers[markBit].back, 
vsDraw.markers[markBit].alpha);
+                       } else if (vsDraw.markers[markBit].markType == SC_MARK_UNDERLINE) {
+                               PRectangle rcUnderline = rcLine;
+                               rcUnderline.top = rcUnderline.bottom - 2;
+                               SimpleAlphaRectangle(surface, rcUnderline, vsDraw.markers[markBit].back, 
vsDraw.markers[markBit].alpha);
+                       }
+               }
+               marksDrawnInText >>= 1;
+       }
+       int marksDrawnInLine = marksOfLine & vsDraw.maskInLine;
+       for (int markBit = 0; (markBit < 32) && marksDrawnInLine; markBit++) {
+               if (marksDrawnInLine & 1) {
+                       SimpleAlphaRectangle(surface, rcLine, vsDraw.markers[markBit].back, 
vsDraw.markers[markBit].alpha);
+               }
+               marksDrawnInLine >>= 1;
+       }
+}
+
+void EditView::DrawForeground(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       Sci::Line lineVisible, PRectangle rcLine, Range lineRange, Sci::Position posLineStart, int xStart,
+       int subLine, ColourOptional background) {
+
+       const bool selBackDrawn = vsDraw.SelectionBackgroundDrawn();
+       const bool drawWhitespaceBackground = vsDraw.WhitespaceBackgroundDrawn() && !background.isSet;
+       bool inIndentation = subLine == 0;      // Do not handle indentation except on first subline.
+
+       const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
+       const XYPOSITION indentWidth = model.pdoc->IndentSize() * vsDraw.spaceWidth;
+
+       // Does not take margin into account but not significant
+       const int xStartVisible = static_cast<int>(subLineStart)-xStart;
+
+       // Foreground drawing loop
+       BreakFinder bfFore(ll, &model.sel, lineRange, posLineStart, xStartVisible,
+               (((phasesDraw == phasesOne) && selBackDrawn) || vsDraw.selColours.fore.isSet), model.pdoc, 
&model.reprs, &vsDraw);
+
+       while (bfFore.More()) {
+
+               const TextSegment ts = bfFore.Next();
+               const Sci::Position i = ts.end() - 1;
+               const Sci::Position iDoc = i + posLineStart;
+
+               PRectangle rcSegment = rcLine;
+               rcSegment.left = ll->positions[ts.start] + xStart - static_cast<XYPOSITION>(subLineStart);
+               rcSegment.right = ll->positions[ts.end()] + xStart - static_cast<XYPOSITION>(subLineStart);
+               // Only try to draw if really visible - enhances performance by not calling environment to
+               // draw strings that are completely past the right side of the window.
+               if (rcSegment.Intersects(rcLine)) {
+                       int styleMain = ll->styles[i];
+                       ColourDesired textFore = vsDraw.styles[styleMain].fore;
+                       FontAlias textFont = vsDraw.styles[styleMain].font;
+                       //hotspot foreground
+                       const bool inHotspot = (ll->hotspot.Valid()) && ll->hotspot.ContainsCharacter(iDoc);
+                       if (inHotspot) {
+                               if (vsDraw.hotspotColours.fore.isSet)
+                                       textFore = vsDraw.hotspotColours.fore;
+                       }
+                       if (vsDraw.indicatorsSetFore) {
+                               // At least one indicator sets the text colour so see if it applies to this 
segment
+                               for (const Decoration *deco : model.pdoc->decorations.View()) {
+                                       const int indicatorValue = deco->rs.ValueAt(ts.start + posLineStart);
+                                       if (indicatorValue) {
+                                               const Indicator &indicator = 
vsDraw.indicators[deco->Indicator()];
+                                               const bool hover = indicator.IsDynamic() &&
+                                                       ((model.hoverIndicatorPos >= ts.start + posLineStart) 
&&
+                                                       (model.hoverIndicatorPos <= ts.end() + posLineStart));
+                                               if (hover) {
+                                                       if (indicator.sacHover.style == INDIC_TEXTFORE) {
+                                                               textFore = indicator.sacHover.fore;
+                                                       }
+                                               } else {
+                                                       if (indicator.sacNormal.style == INDIC_TEXTFORE) {
+                                                               if (indicator.Flags() & 
SC_INDICFLAG_VALUEFORE)
+                                                                       textFore = indicatorValue & 
SC_INDICVALUEMASK;
+                                                               else
+                                                                       textFore = indicator.sacNormal.fore;
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+                       const int inSelection = hideSelection ? 0 : model.sel.CharacterInSelection(iDoc);
+                       if (inSelection && (vsDraw.selColours.fore.isSet)) {
+                               textFore = (inSelection == 1) ? vsDraw.selColours.fore : 
vsDraw.selAdditionalForeground;
+                       }
+                       ColourDesired textBack = TextBackground(model, vsDraw, ll, background, inSelection, 
inHotspot, styleMain, i);
+                       if (ts.representation) {
+                               if (ll->chars[i] == '\t') {
+                                       // Tab display
+                                       if (phasesDraw == phasesOne) {
+                                               if (drawWhitespaceBackground && 
vsDraw.WhiteSpaceVisible(inIndentation))
+                                                       textBack = vsDraw.whitespaceColours.back;
+                                               surface->FillRectangle(rcSegment, textBack);
+                                       }
+                                       if (inIndentation && vsDraw.viewIndentationGuides == ivReal) {
+                                               for (int indentCount = static_cast<int>((ll->positions[i] + 
epsilon) / indentWidth);
+                                                       indentCount <= (ll->positions[i + 1] - epsilon) / 
indentWidth;
+                                                       indentCount++) {
+                                                       if (indentCount > 0) {
+                                                               int xIndent = static_cast<int>(indentCount * 
indentWidth);
+                                                               DrawIndentGuide(surface, lineVisible, 
vsDraw.lineHeight, xIndent + xStart, rcSegment,
+                                                                       (ll->xHighlightGuide == xIndent));
+                                                       }
+                                               }
+                                       }
+                                       if (vsDraw.viewWhitespace != wsInvisible) {
+                                               if (vsDraw.WhiteSpaceVisible(inIndentation)) {
+                                                       if (vsDraw.whitespaceColours.fore.isSet)
+                                                               textFore = vsDraw.whitespaceColours.fore;
+                                                       surface->PenColour(textFore);
+                                                       PRectangle rcTab(rcSegment.left + 1, rcSegment.top + 
tabArrowHeight,
+                                                               rcSegment.right - 1, rcSegment.bottom - 
vsDraw.maxDescent);
+                                                       if (customDrawTabArrow == NULL)
+                                                               DrawTabArrow(surface, rcTab, 
static_cast<int>(rcSegment.top + vsDraw.lineHeight / 2), vsDraw);
+                                                       else
+                                                               customDrawTabArrow(surface, rcTab, 
static_cast<int>(rcSegment.top + vsDraw.lineHeight / 2));
+                                               }
+                                       }
+                               } else {
+                                       inIndentation = false;
+                                       if (vsDraw.controlCharSymbol >= 32) {
+                                               // Using one font for all control characters so it can be 
controlled independently to ensure
+                                               // the box goes around the characters tightly. Seems to be no 
way to work out what height
+                                               // is taken by an individual character - internal leading 
gives varying results.
+                                               FontAlias ctrlCharsFont = 
vsDraw.styles[STYLE_CONTROLCHAR].font;
+                                               char cc[2] = { static_cast<char>(vsDraw.controlCharSymbol), 
'\0' };
+                                               surface->DrawTextNoClip(rcSegment, ctrlCharsFont,
+                                                       rcSegment.top + vsDraw.maxAscent,
+                                                       cc, 1, textBack, textFore);
+                                       } else {
+                                               DrawTextBlob(surface, vsDraw, rcSegment, 
ts.representation->stringRep.c_str(),
+                                                       textBack, textFore, phasesDraw == phasesOne);
+                                       }
+                               }
+                       } else {
+                               // Normal text display
+                               if (vsDraw.styles[styleMain].visible) {
+                                       if (phasesDraw != phasesOne) {
+                                               surface->DrawTextTransparent(rcSegment, textFont,
+                                                       rcSegment.top + vsDraw.maxAscent, 
&ll->chars[ts.start],
+                                                       i - ts.start + 1, textFore);
+                                       } else {
+                                               surface->DrawTextNoClip(rcSegment, textFont,
+                                                       rcSegment.top + vsDraw.maxAscent, 
&ll->chars[ts.start],
+                                                       i - ts.start + 1, textFore, textBack);
+                                       }
+                               }
+                               if (vsDraw.viewWhitespace != wsInvisible ||
+                                       (inIndentation && vsDraw.viewIndentationGuides != ivNone)) {
+                                       for (int cpos = 0; cpos <= i - ts.start; cpos++) {
+                                               if (ll->chars[cpos + ts.start] == ' ') {
+                                                       if (vsDraw.viewWhitespace != wsInvisible) {
+                                                               if (vsDraw.whitespaceColours.fore.isSet)
+                                                                       textFore = 
vsDraw.whitespaceColours.fore;
+                                                               if (vsDraw.WhiteSpaceVisible(inIndentation)) {
+                                                                       XYPOSITION xmid = (ll->positions[cpos 
+ ts.start] + ll->positions[cpos + ts.start + 1]) / 2;
+                                                                       if ((phasesDraw == phasesOne) && 
drawWhitespaceBackground) {
+                                                                               textBack = 
vsDraw.whitespaceColours.back;
+                                                                               PRectangle rcSpace(
+                                                                                       ll->positions[cpos + 
ts.start] + xStart - static_cast<XYPOSITION>(subLineStart),
+                                                                                       rcSegment.top,
+                                                                                       ll->positions[cpos + 
ts.start + 1] + xStart - static_cast<XYPOSITION>(subLineStart),
+                                                                                       rcSegment.bottom);
+                                                                               
surface->FillRectangle(rcSpace, textBack);
+                                                                       }
+                                                                       const int halfDotWidth = 
vsDraw.whitespaceSize / 2;
+                                                                       PRectangle rcDot(xmid + xStart - 
halfDotWidth - static_cast<XYPOSITION>(subLineStart),
+                                                                               rcSegment.top + 
vsDraw.lineHeight / 2, 0.0f, 0.0f);
+                                                                       rcDot.right = rcDot.left + 
vsDraw.whitespaceSize;
+                                                                       rcDot.bottom = rcDot.top + 
vsDraw.whitespaceSize;
+                                                                       surface->FillRectangle(rcDot, 
textFore);
+                                                               }
+                                                       }
+                                                       if (inIndentation && vsDraw.viewIndentationGuides == 
ivReal) {
+                                                               for (int indentCount = 
static_cast<int>((ll->positions[cpos + ts.start] + epsilon) / indentWidth);
+                                                                       indentCount <= (ll->positions[cpos + 
ts.start + 1] - epsilon) / indentWidth;
+                                                                       indentCount++) {
+                                                                       if (indentCount > 0) {
+                                                                               int xIndent = 
static_cast<int>(indentCount * indentWidth);
+                                                                               DrawIndentGuide(surface, 
lineVisible, vsDraw.lineHeight, xIndent + xStart, rcSegment,
+                                                                                       (ll->xHighlightGuide 
== xIndent));
+                                                                       }
+                                                               }
+                                                       }
+                                               } else {
+                                                       inIndentation = false;
+                                               }
+                                       }
+                               }
+                       }
+                       if (ll->hotspot.Valid() && vsDraw.hotspotUnderline && 
ll->hotspot.ContainsCharacter(iDoc)) {
+                               PRectangle rcUL = rcSegment;
+                               rcUL.top = rcUL.top + vsDraw.maxAscent + 1;
+                               rcUL.bottom = rcUL.top + 1;
+                               if (vsDraw.hotspotColours.fore.isSet)
+                                       surface->FillRectangle(rcUL, vsDraw.hotspotColours.fore);
+                               else
+                                       surface->FillRectangle(rcUL, textFore);
+                       } else if (vsDraw.styles[styleMain].underline) {
+                               PRectangle rcUL = rcSegment;
+                               rcUL.top = rcUL.top + vsDraw.maxAscent + 1;
+                               rcUL.bottom = rcUL.top + 1;
+                               surface->FillRectangle(rcUL, textFore);
+                       }
+               } else if (rcSegment.left > rcLine.right) {
+                       break;
+               }
+       }
+}
+
+void EditView::DrawIndentGuidesOverEmpty(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, 
const LineLayout *ll,
+       Sci::Line line, Sci::Line lineVisible, PRectangle rcLine, int xStart, int subLine) {
+       if ((vsDraw.viewIndentationGuides == ivLookForward || vsDraw.viewIndentationGuides == ivLookBoth)
+               && (subLine == 0)) {
+               const Sci::Position posLineStart = model.pdoc->LineStart(line);
+               int indentSpace = model.pdoc->GetLineIndentation(line);
+               int xStartText = static_cast<int>(ll->positions[model.pdoc->GetLineIndentPosition(line) - 
posLineStart]);
+
+               // Find the most recent line with some text
+
+               Sci::Line lineLastWithText = line;
+               while (lineLastWithText > std::max(line - 20, 0) && 
model.pdoc->IsWhiteLine(lineLastWithText)) {
+                       lineLastWithText--;
+               }
+               if (lineLastWithText < line) {
+                       xStartText = 100000;    // Don't limit to visible indentation on empty line
+                       // This line is empty, so use indentation of last line with text
+                       int indentLastWithText = model.pdoc->GetLineIndentation(lineLastWithText);
+                       const int isFoldHeader = model.pdoc->GetLevel(lineLastWithText) & 
SC_FOLDLEVELHEADERFLAG;
+                       if (isFoldHeader) {
+                               // Level is one more level than parent
+                               indentLastWithText += model.pdoc->IndentSize();
+                       }
+                       if (vsDraw.viewIndentationGuides == ivLookForward) {
+                               // In viLookForward mode, previous line only used if it is a fold header
+                               if (isFoldHeader) {
+                                       indentSpace = std::max(indentSpace, indentLastWithText);
+                               }
+                       } else {        // viLookBoth
+                               indentSpace = std::max(indentSpace, indentLastWithText);
+                       }
+               }
+
+               Sci::Line lineNextWithText = line;
+               while (lineNextWithText < std::min(line + 20, model.pdoc->LinesTotal()) && 
model.pdoc->IsWhiteLine(lineNextWithText)) {
+                       lineNextWithText++;
+               }
+               if (lineNextWithText > line) {
+                       xStartText = 100000;    // Don't limit to visible indentation on empty line
+                       // This line is empty, so use indentation of first next line with text
+                       indentSpace = std::max(indentSpace,
+                               model.pdoc->GetLineIndentation(lineNextWithText));
+               }
+
+               for (int indentPos = model.pdoc->IndentSize(); indentPos < indentSpace; indentPos += 
model.pdoc->IndentSize()) {
+                       int xIndent = static_cast<int>(indentPos * vsDraw.spaceWidth);
+                       if (xIndent < xStartText) {
+                               DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIndent + xStart, 
rcLine,
+                                       (ll->xHighlightGuide == xIndent));
+                       }
+               }
+       }
+}
+
+void EditView::DrawLine(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout 
*ll,
+       Sci::Line line, Sci::Line lineVisible, int xStart, PRectangle rcLine, int subLine, DrawPhase phase) {
+
+       if (subLine >= ll->lines) {
+               DrawAnnotation(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, phase);
+               return; // No further drawing
+       }
+
+       // See if something overrides the line background color.
+       const ColourOptional background = vsDraw.Background(model.pdoc->GetMark(line), model.caret.active, 
ll->containsCaret);
+
+       const Sci::Position posLineStart = model.pdoc->LineStart(line);
+
+       const Range lineRange = ll->SubLineRange(subLine);
+       const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
+
+       if ((ll->wrapIndent != 0) && (subLine > 0)) {
+               if (phase & drawBack) {
+                       DrawWrapIndentAndMarker(surface, vsDraw, ll, xStart, rcLine, background, 
customDrawWrapMarker, model.caret.active);
+               }
+               xStart += static_cast<int>(ll->wrapIndent);
+       }
+
+       if (phasesDraw != phasesOne) {
+               if (phase & drawBack) {
+                       DrawBackground(surface, model, vsDraw, ll, rcLine, lineRange, posLineStart, xStart,
+                               subLine, background);
+                       DrawFoldDisplayText(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, 
subLineStart, drawBack);
+                       phase = static_cast<DrawPhase>(phase & ~drawBack);      // Remove drawBack to not 
draw again in DrawFoldDisplayText
+                       DrawEOL(surface, model, vsDraw, ll, rcLine, line, lineRange.end,
+                               xStart, subLine, subLineStart, background);
+                       if (vsDraw.IsLineFrameOpaque(model.caret.active, ll->containsCaret))
+                               DrawCaretLineFramed(surface, vsDraw, ll, rcLine, subLine);
+               }
+
+               if (phase & drawIndicatorsBack) {
+                       DrawIndicators(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, 
lineRange.end, true, model.hoverIndicatorPos);
+                       DrawEdgeLine(surface, vsDraw, ll, rcLine, lineRange, xStart);
+                       DrawMarkUnderline(surface, model, vsDraw, line, rcLine);
+               }
+       }
+
+       if (phase & drawText) {
+               DrawForeground(surface, model, vsDraw, ll, lineVisible, rcLine, lineRange, posLineStart, 
xStart,
+                       subLine, background);
+       }
+
+       if (phase & drawIndentationGuides) {
+               DrawIndentGuidesOverEmpty(surface, model, vsDraw, ll, line, lineVisible, rcLine, xStart, 
subLine);
+       }
+
+       if (phase & drawIndicatorsFore) {
+               DrawIndicators(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, lineRange.end, 
false, model.hoverIndicatorPos);
+       }
+
+       DrawFoldDisplayText(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, subLineStart, phase);
+
+       if (phasesDraw == phasesOne) {
+               DrawEOL(surface, model, vsDraw, ll, rcLine, line, lineRange.end,
+                       xStart, subLine, subLineStart, background);
+               if (vsDraw.IsLineFrameOpaque(model.caret.active, ll->containsCaret))
+                       DrawCaretLineFramed(surface, vsDraw, ll, rcLine, subLine);
+               DrawEdgeLine(surface, vsDraw, ll, rcLine, lineRange, xStart);
+               DrawMarkUnderline(surface, model, vsDraw, line, rcLine);
+       }
+
+       if (!hideSelection && (phase & drawSelectionTranslucent)) {
+               DrawTranslucentSelection(surface, model, vsDraw, ll, line, rcLine, subLine, lineRange, 
xStart);
+       }
+
+       if (phase & drawLineTranslucent) {
+               DrawTranslucentLineState(surface, model, vsDraw, ll, line, rcLine, subLine);
+       }
+}
+
+static void DrawFoldLines(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, Sci::Line line, 
PRectangle rcLine) {
+       const bool expanded = model.cs.GetExpanded(line);
+       const int level = model.pdoc->GetLevel(line);
+       const int levelNext = model.pdoc->GetLevel(line + 1);
+       if ((level & SC_FOLDLEVELHEADERFLAG) &&
+               (LevelNumber(level) < LevelNumber(levelNext))) {
+               // Paint the line above the fold
+               if ((expanded && (model.foldFlags & SC_FOLDFLAG_LINEBEFORE_EXPANDED))
+                       ||
+                       (!expanded && (model.foldFlags & SC_FOLDFLAG_LINEBEFORE_CONTRACTED))) {
+                       PRectangle rcFoldLine = rcLine;
+                       rcFoldLine.bottom = rcFoldLine.top + 1;
+                       surface->FillRectangle(rcFoldLine, vsDraw.styles[STYLE_DEFAULT].fore);
+               }
+               // Paint the line below the fold
+               if ((expanded && (model.foldFlags & SC_FOLDFLAG_LINEAFTER_EXPANDED))
+                       ||
+                       (!expanded && (model.foldFlags & SC_FOLDFLAG_LINEAFTER_CONTRACTED))) {
+                       PRectangle rcFoldLine = rcLine;
+                       rcFoldLine.top = rcFoldLine.bottom - 1;
+                       surface->FillRectangle(rcFoldLine, vsDraw.styles[STYLE_DEFAULT].fore);
+               }
+       }
+}
+
+void EditView::PaintText(Surface *surfaceWindow, const EditModel &model, PRectangle rcArea,
+       PRectangle rcClient, const ViewStyle &vsDraw) {
+       // Allow text at start of line to overlap 1 pixel into the margin as this displays
+       // serifs and italic stems for aliased text.
+       const int leftTextOverlap = ((model.xOffset == 0) && (vsDraw.leftMarginWidth > 0)) ? 1 : 0;
+
+       // Do the painting
+       if (rcArea.right > vsDraw.textStart - leftTextOverlap) {
+
+               Surface *surface = surfaceWindow;
+               if (bufferedDraw) {
+                       surface = pixmapLine.get();
+                       PLATFORM_ASSERT(pixmapLine->Initialised());
+               }
+               surface->SetUnicodeMode(SC_CP_UTF8 == model.pdoc->dbcsCodePage);
+               surface->SetDBCSMode(model.pdoc->dbcsCodePage);
+
+               const Point ptOrigin = model.GetVisibleOriginInMain();
+
+               const int screenLinePaintFirst = static_cast<int>(rcArea.top) / vsDraw.lineHeight;
+               const int xStart = vsDraw.textStart - model.xOffset + static_cast<int>(ptOrigin.x);
+
+               SelectionPosition posCaret = model.sel.RangeMain().caret;
+               if (model.posDrag.IsValid())
+                       posCaret = model.posDrag;
+               const Sci::Line lineCaret = model.pdoc->LineFromPosition(posCaret.Position());
+
+               PRectangle rcTextArea = rcClient;
+               if (vsDraw.marginInside) {
+                       rcTextArea.left += vsDraw.textStart;
+                       rcTextArea.right -= vsDraw.rightMarginWidth;
+               } else {
+                       rcTextArea = rcArea;
+               }
+
+               // Remove selection margin from drawing area so text will not be drawn
+               // on it in unbuffered mode.
+               if (!bufferedDraw && vsDraw.marginInside) {
+                       PRectangle rcClipText = rcTextArea;
+                       rcClipText.left -= leftTextOverlap;
+                       surfaceWindow->SetClip(rcClipText);
+               }
+
+               // Loop on visible lines
+               //double durLayout = 0.0;
+               //double durPaint = 0.0;
+               //double durCopy = 0.0;
+               //ElapsedTime etWhole;
+
+               const bool bracesIgnoreStyle = ((vsDraw.braceHighlightIndicatorSet && (model.bracesMatchStyle 
== STYLE_BRACELIGHT)) ||
+                       (vsDraw.braceBadLightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACEBAD)));
+
+               Sci::Line lineDocPrevious = -1; // Used to avoid laying out one document line multiple times
+               AutoLineLayout ll(llc, 0);
+               std::vector<DrawPhase> phases;
+               if ((phasesDraw == phasesMultiple) && !bufferedDraw) {
+                       for (DrawPhase phase = drawBack; phase <= drawCarets; phase = 
static_cast<DrawPhase>(phase * 2)) {
+                               phases.push_back(phase);
+                       }
+               } else {
+                       phases.push_back(drawAll);
+               }
+               for (const DrawPhase &phase : phases) {
+                       int ypos = 0;
+                       if (!bufferedDraw)
+                               ypos += screenLinePaintFirst * vsDraw.lineHeight;
+                       int yposScreen = screenLinePaintFirst * vsDraw.lineHeight;
+                       Sci::Line visibleLine = model.TopLineOfMain() + screenLinePaintFirst;
+                       while (visibleLine < model.cs.LinesDisplayed() && yposScreen < rcArea.bottom) {
+
+                               const Sci::Line lineDoc = model.cs.DocFromDisplay(visibleLine);
+                               // Only visible lines should be handled by the code within the loop
+                               PLATFORM_ASSERT(model.cs.GetVisible(lineDoc));
+                               const Sci::Line lineStartSet = model.cs.DisplayFromDoc(lineDoc);
+                               const int subLine = visibleLine - lineStartSet;
+
+                               // Copy this line and its styles from the document into local arrays
+                               // and determine the x position at which each character starts.
+                               //ElapsedTime et;
+                               if (lineDoc != lineDocPrevious) {
+                                       ll.Set(0);
+                                       ll.Set(RetrieveLineLayout(lineDoc, model));
+                                       LayoutLine(model, lineDoc, surface, vsDraw, ll, model.wrapWidth);
+                                       lineDocPrevious = lineDoc;
+                               }
+                               //durLayout += et.Duration(true);
+
+                               if (ll) {
+                                       ll->containsCaret = !hideSelection && (lineDoc == lineCaret);
+                                       ll->hotspot = model.GetHotSpotRange();
+
+                                       PRectangle rcLine = rcTextArea;
+                                       rcLine.top = static_cast<XYPOSITION>(ypos);
+                                       rcLine.bottom = static_cast<XYPOSITION>(ypos + vsDraw.lineHeight);
+
+                                       Range rangeLine(model.pdoc->LineStart(lineDoc), 
model.pdoc->LineStart(lineDoc + 1));
+
+                                       // Highlight the current braces if any
+                                       ll->SetBracesHighlight(rangeLine, model.braces, 
static_cast<char>(model.bracesMatchStyle),
+                                               static_cast<int>(model.highlightGuideColumn * 
vsDraw.spaceWidth), bracesIgnoreStyle);
+
+                                       if (leftTextOverlap && (bufferedDraw || ((phasesDraw < 
phasesMultiple) && (phase & drawBack)))) {
+                                               // Clear the left margin
+                                               PRectangle rcSpacer = rcLine;
+                                               rcSpacer.right = rcSpacer.left;
+                                               rcSpacer.left -= 1;
+                                               surface->FillRectangle(rcSpacer, 
vsDraw.styles[STYLE_DEFAULT].back);
+                                       }
+
+                                       DrawLine(surface, model, vsDraw, ll, lineDoc, visibleLine, xStart, 
rcLine, subLine, phase);
+                                       //durPaint += et.Duration(true);
+
+                                       // Restore the previous styles for the brace highlights in case 
layout is in cache.
+                                       ll->RestoreBracesHighlight(rangeLine, model.braces, 
bracesIgnoreStyle);
+
+                                       if (phase & drawFoldLines) {
+                                               DrawFoldLines(surface, model, vsDraw, lineDoc, rcLine);
+                                       }
+
+                                       if (phase & drawCarets) {
+                                               DrawCarets(surface, model, vsDraw, ll, lineDoc, xStart, 
rcLine, subLine);
+                                       }
+
+                                       if (bufferedDraw) {
+                                               Point from = Point::FromInts(vsDraw.textStart - 
leftTextOverlap, 0);
+                                               PRectangle rcCopyArea = PRectangle::FromInts(vsDraw.textStart 
- leftTextOverlap, yposScreen,
+                                                       static_cast<int>(rcClient.right - 
vsDraw.rightMarginWidth),
+                                                       yposScreen + vsDraw.lineHeight);
+                                               surfaceWindow->Copy(rcCopyArea, from, *pixmapLine);
+                                       }
+
+                                       lineWidthMaxSeen = std::max(
+                                               lineWidthMaxSeen, 
static_cast<int>(ll->positions[ll->numCharsInLine]));
+                                       //durCopy += et.Duration(true);
+                               }
+
+                               if (!bufferedDraw) {
+                                       ypos += vsDraw.lineHeight;
+                               }
+
+                               yposScreen += vsDraw.lineHeight;
+                               visibleLine++;
+                       }
+               }
+               ll.Set(0);
+               //if (durPaint < 0.00000001)
+               //      durPaint = 0.00000001;
+
+               // Right column limit indicator
+               PRectangle rcBeyondEOF = (vsDraw.marginInside) ? rcClient : rcArea;
+               rcBeyondEOF.left = static_cast<XYPOSITION>(vsDraw.textStart);
+               rcBeyondEOF.right = rcBeyondEOF.right - ((vsDraw.marginInside) ? vsDraw.rightMarginWidth : 0);
+               rcBeyondEOF.top = static_cast<XYPOSITION>((model.cs.LinesDisplayed() - model.TopLineOfMain()) 
* vsDraw.lineHeight);
+               if (rcBeyondEOF.top < rcBeyondEOF.bottom) {
+                       surfaceWindow->FillRectangle(rcBeyondEOF, vsDraw.styles[STYLE_DEFAULT].back);
+                       if (vsDraw.edgeState == EDGE_LINE) {
+                               int edgeX = static_cast<int>(vsDraw.theEdge.column * vsDraw.spaceWidth);
+                               rcBeyondEOF.left = static_cast<XYPOSITION>(edgeX + xStart);
+                               rcBeyondEOF.right = rcBeyondEOF.left + 1;
+                               surfaceWindow->FillRectangle(rcBeyondEOF, vsDraw.theEdge.colour);
+                       } else if (vsDraw.edgeState == EDGE_MULTILINE) {
+                               for (size_t edge = 0; edge < vsDraw.theMultiEdge.size(); edge++) {
+                                       if (vsDraw.theMultiEdge[edge].column >= 0) {
+                                               int edgeX = static_cast<int>(vsDraw.theMultiEdge[edge].column 
* vsDraw.spaceWidth);
+                                               rcBeyondEOF.left = static_cast<XYPOSITION>(edgeX + xStart);
+                                               rcBeyondEOF.right = rcBeyondEOF.left + 1;
+                                               surfaceWindow->FillRectangle(rcBeyondEOF, 
vsDraw.theMultiEdge[edge].colour);
+                                       }
+                               }
+                       }
+               }
+               //Platform::DebugPrintf("start display %d, offset = %d\n", pdoc->Length(), xOffset);
+
+               //Platform::DebugPrintf(
+               //"Layout:%9.6g    Paint:%9.6g    Ratio:%9.6g   Copy:%9.6g   Total:%9.6g\n",
+               //durLayout, durPaint, durLayout / durPaint, durCopy, etWhole.Duration());
+       }
+}
+
+void EditView::FillLineRemainder(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+       Sci::Line line, PRectangle rcArea, int subLine) const {
+               int eolInSelection = 0;
+               int alpha = SC_ALPHA_NOALPHA;
+               if (!hideSelection) {
+                       Sci::Position posAfterLineEnd = model.pdoc->LineStart(line + 1);
+                       eolInSelection = (subLine == (ll->lines - 1)) ? 
model.sel.InSelectionForEOL(posAfterLineEnd) : 0;
+                       alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
+               }
+
+               const ColourOptional background = vsDraw.Background(model.pdoc->GetMark(line), 
model.caret.active, ll->containsCaret);
+
+               if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selColours.back.isSet && (line < 
model.pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
+                       surface->FillRectangle(rcArea, SelectionBackground(vsDraw, eolInSelection == 1, 
model.primarySelection));
+               } else {
+                       if (background.isSet) {
+                               surface->FillRectangle(rcArea, background);
+                       } else if (vsDraw.styles[ll->styles[ll->numCharsInLine]].eolFilled) {
+                               surface->FillRectangle(rcArea, 
vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
+                       } else {
+                               surface->FillRectangle(rcArea, vsDraw.styles[STYLE_DEFAULT].back);
+                       }
+                       if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selColours.back.isSet && (line < 
model.pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
+                               SimpleAlphaRectangle(surface, rcArea, SelectionBackground(vsDraw, 
eolInSelection == 1, model.primarySelection), alpha);
+                       }
+               }
+}
+
+// Space (3 space characters) between line numbers and text when printing.
+#define lineNumberPrintSpace "   "
+
+static ColourDesired InvertedLight(ColourDesired orig) {
+       unsigned int r = orig.GetRed();
+       unsigned int g = orig.GetGreen();
+       unsigned int b = orig.GetBlue();
+       const unsigned int l = (r + g + b) / 3;         // There is a better calculation for this that 
matches human eye
+       const unsigned int il = 0xff - l;
+       if (l == 0)
+               return ColourDesired(0xff, 0xff, 0xff);
+       r = r * il / l;
+       g = g * il / l;
+       b = b * il / l;
+       return ColourDesired(std::min(r, 0xffu), std::min(g, 0xffu), std::min(b, 0xffu));
+}
+
+long EditView::FormatRange(bool draw, Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
+       const EditModel &model, const ViewStyle &vs) {
+       // Can't use measurements cached for screen
+       posCache.Clear();
+
+       ViewStyle vsPrint(vs);
+       vsPrint.technology = SC_TECHNOLOGY_DEFAULT;
+
+       // Modify the view style for printing as do not normally want any of the transient features to be 
printed
+       // Printing supports only the line number margin.
+       int lineNumberIndex = -1;
+       for (size_t margin = 0; margin < vs.ms.size(); margin++) {
+               if ((vsPrint.ms[margin].style == SC_MARGIN_NUMBER) && (vsPrint.ms[margin].width > 0)) {
+                       lineNumberIndex = static_cast<int>(margin);
+               } else {
+                       vsPrint.ms[margin].width = 0;
+               }
+       }
+       vsPrint.fixedColumnWidth = 0;
+       vsPrint.zoomLevel = printParameters.magnification;
+       // Don't show indentation guides
+       // If this ever gets changed, cached pixmap would need to be recreated if technology != 
SC_TECHNOLOGY_DEFAULT
+       vsPrint.viewIndentationGuides = ivNone;
+       // Don't show the selection when printing
+       vsPrint.selColours.back.isSet = false;
+       vsPrint.selColours.fore.isSet = false;
+       vsPrint.selAlpha = SC_ALPHA_NOALPHA;
+       vsPrint.selAdditionalAlpha = SC_ALPHA_NOALPHA;
+       vsPrint.whitespaceColours.back.isSet = false;
+       vsPrint.whitespaceColours.fore.isSet = false;
+       vsPrint.showCaretLineBackground = false;
+       vsPrint.alwaysShowCaretLineBackground = false;
+       // Don't highlight matching braces using indicators
+       vsPrint.braceHighlightIndicatorSet = false;
+       vsPrint.braceBadLightIndicatorSet = false;
+
+       // Set colours for printing according to users settings
+       for (size_t sty = 0; sty < vsPrint.styles.size(); sty++) {
+               if (printParameters.colourMode == SC_PRINT_INVERTLIGHT) {
+                       vsPrint.styles[sty].fore = InvertedLight(vsPrint.styles[sty].fore);
+                       vsPrint.styles[sty].back = InvertedLight(vsPrint.styles[sty].back);
+               } else if (printParameters.colourMode == SC_PRINT_BLACKONWHITE) {
+                       vsPrint.styles[sty].fore = ColourDesired(0, 0, 0);
+                       vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
+               } else if (printParameters.colourMode == SC_PRINT_COLOURONWHITE) {
+                       vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
+               } else if (printParameters.colourMode == SC_PRINT_COLOURONWHITEDEFAULTBG) {
+                       if (sty <= STYLE_DEFAULT) {
+                               vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
+                       }
+               }
+       }
+       // White background for the line numbers
+       vsPrint.styles[STYLE_LINENUMBER].back = ColourDesired(0xff, 0xff, 0xff);
+
+       // Printing uses different margins, so reset screen margins
+       vsPrint.leftMarginWidth = 0;
+       vsPrint.rightMarginWidth = 0;
+
+       vsPrint.Refresh(*surfaceMeasure, model.pdoc->tabInChars);
+       // Determining width must happen after fonts have been realised in Refresh
+       int lineNumberWidth = 0;
+       if (lineNumberIndex >= 0) {
+               lineNumberWidth = 
static_cast<int>(surfaceMeasure->WidthText(vsPrint.styles[STYLE_LINENUMBER].font,
+                       "99999" lineNumberPrintSpace, 5 + static_cast<int>(strlen(lineNumberPrintSpace))));
+               vsPrint.ms[lineNumberIndex].width = lineNumberWidth;
+               vsPrint.Refresh(*surfaceMeasure, model.pdoc->tabInChars);       // Recalculate 
fixedColumnWidth
+       }
+
+       Sci::Line linePrintStart = model.pdoc->LineFromPosition(static_cast<int>(pfr->chrg.cpMin));
+       Sci::Line linePrintLast = linePrintStart + (pfr->rc.bottom - pfr->rc.top) / vsPrint.lineHeight - 1;
+       if (linePrintLast < linePrintStart)
+               linePrintLast = linePrintStart;
+       Sci::Line linePrintMax = model.pdoc->LineFromPosition(static_cast<int>(pfr->chrg.cpMax));
+       if (linePrintLast > linePrintMax)
+               linePrintLast = linePrintMax;
+       //Platform::DebugPrintf("Formatting lines=[%0d,%0d,%0d] top=%0d bottom=%0d line=%0d %0d\n",
+       //      linePrintStart, linePrintLast, linePrintMax, pfr->rc.top, pfr->rc.bottom, vsPrint.lineHeight,
+       //      surfaceMeasure->Height(vsPrint.styles[STYLE_LINENUMBER].font));
+       Sci::Position endPosPrint = model.pdoc->Length();
+       if (linePrintLast < model.pdoc->LinesTotal())
+               endPosPrint = model.pdoc->LineStart(linePrintLast + 1);
+
+       // Ensure we are styled to where we are formatting.
+       model.pdoc->EnsureStyledTo(endPosPrint);
+
+       int xStart = vsPrint.fixedColumnWidth + pfr->rc.left;
+       int ypos = pfr->rc.top;
+
+       Sci::Line lineDoc = linePrintStart;
+
+       Sci::Position nPrintPos = static_cast<Sci::Position>(pfr->chrg.cpMin);
+       int visibleLine = 0;
+       int widthPrint = pfr->rc.right - pfr->rc.left - vsPrint.fixedColumnWidth;
+       if (printParameters.wrapState == eWrapNone)
+               widthPrint = LineLayout::wrapWidthInfinite;
+
+       while (lineDoc <= linePrintLast && ypos < pfr->rc.bottom) {
+
+               // When printing, the hdc and hdcTarget may be the same, so
+               // changing the state of surfaceMeasure may change the underlying
+               // state of surface. Therefore, any cached state is discarded before
+               // using each surface.
+               surfaceMeasure->FlushCachedState();
+
+               // Copy this line and its styles from the document into local arrays
+               // and determine the x position at which each character starts.
+               LineLayout ll(model.pdoc->LineStart(lineDoc + 1) - model.pdoc->LineStart(lineDoc) + 1);
+               LayoutLine(model, lineDoc, surfaceMeasure, vsPrint, &ll, widthPrint);
+
+               ll.containsCaret = false;
+
+               PRectangle rcLine = PRectangle::FromInts(
+                       pfr->rc.left,
+                       ypos,
+                       pfr->rc.right - 1,
+                       ypos + vsPrint.lineHeight);
+
+               // When document line is wrapped over multiple display lines, find where
+               // to start printing from to ensure a particular position is on the first
+               // line of the page.
+               if (visibleLine == 0) {
+                       const Sci::Position startWithinLine = nPrintPos - model.pdoc->LineStart(lineDoc);
+                       for (int iwl = 0; iwl < ll.lines - 1; iwl++) {
+                               if (ll.LineStart(iwl) <= startWithinLine && ll.LineStart(iwl + 1) >= 
startWithinLine) {
+                                       visibleLine = -iwl;
+                               }
+                       }
+
+                       if (ll.lines > 1 && startWithinLine >= ll.LineStart(ll.lines - 1)) {
+                               visibleLine = -(ll.lines - 1);
+                       }
+               }
+
+               if (draw && lineNumberWidth &&
+                       (ypos + vsPrint.lineHeight <= pfr->rc.bottom) &&
+                       (visibleLine >= 0)) {
+                       char number[100];
+                       sprintf(number, "%d" lineNumberPrintSpace, lineDoc + 1);
+                       PRectangle rcNumber = rcLine;
+                       rcNumber.right = rcNumber.left + lineNumberWidth;
+                       // Right justify
+                       rcNumber.left = rcNumber.right - surfaceMeasure->WidthText(
+                               vsPrint.styles[STYLE_LINENUMBER].font, number, 
static_cast<int>(strlen(number)));
+                       surface->FlushCachedState();
+                       surface->DrawTextNoClip(rcNumber, vsPrint.styles[STYLE_LINENUMBER].font,
+                               static_cast<XYPOSITION>(ypos + vsPrint.maxAscent), number, 
static_cast<int>(strlen(number)),
+                               vsPrint.styles[STYLE_LINENUMBER].fore,
+                               vsPrint.styles[STYLE_LINENUMBER].back);
+               }
+
+               // Draw the line
+               surface->FlushCachedState();
+
+               for (int iwl = 0; iwl < ll.lines; iwl++) {
+                       if (ypos + vsPrint.lineHeight <= pfr->rc.bottom) {
+                               if (visibleLine >= 0) {
+                                       if (draw) {
+                                               rcLine.top = static_cast<XYPOSITION>(ypos);
+                                               rcLine.bottom = static_cast<XYPOSITION>(ypos + 
vsPrint.lineHeight);
+                                               DrawLine(surface, model, vsPrint, &ll, lineDoc, visibleLine, 
xStart, rcLine, iwl, drawAll);
+                                       }
+                                       ypos += vsPrint.lineHeight;
+                               }
+                               visibleLine++;
+                               if (iwl == ll.lines - 1)
+                                       nPrintPos = model.pdoc->LineStart(lineDoc + 1);
+                               else
+                                       nPrintPos += ll.LineStart(iwl + 1) - ll.LineStart(iwl);
+                       }
+               }
+
+               ++lineDoc;
+       }
+
+       // Clear cache so measurements are not used for screen
+       posCache.Clear();
+
+       return nPrintPos;
+}
diff --git a/plugins/scintilla/scintilla/src/EditView.h b/plugins/scintilla/scintilla/src/EditView.h
new file mode 100644
index 0000000..a842ac6
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/EditView.h
@@ -0,0 +1,184 @@
+// Scintilla source code edit control
+/** @file EditView.h
+ ** Defines the appearance of the main text area of the editor window.
+ **/
+// Copyright 1998-2014 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef EDITVIEW_H
+#define EDITVIEW_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+struct PrintParameters {
+       int magnification;
+       int colourMode;
+       WrapMode wrapState;
+       PrintParameters();
+};
+
+/**
+* The view may be drawn in separate phases.
+*/
+enum DrawPhase {
+       drawBack = 0x1,
+       drawIndicatorsBack = 0x2,
+       drawText = 0x4,
+       drawIndentationGuides = 0x8,
+       drawIndicatorsFore = 0x10,
+       drawSelectionTranslucent = 0x20,
+       drawLineTranslucent = 0x40,
+       drawFoldLines = 0x80,
+       drawCarets = 0x100,
+       drawAll = 0x1FF
+};
+
+bool ValidStyledText(const ViewStyle &vs, size_t styleOffset, const StyledText &st);
+int WidestLineWidth(Surface *surface, const ViewStyle &vs, int styleOffset, const StyledText &st);
+void DrawTextNoClipPhase(Surface *surface, PRectangle rc, const Style &style, XYPOSITION ybase,
+       const char *s, int len, DrawPhase phase);
+void DrawStyledText(Surface *surface, const ViewStyle &vs, int styleOffset, PRectangle rcText,
+       const StyledText &st, size_t start, size_t length, DrawPhase phase);
+
+typedef void (*DrawTabArrowFn)(Surface *surface, PRectangle rcTab, int ymid);
+
+/**
+* EditView draws the main text area.
+*/
+class EditView {
+public:
+       PrintParameters printParameters;
+       std::unique_ptr<PerLine> ldTabstops;
+       int tabWidthMinimumPixels;
+
+       bool hideSelection;
+       bool drawOverstrikeCaret;
+
+       /** In bufferedDraw mode, graphics operations are drawn to a pixmap and then copied to
+       * the screen. This avoids flashing but is about 30% slower. */
+       bool bufferedDraw;
+       /** In phasesTwo mode, drawing is performed in two phases, first the background
+       * and then the foreground. This avoids chopping off characters that overlap the next run.
+       * In multiPhaseDraw mode, drawing is performed in multiple phases with each phase drawing
+       * one feature over the whole drawing area, instead of within one line. This allows text to
+       * overlap from one line to the next. */
+       enum PhasesDraw { phasesOne, phasesTwo, phasesMultiple };
+       PhasesDraw phasesDraw;
+
+       int lineWidthMaxSeen;
+
+       bool additionalCaretsBlink;
+       bool additionalCaretsVisible;
+
+       bool imeCaretBlockOverride;
+
+       std::unique_ptr<Surface> pixmapLine;
+       std::unique_ptr<Surface> pixmapIndentGuide;
+       std::unique_ptr<Surface> pixmapIndentGuideHighlight;
+
+       LineLayoutCache llc;
+       PositionCache posCache;
+
+       int tabArrowHeight; // draw arrow heads this many pixels above/below line midpoint
+       /** Some platforms, notably PLAT_CURSES, do not support Scintilla's native
+        * DrawTabArrow function for drawing tab characters. Allow those platforms to
+        * override it instead of creating a new method in the Surface class that
+        * existing platforms must implement as empty. */
+       DrawTabArrowFn customDrawTabArrow;
+       DrawWrapMarkerFn customDrawWrapMarker;
+
+       EditView();
+       // Deleted so EditView objects can not be copied.
+       EditView(const EditView &) = delete;
+       void operator=(const EditView &) = delete;
+       virtual ~EditView();
+
+       bool SetTwoPhaseDraw(bool twoPhaseDraw);
+       bool SetPhasesDraw(int phases);
+       bool LinesOverlap() const;
+
+       void ClearAllTabstops();
+       XYPOSITION NextTabstopPos(Sci::Line line, XYPOSITION x, XYPOSITION tabWidth) const;
+       bool ClearTabstops(Sci::Line line);
+       bool AddTabstop(Sci::Line line, int x);
+       int GetNextTabstop(Sci::Line line, int x) const;
+       void LinesAddedOrRemoved(Sci::Line lineOfPos, Sci::Line linesAdded);
+
+       void DropGraphics(bool freeObjects);
+       void AllocateGraphics(const ViewStyle &vsDraw);
+       void RefreshPixMaps(Surface *surfaceWindow, WindowID wid, const ViewStyle &vsDraw);
+
+       LineLayout *RetrieveLineLayout(Sci::Line lineNumber, const EditModel &model);
+       void LayoutLine(const EditModel &model, Sci::Line line, Surface *surface, const ViewStyle &vstyle,
+               LineLayout *ll, int width = LineLayout::wrapWidthInfinite);
+
+       Point LocationFromPosition(Surface *surface, const EditModel &model, SelectionPosition pos, Sci::Line 
topLine,
+                                  const ViewStyle &vs, PointEnd pe);
+       Range RangeDisplayLine(Surface *surface, const EditModel &model, Sci::Line lineVisible, const 
ViewStyle &vs);
+       SelectionPosition SPositionFromLocation(Surface *surface, const EditModel &model, PointDocument pt, 
bool canReturnInvalid,
+               bool charPosition, bool virtualSpace, const ViewStyle &vs);
+       SelectionPosition SPositionFromLineX(Surface *surface, const EditModel &model, Sci::Line lineDoc, int 
x, const ViewStyle &vs);
+       Sci::Line DisplayFromPosition(Surface *surface, const EditModel &model, Sci::Position pos, const 
ViewStyle &vs);
+       Sci::Position StartEndDisplayLine(Surface *surface, const EditModel &model, Sci::Position pos, bool 
start, const ViewStyle &vs);
+
+       void DrawIndentGuide(Surface *surface, Sci::Line lineVisible, int lineHeight, Sci::Position start, 
PRectangle rcSegment, bool highlight);
+       void DrawEOL(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll, 
PRectangle rcLine,
+               Sci::Line line, Sci::Position lineEnd, int xStart, int subLine, XYACCUMULATOR subLineStart,
+               ColourOptional background);
+       void DrawFoldDisplayText(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+               Sci::Line line, int xStart, PRectangle rcLine, int subLine, XYACCUMULATOR subLineStart, 
DrawPhase phase);
+       void DrawAnnotation(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+               Sci::Line line, int xStart, PRectangle rcLine, int subLine, DrawPhase phase);
+       void DrawCarets(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout 
*ll, Sci::Line lineDoc,
+               int xStart, PRectangle rcLine, int subLine) const;
+       void DrawBackground(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll, PRectangle rcLine,
+               Range lineRange, Sci::Position posLineStart, int xStart,
+               int subLine, ColourOptional background) const;
+       void DrawForeground(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll, Sci::Line lineVisible,
+               PRectangle rcLine, Range lineRange, Sci::Position posLineStart, int xStart,
+               int subLine, ColourOptional background);
+       void DrawIndentGuidesOverEmpty(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, 
const LineLayout *ll,
+               Sci::Line line, Sci::Line lineVisible, PRectangle rcLine, int xStart, int subLine);
+       void DrawLine(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout 
*ll, Sci::Line line,
+               Sci::Line lineVisible, int xStart, PRectangle rcLine, int subLine, DrawPhase phase);
+       void PaintText(Surface *surfaceWindow, const EditModel &model, PRectangle rcArea, PRectangle rcClient,
+               const ViewStyle &vsDraw);
+       void FillLineRemainder(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const 
LineLayout *ll,
+               Sci::Line line, PRectangle rcArea, int subLine) const;
+       long FormatRange(bool draw, Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
+               const EditModel &model, const ViewStyle &vs);
+};
+
+/**
+* Convenience class to ensure LineLayout objects are always disposed.
+*/
+class AutoLineLayout {
+       LineLayoutCache &llc;
+       LineLayout *ll;
+public:
+       AutoLineLayout(LineLayoutCache &llc_, LineLayout *ll_) : llc(llc_), ll(ll_) {}
+       explicit AutoLineLayout(const AutoLineLayout &) = delete;
+       AutoLineLayout &operator=(const AutoLineLayout &) = delete;
+       ~AutoLineLayout() {
+               llc.Dispose(ll);
+               ll = 0;
+       }
+       LineLayout *operator->() const {
+               return ll;
+       }
+       operator LineLayout *() const {
+               return ll;
+       }
+       void Set(LineLayout *ll_) {
+               llc.Dispose(ll);
+               ll = ll_;
+       }
+};
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/Editor.cxx b/plugins/scintilla/scintilla/src/Editor.cxx
index acb840f..1dfb8d9 100644
--- a/plugins/scintilla/scintilla/src/Editor.cxx
+++ b/plugins/scintilla/scintilla/src/Editor.cxx
@@ -5,16 +5,19 @@
 // Copyright 1998-2011 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <math.h>
-#include <assert.h>
-
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cctype>
+#include <cstdio>
+
+#include <cmath>
+#include <stdexcept>
 #include <string>
 #include <vector>
 #include <map>
+#include <forward_list>
 #include <algorithm>
 #include <memory>
 
@@ -23,11 +26,15 @@
 #include "ILexer.h"
 #include "Scintilla.h"
 
+#include "StringCopy.h"
+#include "Position.h"
+#include "UniqueString.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
 #include "ContractionState.h"
 #include "CellBuffer.h"
+#include "PerLine.h"
 #include "KeyMap.h"
 #include "Indicator.h"
 #include "XPM.h"
@@ -41,6 +48,9 @@
 #include "UniConversion.h"
 #include "Selection.h"
 #include "PositionCache.h"
+#include "EditModel.h"
+#include "MarginView.h"
+#include "EditView.h"
 #include "Editor.h"
 
 #ifdef SCI_NAMESPACE
@@ -78,21 +88,13 @@ static bool IsLastStep(const DocModification &mh) {
            && (mh.modificationType & SC_MULTILINEUNDOREDO) != 0;
 }
 
-Caret::Caret() :
-               active(false), on(false), period(500) {}
-
 Timer::Timer() :
                ticking(false), ticksToWait(0), tickerID(0) {}
 
 Idler::Idler() :
                state(false), idlerID(0) {}
 
-static inline bool IsControlCharacter(int ch) {
-       // iscntrl returns true for lots of chars > 127 which are displayable
-       return ch >= 0 && ch < ' ';
-}
-
-static inline bool IsAllSpacesOrTabs(char *s, unsigned int len) {
+static inline bool IsAllSpacesOrTabs(const char *s, unsigned int len) {
        for (unsigned int i = 0; i < len; i++) {
                // This is safe because IsSpaceOrTab() will return false for null terminators
                if (!IsSpaceOrTab(s[i]))
@@ -106,25 +108,17 @@ Editor::Editor() {
 
        stylesValid = false;
        technology = SC_TECHNOLOGY_DEFAULT;
-       scaleRGBAImage = 100;
+       scaleRGBAImage = 100.0f;
 
-       printMagnification = 0;
-       printColourMode = SC_PRINT_NORMAL;
-       printWrapState = eWrapWord;
        cursorMode = SC_CURSORNORMAL;
-       controlCharSymbol = 0;  /* Draw the control characters */
 
        hasFocus = false;
-       hideSelection = false;
-       inOverstrike = false;
-       drawOverstrikeCaret = true;
        errorStatus = 0;
        mouseDownCaptures = true;
-
-       bufferedDraw = true;
-       twoPhaseDraw = true;
+       mouseWheelCaptures = true;
 
        lastClickTime = 0;
+       doubleClickCloseThreshold = Point(3, 3);
        dwellDelay = SC_TIME_FOREVER;
        ticksToDwell = SC_TIME_FOREVER;
        dwelling = false;
@@ -132,8 +126,7 @@ Editor::Editor() {
        ptMouseLast.y = 0;
        inDragDrop = ddNone;
        dropWentOutside = false;
-       posDrag = SelectionPosition(invalidPosition);
-       posDrop = SelectionPosition(invalidPosition);
+       posDrop = SelectionPosition(Sci::invalidPosition);
        hotSpotClickPos = INVALID_POSITION;
        selectionType = selChar;
 
@@ -144,8 +137,6 @@ Editor::Editor() {
        wordSelectAnchorEndPos = 0;
        wordSelectInitialCaretPos = -1;
 
-       primarySelection = true;
-
        caretXPolicy = CARET_SLOP | CARET_EVEN;
        caretXSlop = 50;
 
@@ -157,30 +148,19 @@ Editor::Editor() {
 
        searchAnchor = 0;
 
-       xOffset = 0;
        xCaretMargin = 50;
        horizontalScrollBarVisible = true;
        scrollWidth = 2000;
-       trackLineWidth = false;
-       lineWidthMaxSeen = 0;
        verticalScrollBarVisible = true;
        endAtLastLine = true;
        caretSticky = SC_CARETSTICKY_OFF;
        marginOptions = SC_MARGINOPTION_NONE;
+       mouseSelectionRectangularSwitch = false;
        multipleSelection = false;
        additionalSelectionTyping = false;
        multiPasteMode = SC_MULTIPASTE_ONCE;
-       additionalCaretsBlink = true;
-       additionalCaretsVisible = true;
        virtualSpaceOptions = SCVS_NONE;
 
-       pixmapLine = 0;
-       pixmapSelMargin = 0;
-       pixmapSelPattern = 0;
-       pixmapSelPatternOffset1 = 0;
-       pixmapIndentGuide = 0;
-       pixmapIndentGuideHighlight = 0;
-
        targetStart = 0;
        targetEnd = 0;
        searchFlags = 0;
@@ -192,50 +172,28 @@ Editor::Editor() {
 
        needUpdateUI = 0;
        ContainerNeedsUpdate(SC_UPDATE_CONTENT);
-       braces[0] = invalidPosition;
-       braces[1] = invalidPosition;
-       bracesMatchStyle = STYLE_BRACEBAD;
-       highlightGuideColumn = 0;
-
-       theEdge = 0;
 
        paintState = notPainting;
+       paintAbandonedByStyling = false;
+       paintingAllText = false;
        willRedrawAll = false;
+       idleStyling = SC_IDLESTYLING_NONE;
+       needIdleStyling = false;
 
        modEventMask = SC_MODEVENTMASKALL;
 
-       pdoc = new Document();
-       pdoc->AddRef();
        pdoc->AddWatcher(this, 0);
 
        recordingMacro = false;
-       foldFlags = 0;
        foldAutomatic = 0;
 
-       wrapState = eWrapNone;
-       wrapWidth = LineLayout::wrapWidthInfinite;
-       wrapVisualFlags = 0;
-       wrapVisualFlagsLocation = 0;
-       wrapVisualStartIndent = 0;
-       wrapIndentMode = SC_WRAPINDENT_FIXED;
-
        convertPastes = true;
 
-       marginNumberPadding = 3;
-       ctrlCharPadding = 3; // +3 For a blank on front and rounded edge each side
-       lastSegItalicsOffset = 2;
-
-       hsStart = -1;
-       hsEnd = -1;
-
-       llc.SetLevel(LineLayoutCache::llcCaret);
-       posCache.SetSize(0x400);
+       SetRepresentations();
 }
 
 Editor::~Editor() {
        pdoc->RemoveWatcher(this, 0);
-       pdoc->Release();
-       pdoc = 0;
        DropGraphics(true);
 }
 
@@ -244,49 +202,57 @@ void Editor::Finalise() {
        CancelModes();
 }
 
-void Editor::DropGraphics(bool freeObjects) {
-       if (freeObjects) {
-               delete pixmapLine;
-               pixmapLine = 0;
-               delete pixmapSelMargin;
-               pixmapSelMargin = 0;
-               delete pixmapSelPattern;
-               pixmapSelPattern = 0;
-               delete pixmapSelPatternOffset1;
-               pixmapSelPatternOffset1 = 0;
-               delete pixmapIndentGuide;
-               pixmapIndentGuide = 0;
-               delete pixmapIndentGuideHighlight;
-               pixmapIndentGuideHighlight = 0;
-       } else {
-               if (pixmapLine)
-                       pixmapLine->Release();
-               if (pixmapSelMargin)
-                       pixmapSelMargin->Release();
-               if (pixmapSelPattern)
-                       pixmapSelPattern->Release();
-               if (pixmapSelPatternOffset1)
-                       pixmapSelPatternOffset1->Release();
-               if (pixmapIndentGuide)
-                       pixmapIndentGuide->Release();
-               if (pixmapIndentGuideHighlight)
-                       pixmapIndentGuideHighlight->Release();
+void Editor::SetRepresentations() {
+       reprs.Clear();
+
+       // C0 control set
+       const char *reps[] = {
+               "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
+               "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
+               "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
+               "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US"
+       };
+       for (size_t j=0; j < ELEMENTS(reps); j++) {
+               char c[2] = { static_cast<char>(j), 0 };
+               reprs.SetRepresentation(c, reps[j]);
+       }
+
+       // C1 control set
+       // As well as Unicode mode, ISO-8859-1 should use these
+       if (IsUnicodeMode()) {
+               const char *repsC1[] = {
+                       "PAD", "HOP", "BPH", "NBH", "IND", "NEL", "SSA", "ESA",
+                       "HTS", "HTJ", "VTS", "PLD", "PLU", "RI", "SS2", "SS3",
+                       "DCS", "PU1", "PU2", "STS", "CCH", "MW", "SPA", "EPA",
+                       "SOS", "SGCI", "SCI", "CSI", "ST", "OSC", "PM", "APC"
+               };
+               for (size_t j=0; j < ELEMENTS(repsC1); j++) {
+                       char c1[3] = { '\xc2',  static_cast<char>(0x80+j), 0 };
+                       reprs.SetRepresentation(c1, repsC1[j]);
+               }
+               reprs.SetRepresentation("\xe2\x80\xa8", "LS");
+               reprs.SetRepresentation("\xe2\x80\xa9", "PS");
+       }
+
+       // UTF-8 invalid bytes
+       if (IsUnicodeMode()) {
+               for (int k=0x80; k < 0x100; k++) {
+                       char hiByte[2] = {  static_cast<char>(k), 0 };
+                       char hexits[4];
+                       sprintf(hexits, "x%2X", k);
+                       reprs.SetRepresentation(hiByte, hexits);
+               }
        }
 }
 
+void Editor::DropGraphics(bool freeObjects) {
+       marginView.DropGraphics(freeObjects);
+       view.DropGraphics(freeObjects);
+}
+
 void Editor::AllocateGraphics() {
-       if (!pixmapLine)
-               pixmapLine = Surface::Allocate(technology);
-       if (!pixmapSelMargin)
-               pixmapSelMargin = Surface::Allocate(technology);
-       if (!pixmapSelPattern)
-               pixmapSelPattern = Surface::Allocate(technology);
-       if (!pixmapSelPatternOffset1)
-               pixmapSelPatternOffset1 = Surface::Allocate(technology);
-       if (!pixmapIndentGuide)
-               pixmapIndentGuide = Surface::Allocate(technology);
-       if (!pixmapIndentGuideHighlight)
-               pixmapIndentGuideHighlight = Surface::Allocate(technology);
+       marginView.AllocateGraphics(vs);
+       view.AllocateGraphics(vs);
 }
 
 void Editor::InvalidateStyleData() {
@@ -294,8 +260,8 @@ void Editor::InvalidateStyleData() {
        vs.technology = technology;
        DropGraphics(false);
        AllocateGraphics();
-       llc.Invalidate(LineLayout::llInvalid);
-       posCache.Clear();
+       view.llc.Invalidate(LineLayout::llInvalid);
+       view.posCache.Clear();
 }
 
 void Editor::InvalidateStyleRedraw() {
@@ -309,21 +275,21 @@ void Editor::RefreshStyleData() {
                stylesValid = true;
                AutoSurface surface(this);
                if (surface) {
-                       vs.Refresh(*surface);
+                       vs.Refresh(*surface, pdoc->tabInChars);
                }
                SetScrollBars();
                SetRectangularRange();
        }
 }
 
-Point Editor::GetVisibleOriginInMain() {
+Point Editor::GetVisibleOriginInMain() const {
        return Point(0,0);
 }
 
-Point Editor::DocumentPointFromView(Point ptView) {
-       Point ptDocument = ptView;
+PointDocument Editor::DocumentPointFromView(Point ptView) const {
+       PointDocument ptDocument(ptView);
        if (wMargin.GetID()) {
-               Point ptOrigin = GetVisibleOriginInMain();
+               const Point ptOrigin = GetVisibleOriginInMain();
                ptDocument.x += ptOrigin.x;
                ptDocument.y += ptOrigin.y;
        } else {
@@ -333,43 +299,48 @@ Point Editor::DocumentPointFromView(Point ptView) {
        return ptDocument;
 }
 
-int Editor::TopLineOfMain() const {
+Sci::Line Editor::TopLineOfMain() const {
        if (wMargin.GetID())
                return 0;
        else
                return topLine;
 }
 
-PRectangle Editor::GetClientRectangle() {
-       return wMain.GetClientPosition();
+PRectangle Editor::GetClientRectangle() const {
+       Window win = wMain;
+       return win.GetClientPosition();
 }
 
-PRectangle Editor::GetTextRectangle() {
+PRectangle Editor::GetClientDrawingRectangle() {
+       return GetClientRectangle();
+}
+
+PRectangle Editor::GetTextRectangle() const {
        PRectangle rc = GetClientRectangle();
        rc.left += vs.textStart;
        rc.right -= vs.rightMarginWidth;
        return rc;
 }
 
-int Editor::LinesOnScreen() {
-       PRectangle rcClient = GetClientRectangle();
-       int htClient = rcClient.bottom - rcClient.top;
+Sci::Line Editor::LinesOnScreen() const {
+       const PRectangle rcClient = GetClientRectangle();
+       const int htClient = static_cast<int>(rcClient.bottom - rcClient.top);
        //Platform::DebugPrintf("lines on screen = %d\n", htClient / lineHeight + 1);
        return htClient / vs.lineHeight;
 }
 
-int Editor::LinesToScroll() {
-       int retVal = LinesOnScreen() - 1;
+Sci::Line Editor::LinesToScroll() const {
+       Sci::Line retVal = LinesOnScreen() - 1;
        if (retVal < 1)
                return 1;
        else
                return retVal;
 }
 
-int Editor::MaxScrollPos() {
+Sci::Line Editor::MaxScrollPos() const {
        //Platform::DebugPrintf("Lines %d screen = %d maxScroll = %d\n",
        //LinesTotal(), LinesOnScreen(), LinesTotal() - LinesOnScreen() + 1);
-       int retVal = cs.LinesDisplayed();
+       Sci::Line retVal = cs.LinesDisplayed();
        if (endAtLastLine) {
                retVal -= LinesOnScreen();
        } else {
@@ -382,45 +353,6 @@ int Editor::MaxScrollPos() {
        }
 }
 
-const char *ControlCharacterString(unsigned char ch) {
-       const char *reps[] = {
-               "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
-               "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
-               "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
-               "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US"
-       };
-       if (ch < (sizeof(reps) / sizeof(reps[0]))) {
-               return reps[ch];
-       } else {
-               return "BAD";
-       }
-}
-
-/**
- * Convenience class to ensure LineLayout objects are always disposed.
- */
-class AutoLineLayout {
-       LineLayoutCache &llc;
-       LineLayout *ll;
-       AutoLineLayout &operator=(const AutoLineLayout &);
-public:
-       AutoLineLayout(LineLayoutCache &llc_, LineLayout *ll_) : llc(llc_), ll(ll_) {}
-       ~AutoLineLayout() {
-               llc.Dispose(ll);
-               ll = 0;
-       }
-       LineLayout *operator->() const {
-               return ll;
-       }
-       operator LineLayout *() const {
-               return ll;
-       }
-       void Set(LineLayout *ll_) {
-               llc.Dispose(ll);
-               ll = ll_;
-       }
-};
-
 SelectionPosition Editor::ClampPositionIntoDocument(SelectionPosition sp) const {
        if (sp.Position() < 0) {
                return SelectionPosition(0);
@@ -434,77 +366,35 @@ SelectionPosition Editor::ClampPositionIntoDocument(SelectionPosition sp) const
        }
 }
 
-Point Editor::LocationFromPosition(SelectionPosition pos) {
-       Point pt;
+Point Editor::LocationFromPosition(SelectionPosition pos, PointEnd pe) {
        RefreshStyleData();
-       if (pos.Position() == INVALID_POSITION)
-               return pt;
-       int line = pdoc->LineFromPosition(pos.Position());
-       int lineVisible = cs.DisplayFromDoc(line);
-       //Platform::DebugPrintf("line=%d\n", line);
        AutoSurface surface(this);
-       AutoLineLayout ll(llc, RetrieveLineLayout(line));
-       if (surface && ll) {
-               // -1 because of adding in for visible lines in following loop.
-               pt.y = (lineVisible - topLine - 1) * vs.lineHeight;
-               pt.x = 0;
-               unsigned int posLineStart = pdoc->LineStart(line);
-               LayoutLine(line, surface, vs, ll, wrapWidth);
-               int posInLine = pos.Position() - posLineStart;
-               // In case of very long line put x at arbitrary large position
-               if (posInLine > ll->maxLineLength) {
-                       pt.x = ll->positions[ll->maxLineLength] - ll->positions[ll->LineStart(ll->lines)];
-               }
-
-               for (int subLine = 0; subLine < ll->lines; subLine++) {
-                       if ((posInLine >= ll->LineStart(subLine)) && (posInLine <= ll->LineStart(subLine + 
1))) {
-                               pt.x = ll->positions[posInLine] - ll->positions[ll->LineStart(subLine)];
-                               if (ll->wrapIndent != 0) {
-                                       int lineStart = ll->LineStart(subLine);
-                                       if (lineStart != 0)     // Wrapped
-                                               pt.x += ll->wrapIndent;
-                               }
-                       }
-                       if (posInLine >= ll->LineStart(subLine)) {
-                               pt.y += vs.lineHeight;
-                       }
-               }
-               pt.x += vs.textStart - xOffset;
-       }
-       pt.x += pos.VirtualSpace() * vs.styles[ll->EndLineStyle()].spaceWidth;
-       return pt;
+       return view.LocationFromPosition(surface, *this, pos, topLine, vs, pe);
 }
 
-Point Editor::LocationFromPosition(int pos) {
-       return LocationFromPosition(SelectionPosition(pos));
+Point Editor::LocationFromPosition(Sci::Position pos, PointEnd pe) {
+       return LocationFromPosition(SelectionPosition(pos), pe);
 }
 
-int Editor::XFromPosition(int pos) {
+int Editor::XFromPosition(Sci::Position pos) {
        Point pt = LocationFromPosition(pos);
-       return pt.x - vs.textStart + xOffset;
+       return static_cast<int>(pt.x) - vs.textStart + xOffset;
 }
 
 int Editor::XFromPosition(SelectionPosition sp) {
        Point pt = LocationFromPosition(sp);
-       return pt.x - vs.textStart + xOffset;
-}
-
-int Editor::LineFromLocation(Point pt) const {
-       return cs.DocFromDisplay(pt.y / vs.lineHeight + topLine);
-}
-
-void Editor::SetTopLine(int topLineNew) {
-       if ((topLine != topLineNew) && (topLineNew >= 0)) {
-               topLine = topLineNew;
-               ContainerNeedsUpdate(SC_UPDATE_V_SCROLL);
-       }
-       posTopLine = pdoc->LineStart(cs.DocFromDisplay(topLine));
+       return static_cast<int>(pt.x) - vs.textStart + xOffset;
 }
 
 SelectionPosition Editor::SPositionFromLocation(Point pt, bool canReturnInvalid, bool charPosition, bool 
virtualSpace) {
        RefreshStyleData();
+       AutoSurface surface(this);
+
        if (canReturnInvalid) {
                PRectangle rcClient = GetTextRectangle();
+               // May be in scroll view coordinates so translate back to main view
+               Point ptOrigin = GetVisibleOriginInMain();
+               rcClient.Move(-ptOrigin.x, -ptOrigin.y);
                if (!rcClient.Contains(pt))
                        return SelectionPosition(INVALID_POSITION);
                if (pt.x < vs.textStart)
@@ -512,113 +402,44 @@ SelectionPosition Editor::SPositionFromLocation(Point pt, bool canReturnInvalid,
                if (pt.y < 0)
                        return SelectionPosition(INVALID_POSITION);
        }
-       pt = DocumentPointFromView(pt);
-       pt.x = pt.x - vs.textStart;
-       int visibleLine = floor(pt.y / vs.lineHeight);
-       if (!canReturnInvalid && (visibleLine < 0))
-               visibleLine = 0;
-       int lineDoc = cs.DocFromDisplay(visibleLine);
-       if (canReturnInvalid && (lineDoc < 0))
-               return SelectionPosition(INVALID_POSITION);
-       if (lineDoc >= pdoc->LinesTotal())
-               return SelectionPosition(canReturnInvalid ? INVALID_POSITION : pdoc->Length());
-       unsigned int posLineStart = pdoc->LineStart(lineDoc);
-       SelectionPosition retVal(canReturnInvalid ? INVALID_POSITION : static_cast<int>(posLineStart));
-       AutoSurface surface(this);
-       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc));
-       if (surface && ll) {
-               LayoutLine(lineDoc, surface, vs, ll, wrapWidth);
-               int lineStartSet = cs.DisplayFromDoc(lineDoc);
-               int subLine = visibleLine - lineStartSet;
-               if (subLine < ll->lines) {
-                       int lineStart = ll->LineStart(subLine);
-                       int lineEnd = ll->LineLastVisible(subLine);
-                       XYPOSITION subLineStart = ll->positions[lineStart];
-
-                       if (ll->wrapIndent != 0) {
-                               if (lineStart != 0)     // Wrapped
-                                       pt.x -= ll->wrapIndent;
-                       }
-                       int i = ll->FindBefore(pt.x + subLineStart, lineStart, lineEnd);
-                       while (i < lineEnd) {
-                               if (charPosition) {
-                                       if ((pt.x + subLineStart) < (ll->positions[i + 1])) {
-                                               return SelectionPosition(pdoc->MovePositionOutsideChar(i + 
posLineStart, 1));
-                                       }
-                               } else {
-                                       if ((pt.x + subLineStart) < ((ll->positions[i] + ll->positions[i + 
1]) / 2)) {
-                                               return SelectionPosition(pdoc->MovePositionOutsideChar(i + 
posLineStart, 1));
-                                       }
-                               }
-                               i++;
-                       }
-                       if (virtualSpace) {
-                               const XYPOSITION spaceWidth = vs.styles[ll->EndLineStyle()].spaceWidth;
-                               int spaceOffset = (pt.x + subLineStart - ll->positions[lineEnd] + spaceWidth 
/ 2) /
-                                       spaceWidth;
-                               return SelectionPosition(lineEnd + posLineStart, spaceOffset);
-                       } else if (canReturnInvalid) {
-                               if (pt.x < (ll->positions[lineEnd] - subLineStart)) {
-                                       return SelectionPosition(pdoc->MovePositionOutsideChar(lineEnd + 
posLineStart, 1));
-                               }
-                       } else {
-                               return SelectionPosition(lineEnd + posLineStart);
-                       }
-               }
-               if (!canReturnInvalid)
-                       return SelectionPosition(ll->numCharsInLine + posLineStart);
-       }
-       return retVal;
+       PointDocument ptdoc = DocumentPointFromView(pt);
+       return view.SPositionFromLocation(surface, *this, ptdoc, canReturnInvalid, charPosition, 
virtualSpace, vs);
 }
 
-int Editor::PositionFromLocation(Point pt, bool canReturnInvalid, bool charPosition) {
+Sci::Position Editor::PositionFromLocation(Point pt, bool canReturnInvalid, bool charPosition) {
        return SPositionFromLocation(pt, canReturnInvalid, charPosition, false).Position();
 }
 
 /**
- * Find the document position corresponding to an x coordinate on a particular document line.
- * Ensure is between whole characters when document is in multi-byte or UTF-8 mode.
- */
-SelectionPosition Editor::SPositionFromLineX(int lineDoc, int x) {
+* Find the document position corresponding to an x coordinate on a particular document line.
+* Ensure is between whole characters when document is in multi-byte or UTF-8 mode.
+* This method is used for rectangular selections and does not work on wrapped lines.
+*/
+SelectionPosition Editor::SPositionFromLineX(Sci::Line lineDoc, int x) {
        RefreshStyleData();
        if (lineDoc >= pdoc->LinesTotal())
                return SelectionPosition(pdoc->Length());
        //Platform::DebugPrintf("Position of (%d,%d) line = %d top=%d\n", pt.x, pt.y, line, topLine);
        AutoSurface surface(this);
-       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc));
-       int retVal = 0;
-       if (surface && ll) {
-               unsigned int posLineStart = pdoc->LineStart(lineDoc);
-               LayoutLine(lineDoc, surface, vs, ll, wrapWidth);
-               int subLine = 0;
-               int lineStart = ll->LineStart(subLine);
-               int lineEnd = ll->LineLastVisible(subLine);
-               XYPOSITION subLineStart = ll->positions[lineStart];
-               XYPOSITION newX = x;
-
-               if (ll->wrapIndent != 0) {
-                       if (lineStart != 0)     // Wrapped
-                               newX -= ll->wrapIndent;
-               }
-               int i = ll->FindBefore(newX + subLineStart, lineStart, lineEnd);
-               while (i < lineEnd) {
-                       if ((newX + subLineStart) < ((ll->positions[i] + ll->positions[i + 1]) / 2)) {
-                               retVal = pdoc->MovePositionOutsideChar(i + posLineStart, 1);
-                               return SelectionPosition(retVal);
-                       }
-                       i++;
-               }
-               const XYPOSITION spaceWidth = vs.styles[ll->EndLineStyle()].spaceWidth;
-               int spaceOffset = (newX + subLineStart - ll->positions[lineEnd] + spaceWidth / 2) / 
spaceWidth;
-               return SelectionPosition(lineEnd + posLineStart, spaceOffset);
-       }
-       return SelectionPosition(retVal);
+       return view.SPositionFromLineX(surface, *this, lineDoc, x, vs);
 }
 
-int Editor::PositionFromLineX(int lineDoc, int x) {
+Sci::Position Editor::PositionFromLineX(Sci::Line lineDoc, int x) {
        return SPositionFromLineX(lineDoc, x).Position();
 }
 
+Sci::Line Editor::LineFromLocation(Point pt) const {
+       return cs.DocFromDisplay(static_cast<int>(pt.y) / vs.lineHeight + topLine);
+}
+
+void Editor::SetTopLine(Sci::Line topLineNew) {
+       if ((topLine != topLineNew) && (topLineNew >= 0)) {
+               topLine = topLineNew;
+               ContainerNeedsUpdate(SC_UPDATE_V_SCROLL);
+       }
+       posTopLine = pdoc->LineStart(cs.DocFromDisplay(topLine));
+}
+
 /**
  * If painting then abandon the painting because a wider redraw is needed.
  * @return true if calling code should stop drawing.
@@ -649,6 +470,10 @@ void Editor::RedrawRect(PRectangle rc) {
        }
 }
 
+void Editor::DiscardOverdraw() {
+       // Overridden on platforms that may draw outside visible area.
+}
+
 void Editor::Redraw() {
        //Platform::DebugPrintf("Redraw all\n");
        PRectangle rcClient = GetClientRectangle();
@@ -658,71 +483,73 @@ void Editor::Redraw() {
        //wMain.InvalidateAll();
 }
 
-void Editor::RedrawSelMargin(int line, bool allAfter) {
-       if (!AbandonPaint()) {
-               if (vs.maskInLine) {
-                       Redraw();
-               } else {
-                       PRectangle rcSelMargin = GetClientRectangle();
-                       rcSelMargin.right = rcSelMargin.left + vs.fixedColumnWidth;
-                       if (line != -1) {
-                               int position = pdoc->LineStart(line);
-                               PRectangle rcLine = RectangleFromRange(position, position);
-
-                               // Inflate line rectangle if there are image markers with height larger than 
line height
-                               if (vs.largestMarkerHeight > vs.lineHeight) {
-                                       int delta = (vs.largestMarkerHeight - vs.lineHeight + 1) / 2;
-                                       rcLine.top -= delta;
-                                       rcLine.bottom += delta;
-                                       if (rcLine.top < rcSelMargin.top)
-                                               rcLine.top = rcSelMargin.top;
-                                       if (rcLine.bottom > rcSelMargin.bottom)
-                                               rcLine.bottom = rcSelMargin.bottom;
-                               }
-
-                               rcSelMargin.top = rcLine.top;
-                               if (!allAfter)
-                                       rcSelMargin.bottom = rcLine.bottom;
-                       }
-                       if (wMargin.GetID()) {
-                               Point ptOrigin = GetVisibleOriginInMain();
-                               rcSelMargin.Move(-ptOrigin.x, -ptOrigin.y);
-                               wMargin.InvalidateRectangle(rcSelMargin);
-                       } else {
-                               wMain.InvalidateRectangle(rcSelMargin);
-                       }
+void Editor::RedrawSelMargin(Sci::Line line, bool allAfter) {
+       const bool markersInText = vs.maskInLine || vs.maskDrawInText;
+       if (!wMargin.GetID() || markersInText) {        // May affect text area so may need to abandon and 
retry
+               if (AbandonPaint()) {
+                       return;
                }
        }
+       if (wMargin.GetID() && markersInText) {
+               Redraw();
+               return;
+       }
+       PRectangle rcMarkers = GetClientRectangle();
+       if (!markersInText) {
+               // Normal case: just draw the margin
+               rcMarkers.right = rcMarkers.left + vs.fixedColumnWidth;
+       }
+       if (line != -1) {
+               PRectangle rcLine = RectangleFromRange(Range(pdoc->LineStart(line)), 0);
+
+               // Inflate line rectangle if there are image markers with height larger than line height
+               if (vs.largestMarkerHeight > vs.lineHeight) {
+                       int delta = (vs.largestMarkerHeight - vs.lineHeight + 1) / 2;
+                       rcLine.top -= delta;
+                       rcLine.bottom += delta;
+                       if (rcLine.top < rcMarkers.top)
+                               rcLine.top = rcMarkers.top;
+                       if (rcLine.bottom > rcMarkers.bottom)
+                               rcLine.bottom = rcMarkers.bottom;
+               }
+
+               rcMarkers.top = rcLine.top;
+               if (!allAfter)
+                       rcMarkers.bottom = rcLine.bottom;
+               if (rcMarkers.Empty())
+                       return;
+       }
+       if (wMargin.GetID()) {
+               Point ptOrigin = GetVisibleOriginInMain();
+               rcMarkers.Move(-ptOrigin.x, -ptOrigin.y);
+               wMargin.InvalidateRectangle(rcMarkers);
+       } else {
+               wMain.InvalidateRectangle(rcMarkers);
+       }
 }
 
-PRectangle Editor::RectangleFromRange(int start, int end) {
-       int minPos = start;
-       if (minPos > end)
-               minPos = end;
-       int maxPos = start;
-       if (maxPos < end)
-               maxPos = end;
-       int minLine = cs.DisplayFromDoc(pdoc->LineFromPosition(minPos));
-       int lineDocMax = pdoc->LineFromPosition(maxPos);
-       int maxLine = cs.DisplayFromDoc(lineDocMax) + cs.GetHeight(lineDocMax) - 1;
-       PRectangle rcClient = GetTextRectangle();
+PRectangle Editor::RectangleFromRange(Range r, int overlap) {
+       const Sci::Line minLine = cs.DisplayFromDoc(pdoc->LineFromPosition(r.First()));
+       const Sci::Line maxLine = cs.DisplayLastFromDoc(pdoc->LineFromPosition(r.Last()));
+       const PRectangle rcClientDrawing = GetClientDrawingRectangle();
        PRectangle rc;
        const int leftTextOverlap = ((xOffset == 0) && (vs.leftMarginWidth > 0)) ? 1 : 0;
-       rc.left = vs.textStart - leftTextOverlap;
-       rc.top = (minLine - TopLineOfMain()) * vs.lineHeight;
-       if (rc.top < rcClient.top)
-               rc.top = rcClient.top;
-       rc.right = rcClient.right;
-       rc.bottom = (maxLine - TopLineOfMain() + 1) * vs.lineHeight;
+       rc.left = static_cast<XYPOSITION>(vs.textStart - leftTextOverlap);
+       rc.top = static_cast<XYPOSITION>((minLine - TopLineOfMain()) * vs.lineHeight - overlap);
+       if (rc.top < rcClientDrawing.top)
+               rc.top = rcClientDrawing.top;
+       // Extend to right of prepared area if any to prevent artifacts from caret line highlight
+       rc.right = rcClientDrawing.right;
+       rc.bottom = static_cast<XYPOSITION>((maxLine - TopLineOfMain() + 1) * vs.lineHeight + overlap);
 
        return rc;
 }
 
-void Editor::InvalidateRange(int start, int end) {
-       RedrawRect(RectangleFromRange(start, end));
+void Editor::InvalidateRange(Sci::Position start, Sci::Position end) {
+       RedrawRect(RectangleFromRange(Range(start, end), view.LinesOverlap() ? vs.lineOverlap : 0));
 }
 
-int Editor::CurrentPosition() const {
+Sci::Position Editor::CurrentPosition() const {
        return sel.MainCaret();
 }
 
@@ -740,15 +567,15 @@ SelectionPosition Editor::SelectionEnd() {
 
 void Editor::SetRectangularRange() {
        if (sel.IsRectangular()) {
-               int xAnchor = XFromPosition(sel.Rectangular().anchor);
+               const int xAnchor = XFromPosition(sel.Rectangular().anchor);
                int xCaret = XFromPosition(sel.Rectangular().caret);
                if (sel.selType == Selection::selThin) {
                        xCaret = xAnchor;
                }
-               int lineAnchorRect = pdoc->LineFromPosition(sel.Rectangular().anchor.Position());
-               int lineCaret = pdoc->LineFromPosition(sel.Rectangular().caret.Position());
-               int increment = (lineCaret > lineAnchorRect) ? 1 : -1;
-               for (int line=lineAnchorRect; line != lineCaret+increment; line += increment) {
+               const Sci::Line lineAnchorRect = pdoc->LineFromPosition(sel.Rectangular().anchor.Position());
+               const Sci::Line lineCaret = pdoc->LineFromPosition(sel.Rectangular().caret.Position());
+               const int increment = (lineCaret > lineAnchorRect) ? 1 : -1;
+               for (Sci::Line line=lineAnchorRect; line != lineCaret+increment; line += increment) {
                        SelectionRange range(SPositionFromLineX(line, xCaret), SPositionFromLineX(line, 
xAnchor));
                        if ((virtualSpaceOptions & SCVS_RECTANGULARSELECTION) == 0)
                                range.ClearVirtualSpace();
@@ -776,26 +603,30 @@ void Editor::InvalidateSelection(SelectionRange newMain, bool invalidateWholeSel
        if (sel.Count() > 1 || !(sel.RangeMain().anchor == newMain.anchor) || sel.IsRectangular()) {
                invalidateWholeSelection = true;
        }
-       int firstAffected = Platform::Minimum(sel.RangeMain().Start().Position(), newMain.Start().Position());
+       Sci::Position firstAffected = std::min(sel.RangeMain().Start().Position(), 
newMain.Start().Position());
        // +1 for lastAffected ensures caret repainted
-       int lastAffected = Platform::Maximum(newMain.caret.Position()+1, newMain.anchor.Position());
-       lastAffected = Platform::Maximum(lastAffected, sel.RangeMain().End().Position());
+       Sci::Position lastAffected = std::max(newMain.caret.Position()+1, newMain.anchor.Position());
+       lastAffected = std::max(lastAffected, sel.RangeMain().End().Position());
        if (invalidateWholeSelection) {
                for (size_t r=0; r<sel.Count(); r++) {
-                       firstAffected = Platform::Minimum(firstAffected, sel.Range(r).caret.Position());
-                       firstAffected = Platform::Minimum(firstAffected, sel.Range(r).anchor.Position());
-                       lastAffected = Platform::Maximum(lastAffected, sel.Range(r).caret.Position()+1);
-                       lastAffected = Platform::Maximum(lastAffected, sel.Range(r).anchor.Position());
+                       firstAffected = std::min(firstAffected, sel.Range(r).caret.Position());
+                       firstAffected = std::min(firstAffected, sel.Range(r).anchor.Position());
+                       lastAffected = std::max(lastAffected, sel.Range(r).caret.Position()+1);
+                       lastAffected = std::max(lastAffected, sel.Range(r).anchor.Position());
                }
        }
        ContainerNeedsUpdate(SC_UPDATE_SELECTION);
        InvalidateRange(firstAffected, lastAffected);
 }
 
+void Editor::InvalidateWholeSelection() {
+       InvalidateSelection(sel.RangeMain(), true);
+}
+
 void Editor::SetSelection(SelectionPosition currentPos_, SelectionPosition anchor_) {
        currentPos_ = ClampPositionIntoDocument(currentPos_);
        anchor_ = ClampPositionIntoDocument(anchor_);
-       int currentLine = pdoc->LineFromPosition(currentPos_.Position());
+       Sci::Line currentLine = pdoc->LineFromPosition(currentPos_.Position());
        /* For Line selection - ensure the anchor and caret are always
           at the beginning and end of the region lines. */
        if (sel.selType == Selection::selLines) {
@@ -814,21 +645,22 @@ void Editor::SetSelection(SelectionPosition currentPos_, SelectionPosition ancho
        sel.RangeMain() = rangeNew;
        SetRectangularRange();
        ClaimSelection();
+       SetHoverIndicatorPosition(sel.MainCaret());
 
-       if (highlightDelimiter.NeedsDrawing(currentLine)) {
+       if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
                RedrawSelMargin();
        }
        QueueIdleWork(WorkNeeded::workUpdateUI);
 }
 
-void Editor::SetSelection(int currentPos_, int anchor_) {
+void Editor::SetSelection(Sci::Position currentPos_, Sci::Position anchor_) {
        SetSelection(SelectionPosition(currentPos_), SelectionPosition(anchor_));
 }
 
 // Just move the caret on the main selection
 void Editor::SetSelection(SelectionPosition currentPos_) {
        currentPos_ = ClampPositionIntoDocument(currentPos_);
-       int currentLine = pdoc->LineFromPosition(currentPos_.Position());
+       Sci::Line currentLine = pdoc->LineFromPosition(currentPos_.Position());
        if (sel.Count() > 1 || !(sel.RangeMain().caret == currentPos_)) {
                InvalidateSelection(SelectionRange(currentPos_));
        }
@@ -841,8 +673,9 @@ void Editor::SetSelection(SelectionPosition currentPos_) {
                        SelectionRange(SelectionPosition(currentPos_), sel.RangeMain().anchor);
        }
        ClaimSelection();
+       SetHoverIndicatorPosition(sel.MainCaret());
 
-       if (highlightDelimiter.NeedsDrawing(currentLine)) {
+       if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
                RedrawSelMargin();
        }
        QueueIdleWork(WorkNeeded::workUpdateUI);
@@ -853,7 +686,7 @@ void Editor::SetSelection(int currentPos_) {
 }
 
 void Editor::SetEmptySelection(SelectionPosition currentPos_) {
-       int currentLine = pdoc->LineFromPosition(currentPos_.Position());
+       Sci::Line currentLine = pdoc->LineFromPosition(currentPos_.Position());
        SelectionRange rangeNew(ClampPositionIntoDocument(currentPos_));
        if (sel.Count() > 1 || !(sel.RangeMain() == rangeNew)) {
                InvalidateSelection(rangeNew);
@@ -862,27 +695,80 @@ void Editor::SetEmptySelection(SelectionPosition currentPos_) {
        sel.RangeMain() = rangeNew;
        SetRectangularRange();
        ClaimSelection();
+       SetHoverIndicatorPosition(sel.MainCaret());
 
-       if (highlightDelimiter.NeedsDrawing(currentLine)) {
+       if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
                RedrawSelMargin();
        }
        QueueIdleWork(WorkNeeded::workUpdateUI);
 }
 
-void Editor::SetEmptySelection(int currentPos_) {
+void Editor::SetEmptySelection(Sci::Position currentPos_) {
        SetEmptySelection(SelectionPosition(currentPos_));
 }
 
-bool Editor::RangeContainsProtected(int start, int end) const {
+void Editor::MultipleSelectAdd(AddNumber addNumber) {
+       if (SelectionEmpty() || !multipleSelection) {
+               // Select word at caret
+               const Sci::Position startWord = pdoc->ExtendWordSelect(sel.MainCaret(), -1, true);
+               const Sci::Position endWord = pdoc->ExtendWordSelect(startWord, 1, true);
+               TrimAndSetSelection(endWord, startWord);
+
+       } else {
+
+               if (!pdoc->HasCaseFolder())
+                       pdoc->SetCaseFolder(CaseFolderForEncoding());
+
+               const Range rangeMainSelection(sel.RangeMain().Start().Position(), 
sel.RangeMain().End().Position());
+               const std::string selectedText = RangeText(rangeMainSelection.start, rangeMainSelection.end);
+
+               const Range rangeTarget(targetStart, targetEnd);
+               std::vector<Range> searchRanges;
+               // Search should be over the target range excluding the current selection so
+               // may need to search 2 ranges, after the selection then before the selection.
+               if (rangeTarget.Overlaps(rangeMainSelection)) {
+                       // Common case is that the selection is completely within the target but
+                       // may also have overlap at start or end.
+                       if (rangeMainSelection.end < rangeTarget.end)
+                               searchRanges.push_back(Range(rangeMainSelection.end, rangeTarget.end));
+                       if (rangeTarget.start < rangeMainSelection.start)
+                               searchRanges.push_back(Range(rangeTarget.start, rangeMainSelection.start));
+               } else {
+                       // No overlap
+                       searchRanges.push_back(rangeTarget);
+               }
+
+               for (std::vector<Range>::const_iterator it = searchRanges.begin(); it != searchRanges.end(); 
++it) {
+                       Sci::Position searchStart = it->start;
+                       const Sci::Position searchEnd = it->end;
+                       for (;;) {
+                               Sci::Position lengthFound = static_cast<Sci::Position>(selectedText.length());
+                               Sci::Position pos = static_cast<Sci::Position>(pdoc->FindText(searchStart, 
searchEnd,
+                                       selectedText.c_str(), searchFlags, &lengthFound));
+                               if (pos >= 0) {
+                                       sel.AddSelection(SelectionRange(pos + lengthFound, pos));
+                                       ScrollRange(sel.RangeMain());
+                                       Redraw();
+                                       if (addNumber == addOne)
+                                               return;
+                                       searchStart = pos + lengthFound;
+                               } else {
+                                       break;
+                               }
+                       }
+               }
+       }
+}
+
+bool Editor::RangeContainsProtected(Sci::Position start, Sci::Position end) const {
        if (vs.ProtectionActive()) {
                if (start > end) {
-                       int t = start;
+                       Sci::Position t = start;
                        start = end;
                        end = t;
                }
-               int mask = pdoc->stylingBitsMask;
-               for (int pos = start; pos < end; pos++) {
-                       if (vs.styles[pdoc->StyleAt(pos) & mask].IsProtected())
+               for (Sci::Position pos = start; pos < end; pos++) {
+                       if (vs.styles[pdoc->StyleIndexAt(pos)].IsProtected())
                                return true;
                }
        }
@@ -902,26 +788,25 @@ bool Editor::SelectionContainsProtected() {
 /**
  * Asks document to find a good position and then moves out of any invisible positions.
  */
-int Editor::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) const {
+Sci::Position Editor::MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool checkLineEnd) 
const {
        return MovePositionOutsideChar(SelectionPosition(pos), moveDir, checkLineEnd).Position();
 }
 
-SelectionPosition Editor::MovePositionOutsideChar(SelectionPosition pos, int moveDir, bool checkLineEnd) 
const {
-       int posMoved = pdoc->MovePositionOutsideChar(pos.Position(), moveDir, checkLineEnd);
+SelectionPosition Editor::MovePositionOutsideChar(SelectionPosition pos, Sci::Position moveDir, bool 
checkLineEnd) const {
+       Sci::Position posMoved = pdoc->MovePositionOutsideChar(pos.Position(), moveDir, checkLineEnd);
        if (posMoved != pos.Position())
                pos.SetPosition(posMoved);
        if (vs.ProtectionActive()) {
-               int mask = pdoc->stylingBitsMask;
                if (moveDir > 0) {
-                       if ((pos.Position() > 0) && vs.styles[pdoc->StyleAt(pos.Position() - 1) & 
mask].IsProtected()) {
+                       if ((pos.Position() > 0) && vs.styles[pdoc->StyleIndexAt(pos.Position() - 
1)].IsProtected()) {
                                while ((pos.Position() < pdoc->Length()) &&
-                                       (vs.styles[pdoc->StyleAt(pos.Position()) & mask].IsProtected()))
+                                       (vs.styles[pdoc->StyleIndexAt(pos.Position())].IsProtected()))
                                        pos.Add(1);
                        }
                } else if (moveDir < 0) {
-                       if (vs.styles[pdoc->StyleAt(pos.Position()) & mask].IsProtected()) {
+                       if (vs.styles[pdoc->StyleIndexAt(pos.Position())].IsProtected()) {
                                while ((pos.Position() > 0) &&
-                                       (vs.styles[pdoc->StyleAt(pos.Position() - 1) & mask].IsProtected()))
+                                       (vs.styles[pdoc->StyleIndexAt(pos.Position() - 1)].IsProtected()))
                                        pos.Add(-1);
                        }
                }
@@ -929,21 +814,50 @@ SelectionPosition Editor::MovePositionOutsideChar(SelectionPosition pos, int mov
        return pos;
 }
 
-int Editor::MovePositionTo(SelectionPosition newPos, Selection::selTypes selt, bool ensureVisible) {
-       bool simpleCaret = (sel.Count() == 1) && sel.Empty();
-       SelectionPosition spCaret = sel.Last();
+void Editor::MovedCaret(SelectionPosition newPos, SelectionPosition previousPos, bool ensureVisible) {
+       const Sci::Line currentLine = pdoc->LineFromPosition(newPos.Position());
+       if (ensureVisible) {
+               // In case in need of wrapping to ensure DisplayFromDoc works.
+               if (currentLine >= wrapPending.start)
+                       WrapLines(WrapScope::wsAll);
+               XYScrollPosition newXY = XYScrollToMakeVisible(
+                       SelectionRange(posDrag.IsValid() ? posDrag : newPos), xysDefault);
+               if (previousPos.IsValid() && (newXY.xOffset == xOffset)) {
+                       // simple vertical scroll then invalidate
+                       ScrollTo(newXY.topLine);
+                       InvalidateSelection(SelectionRange(previousPos), true);
+               } else {
+                       SetXYScroll(newXY);
+               }
+       }
+
+       ShowCaretAtCurrentPosition();
+       NotifyCaretMove();
+
+       ClaimSelection();
+       SetHoverIndicatorPosition(sel.MainCaret());
+       QueueIdleWork(WorkNeeded::workUpdateUI);
+
+       if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
+               RedrawSelMargin();
+       }
+}
+
+void Editor::MovePositionTo(SelectionPosition newPos, Selection::selTypes selt, bool ensureVisible) {
+       const SelectionPosition spCaret = ((sel.Count() == 1) && sel.Empty()) ?
+               sel.Last() : SelectionPosition(INVALID_POSITION);
 
-       int delta = newPos.Position() - sel.MainCaret();
+       Sci::Position delta = newPos.Position() - sel.MainCaret();
        newPos = ClampPositionIntoDocument(newPos);
        newPos = MovePositionOutsideChar(newPos, delta);
        if (!multipleSelection && sel.IsRectangular() && (selt == Selection::selStream)) {
                // Can't turn into multiple selection so clear additional selections
                InvalidateSelection(SelectionRange(newPos), true);
-               SelectionRange rangeMain = sel.RangeMain();
-               sel.SetSelection(rangeMain);
+               sel.DropAdditionalRanges();
        }
        if (!sel.IsRectangular() && (selt == Selection::selRectangle)) {
                // Switching to rectangular
+               InvalidateSelection(sel.RangeMain(), false);
                SelectionRange rangeMain = sel.RangeMain();
                sel.Clear();
                sel.Rectangular() = rangeMain;
@@ -956,42 +870,22 @@ int Editor::MovePositionTo(SelectionPosition newPos, Selection::selTypes selt, b
        } else {
                SetEmptySelection(newPos);
        }
-       ShowCaretAtCurrentPosition();
 
-       int currentLine = pdoc->LineFromPosition(newPos.Position());
-       if (ensureVisible) {
-               // In case in need of wrapping to ensure DisplayFromDoc works.
-               if (currentLine >= wrapPending.start)
-                       WrapLines(wsAll);
-               XYScrollPosition newXY = XYScrollToMakeVisible(
-                       SelectionRange(posDrag.IsValid() ? posDrag : sel.RangeMain().caret), xysDefault);
-               if (simpleCaret && (newXY.xOffset == xOffset)) {
-                       // simple vertical scroll then invalidate
-                       ScrollTo(newXY.topLine);
-                       InvalidateSelection(SelectionRange(spCaret), true);
-               } else {
-                       SetXYScroll(newXY);
-               }
-       }
-
-       if (highlightDelimiter.NeedsDrawing(currentLine)) {
-               RedrawSelMargin();
-       }
-       return 0;
+       MovedCaret(newPos, spCaret, ensureVisible);
 }
 
-int Editor::MovePositionTo(int newPos, Selection::selTypes selt, bool ensureVisible) {
-       return MovePositionTo(SelectionPosition(newPos), selt, ensureVisible);
+void Editor::MovePositionTo(Sci::Position newPos, Selection::selTypes selt, bool ensureVisible) {
+       MovePositionTo(SelectionPosition(newPos), selt, ensureVisible);
 }
 
 SelectionPosition Editor::MovePositionSoVisible(SelectionPosition pos, int moveDir) {
        pos = ClampPositionIntoDocument(pos);
        pos = MovePositionOutsideChar(pos, moveDir);
-       int lineDoc = pdoc->LineFromPosition(pos.Position());
+       Sci::Line lineDoc = pdoc->LineFromPosition(pos.Position());
        if (cs.GetVisible(lineDoc)) {
                return pos;
        } else {
-               int lineDisplay = cs.DisplayFromDoc(lineDoc);
+               Sci::Line lineDisplay = cs.DisplayFromDoc(lineDoc);
                if (moveDir > 0) {
                        // lineDisplay is already line before fold as lines in fold use display line of line 
after fold
                        lineDisplay = Platform::Clamp(lineDisplay, 0, cs.LinesDisplayed());
@@ -1003,7 +897,7 @@ SelectionPosition Editor::MovePositionSoVisible(SelectionPosition pos, int moveD
        }
 }
 
-SelectionPosition Editor::MovePositionSoVisible(int pos, int moveDir) {
+SelectionPosition Editor::MovePositionSoVisible(Sci::Position pos, int moveDir) {
        return MovePositionSoVisible(SelectionPosition(pos), moveDir);
 }
 
@@ -1017,22 +911,22 @@ Point Editor::PointMainCaret() {
  */
 void Editor::SetLastXChosen() {
        Point pt = PointMainCaret();
-       lastXChosen = pt.x + xOffset;
+       lastXChosen = static_cast<Sci::Position>(pt.x) + xOffset;
 }
 
-void Editor::ScrollTo(int line, bool moveThumb) {
-       int topLineNew = Platform::Clamp(line, 0, MaxScrollPos());
+void Editor::ScrollTo(Sci::Line line, bool moveThumb) {
+       const Sci::Line topLineNew = Platform::Clamp(line, 0, MaxScrollPos());
        if (topLineNew != topLine) {
                // Try to optimise small scrolls
 #ifndef UNDER_CE
-               int linesToMove = topLine - topLineNew;
-               bool performBlit = (abs(linesToMove) <= 10) && (paintState == notPainting);
+               const Sci::Line linesToMove = topLine - topLineNew;
+               const bool performBlit = (abs(linesToMove) <= 10) && (paintState == notPainting);
                willRedrawAll = !performBlit;
 #endif
                SetTopLine(topLineNew);
                // Optimize by styling the view as this will invalidate any needed area
                // which could abort the initial paint if discovered later.
-               StyleToPositionInView(PositionAfterArea(GetClientRectangle()));
+               StyleAreaBounded(GetClientRectangle(), true);
 #ifndef UNDER_CE
                // Perform redraw rather than scroll if many lines would be redrawn anyway.
                if (performBlit) {
@@ -1050,7 +944,7 @@ void Editor::ScrollTo(int line, bool moveThumb) {
        }
 }
 
-void Editor::ScrollText(int /* linesToMove */) {
+void Editor::ScrollText(Sci::Line /* linesToMove */) {
        //Platform::DebugPrintf("Editor::ScrollText %d\n", linesToMove);
        Redraw();
 }
@@ -1059,7 +953,7 @@ void Editor::HorizontalScrollTo(int xPos) {
        //Platform::DebugPrintf("HorizontalScroll %d\n", xPos);
        if (xPos < 0)
                xPos = 0;
-       if ((wrapState == eWrapNone) && (xOffset != xPos)) {
+       if (!Wrapping() && (xOffset != xPos)) {
                xOffset = xPos;
                ContainerNeedsUpdate(SC_UPDATE_H_SCROLL);
                SetHorizontalScrollPos();
@@ -1068,9 +962,9 @@ void Editor::HorizontalScrollTo(int xPos) {
 }
 
 void Editor::VerticalCentreCaret() {
-       int lineDoc = pdoc->LineFromPosition(sel.IsRectangular() ? sel.Rectangular().caret.Position() : 
sel.MainCaret());
-       int lineDisplay = cs.DisplayFromDoc(lineDoc);
-       int newTop = lineDisplay - (LinesOnScreen() / 2);
+       const Sci::Line lineDoc = pdoc->LineFromPosition(sel.IsRectangular() ? 
sel.Rectangular().caret.Position() : sel.MainCaret());
+       const Sci::Line lineDisplay = cs.DisplayFromDoc(lineDoc);
+       const Sci::Line newTop = lineDisplay - (LinesOnScreen() / 2);
        if (topLine != newTop) {
                SetTopLine(newTop > 0 ? newTop : 0);
                RedrawRect(GetClientRectangle());
@@ -1080,22 +974,22 @@ void Editor::VerticalCentreCaret() {
 // Avoid 64 bit compiler warnings.
 // Scintilla does not support text buffers larger than 2**31
 static int istrlen(const char *s) {
-       return static_cast<int>(strlen(s));
+       return static_cast<int>(s ? strlen(s) : 0);
 }
 
 void Editor::MoveSelectedLines(int lineDelta) {
 
        // if selection doesn't start at the beginning of the line, set the new start
-       int selectionStart = SelectionStart().Position();
-       int startLine = pdoc->LineFromPosition(selectionStart);
-       int beginningOfStartLine = pdoc->LineStart(startLine);
+       Sci::Position selectionStart = SelectionStart().Position();
+       const Sci::Line startLine = pdoc->LineFromPosition(selectionStart);
+       const Sci::Position beginningOfStartLine = pdoc->LineStart(startLine);
        selectionStart = beginningOfStartLine;
 
        // if selection doesn't end at the beginning of a line greater than that of the start,
        // then set it at the beginning of the next one
-       int selectionEnd = SelectionEnd().Position();
-       int endLine = pdoc->LineFromPosition(selectionEnd);
-       int beginningOfEndLine = pdoc->LineStart(endLine);
+       Sci::Position selectionEnd = SelectionEnd().Position();
+       const Sci::Line endLine = pdoc->LineFromPosition(selectionEnd);
+       const Sci::Position beginningOfEndLine = pdoc->LineStart(endLine);
        bool appendEol = false;
        if (selectionEnd > beginningOfEndLine
                || selectionStart == selectionEnd) {
@@ -1124,9 +1018,9 @@ void Editor::MoveSelectedLines(int lineDelta) {
        SelectionText selectedText;
        CopySelectionRange(&selectedText);
 
-       int selectionLength = SelectionRange(selectionStart, selectionEnd).Length();
+       Sci::Position selectionLength = SelectionRange(selectionStart, selectionEnd).Length();
        Point currentLocation = LocationFromPosition(CurrentPosition());
-       int currentLine = LineFromLocation(currentLocation);
+       Sci::Line currentLine = LineFromLocation(currentLocation);
 
        if (appendEol)
                SetSelection(pdoc->MovePositionOutsideChar(selectionStart - 1, -1), selectionEnd);
@@ -1134,13 +1028,13 @@ void Editor::MoveSelectedLines(int lineDelta) {
 
        const char *eol = StringFromEOLMode(pdoc->eolMode);
        if (currentLine + lineDelta >= pdoc->LinesTotal())
-               pdoc->InsertCString(pdoc->Length(), eol);
+               pdoc->InsertString(pdoc->Length(), eol, istrlen(eol));
        GoToLine(currentLine + lineDelta);
 
-       pdoc->InsertCString(CurrentPosition(), selectedText.Data());
+       selectionLength = pdoc->InsertString(CurrentPosition(), selectedText.Data(), selectionLength);
        if (appendEol) {
-               pdoc->InsertCString(CurrentPosition() + selectionLength, eol);
-               selectionLength += istrlen(eol);
+               const Sci::Position lengthInserted = pdoc->InsertString(CurrentPosition() + selectionLength, 
eol, istrlen(eol));
+               selectionLength += lengthInserted;
        }
        SetSelection(CurrentPosition(), CurrentPosition() + selectionLength);
 }
@@ -1158,35 +1052,21 @@ void Editor::MoveCaretInsideView(bool ensureVisible) {
        Point pt = PointMainCaret();
        if (pt.y < rcClient.top) {
                MovePositionTo(SPositionFromLocation(
-                           Point(lastXChosen - xOffset, rcClient.top),
+                           Point::FromInts(lastXChosen - xOffset, static_cast<int>(rcClient.top)),
                                        false, false, UserVirtualSpace()),
                                        Selection::noSel, ensureVisible);
        } else if ((pt.y + vs.lineHeight - 1) > rcClient.bottom) {
-               int yOfLastLineFullyDisplayed = rcClient.top + (LinesOnScreen() - 1) * vs.lineHeight;
+               Sci::Position yOfLastLineFullyDisplayed = static_cast<Sci::Position>(rcClient.top) + 
(LinesOnScreen() - 1) * vs.lineHeight;
                MovePositionTo(SPositionFromLocation(
-                           Point(lastXChosen - xOffset, rcClient.top + yOfLastLineFullyDisplayed),
+                           Point::FromInts(lastXChosen - xOffset, static_cast<int>(rcClient.top) + 
yOfLastLineFullyDisplayed),
                                        false, false, UserVirtualSpace()),
                        Selection::noSel, ensureVisible);
        }
 }
 
-int Editor::DisplayFromPosition(int pos) {
-       int lineDoc = pdoc->LineFromPosition(pos);
-       int lineDisplay = cs.DisplayFromDoc(lineDoc);
+Sci::Line Editor::DisplayFromPosition(Sci::Position pos) {
        AutoSurface surface(this);
-       AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc));
-       if (surface && ll) {
-               LayoutLine(lineDoc, surface, vs, ll, wrapWidth);
-               unsigned int posLineStart = pdoc->LineStart(lineDoc);
-               int posInLine = pos - posLineStart;
-               lineDisplay--; // To make up for first increment ahead.
-               for (int subLine = 0; subLine < ll->lines; subLine++) {
-                       if (posInLine >= ll->LineStart(subLine)) {
-                               lineDisplay++;
-                       }
-               }
-       }
-       return lineDisplay;
+       return view.DisplayFromPosition(surface, *this, pos, vs);
 }
 
 /**
@@ -1213,7 +1093,7 @@ so the caret can move in the same direction longer before the policy is applied
 
 If even is not set, instead of having symmetrical UZs,
 the left and bottom UZs are extended up to right and top UZs respectively.
-This way, we favour the displaying of useful information: the begining of lines,
+This way, we favour the displaying of useful information: the beginning of lines,
 where most code reside, and the lines after the caret, eg. the body of a function.
 
      |        |       |      |                                            |
@@ -1235,8 +1115,8 @@ slop | strict | jumps | even | Caret can go to the margin                 | When
   1  |   1    |   1   |   1  | No, kept out of UZ                         | moved to put caret at 3UZ of the 
margin
 */
 
-Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange range, const XYScrollOptions 
options) {
-       PRectangle rcClient = GetTextRectangle();
+Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange &range, const XYScrollOptions 
options) {
+       const PRectangle rcClient = GetTextRectangle();
        Point pt = LocationFromPosition(range.caret);
        Point ptAnchor = LocationFromPosition(range.anchor);
        const Point ptOrigin = GetVisibleOriginInMain();
@@ -1253,9 +1133,9 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
 
        // Vertical positioning
        if ((options & xysVertical) && (pt.y < rcClient.top || ptBottomCaret.y >= rcClient.bottom || 
(caretYPolicy & CARET_STRICT) != 0)) {
-               const int lineCaret = DisplayFromPosition(range.caret.Position());
-               const int linesOnScreen = LinesOnScreen();
-               const int halfScreen = Platform::Maximum(linesOnScreen - 1, 2) / 2;
+               const Sci::Line lineCaret = DisplayFromPosition(range.caret.Position());
+               const Sci::Line linesOnScreen = LinesOnScreen();
+               const Sci::Line halfScreen = std::max(linesOnScreen - 1, 2) / 2;
                const bool bSlop = (caretYPolicy & CARET_SLOP) != 0;
                const bool bStrict = (caretYPolicy & CARET_STRICT) != 0;
                const bool bJump = (caretYPolicy & CARET_JUMPS) != 0;
@@ -1264,9 +1144,9 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                // It should be possible to scroll the window to show the caret,
                // but this fails to remove the caret on GTK+
                if (bSlop) {    // A margin is defined
-                       int yMoveT, yMoveB;
+                       Sci::Line yMoveT, yMoveB;
                        if (bStrict) {
-                               int yMarginT, yMarginB;
+                               Sci::Line yMarginT, yMarginB;
                                if (!(options & xysUseMargin)) {
                                        // In drag mode, avoid moves
                                        // otherwise, a double click will select several lines.
@@ -1338,7 +1218,7 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                        }
                }
                if (!(range.caret == range.anchor)) {
-                       const int lineAnchor = DisplayFromPosition(range.anchor.Position());
+                       const Sci::Line lineAnchor = DisplayFromPosition(range.anchor.Position());
                        if (lineAnchor < lineCaret) {
                                // Shift up to show anchor or as much of range as possible
                                newXY.topLine = std::min(newXY.topLine, lineAnchor);
@@ -1353,8 +1233,8 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
        }
 
        // Horizontal positioning
-       if ((options & xysHorizontal) && (wrapState == eWrapNone)) {
-               const int halfScreen = Platform::Maximum(rcClient.Width() - 4, 4) / 2;
+       if ((options & xysHorizontal) && !Wrapping()) {
+               const int halfScreen = std::max(static_cast<int>(rcClient.Width()) - 4, 4) / 2;
                const bool bSlop = (caretXPolicy & CARET_SLOP) != 0;
                const bool bStrict = (caretXPolicy & CARET_STRICT) != 0;
                const bool bJump = (caretXPolicy & CARET_JUMPS) != 0;
@@ -1375,7 +1255,7 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                                        if (bEven) {
                                                xMarginL = xMarginR;
                                        } else {
-                                               xMarginL = rcClient.Width() - xMarginR - 4;
+                                               xMarginL = static_cast<int>(rcClient.Width()) - xMarginR - 4;
                                        }
                                }
                                if (bJump && bEven) {
@@ -1390,7 +1270,7 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                                                newXY.xOffset -= xMoveL;
                                        } else {
                                                // Move just enough to allow to display the caret
-                                               newXY.xOffset -= (rcClient.left + xMarginL) - pt.x;
+                                               newXY.xOffset -= static_cast<int>((rcClient.left + xMarginL) 
- pt.x);
                                        }
                                } else if (pt.x >= rcClient.right - xMarginR) {
                                        // Caret is on the right of the display
@@ -1398,7 +1278,7 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                                                newXY.xOffset += xMoveR;
                                        } else {
                                                // Move just enough to allow to display the caret
-                                               newXY.xOffset += pt.x - (rcClient.right - xMarginR) + 1;
+                                               newXY.xOffset += static_cast<int>(pt.x - (rcClient.right - 
xMarginR) + 1);
                                        }
                                }
                        } else {        // Not strict
@@ -1407,7 +1287,7 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                                if (bEven) {
                                        xMoveL = xMoveR;
                                } else {
-                                       xMoveL = rcClient.Width() - xMoveR - 4;
+                                       xMoveL = static_cast<int>(rcClient.Width()) - xMoveR - 4;
                                }
                                if (pt.x < rcClient.left) {
                                        // Caret is on the left of the display
@@ -1423,32 +1303,32 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                                // Strict or going out of display
                                if (bEven) {
                                        // Center caret
-                                       newXY.xOffset += pt.x - rcClient.left - halfScreen;
+                                       newXY.xOffset += static_cast<int>(pt.x - rcClient.left - halfScreen);
                                } else {
                                        // Put caret on right
-                                       newXY.xOffset += pt.x - rcClient.right + 1;
+                                       newXY.xOffset += static_cast<int>(pt.x - rcClient.right + 1);
                                }
                        } else {
                                // Move just enough to allow to display the caret
                                if (pt.x < rcClient.left) {
                                        // Caret is on the left of the display
                                        if (bEven) {
-                                               newXY.xOffset -= rcClient.left - pt.x;
+                                               newXY.xOffset -= static_cast<int>(rcClient.left - pt.x);
                                        } else {
-                                               newXY.xOffset += pt.x - rcClient.right + 1;
+                                               newXY.xOffset += static_cast<int>(pt.x - rcClient.right) + 1;
                                        }
                                } else if (pt.x >= rcClient.right) {
                                        // Caret is on the right of the display
-                                       newXY.xOffset += pt.x - rcClient.right + 1;
+                                       newXY.xOffset += static_cast<int>(pt.x - rcClient.right) + 1;
                                }
                        }
                }
                // In case of a jump (find result) largely out of display, adjust the offset to display the 
caret
                if (pt.x + xOffset < rcClient.left + newXY.xOffset) {
-                       newXY.xOffset = pt.x + xOffset - rcClient.left;
+                       newXY.xOffset = static_cast<int>(pt.x + xOffset - rcClient.left) - 2;
                } else if (pt.x + xOffset >= rcClient.right + newXY.xOffset) {
-                       newXY.xOffset = pt.x + xOffset - rcClient.right + 1;
-                       if (vs.caretStyle == CARETSTYLE_BLOCK) {
+                       newXY.xOffset = static_cast<int>(pt.x + xOffset - rcClient.right) + 2;
+                       if ((vs.caretStyle == CARETSTYLE_BLOCK) || view.imeCaretBlockOverride) {
                                // Ensure we can see a good portion of the block caret
                                newXY.xOffset += static_cast<int>(vs.aveCharWidth);
                        }
@@ -1456,14 +1336,14 @@ Editor::XYScrollPosition Editor::XYScrollToMakeVisible(const SelectionRange rang
                if (!(range.caret == range.anchor)) {
                        if (ptAnchor.x < pt.x) {
                                // Shift to left to show anchor or as much of range as possible
-                               int maxOffset = ptAnchor.x + xOffset - rcClient.left - 1;
-                               int minOffset = pt.x + xOffset - rcClient.right + 1;
+                               const int maxOffset = static_cast<int>(ptAnchor.x + xOffset - rcClient.left) 
- 1;
+                               const int minOffset = static_cast<int>(pt.x + xOffset - rcClient.right) + 1;
                                newXY.xOffset = std::min(newXY.xOffset, maxOffset);
                                newXY.xOffset = std::max(newXY.xOffset, minOffset);
                        } else {
                                // Shift to right to show anchor or as much of range as possible
-                               int minOffset = ptAnchor.x + xOffset - rcClient.right + 1;
-                               int maxOffset = pt.x + xOffset - rcClient.left - 1;
+                               const int minOffset = static_cast<Sci::Position>(ptAnchor.x + xOffset - 
rcClient.right) + 1;
+                               const int maxOffset = static_cast<Sci::Position>(pt.x + xOffset - 
rcClient.left) - 1;
                                newXY.xOffset = std::max(newXY.xOffset, minOffset);
                                newXY.xOffset = std::min(newXY.xOffset, maxOffset);
                        }
@@ -1486,10 +1366,10 @@ void Editor::SetXYScroll(XYScrollPosition newXY) {
                        xOffset = newXY.xOffset;
                        ContainerNeedsUpdate(SC_UPDATE_H_SCROLL);
                        if (newXY.xOffset > 0) {
-                               PRectangle rcText = GetTextRectangle();
+                               const PRectangle rcText = GetTextRectangle();
                                if (horizontalScrollBarVisible &&
                                        rcText.Width() + xOffset > scrollWidth) {
-                                       scrollWidth = xOffset + rcText.Width();
+                                       scrollWidth = xOffset + static_cast<Sci::Position>(rcText.Width());
                                        SetScrollBars();
                                }
                        }
@@ -1513,19 +1393,44 @@ void Editor::ShowCaretAtCurrentPosition() {
        if (hasFocus) {
                caret.active = true;
                caret.on = true;
-               SetTicking(true);
+               if (FineTickerAvailable()) {
+                       FineTickerCancel(tickCaret);
+                       if (caret.period > 0)
+                               FineTickerStart(tickCaret, caret.period, caret.period/10);
+               } else {
+                       SetTicking(true);
+               }
        } else {
                caret.active = false;
                caret.on = false;
+               if (FineTickerAvailable()) {
+                       FineTickerCancel(tickCaret);
+               }
        }
        InvalidateCaret();
 }
 
 void Editor::DropCaret() {
        caret.active = false;
+       if (FineTickerAvailable()) {
+               FineTickerCancel(tickCaret);
+       }
        InvalidateCaret();
 }
 
+void Editor::CaretSetPeriod(int period) {
+       if (caret.period != period) {
+               caret.period = period;
+               caret.on = true;
+               if (FineTickerAvailable()) {
+                       FineTickerCancel(tickCaret);
+                       if ((caret.active) && (caret.period > 0))
+                               FineTickerStart(tickCaret, caret.period, caret.period/10);
+               }
+               InvalidateCaret();
+       }
+}
+
 void Editor::InvalidateCaret() {
        if (posDrag.IsValid()) {
                InvalidateRange(posDrag.Position(), posDrag.Position() + 1);
@@ -1537,25 +1442,32 @@ void Editor::InvalidateCaret() {
        UpdateSystemCaret();
 }
 
+void Editor::NotifyCaretMove() {
+}
+
 void Editor::UpdateSystemCaret() {
 }
 
-void Editor::NeedWrapping(int docLineStart, int docLineEnd) {
+bool Editor::Wrapping() const {
+       return vs.wrapState != eWrapNone;
+}
+
+void Editor::NeedWrapping(Sci::Line docLineStart, Sci::Line docLineEnd) {
 //Platform::DebugPrintf("\nNeedWrapping: %0d..%0d\n", docLineStart, docLineEnd);
        if (wrapPending.AddRange(docLineStart, docLineEnd)) {
-               llc.Invalidate(LineLayout::llPositions);
+               view.llc.Invalidate(LineLayout::llPositions);
        }
        // Wrap lines during idle.
-       if ((wrapState != eWrapNone) && wrapPending.NeedsWrap()) {
+       if (Wrapping() && wrapPending.NeedsWrap()) {
                SetIdle(true);
        }
 }
 
-bool Editor::WrapOneLine(Surface *surface, int lineToWrap) {
-       AutoLineLayout ll(llc, RetrieveLineLayout(lineToWrap));
+bool Editor::WrapOneLine(Surface *surface, Sci::Line lineToWrap) {
+       AutoLineLayout ll(view.llc, view.RetrieveLineLayout(lineToWrap, *this));
        int linesWrapped = 1;
        if (ll) {
-               LayoutLine(lineToWrap, surface, vs, ll, wrapWidth);
+               view.LayoutLine(*this, lineToWrap, surface, vs, ll, wrapWidth);
                linesWrapped = ll->lines;
        }
        return cs.SetHeight(lineToWrap, linesWrapped +
@@ -1567,13 +1479,13 @@ bool Editor::WrapOneLine(Surface *surface, int lineToWrap) {
 // wsVisible: wrap currently visible lines
 // wsIdle: wrap one page + 100 lines
 // Return true if wrapping occurred.
-bool Editor::WrapLines(enum wrapScope ws) {
-       int goodTopLine = topLine;
+bool Editor::WrapLines(WrapScope ws) {
+       Sci::Line goodTopLine = topLine;
        bool wrapOccurred = false;
-       if (wrapState == eWrapNone) {
+       if (!Wrapping()) {
                if (wrapWidth != LineLayout::wrapWidthInfinite) {
                        wrapWidth = LineLayout::wrapWidthInfinite;
-                       for (int lineDoc = 0; lineDoc < pdoc->LinesTotal(); lineDoc++) {
+                       for (Sci::Line lineDoc = 0; lineDoc < pdoc->LinesTotal(); lineDoc++) {
                                cs.SetHeight(lineDoc, 1 +
                                        (vs.annotationVisible ? pdoc->AnnotationLines(lineDoc) : 0));
                        }
@@ -1585,20 +1497,20 @@ bool Editor::WrapLines(enum wrapScope ws) {
                wrapPending.start = std::min(wrapPending.start, pdoc->LinesTotal());
                if (!SetIdle(true)) {
                        // Idle processing not supported so full wrap required.
-                       ws = wsAll;
+                       ws = WrapScope::wsAll;
                }
                // Decide where to start wrapping
-               int lineToWrap = wrapPending.start;
-               int lineToWrapEnd = std::min(wrapPending.end, pdoc->LinesTotal());
-               const int lineDocTop = cs.DocFromDisplay(topLine);
+               Sci::Line lineToWrap = wrapPending.start;
+               Sci::Line lineToWrapEnd = std::min(wrapPending.end, pdoc->LinesTotal());
+               const Sci::Line lineDocTop = cs.DocFromDisplay(topLine);
                const int subLineTop = topLine - cs.DisplayFromDoc(lineDocTop);
-               if (ws == wsVisible) {
+               if (ws == WrapScope::wsVisible) {
                        lineToWrap = Platform::Clamp(lineDocTop-5, wrapPending.start, pdoc->LinesTotal());
                        // Priority wrap to just after visible area.
                        // Since wrapping could reduce display lines, treat each
                        // as taking only one display line.
                        lineToWrapEnd = lineDocTop;
-                       int lines = LinesOnScreen() + 1;
+                       Sci::Line lines = LinesOnScreen() + 1;
                        while ((lineToWrapEnd < cs.LinesInDoc()) && (lines>0)) {
                                if (cs.GetVisible(lineToWrapEnd))
                                        lines--;
@@ -1609,10 +1521,10 @@ bool Editor::WrapLines(enum wrapScope ws) {
                                // Currently visible text does not need wrapping
                                return false;
                        }
-               } else if (ws == wsIdle) {
+               } else if (ws == WrapScope::wsIdle) {
                        lineToWrapEnd = lineToWrap + LinesOnScreen() + 100;
                }
-               const int lineEndNeedWrap = std::min(wrapPending.end, pdoc->LinesTotal());
+               const Sci::Line lineEndNeedWrap = std::min(wrapPending.end, pdoc->LinesTotal());
                lineToWrapEnd = std::min(lineToWrapEnd, lineEndNeedWrap);
 
                // Ensure all lines being wrapped are styled.
@@ -1621,9 +1533,9 @@ bool Editor::WrapLines(enum wrapScope ws) {
                if (lineToWrap < lineToWrapEnd) {
 
                        PRectangle rcTextArea = GetClientRectangle();
-                       rcTextArea.left = vs.textStart;
+                       rcTextArea.left = static_cast<XYPOSITION>(vs.textStart);
                        rcTextArea.right -= vs.rightMarginWidth;
-                       wrapWidth = rcTextArea.Width();
+                       wrapWidth = static_cast<int>(rcTextArea.Width());
                        RefreshStyleData();
                        AutoSurface surface(this);
                        if (surface) {
@@ -1660,14 +1572,14 @@ void Editor::LinesJoin() {
        if (!RangeContainsProtected(targetStart, targetEnd)) {
                UndoGroup ug(pdoc);
                bool prevNonWS = true;
-               for (int pos = targetStart; pos < targetEnd; pos++) {
+               for (Sci::Position pos = targetStart; pos < targetEnd; pos++) {
                        if (pdoc->IsPositionInLineEnd(pos)) {
                                targetEnd -= pdoc->LenChar(pos);
                                pdoc->DelChar(pos);
                                if (prevNonWS) {
                                        // Ensure at least one space separating previous lines
-                                       pdoc->InsertChar(pos, ' ');
-                                       targetEnd++;
+                                       const Sci::Position lengthInserted = pdoc->InsertString(pos, " ", 1);
+                                       targetEnd += lengthInserted;
                                }
                        } else {
                                prevNonWS = pdoc->CharAt(pos) != ' ';
@@ -1689,25 +1601,27 @@ const char *Editor::StringFromEOLMode(int eolMode) {
 void Editor::LinesSplit(int pixelWidth) {
        if (!RangeContainsProtected(targetStart, targetEnd)) {
                if (pixelWidth == 0) {
-                       PRectangle rcText = GetTextRectangle();
-                       pixelWidth = rcText.Width();
+                       const PRectangle rcText = GetTextRectangle();
+                       pixelWidth = static_cast<int>(rcText.Width());
                }
-               int lineStart = pdoc->LineFromPosition(targetStart);
-               int lineEnd = pdoc->LineFromPosition(targetEnd);
+               Sci::Line lineStart = pdoc->LineFromPosition(targetStart);
+               Sci::Line lineEnd = pdoc->LineFromPosition(targetEnd);
                const char *eol = StringFromEOLMode(pdoc->eolMode);
                UndoGroup ug(pdoc);
-               for (int line = lineStart; line <= lineEnd; line++) {
+               for (Sci::Line line = lineStart; line <= lineEnd; line++) {
                        AutoSurface surface(this);
-                       AutoLineLayout ll(llc, RetrieveLineLayout(line));
+                       AutoLineLayout ll(view.llc, view.RetrieveLineLayout(line, *this));
                        if (surface && ll) {
-                               unsigned int posLineStart = pdoc->LineStart(line);
-                               LayoutLine(line, surface, vs, ll, pixelWidth);
+                               Sci::Position posLineStart = pdoc->LineStart(line);
+                               view.LayoutLine(*this, line, surface, vs, ll, pixelWidth);
+                               Sci::Position lengthInsertedTotal = 0;
                                for (int subLine = 1; subLine < ll->lines; subLine++) {
-                                       pdoc->InsertCString(
-                                               static_cast<int>(posLineStart + (subLine - 1) * strlen(eol) +
+                                       const Sci::Position lengthInserted = pdoc->InsertString(
+                                               static_cast<int>(posLineStart + lengthInsertedTotal +
                                                        ll->LineStart(subLine)),
-                                               eol);
-                                       targetEnd += static_cast<int>(strlen(eol));
+                                                       eol, istrlen(eol));
+                                       targetEnd += lengthInserted;
+                                       lengthInsertedTotal += lengthInserted;
                                }
                        }
                        lineEnd = pdoc->LineFromPosition(targetEnd);
@@ -1715,117 +1629,35 @@ void Editor::LinesSplit(int pixelWidth) {
        }
 }
 
-int Editor::SubstituteMarkerIfEmpty(int markerCheck, int markerDefault) const {
-       if (vs.markers[markerCheck].markType == SC_MARK_EMPTY)
-               return markerDefault;
-       return markerCheck;
-}
-
-bool ValidStyledText(ViewStyle &vs, size_t styleOffset, const StyledText &st) {
-       if (st.multipleStyles) {
-               for (size_t iStyle=0; iStyle<st.length; iStyle++) {
-                       if (!vs.ValidStyle(styleOffset + st.styles[iStyle]))
-                               return false;
-               }
-       } else {
-               if (!vs.ValidStyle(styleOffset + st.style))
-                       return false;
-       }
-       return true;
-}
-
-static int WidthStyledText(Surface *surface, ViewStyle &vs, int styleOffset,
-       const char *text, const unsigned char *styles, size_t len) {
-       int width = 0;
-       size_t start = 0;
-       while (start < len) {
-               size_t style = styles[start];
-               size_t endSegment = start;
-               while ((endSegment+1 < len) && (static_cast<size_t>(styles[endSegment+1]) == style))
-                       endSegment++;
-               width += surface->WidthText(vs.styles[style+styleOffset].font, text + start,
-                       static_cast<int>(endSegment - start + 1));
-               start = endSegment + 1;
-       }
-       return width;
-}
-
-static int WidestLineWidth(Surface *surface, ViewStyle &vs, int styleOffset, const StyledText &st) {
-       int widthMax = 0;
-       size_t start = 0;
-       while (start < st.length) {
-               size_t lenLine = st.LineLength(start);
-               int widthSubLine;
-               if (st.multipleStyles) {
-                       widthSubLine = WidthStyledText(surface, vs, styleOffset, st.text + start, st.styles + 
start, lenLine);
-               } else {
-                       widthSubLine = surface->WidthText(vs.styles[styleOffset + st.style].font,
-                               st.text + start, static_cast<int>(lenLine));
-               }
-               if (widthSubLine > widthMax)
-                       widthMax = widthSubLine;
-               start += lenLine + 1;
-       }
-       return widthMax;
-}
-
-void DrawStyledText(Surface *surface, ViewStyle &vs, int styleOffset, PRectangle rcText, int ascent,
-       const StyledText &st, size_t start, size_t length) {
-
-       if (st.multipleStyles) {
-               int x = rcText.left;
-               size_t i = 0;
-               while (i < length) {
-                       size_t end = i;
-                       int style = st.styles[i + start];
-                       while (end < length-1 && st.styles[start+end+1] == style)
-                               end++;
-                       style += styleOffset;
-                       int width = surface->WidthText(vs.styles[style].font,
-                               st.text + start + i, static_cast<int>(end - i + 1));
-                       PRectangle rcSegment = rcText;
-                       rcSegment.left = x;
-                       rcSegment.right = x + width + 1;
-                       surface->DrawTextNoClip(rcSegment, vs.styles[style].font,
-                                       ascent, st.text + start + i,
-                                       static_cast<int>(end - i + 1),
-                                       vs.styles[style].fore,
-                                       vs.styles[style].back);
-                       x += width;
-                       i = end + 1;
-               }
-       } else {
-               size_t style = st.style + styleOffset;
-               surface->DrawTextNoClip(rcText, vs.styles[style].font,
-                               rcText.top + vs.maxAscent, st.text + start,
-                               static_cast<int>(length),
-                               vs.styles[style].fore,
-                               vs.styles[style].back);
-       }
-}
-
-void Editor::PaintSelMargin(Surface *surfWindow, PRectangle &rc) {
+void Editor::PaintSelMargin(Surface *surfaceWindow, PRectangle &rc) {
        if (vs.fixedColumnWidth == 0)
                return;
 
        AllocateGraphics();
        RefreshStyleData();
-       RefreshPixMaps(surfWindow);
+       RefreshPixMaps(surfaceWindow);
+
+       // On GTK+ with Ubuntu overlay scroll bars, the surface may have been finished
+       // at this point. The Initialised call checks for this case and sets the status
+       // to be bad which avoids crashes in following calls.
+       if (!surfaceWindow->Initialised()) {
+               return;
+       }
 
        PRectangle rcMargin = GetClientRectangle();
        Point ptOrigin = GetVisibleOriginInMain();
        rcMargin.Move(0, -ptOrigin.y);
        rcMargin.left = 0;
-       rcMargin.right = vs.fixedColumnWidth;
+       rcMargin.right = static_cast<XYPOSITION>(vs.fixedColumnWidth);
 
        if (!rc.Intersects(rcMargin))
                return;
 
        Surface *surface;
-       if (bufferedDraw) {
-               surface = pixmapSelMargin;
+       if (view.bufferedDraw) {
+               surface = marginView.pixmapSelMargin.get();
        } else {
-               surface = surfWindow;
+               surface = surfaceWindow;
        }
 
        // Clip vertically to paint area to avoid drawing line numbers
@@ -1834,1679 +1666,27 @@ void Editor::PaintSelMargin(Surface *surfWindow, PRectangle &rc) {
        if (rcMargin.top < rc.top)
                rcMargin.top = rc.top;
 
-       PRectangle rcSelMargin = rcMargin;
-       rcSelMargin.right = rcMargin.left;
-       if (rcSelMargin.bottom < rc.bottom)
-               rcSelMargin.bottom = rc.bottom;
-
-       for (int margin = 0; margin <= SC_MAX_MARGIN; margin++) {
-               if (vs.ms[margin].width > 0) {
-
-                       rcSelMargin.left = rcSelMargin.right;
-                       rcSelMargin.right = rcSelMargin.left + vs.ms[margin].width;
-
-                       if (vs.ms[margin].style != SC_MARGIN_NUMBER) {
-                               if (vs.ms[margin].mask & SC_MASK_FOLDERS) {
-                                       // Required because of special way brush is created for selection 
margin
-                                       // Ensure patterns line up when scrolling with separate margin view
-                                       // by choosing correctly aligned variant.
-                                       bool invertPhase = static_cast<int>(ptOrigin.y) & 1;
-                                       surface->FillRectangle(rcSelMargin,
-                                         invertPhase ? *pixmapSelPattern : *pixmapSelPatternOffset1);
-                               } else {
-                                       ColourDesired colour;
-                                       switch (vs.ms[margin].style) {
-                                       case SC_MARGIN_BACK:
-                                               colour = vs.styles[STYLE_DEFAULT].back;
-                                               break;
-                                       case SC_MARGIN_FORE:
-                                               colour = vs.styles[STYLE_DEFAULT].fore;
-                                               break;
-                                       default:
-                                               colour = vs.styles[STYLE_LINENUMBER].back;
-                                               break;
-                                       }
-                                       surface->FillRectangle(rcSelMargin, colour);
-                               }
-                       } else {
-                               surface->FillRectangle(rcSelMargin, vs.styles[STYLE_LINENUMBER].back);
-                       }
-
-                       const int lineStartPaint = (rcMargin.top + ptOrigin.y) / vs.lineHeight;
-                       int visibleLine = TopLineOfMain() + lineStartPaint;
-                       int yposScreen = lineStartPaint * vs.lineHeight - ptOrigin.y;
-                       // Work out whether the top line is whitespace located after a
-                       // lessening of fold level which implies a 'fold tail' but which should not
-                       // be displayed until the last of a sequence of whitespace.
-                       bool needWhiteClosure = false;
-                       if (vs.ms[margin].mask & SC_MASK_FOLDERS) {
-                               int level = pdoc->GetLevel(cs.DocFromDisplay(visibleLine));
-                               if (level & SC_FOLDLEVELWHITEFLAG) {
-                                       int lineBack = cs.DocFromDisplay(visibleLine);
-                                       int levelPrev = level;
-                                       while ((lineBack > 0) && (levelPrev & SC_FOLDLEVELWHITEFLAG)) {
-                                               lineBack--;
-                                               levelPrev = pdoc->GetLevel(lineBack);
-                                       }
-                                       if (!(levelPrev & SC_FOLDLEVELHEADERFLAG)) {
-                                               if ((level & SC_FOLDLEVELNUMBERMASK) < (levelPrev & 
SC_FOLDLEVELNUMBERMASK))
-                                                       needWhiteClosure = true;
-                                       }
-                               }
-                               if (highlightDelimiter.isEnabled) {
-                                       int lastLine = cs.DocFromDisplay(topLine + LinesOnScreen()) + 1;
-                                       pdoc->GetHighlightDelimiters(highlightDelimiter, 
pdoc->LineFromPosition(CurrentPosition()), lastLine);
-                               }
-                       }
-
-                       // Old code does not know about new markers needed to distinguish all cases
-                       int folderOpenMid = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEROPENMID,
-                               SC_MARKNUM_FOLDEROPEN);
-                       int folderEnd = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEREND,
-                               SC_MARKNUM_FOLDER);
-
-                       while ((visibleLine < cs.LinesDisplayed()) && yposScreen < rc.bottom) {
-
-                               PLATFORM_ASSERT(visibleLine < cs.LinesDisplayed());
-                               int lineDoc = cs.DocFromDisplay(visibleLine);
-                               PLATFORM_ASSERT(cs.GetVisible(lineDoc));
-                               bool firstSubLine = visibleLine == cs.DisplayFromDoc(lineDoc);
-                               bool lastSubLine = visibleLine == (cs.DisplayFromDoc(lineDoc + 1) - 1);
-
-                               int marks = pdoc->GetMark(lineDoc);
-                               if (!firstSubLine)
-                                       marks = 0;
-
-                               bool headWithTail = false;
-
-                               if (vs.ms[margin].mask & SC_MASK_FOLDERS) {
-                                       // Decide which fold indicator should be displayed
-                                       int level = pdoc->GetLevel(lineDoc);
-                                       int levelNext = pdoc->GetLevel(lineDoc + 1);
-                                       int levelNum = level & SC_FOLDLEVELNUMBERMASK;
-                                       int levelNextNum = levelNext & SC_FOLDLEVELNUMBERMASK;
-                                       if (level & SC_FOLDLEVELHEADERFLAG) {
-                                               if (firstSubLine) {
-                                                       if (levelNum < levelNextNum) {
-                                                               if (cs.GetExpanded(lineDoc)) {
-                                                                       if (levelNum == SC_FOLDLEVELBASE)
-                                                                               marks |= 1 << 
SC_MARKNUM_FOLDEROPEN;
-                                                                       else
-                                                                               marks |= 1 << folderOpenMid;
-                                                               } else {
-                                                                       if (levelNum == SC_FOLDLEVELBASE)
-                                                                               marks |= 1 << 
SC_MARKNUM_FOLDER;
-                                                                       else
-                                                                               marks |= 1 << folderEnd;
-                                                               }
-                                                       } else if (levelNum > SC_FOLDLEVELBASE) {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                       }
-                                               } else {
-                                                       if (levelNum < levelNextNum) {
-                                                               if (cs.GetExpanded(lineDoc)) {
-                                                                       marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                               } else if (levelNum > SC_FOLDLEVELBASE) {
-                                                                       marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                               }
-                                                       } else if (levelNum > SC_FOLDLEVELBASE) {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                       }
-                                               }
-                                               needWhiteClosure = false;
-                                               int firstFollowupLine = 
cs.DocFromDisplay(cs.DisplayFromDoc(lineDoc + 1));
-                                               int firstFollowupLineLevel = 
pdoc->GetLevel(firstFollowupLine);
-                                               int secondFollowupLineLevelNum = 
pdoc->GetLevel(firstFollowupLine + 1) & SC_FOLDLEVELNUMBERMASK;
-                                               if (!cs.GetExpanded(lineDoc)) {
-                                                       if ((firstFollowupLineLevel & SC_FOLDLEVELWHITEFLAG) 
&&
-                                                               (levelNum > secondFollowupLineLevelNum))
-                                                               needWhiteClosure = true;
-
-                                                       if 
(highlightDelimiter.IsFoldBlockHighlighted(firstFollowupLine))
-                                                               headWithTail = true;
-                                               }
-                                       } else if (level & SC_FOLDLEVELWHITEFLAG) {
-                                               if (needWhiteClosure) {
-                                                       if (levelNext & SC_FOLDLEVELWHITEFLAG) {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                       } else if (levelNextNum > SC_FOLDLEVELBASE) {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL;
-                                                               needWhiteClosure = false;
-                                                       } else {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERTAIL;
-                                                               needWhiteClosure = false;
-                                                       }
-                                               } else if (levelNum > SC_FOLDLEVELBASE) {
-                                                       if (levelNextNum < levelNum) {
-                                                               if (levelNextNum > SC_FOLDLEVELBASE) {
-                                                                       marks |= 1 << 
SC_MARKNUM_FOLDERMIDTAIL;
-                                                               } else {
-                                                                       marks |= 1 << SC_MARKNUM_FOLDERTAIL;
-                                                               }
-                                                       } else {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                       }
-                                               }
-                                       } else if (levelNum > SC_FOLDLEVELBASE) {
-                                               if (levelNextNum < levelNum) {
-                                                       needWhiteClosure = false;
-                                                       if (levelNext & SC_FOLDLEVELWHITEFLAG) {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                               needWhiteClosure = true;
-                                                       } else if (lastSubLine) {
-                                                               if (levelNextNum > SC_FOLDLEVELBASE) {
-                                                                       marks |= 1 << 
SC_MARKNUM_FOLDERMIDTAIL;
-                                                               } else {
-                                                                       marks |= 1 << SC_MARKNUM_FOLDERTAIL;
-                                                               }
-                                                       } else {
-                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                                       }
-                                               } else {
-                                                       marks |= 1 << SC_MARKNUM_FOLDERSUB;
-                                               }
-                                       }
-                               }
-
-                               marks &= vs.ms[margin].mask;
-
-                               PRectangle rcMarker = rcSelMargin;
-                               rcMarker.top = yposScreen;
-                               rcMarker.bottom = yposScreen + vs.lineHeight;
-                               if (vs.ms[margin].style == SC_MARGIN_NUMBER) {
-                                       if (firstSubLine) {
-                                               char number[100] = "";
-                                               if (lineDoc >= 0)
-                                                       sprintf(number, "%d", lineDoc + 1);
-                                               if (foldFlags & SC_FOLDFLAG_LEVELNUMBERS) {
-                                                       int lev = pdoc->GetLevel(lineDoc);
-                                                       sprintf(number, "%c%c %03X %03X",
-                                                                       (lev & SC_FOLDLEVELHEADERFLAG) ? 'H' 
: '_',
-                                                                       (lev & SC_FOLDLEVELWHITEFLAG) ? 'W' : 
'_',
-                                                                       lev & SC_FOLDLEVELNUMBERMASK,
-                                                                       lev >> 16
-                                                                  );
-                                               }
-                                               PRectangle rcNumber = rcMarker;
-                                               // Right justify
-                                               XYPOSITION width = 
surface->WidthText(vs.styles[STYLE_LINENUMBER].font, number, istrlen(number));
-                                               XYPOSITION xpos = rcNumber.right - width - 
marginNumberPadding;
-                                               rcNumber.left = xpos;
-                                               surface->DrawTextNoClip(rcNumber, 
vs.styles[STYLE_LINENUMBER].font,
-                                                               rcNumber.top + vs.maxAscent, number, 
istrlen(number),
-                                                               vs.styles[STYLE_LINENUMBER].fore,
-                                                               vs.styles[STYLE_LINENUMBER].back);
-                                       } else if (wrapVisualFlags & SC_WRAPVISUALFLAG_MARGIN) {
-                                               PRectangle rcWrapMarker = rcMarker;
-                                               rcWrapMarker.right -= 3;
-                                               rcWrapMarker.left = rcWrapMarker.right - 
vs.styles[STYLE_LINENUMBER].aveCharWidth;
-                                               DrawWrapMarker(surface, rcWrapMarker, false, 
vs.styles[STYLE_LINENUMBER].fore);
-                                       }
-                               } else if (vs.ms[margin].style == SC_MARGIN_TEXT || vs.ms[margin].style == 
SC_MARGIN_RTEXT) {
-                                       if (firstSubLine) {
-                                               const StyledText stMargin  = pdoc->MarginStyledText(lineDoc);
-                                               if (stMargin.text && ValidStyledText(vs, 
vs.marginStyleOffset, stMargin)) {
-                                                       surface->FillRectangle(rcMarker,
-                                                               
vs.styles[stMargin.StyleAt(0)+vs.marginStyleOffset].back);
-                                                       if (vs.ms[margin].style == SC_MARGIN_RTEXT) {
-                                                               int width = WidestLineWidth(surface, vs, 
vs.marginStyleOffset, stMargin);
-                                                               rcMarker.left = rcMarker.right - width - 3;
-                                                       }
-                                                       DrawStyledText(surface, vs, vs.marginStyleOffset, 
rcMarker, rcMarker.top + vs.maxAscent,
-                                                               stMargin, 0, stMargin.length);
-                                               }
-                                       }
-                               }
-
-                               if (marks) {
-                                       for (int markBit = 0; (markBit < 32) && marks; markBit++) {
-                                               if (marks & 1) {
-                                                       LineMarker::typeOfFold tFold = LineMarker::undefined;
-                                                       if ((vs.ms[margin].mask & SC_MASK_FOLDERS) && 
highlightDelimiter.IsFoldBlockHighlighted(lineDoc)) {
-                                                               if 
(highlightDelimiter.IsBodyOfFoldBlock(lineDoc)) {
-                                                                       tFold = LineMarker::body;
-                                                               } else if 
(highlightDelimiter.IsHeadOfFoldBlock(lineDoc)) {
-                                                                       if (firstSubLine) {
-                                                                               tFold = headWithTail ? 
LineMarker::headWithTail : LineMarker::head;
-                                                                       } else {
-                                                                               if (cs.GetExpanded(lineDoc) 
|| headWithTail) {
-                                                                                       tFold = 
LineMarker::body;
-                                                                               } else {
-                                                                                       tFold = 
LineMarker::undefined;
-                                                                               }
-                                                                       }
-                                                               } else if 
(highlightDelimiter.IsTailOfFoldBlock(lineDoc)) {
-                                                                       tFold = LineMarker::tail;
-                                                               }
-                                                       }
-                                                       vs.markers[markBit].Draw(surface, rcMarker, 
vs.styles[STYLE_LINENUMBER].font, tFold, vs.ms[margin].style);
-                                               }
-                                               marks >>= 1;
-                                       }
-                               }
-
-                               visibleLine++;
-                               yposScreen += vs.lineHeight;
-                       }
-               }
-       }
-
-       PRectangle rcBlankMargin = rcMargin;
-       rcBlankMargin.left = rcSelMargin.right;
-       surface->FillRectangle(rcBlankMargin, vs.styles[STYLE_DEFAULT].back);
-
-       if (bufferedDraw) {
-               surfWindow->Copy(rcMargin, Point(rcMargin.left, rcMargin.top), *pixmapSelMargin);
-       }
-}
-
-void DrawTabArrow(Surface *surface, PRectangle rcTab, int ymid) {
-       int ydiff = (rcTab.bottom - rcTab.top) / 2;
-       int xhead = rcTab.right - 1 - ydiff;
-       if (xhead <= rcTab.left) {
-               ydiff -= rcTab.left - xhead - 1;
-               xhead = rcTab.left - 1;
-       }
-       if ((rcTab.left + 2) < (rcTab.right - 1))
-               surface->MoveTo(rcTab.left + 2, ymid);
-       else
-               surface->MoveTo(rcTab.right - 1, ymid);
-       surface->LineTo(rcTab.right - 1, ymid);
-       surface->LineTo(xhead, ymid - ydiff);
-       surface->MoveTo(rcTab.right - 1, ymid);
-       surface->LineTo(xhead, ymid + ydiff);
-}
-
-LineLayout *Editor::RetrieveLineLayout(int lineNumber) {
-       int posLineStart = pdoc->LineStart(lineNumber);
-       int posLineEnd = pdoc->LineStart(lineNumber + 1);
-       PLATFORM_ASSERT(posLineEnd >= posLineStart);
-       int lineCaret = pdoc->LineFromPosition(sel.MainCaret());
-       return llc.Retrieve(lineNumber, lineCaret,
-               posLineEnd - posLineStart, pdoc->GetStyleClock(),
-               LinesOnScreen() + 1, pdoc->LinesTotal());
-}
-
-bool BadUTF(const char *s, int len, int &trailBytes) {
-       // For the rules: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
-       if (trailBytes) {
-               trailBytes--;
-               return false;
-       }
-       int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(s), len);
-       if (utf8status & UTF8MaskInvalid) {
-               return true;
-       } else {
-               trailBytes = (utf8status & UTF8MaskWidth) - 1;
-               return false;
-       }
-}
-
-/**
- * Fill in the LineLayout data for the given line.
- * Copy the given @a line and its styles from the document into local arrays.
- * Also determine the x position at which each character starts.
- */
-void Editor::LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayout *ll, int width) {
-       if (!ll)
-               return;
+       marginView.PaintMargin(surface, topLine, rc, rcMargin, *this, vs);
 
-       PLATFORM_ASSERT(line < pdoc->LinesTotal());
-       PLATFORM_ASSERT(ll->chars != NULL);
-       int posLineStart = pdoc->LineStart(line);
-       int posLineEnd = pdoc->LineStart(line + 1);
-       // If the line is very long, limit the treatment to a length that should fit in the viewport
-       if (posLineEnd > (posLineStart + ll->maxLineLength)) {
-               posLineEnd = posLineStart + ll->maxLineLength;
-       }
-       if (ll->validity == LineLayout::llCheckTextAndStyle) {
-               int lineLength = posLineEnd - posLineStart;
-               if (!vstyle.viewEOL) {
-                       lineLength = pdoc->LineEnd(line) - posLineStart;
-               }
-               if (lineLength == ll->numCharsInLine) {
-                       // See if chars, styles, indicators, are all the same
-                       bool allSame = true;
-                       const int styleMask = pdoc->stylingBitsMask;
-                       // Check base line layout
-                       char styleByte = 0;
-                       int numCharsInLine = 0;
-                       while (numCharsInLine < lineLength) {
-                               int charInDoc = numCharsInLine + posLineStart;
-                               char chDoc = pdoc->CharAt(charInDoc);
-                               styleByte = pdoc->StyleAt(charInDoc);
-                               allSame = allSame &&
-                                       (ll->styles[numCharsInLine] == static_cast<unsigned char>(styleByte & 
styleMask));
-                               allSame = allSame &&
-                                       (ll->indicators[numCharsInLine] == static_cast<char>(styleByte & 
~styleMask));
-                               if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseMixed)
-                                       allSame = allSame &&
-                                               (ll->chars[numCharsInLine] == chDoc);
-                               else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == 
Style::caseLower)
-                                       allSame = allSame &&
-                                               (ll->chars[numCharsInLine] == 
static_cast<char>(tolower(chDoc)));
-                               else    // Style::caseUpper
-                                       allSame = allSame &&
-                                               (ll->chars[numCharsInLine] == 
static_cast<char>(toupper(chDoc)));
-                               numCharsInLine++;
-                       }
-                       allSame = allSame && (ll->styles[numCharsInLine] == styleByte); // For eolFilled
-                       if (allSame) {
-                               ll->validity = LineLayout::llPositions;
-                       } else {
-                               ll->validity = LineLayout::llInvalid;
-                       }
-               } else {
-                       ll->validity = LineLayout::llInvalid;
-               }
-       }
-       if (ll->validity == LineLayout::llInvalid) {
-               ll->widthLine = LineLayout::wrapWidthInfinite;
-               ll->lines = 1;
-               if (vstyle.edgeState == EDGE_BACKGROUND) {
-                       ll->edgeColumn = pdoc->FindColumn(line, theEdge);
-                       if (ll->edgeColumn >= posLineStart) {
-                               ll->edgeColumn -= posLineStart;
-                       }
-               } else {
-                       ll->edgeColumn = -1;
-               }
-
-               char styleByte;
-               const int styleMask = pdoc->stylingBitsMask;
-               ll->styleBitsSet = 0;
-               // Fill base line layout
-               const int lineLength = posLineEnd - posLineStart;
-               pdoc->GetCharRange(ll->chars, posLineStart, lineLength);
-               pdoc->GetStyleRange(ll->styles, posLineStart, lineLength);
-               int numCharsBeforeEOL = pdoc->LineEnd(line) - posLineStart;
-               const int numCharsInLine = (vstyle.viewEOL) ? lineLength : numCharsBeforeEOL;
-               for (int styleInLine = 0; styleInLine < numCharsInLine; styleInLine++) {
-                       styleByte = ll->styles[styleInLine];
-                       ll->styleBitsSet |= styleByte;
-                       ll->styles[styleInLine] = static_cast<char>(styleByte & styleMask);
-                       ll->indicators[styleInLine] = static_cast<char>(styleByte & ~styleMask);
-               }
-               styleByte = static_cast<char>(((lineLength > 0) ? ll->styles[lineLength-1] : 0) & styleMask);
-               if (vstyle.someStylesForceCase) {
-                       for (int charInLine = 0; charInLine<lineLength; charInLine++) {
-                               char chDoc = ll->chars[charInLine];
-                               if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseUpper)
-                                       ll->chars[charInLine] = static_cast<char>(toupper(chDoc));
-                               else if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseLower)
-                                       ll->chars[charInLine] = static_cast<char>(tolower(chDoc));
-                       }
-               }
-               ll->xHighlightGuide = 0;
-               // Extra element at the end of the line to hold end x position and act as
-               ll->chars[numCharsInLine] = 0;   // Also triggers processing in the loops as this is a 
control character
-               ll->styles[numCharsInLine] = styleByte; // For eolFilled
-               ll->indicators[numCharsInLine] = 0;
-
-               // Layout the line, determining the position of each character,
-               // with an extra element at the end for the end of the line.
-               int startseg = 0;       // Start of the current segment, in char. number
-               XYACCUMULATOR startsegx = 0;    // Start of the current segment, in pixels
-               ll->positions[0] = 0;
-               XYPOSITION tabWidth = vstyle.spaceWidth * pdoc->tabInChars;
-               bool lastSegItalics = false;
-               Font &ctrlCharsFont = vstyle.styles[STYLE_CONTROLCHAR].font;
-
-               XYPOSITION ctrlCharWidth[32] = {0};
-               bool isControlNext = IsControlCharacter(ll->chars[0]);
-               int trailBytes = 0;
-               bool isBadUTFNext = IsUnicodeMode() && BadUTF(ll->chars, numCharsInLine, trailBytes);
-               for (int charInLine = 0; charInLine < numCharsInLine; charInLine++) {
-                       bool isControl = isControlNext;
-                       isControlNext = IsControlCharacter(ll->chars[charInLine + 1]);
-                       bool isBadUTF = isBadUTFNext;
-                       isBadUTFNext = IsUnicodeMode() && BadUTF(ll->chars + charInLine + 1, numCharsInLine - 
charInLine - 1, trailBytes);
-                       if ((ll->styles[charInLine] != ll->styles[charInLine + 1]) ||
-                               isControl || isControlNext || isBadUTF || isBadUTFNext || ((charInLine+1) >= 
numCharsBeforeEOL)) {
-                               ll->positions[startseg] = 0;
-                               if (vstyle.styles[ll->styles[charInLine]].visible) {
-                                       if (isControl) {
-                                               if (ll->chars[charInLine] == '\t') {
-                                                       ll->positions[charInLine + 1] =
-                                                               ((static_cast<int>((startsegx + 2) / 
tabWidth) + 1) * tabWidth) - startsegx;
-                                               } else if (controlCharSymbol < 32) {
-                                                       if (ctrlCharWidth[ll->chars[charInLine]] == 0) {
-                                                               const char *ctrlChar = 
ControlCharacterString(ll->chars[charInLine]);
-                                                               ctrlCharWidth[ll->chars[charInLine]] =
-                                                                   surface->WidthText(ctrlCharsFont, 
ctrlChar, istrlen(ctrlChar)) + ctrlCharPadding;
-                                                       }
-                                                       ll->positions[charInLine + 1] = 
ctrlCharWidth[ll->chars[charInLine]];
-                                               } else {
-                                                       char cc[2] = { static_cast<char>(controlCharSymbol), 
'\0' };
-                                                       surface->MeasureWidths(ctrlCharsFont, cc, 1,
-                                                               ll->positions + startseg + 1);
-                                               }
-                                               lastSegItalics = false;
-                                       } else if ((isBadUTF) || (charInLine >= numCharsBeforeEOL)) {
-                                               char hexits[4];
-                                               sprintf(hexits, "x%2X", ll->chars[charInLine] & 0xff);
-                                               ll->positions[charInLine + 1] =
-                                                   surface->WidthText(ctrlCharsFont, hexits, 
istrlen(hexits)) + 3;
-                                       } else {        // Regular character
-                                               int lenSeg = charInLine - startseg + 1;
-                                               if ((lenSeg == 1) && (' ' == ll->chars[startseg])) {
-                                                       lastSegItalics = false;
-                                                       // Over half the segments are single characters and 
of these about half are space characters.
-                                                       ll->positions[charInLine + 1] = 
vstyle.styles[ll->styles[charInLine]].spaceWidth;
-                                               } else {
-                                                       lastSegItalics = 
vstyle.styles[ll->styles[charInLine]].italic;
-                                                       posCache.MeasureWidths(surface, vstyle, 
ll->styles[charInLine], ll->chars + startseg,
-                                                               lenSeg, ll->positions + startseg + 1, pdoc);
-                                               }
-                                       }
-                               } else {    // invisible
-                                       for (int posToZero = startseg; posToZero <= (charInLine + 1); 
posToZero++) {
-                                               ll->positions[posToZero] = 0;
-                                       }
-                               }
-                               for (int posToIncrease = startseg; posToIncrease <= (charInLine + 1); 
posToIncrease++) {
-                                       ll->positions[posToIncrease] += startsegx;
-                               }
-                               startsegx = ll->positions[charInLine + 1];
-                               startseg = charInLine + 1;
-                       }
-               }
-               // Small hack to make lines that end with italics not cut off the edge of the last character
-               if ((startseg > 0) && lastSegItalics) {
-                       ll->positions[startseg] += lastSegItalicsOffset;
-               }
-               ll->numCharsInLine = numCharsInLine;
-               ll->numCharsBeforeEOL = numCharsBeforeEOL;
-               ll->validity = LineLayout::llPositions;
-       }
-       // Hard to cope when too narrow, so just assume there is space
-       if (width < 20) {
-               width = 20;
-       }
-       if ((ll->validity == LineLayout::llPositions) || (ll->widthLine != width)) {
-               ll->widthLine = width;
-               if (width == LineLayout::wrapWidthInfinite) {
-                       ll->lines = 1;
-               } else if (width > ll->positions[ll->numCharsInLine]) {
-                       // Simple common case where line does not need wrapping.
-                       ll->lines = 1;
-               } else {
-                       if (wrapVisualFlags & SC_WRAPVISUALFLAG_END) {
-                               width -= static_cast<int>(vstyle.aveCharWidth); // take into account the 
space for end wrap mark
-                       }
-                       XYPOSITION wrapAddIndent = 0; // This will be added to initial indent of line
-                       if (wrapIndentMode == SC_WRAPINDENT_INDENT) {
-                               wrapAddIndent = pdoc->IndentSize() * vstyle.spaceWidth;
-                       } else if (wrapIndentMode == SC_WRAPINDENT_FIXED) {
-                               wrapAddIndent = wrapVisualStartIndent * vstyle.aveCharWidth;
-                       }
-                       ll->wrapIndent = wrapAddIndent;
-                       if (wrapIndentMode != SC_WRAPINDENT_FIXED)
-                               for (int i = 0; i < ll->numCharsInLine; i++) {
-                                       if (!IsSpaceOrTab(ll->chars[i])) {
-                                               ll->wrapIndent += ll->positions[i]; // Add line indent
-                                               break;
-                                       }
-                               }
-                       // Check for text width minimum
-                       if (ll->wrapIndent > width - static_cast<int>(vstyle.aveCharWidth) * 15)
-                               ll->wrapIndent = wrapAddIndent;
-                       // Check for wrapIndent minimum
-                       if ((wrapVisualFlags & SC_WRAPVISUALFLAG_START) && (ll->wrapIndent < 
vstyle.aveCharWidth))
-                               ll->wrapIndent = vstyle.aveCharWidth; // Indent to show start visual
-                       ll->lines = 0;
-                       // Calculate line start positions based upon width.
-                       int lastGoodBreak = 0;
-                       int lastLineStart = 0;
-                       XYACCUMULATOR startOffset = 0;
-                       int p = 0;
-                       while (p < ll->numCharsInLine) {
-                               if ((ll->positions[p + 1] - startOffset) >= width) {
-                                       if (lastGoodBreak == lastLineStart) {
-                                               // Try moving to start of last character
-                                               if (p > 0) {
-                                                       lastGoodBreak = pdoc->MovePositionOutsideChar(p + 
posLineStart, -1)
-                                                               - posLineStart;
-                                               }
-                                               if (lastGoodBreak == lastLineStart) {
-                                                       // Ensure at least one character on line.
-                                                       lastGoodBreak = 
pdoc->MovePositionOutsideChar(lastGoodBreak + posLineStart + 1, 1)
-                                                               - posLineStart;
-                                               }
-                                       }
-                                       lastLineStart = lastGoodBreak;
-                                       ll->lines++;
-                                       ll->SetLineStart(ll->lines, lastGoodBreak);
-                                       startOffset = ll->positions[lastGoodBreak];
-                                       // take into account the space for start wrap mark and indent
-                                       startOffset -= ll->wrapIndent;
-                                       p = lastGoodBreak + 1;
-                                       continue;
-                               }
-                               if (p > 0) {
-                                       if (wrapState == eWrapChar) {
-                                               lastGoodBreak = pdoc->MovePositionOutsideChar(p + 
posLineStart, -1)
-                                                       - posLineStart;
-                                               p = pdoc->MovePositionOutsideChar(p + 1 + posLineStart, 1) - 
posLineStart;
-                                               continue;
-                                       } else if (ll->styles[p] != ll->styles[p - 1]) {
-                                               lastGoodBreak = p;
-                                       } else if (IsSpaceOrTab(ll->chars[p - 1]) && 
!IsSpaceOrTab(ll->chars[p])) {
-                                               lastGoodBreak = p;
-                                       }
-                               }
-                               p++;
-                       }
-                       ll->lines++;
-               }
-               ll->validity = LineLayout::llLines;
+       if (view.bufferedDraw) {
+               surfaceWindow->Copy(rcMargin, Point(rcMargin.left, rcMargin.top), 
*marginView.pixmapSelMargin);
        }
 }
 
-ColourDesired Editor::SelectionBackground(ViewStyle &vsDraw, bool main) const {
-       return main ?
-               (primarySelection ? vsDraw.selbackground : vsDraw.selbackground2) :
-               vsDraw.selAdditionalBackground;
-}
-
-ColourDesired Editor::TextBackground(ViewStyle &vsDraw, bool overrideBackground,
-        ColourDesired background, int inSelection, bool inHotspot, int styleMain, int i, LineLayout *ll) 
const {
-       if (inSelection == 1) {
-               if (vsDraw.selbackset && (vsDraw.selAlpha == SC_ALPHA_NOALPHA)) {
-                       return SelectionBackground(vsDraw, true);
-               }
-       } else if (inSelection == 2) {
-               if (vsDraw.selbackset && (vsDraw.selAdditionalAlpha == SC_ALPHA_NOALPHA)) {
-                       return SelectionBackground(vsDraw, false);
-               }
-       } else {
-               if ((vsDraw.edgeState == EDGE_BACKGROUND) &&
-                       (i >= ll->edgeColumn) &&
-                       (i < ll->numCharsBeforeEOL))
-                       return vsDraw.edgecolour;
-               if (inHotspot && vsDraw.hotspotBackgroundSet)
-                       return vsDraw.hotspotBackground;
-       }
-       if (overrideBackground && (styleMain != STYLE_BRACELIGHT) && (styleMain != STYLE_BRACEBAD)) {
-               return background;
-       } else {
-               return vsDraw.styles[styleMain].back;
-       }
-}
-
-void Editor::DrawIndentGuide(Surface *surface, int lineVisible, int lineHeight, int start, PRectangle 
rcSegment, bool highlight) {
-       Point from(0, ((lineVisible & 1) && (lineHeight & 1)) ? 1 : 0);
-       PRectangle rcCopyArea(start + 1, rcSegment.top, start + 2, rcSegment.bottom);
-       surface->Copy(rcCopyArea, from,
-               highlight ? *pixmapIndentGuideHighlight : *pixmapIndentGuide);
-}
-
-void Editor::DrawWrapMarker(Surface *surface, PRectangle rcPlace,
-        bool isEndMarker, ColourDesired wrapColour) {
-       surface->PenColour(wrapColour);
-
-       enum { xa = 1 }; // gap before start
-       int w = rcPlace.right - rcPlace.left - xa - 1;
-
-       bool xStraight = isEndMarker;  // x-mirrored symbol for start marker
-       bool yStraight = true;
-       //bool yStraight= isEndMarker; // comment in for start marker y-mirrowed
-
-       int x0 = xStraight ? rcPlace.left : rcPlace.right - 1;
-       int y0 = yStraight ? rcPlace.top : rcPlace.bottom - 1;
-
-       int dy = (rcPlace.bottom - rcPlace.top) / 5;
-       int y = (rcPlace.bottom - rcPlace.top) / 2 + dy;
-
-       struct Relative {
-               Surface *surface;
-               int xBase;
-               int xDir;
-               int yBase;
-               int yDir;
-               void MoveTo(int xRelative, int yRelative) {
-                       surface->MoveTo(xBase + xDir * xRelative, yBase + yDir * yRelative);
-               }
-               void LineTo(int xRelative, int yRelative) {
-                       surface->LineTo(xBase + xDir * xRelative, yBase + yDir * yRelative);
-               }
-       };
-       Relative rel = {surface, x0, xStraight ? 1 : -1, y0, yStraight ? 1 : -1};
-
-       // arrow head
-       rel.MoveTo(xa, y);
-       rel.LineTo(xa + 2*w / 3, y - dy);
-       rel.MoveTo(xa, y);
-       rel.LineTo(xa + 2*w / 3, y + dy);
-
-       // arrow body
-       rel.MoveTo(xa, y);
-       rel.LineTo(xa + w, y);
-       rel.LineTo(xa + w, y - 2 * dy);
-       rel.LineTo(xa - 1,   // on windows lineto is exclusive endpoint, perhaps GTK not...
-               y - 2 * dy);
-}
-
-static void SimpleAlphaRectangle(Surface *surface, PRectangle rc, ColourDesired fill, int alpha) {
-       if (alpha != SC_ALPHA_NOALPHA) {
-               surface->AlphaRectangle(rc, 0, fill, alpha, fill, alpha, 0);
-       }
-}
-
-void DrawTextBlob(Surface *surface, ViewStyle &vsDraw, PRectangle rcSegment,
-                                 const char *s, ColourDesired textBack, ColourDesired textFore, bool 
twoPhaseDraw) {
-       if (!twoPhaseDraw) {
-               surface->FillRectangle(rcSegment, textBack);
-       }
-       Font &ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font;
-       int normalCharHeight = surface->Ascent(ctrlCharsFont) -
-               surface->InternalLeading(ctrlCharsFont);
-       PRectangle rcCChar = rcSegment;
-       rcCChar.left = rcCChar.left + 1;
-       rcCChar.top = rcSegment.top + vsDraw.maxAscent - normalCharHeight;
-       rcCChar.bottom = rcSegment.top + vsDraw.maxAscent + 1;
-       PRectangle rcCentral = rcCChar;
-       rcCentral.top++;
-       rcCentral.bottom--;
-       surface->FillRectangle(rcCentral, textFore);
-       PRectangle rcChar = rcCChar;
-       rcChar.left++;
-       rcChar.right--;
-       surface->DrawTextClipped(rcChar, ctrlCharsFont,
-               rcSegment.top + vsDraw.maxAscent, s, istrlen(s),
-               textBack, textFore);
-}
-
-void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, LineLayout *ll,
-        int line, int lineEnd, int xStart, int subLine, XYACCUMULATOR subLineStart,
-        bool overrideBackground, ColourDesired background,
-        bool drawWrapMarkEnd, ColourDesired wrapColour) {
-
-       const int posLineStart = pdoc->LineStart(line);
-       const int styleMask = pdoc->stylingBitsMask;
-       PRectangle rcSegment = rcLine;
-
-       const bool lastSubLine = subLine == (ll->lines - 1);
-       XYPOSITION virtualSpace = 0;
-       if (lastSubLine) {
-               const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
-               virtualSpace = sel.VirtualSpaceFor(pdoc->LineEnd(line)) * spaceWidth;
-       }
-       XYPOSITION xEol = ll->positions[lineEnd] - subLineStart;
-
-       // Fill the virtual space and show selections within it
-       if (virtualSpace) {
-               rcSegment.left = xEol + xStart;
-               rcSegment.right = xEol + xStart + virtualSpace;
-               surface->FillRectangle(rcSegment, overrideBackground ? background : 
vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].back);
-               if (!hideSelection && ((vsDraw.selAlpha == SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha == 
SC_ALPHA_NOALPHA))) {
-                       SelectionSegment virtualSpaceRange(SelectionPosition(pdoc->LineEnd(line)), 
SelectionPosition(pdoc->LineEnd(line), sel.VirtualSpaceFor(pdoc->LineEnd(line))));
-                       for (size_t r=0; r<sel.Count(); r++) {
-                               int alpha = (r == sel.Main()) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
-                               if (alpha == SC_ALPHA_NOALPHA) {
-                                       SelectionSegment portion = sel.Range(r).Intersect(virtualSpaceRange);
-                                       if (!portion.Empty()) {
-                                               const XYPOSITION spaceWidth = 
vsDraw.styles[ll->EndLineStyle()].spaceWidth;
-                                               rcSegment.left = xStart + 
ll->positions[portion.start.Position() - posLineStart] - subLineStart + portion.start.VirtualSpace() * 
spaceWidth;
-                                               rcSegment.right = xStart + 
ll->positions[portion.end.Position() - posLineStart] - subLineStart + portion.end.VirtualSpace() * spaceWidth;
-                                               rcSegment.left = (rcSegment.left > rcLine.left) ? 
rcSegment.left : rcLine.left;
-                                               rcSegment.right = (rcSegment.right < rcLine.right) ? 
rcSegment.right : rcLine.right;
-                                               surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, 
r == sel.Main()));
-                                       }
-                               }
-                       }
-               }
-       }
-
-       int eolInSelection = 0;
-       int alpha = SC_ALPHA_NOALPHA;
-       if (!hideSelection) {
-               int posAfterLineEnd = pdoc->LineStart(line + 1);
-               eolInSelection = (subLine == (ll->lines - 1)) ? sel.InSelectionForEOL(posAfterLineEnd) : 0;
-               alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
-       }
-
-       // Draw the [CR], [LF], or [CR][LF] blobs if visible line ends are on
-       XYPOSITION blobsWidth = 0;
-       if (lastSubLine) {
-               for (int eolPos=ll->numCharsBeforeEOL; eolPos<ll->numCharsInLine; eolPos++) {
-                       rcSegment.left = xStart + ll->positions[eolPos] - subLineStart + virtualSpace;
-                       rcSegment.right = xStart + ll->positions[eolPos+1] - subLineStart + virtualSpace;
-                       blobsWidth += rcSegment.Width();
-                       char hexits[4];
-                       const char *ctrlChar;
-                       unsigned char chEOL = ll->chars[eolPos];
-                       if (UTF8IsAscii(chEOL)) {
-                               ctrlChar = ControlCharacterString(chEOL);
-                       } else {
-                               sprintf(hexits, "x%2X", chEOL);
-                               ctrlChar = hexits;
-                       }
-                       int styleMain = ll->styles[eolPos];
-                       ColourDesired textBack = TextBackground(vsDraw, overrideBackground, background, 
eolInSelection, false, styleMain, eolPos, ll);
-                       ColourDesired textFore = vsDraw.styles[styleMain].fore;
-                       if (eolInSelection && vsDraw.selforeset) {
-                               textFore = (eolInSelection == 1) ? vsDraw.selforeground : 
vsDraw.selAdditionalForeground;
-                       }
-                       if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1)) {
-                               if (alpha == SC_ALPHA_NOALPHA) {
-                                       surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, 
eolInSelection == 1));
-                               } else {
-                                       surface->FillRectangle(rcSegment, textBack);
-                               }
-                       } else {
-                               surface->FillRectangle(rcSegment, textBack);
-                       }
-                       DrawTextBlob(surface, vsDraw, rcSegment, ctrlChar, textBack, textFore, twoPhaseDraw);
-                       if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha 
!= SC_ALPHA_NOALPHA)) {
-                               SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, 
eolInSelection == 1), alpha);
-                       }
-               }
-       }
-
-       // Draw the eol-is-selected rectangle
-       rcSegment.left = xEol + xStart + virtualSpace + blobsWidth;
-       rcSegment.right = rcSegment.left + vsDraw.aveCharWidth;
-
-       if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha == 
SC_ALPHA_NOALPHA)) {
-               surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1));
-       } else {
-               if (overrideBackground) {
-                       surface->FillRectangle(rcSegment, background);
-               } else if (line < pdoc->LinesTotal() - 1) {
-                       surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine] & 
styleMask].back);
-               } else if (vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].eolFilled) {
-                       surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine] & 
styleMask].back);
-               } else {
-                       surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back);
-               }
-               if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha != 
SC_ALPHA_NOALPHA)) {
-                       SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection 
== 1), alpha);
-               }
-       }
-
-       // Fill the remainder of the line
-       rcSegment.left = rcSegment.right;
-       if (rcSegment.left < rcLine.left)
-               rcSegment.left = rcLine.left;
-       rcSegment.right = rcLine.right;
-
-       if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && 
(alpha == SC_ALPHA_NOALPHA)) {
-               surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1));
-       } else {
-               if (overrideBackground) {
-                       surface->FillRectangle(rcSegment, background);
-               } else if (vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].eolFilled) {
-                       surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine] & 
styleMask].back);
-               } else {
-                       surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back);
-               }
-               if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selbackset && (line < pdoc->LinesTotal() 
- 1) && (alpha != SC_ALPHA_NOALPHA)) {
-                       SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection 
== 1), alpha);
-               }
-       }
-
-       if (drawWrapMarkEnd) {
-               PRectangle rcPlace = rcSegment;
-
-               if (wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_END_BY_TEXT) {
-                       rcPlace.left = xEol + xStart + virtualSpace;
-                       rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
-               } else {
-                       // rcLine is clipped to text area
-                       rcPlace.right = rcLine.right;
-                       rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
-               }
-               DrawWrapMarker(surface, rcPlace, true, wrapColour);
-       }
-}
-
-void Editor::DrawIndicator(int indicNum, int startPos, int endPos, Surface *surface, ViewStyle &vsDraw,
-               int xStart, PRectangle rcLine, LineLayout *ll, int subLine) {
-       const XYPOSITION subLineStart = ll->positions[ll->LineStart(subLine)];
-       PRectangle rcIndic(
-               ll->positions[startPos] + xStart - subLineStart,
-               rcLine.top + vsDraw.maxAscent,
-               ll->positions[endPos] + xStart - subLineStart,
-               rcLine.top + vsDraw.maxAscent + 3);
-       vsDraw.indicators[indicNum].Draw(surface, rcIndic, rcLine);
-}
-
-void Editor::DrawIndicators(Surface *surface, ViewStyle &vsDraw, int line, int xStart,
-        PRectangle rcLine, LineLayout *ll, int subLine, int lineEnd, bool under) {
-       // Draw decorators
-       const int posLineStart = pdoc->LineStart(line);
-       const int lineStart = ll->LineStart(subLine);
-       const int posLineEnd = posLineStart + lineEnd;
-
-       if (!under) {
-               // Draw indicators
-               // foreach indicator...
-               for (int indicnum = 0, mask = 1 << pdoc->stylingBits; mask < 0x100; indicnum++) {
-                       if (!(mask & ll->styleBitsSet)) {
-                               mask <<= 1;
-                               continue;
-                       }
-                       int startPos = -1;
-                       // foreach style pos in line...
-                       for (int indicPos = lineStart; indicPos <= lineEnd; indicPos++) {
-                               // look for starts...
-                               if (startPos < 0) {
-                                       // NOT in indicator run, looking for START
-                                       if (indicPos < lineEnd && (ll->indicators[indicPos] & mask))
-                                               startPos = indicPos;
-                               }
-                               // ... or ends
-                               if (startPos >= 0) {
-                                       // IN indicator run, looking for END
-                                       if (indicPos >= lineEnd || !(ll->indicators[indicPos] & mask)) {
-                                               // AT end of indicator run, DRAW it!
-                                               DrawIndicator(indicnum, startPos, indicPos, surface, vsDraw, 
xStart, rcLine, ll, subLine);
-                                               // RESET control var
-                                               startPos = -1;
-                                       }
-                               }
-                       }
-                       mask <<= 1;
-               }
-       }
-
-       for (Decoration *deco = pdoc->decorations.root; deco; deco = deco->next) {
-               if (under == vsDraw.indicators[deco->indicator].under) {
-                       int startPos = posLineStart + lineStart;
-                       if (!deco->rs.ValueAt(startPos)) {
-                               startPos = deco->rs.EndRun(startPos);
-                       }
-                       while ((startPos < posLineEnd) && (deco->rs.ValueAt(startPos))) {
-                               int endPos = deco->rs.EndRun(startPos);
-                               if (endPos > posLineEnd)
-                                       endPos = posLineEnd;
-                               DrawIndicator(deco->indicator, startPos - posLineStart, endPos - posLineStart,
-                                       surface, vsDraw, xStart, rcLine, ll, subLine);
-                               startPos = deco->rs.EndRun(endPos);
-                       }
-               }
-       }
-
-       // Use indicators to highlight matching braces
-       if ((vs.braceHighlightIndicatorSet && (bracesMatchStyle == STYLE_BRACELIGHT)) ||
-               (vs.braceBadLightIndicatorSet && (bracesMatchStyle == STYLE_BRACEBAD))) {
-               int braceIndicator = (bracesMatchStyle == STYLE_BRACELIGHT) ? vs.braceHighlightIndicator : 
vs.braceBadLightIndicator;
-               if (under == vsDraw.indicators[braceIndicator].under) {
-                       Range rangeLine(posLineStart + lineStart, posLineEnd);
-                       if (rangeLine.ContainsCharacter(braces[0])) {
-                               int braceOffset = braces[0] - posLineStart;
-                               if (braceOffset < ll->numCharsInLine) {
-                                       DrawIndicator(braceIndicator, braceOffset, braceOffset + 1, surface, 
vsDraw, xStart, rcLine, ll, subLine);
-                               }
-                       }
-                       if (rangeLine.ContainsCharacter(braces[1])) {
-                               int braceOffset = braces[1] - posLineStart;
-                               if (braceOffset < ll->numCharsInLine) {
-                                       DrawIndicator(braceIndicator, braceOffset, braceOffset + 1, surface, 
vsDraw, xStart, rcLine, ll, subLine);
-                               }
-                       }
-               }
-       }
-}
-
-void Editor::DrawAnnotation(Surface *surface, ViewStyle &vsDraw, int line, int xStart,
-    PRectangle rcLine, LineLayout *ll, int subLine) {
-       int indent = pdoc->GetLineIndentation(line) * vsDraw.spaceWidth;
-       PRectangle rcSegment = rcLine;
-       int annotationLine = subLine - ll->lines;
-       const StyledText stAnnotation  = pdoc->AnnotationStyledText(line);
-       if (stAnnotation.text && ValidStyledText(vsDraw, vsDraw.annotationStyleOffset, stAnnotation)) {
-               surface->FillRectangle(rcSegment, vsDraw.styles[0].back);
-               if (vs.annotationVisible == ANNOTATION_BOXED) {
-                       // Only care about calculating width if need to draw box
-                       int widthAnnotation = WidestLineWidth(surface, vsDraw, vsDraw.annotationStyleOffset, 
stAnnotation);
-                       widthAnnotation += vsDraw.spaceWidth * 2; // Margins
-                       rcSegment.left = xStart + indent;
-                       rcSegment.right = rcSegment.left + widthAnnotation;
-               } else {
-                       rcSegment.left = xStart;
-               }
-               const int annotationLines = pdoc->AnnotationLines(line);
-               size_t start = 0;
-               size_t lengthAnnotation = stAnnotation.LineLength(start);
-               int lineInAnnotation = 0;
-               while ((lineInAnnotation < annotationLine) && (start < stAnnotation.length)) {
-                       start += lengthAnnotation + 1;
-                       lengthAnnotation = stAnnotation.LineLength(start);
-                       lineInAnnotation++;
-               }
-               PRectangle rcText = rcSegment;
-               if (vs.annotationVisible == ANNOTATION_BOXED) {
-                       surface->FillRectangle(rcText,
-                               vsDraw.styles[stAnnotation.StyleAt(start) + 
vsDraw.annotationStyleOffset].back);
-                       rcText.left += vsDraw.spaceWidth;
-               }
-               DrawStyledText(surface, vsDraw, vsDraw.annotationStyleOffset, rcText, rcText.top + 
vsDraw.maxAscent,
-                       stAnnotation, start, lengthAnnotation);
-               if (vs.annotationVisible == ANNOTATION_BOXED) {
-                       surface->PenColour(vsDraw.styles[vsDraw.annotationStyleOffset].fore);
-                       surface->MoveTo(rcSegment.left, rcSegment.top);
-                       surface->LineTo(rcSegment.left, rcSegment.bottom);
-                       surface->MoveTo(rcSegment.right, rcSegment.top);
-                       surface->LineTo(rcSegment.right, rcSegment.bottom);
-                       if (subLine == ll->lines) {
-                               surface->MoveTo(rcSegment.left, rcSegment.top);
-                               surface->LineTo(rcSegment.right, rcSegment.top);
-                       }
-                       if (subLine == ll->lines+annotationLines-1) {
-                               surface->MoveTo(rcSegment.left, rcSegment.bottom - 1);
-                               surface->LineTo(rcSegment.right, rcSegment.bottom - 1);
-                       }
-               }
-       }
-}
-
-void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVisible, int xStart,
-        PRectangle rcLine, LineLayout *ll, int subLine) {
-
-       PRectangle rcSegment = rcLine;
-
-       // Using one font for all control characters so it can be controlled independently to ensure
-       // the box goes around the characters tightly. Seems to be no way to work out what height
-       // is taken by an individual character - internal leading gives varying results.
-       Font &ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font;
-
-       // See if something overrides the line background color:  Either if caret is on the line
-       // and background color is set for that, or if a marker is defined that forces its background
-       // color onto the line, or if a marker is defined but has no selection margin in which to
-       // display itself (as long as it's not an SC_MARK_EMPTY marker).  These are checked in order
-       // with the earlier taking precedence.  When multiple markers cause background override,
-       // the color for the highest numbered one is used.
-       bool overrideBackground = false;
-       ColourDesired background;
-       if ((caret.active || vsDraw.alwaysShowCaretLineBackground) && vsDraw.showCaretLineBackground && 
(vsDraw.caretLineAlpha == SC_ALPHA_NOALPHA) && ll->containsCaret) {
-               overrideBackground = true;
-               background = vsDraw.caretLineBackground;
-       }
-       if (!overrideBackground) {
-               int marks = pdoc->GetMark(line);
-               for (int markBit = 0; (markBit < 32) && marks; markBit++) {
-                       if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_BACKGROUND) &&
-                               (vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
-                               background = vsDraw.markers[markBit].back;
-                               overrideBackground = true;
-                       }
-                       marks >>= 1;
-               }
-       }
-       if (!overrideBackground) {
-               if (vsDraw.maskInLine) {
-                       int marksMasked = pdoc->GetMark(line) & vsDraw.maskInLine;
-                       if (marksMasked) {
-                               for (int markBit = 0; (markBit < 32) && marksMasked; markBit++) {
-                                       if ((marksMasked & 1) && (vsDraw.markers[markBit].markType != 
SC_MARK_EMPTY) &&
-                                               (vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
-                                               overrideBackground = true;
-                                               background = vsDraw.markers[markBit].back;
-                                       }
-                                       marksMasked >>= 1;
-                               }
-                       }
-               }
-       }
-
-       bool drawWhitespaceBackground = (vsDraw.viewWhitespace != wsInvisible) &&
-               (!overrideBackground) && (vsDraw.whitespaceBackgroundSet);
-
-       bool inIndentation = subLine == 0;      // Do not handle indentation except on first subline.
-       const XYPOSITION indentWidth = pdoc->IndentSize() * vsDraw.spaceWidth;
-       const XYPOSITION epsilon = 0.0001f;     // A small nudge to avoid floating point precision issues
-
-       int posLineStart = pdoc->LineStart(line);
-
-       int startseg = ll->LineStart(subLine);
-       XYACCUMULATOR subLineStart = ll->positions[startseg];
-       if (subLine >= ll->lines) {
-               DrawAnnotation(surface, vsDraw, line, xStart, rcLine, ll, subLine);
-               return; // No further drawing
-       }
-       int lineStart = 0;
-       int lineEnd = 0;
-       if (subLine < ll->lines) {
-               lineStart = ll->LineStart(subLine);
-               lineEnd = ll->LineStart(subLine + 1);
-               if (subLine == ll->lines - 1) {
-                       lineEnd = ll->numCharsBeforeEOL;
-               }
-       }
-
-       ColourDesired wrapColour = vsDraw.styles[STYLE_DEFAULT].fore;
-       if (vsDraw.whitespaceForegroundSet)
-               wrapColour = vsDraw.whitespaceForeground;
-
-       bool drawWrapMarkEnd = false;
-
-       if (wrapVisualFlags & SC_WRAPVISUALFLAG_END) {
-               if (subLine + 1 < ll->lines) {
-                       drawWrapMarkEnd = ll->LineStart(subLine + 1) != 0;
-               }
-       }
-
-       if (ll->wrapIndent != 0) {
-
-               bool continuedWrapLine = false;
-               if (subLine < ll->lines) {
-                       continuedWrapLine = ll->LineStart(subLine) != 0;
-               }
-
-               if (continuedWrapLine) {
-                       // draw continuation rect
-                       PRectangle rcPlace = rcSegment;
-
-                       rcPlace.left = ll->positions[startseg] + xStart - subLineStart;
-                       rcPlace.right = rcPlace.left + ll->wrapIndent;
-
-                       // default bgnd here..
-                       surface->FillRectangle(rcSegment, overrideBackground ? background :
-                               vsDraw.styles[STYLE_DEFAULT].back);
-
-                       // main line style would be below but this would be inconsistent with end markers
-                       // also would possibly not be the style at wrap point
-                       //int styleMain = ll->styles[lineStart];
-                       //surface->FillRectangle(rcPlace, vsDraw.styles[styleMain].back);
-
-                       if (wrapVisualFlags & SC_WRAPVISUALFLAG_START) {
-
-                               if (wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_START_BY_TEXT)
-                                       rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
-                               else
-                                       rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
-
-                               DrawWrapMarker(surface, rcPlace, false, wrapColour);
-                       }
-
-                       xStart += static_cast<int>(ll->wrapIndent);
-               }
-       }
-
-       bool selBackDrawn = vsDraw.selbackset &&
-               ((vsDraw.selAlpha == SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha == SC_ALPHA_NOALPHA));
-
-       // Does not take margin into account but not significant
-       int xStartVisible = static_cast<int>(subLineStart) - xStart;
-
-       ll->psel = &sel;
-
-       BreakFinder bfBack(ll, lineStart, lineEnd, posLineStart, xStartVisible, selBackDrawn, pdoc);
-       int next = bfBack.First();
-
-       // Background drawing loop
-       while (twoPhaseDraw && (next < lineEnd)) {
-
-               startseg = next;
-               next = bfBack.Next();
-               int i = next - 1;
-               int iDoc = i + posLineStart;
-
-               rcSegment.left = ll->positions[startseg] + xStart - subLineStart;
-               rcSegment.right = ll->positions[i + 1] + xStart - subLineStart;
-               // Only try to draw if really visible - enhances performance by not calling environment to
-               // draw strings that are completely past the right side of the window.
-               if ((rcSegment.left <= rcLine.right) && (rcSegment.right >= rcLine.left)) {
-                       // Clip to line rectangle, since may have a huge position which will not work with 
some platforms
-                       if (rcSegment.left < rcLine.left)
-                               rcSegment.left = rcLine.left;
-                       if (rcSegment.right > rcLine.right)
-                               rcSegment.right = rcLine.right;
-
-                       int styleMain = ll->styles[i];
-                       const int inSelection = hideSelection ? 0 : sel.CharacterInSelection(iDoc);
-                       bool inHotspot = (ll->hsStart != -1) && (iDoc >= ll->hsStart) && (iDoc < ll->hsEnd);
-                       ColourDesired textBack = TextBackground(vsDraw, overrideBackground, background, 
inSelection, inHotspot, styleMain, i, ll);
-                       if (ll->chars[i] == '\t') {
-                               // Tab display
-                               if (drawWhitespaceBackground &&
-                                       (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways))
-                                       textBack = vsDraw.whitespaceBackground;
-                               surface->FillRectangle(rcSegment, textBack);
-                       } else if (IsControlCharacter(ll->chars[i])) {
-                               // Control character display
-                               inIndentation = false;
-                               surface->FillRectangle(rcSegment, textBack);
-                       } else {
-                               // Normal text display
-                               surface->FillRectangle(rcSegment, textBack);
-                               if (vsDraw.viewWhitespace != wsInvisible ||
-                                       (inIndentation && vsDraw.viewIndentationGuides == ivReal)) {
-                                       for (int cpos = 0; cpos <= i - startseg; cpos++) {
-                                               if (ll->chars[cpos + startseg] == ' ') {
-                                                       if (drawWhitespaceBackground &&
-                                                               (!inIndentation || vsDraw.viewWhitespace == 
wsVisibleAlways)) {
-                                                               PRectangle rcSpace(ll->positions[cpos + 
startseg] + xStart - subLineStart,
-                                                                       rcSegment.top,
-                                                                       ll->positions[cpos + startseg + 1] + 
xStart - subLineStart,
-                                                                       rcSegment.bottom);
-                                                               surface->FillRectangle(rcSpace, 
vsDraw.whitespaceBackground);
-                                                       }
-                                               } else {
-                                                       inIndentation = false;
-                                               }
-                                       }
-                               }
-                       }
-               } else if (rcSegment.left > rcLine.right) {
-                       break;
-               }
-       }
-
-       if (twoPhaseDraw) {
-               DrawEOL(surface, vsDraw, rcLine, ll, line, lineEnd,
-                       xStart, subLine, subLineStart, overrideBackground, background,
-                       drawWrapMarkEnd, wrapColour);
-       }
-
-       DrawIndicators(surface, vsDraw, line, xStart, rcLine, ll, subLine, lineEnd, true);
-
-       if (vsDraw.edgeState == EDGE_LINE) {
-               int edgeX = theEdge * vsDraw.spaceWidth;
-               rcSegment.left = edgeX + xStart;
-               if ((ll->wrapIndent != 0) && (lineStart != 0))
-                       rcSegment.left -= ll->wrapIndent;
-               rcSegment.right = rcSegment.left + 1;
-               surface->FillRectangle(rcSegment, vsDraw.edgecolour);
-       }
-
-       // Draw underline mark as part of background if not transparent
-       int marks = pdoc->GetMark(line);
-       int markBit;
-       for (markBit = 0; (markBit < 32) && marks; markBit++) {
-               if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_UNDERLINE) &&
-                   (vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
-                       PRectangle rcUnderline = rcLine;
-                       rcUnderline.top = rcUnderline.bottom - 2;
-                       surface->FillRectangle(rcUnderline, vsDraw.markers[markBit].back);
-               }
-               marks >>= 1;
-       }
-
-       inIndentation = subLine == 0;   // Do not handle indentation except on first subline.
-       // Foreground drawing loop
-       BreakFinder bfFore(ll, lineStart, lineEnd, posLineStart, xStartVisible,
-               ((!twoPhaseDraw && selBackDrawn) || vsDraw.selforeset), pdoc);
-       next = bfFore.First();
-
-       while (next < lineEnd) {
-
-               startseg = next;
-               next = bfFore.Next();
-               int i = next - 1;
-
-               int iDoc = i + posLineStart;
-
-               rcSegment.left = ll->positions[startseg] + xStart - subLineStart;
-               rcSegment.right = ll->positions[i + 1] + xStart - subLineStart;
-               // Only try to draw if really visible - enhances performance by not calling environment to
-               // draw strings that are completely past the right side of the window.
-               if ((rcSegment.left <= rcLine.right) && (rcSegment.right >= rcLine.left)) {
-                       int styleMain = ll->styles[i];
-                       ColourDesired textFore = vsDraw.styles[styleMain].fore;
-                       Font &textFont = vsDraw.styles[styleMain].font;
-                       //hotspot foreground
-                       if (ll->hsStart != -1 && iDoc >= ll->hsStart && iDoc < hsEnd) {
-                               if (vsDraw.hotspotForegroundSet)
-                                       textFore = vsDraw.hotspotForeground;
-                       }
-                       const int inSelection = hideSelection ? 0 : sel.CharacterInSelection(iDoc);
-                       if (inSelection && (vsDraw.selforeset)) {
-                               textFore = (inSelection == 1) ? vsDraw.selforeground : 
vsDraw.selAdditionalForeground;
-                       }
-                       bool inHotspot = (ll->hsStart != -1) && (iDoc >= ll->hsStart) && (iDoc < ll->hsEnd);
-                       ColourDesired textBack = TextBackground(vsDraw, overrideBackground, background, 
inSelection, inHotspot, styleMain, i, ll);
-                       if (ll->chars[i] == '\t') {
-                               // Tab display
-                               if (!twoPhaseDraw) {
-                                       if (drawWhitespaceBackground &&
-                                               (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways))
-                                               textBack = vsDraw.whitespaceBackground;
-                                       surface->FillRectangle(rcSegment, textBack);
-                               }
-                               if (inIndentation && vsDraw.viewIndentationGuides == ivReal) {
-                                       for (int indentCount = (ll->positions[i] + epsilon) / indentWidth;
-                                               indentCount <= (ll->positions[i + 1] - epsilon) / indentWidth;
-                                               indentCount++) {
-                                               if (indentCount > 0) {
-                                                       int xIndent = indentCount * indentWidth;
-                                                       DrawIndentGuide(surface, lineVisible, 
vsDraw.lineHeight, xIndent + xStart, rcSegment,
-                                                                   (ll->xHighlightGuide == xIndent));
-                                               }
-                                       }
-                               }
-                               if (vsDraw.viewWhitespace != wsInvisible) {
-                                       if (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways) {
-                                               if (vsDraw.whitespaceForegroundSet)
-                                                       textFore = vsDraw.whitespaceForeground;
-                                               surface->PenColour(textFore);
-                                               PRectangle rcTab(rcSegment.left + 1, rcSegment.top + 4,
-                                                       rcSegment.right - 1, rcSegment.bottom - 
vsDraw.maxDescent);
-                                               DrawTabArrow(surface, rcTab, rcSegment.top + 
vsDraw.lineHeight / 2);
-                                       }
-                               }
-                       } else if (IsControlCharacter(ll->chars[i])) {
-                               // Control character display
-                               inIndentation = false;
-                               if (controlCharSymbol < 32) {
-                                       // Draw the character
-                                       const char *ctrlChar = ControlCharacterString(ll->chars[i]);
-                                       DrawTextBlob(surface, vsDraw, rcSegment, ctrlChar, textBack, 
textFore, twoPhaseDraw);
-                               } else {
-                                       char cc[2] = { static_cast<char>(controlCharSymbol), '\0' };
-                                       surface->DrawTextNoClip(rcSegment, ctrlCharsFont,
-                                               rcSegment.top + vsDraw.maxAscent,
-                                               cc, 1, textBack, textFore);
-                               }
-                       } else if ((i == startseg) && (static_cast<unsigned char>(ll->chars[i]) >= 0x80) && 
IsUnicodeMode()) {
-                               // A single byte >= 0x80 in UTF-8 is a bad byte and is displayed as its hex 
value
-                               char hexits[4];
-                               sprintf(hexits, "x%2X", ll->chars[i] & 0xff);
-                               DrawTextBlob(surface, vsDraw, rcSegment, hexits, textBack, textFore, 
twoPhaseDraw);
-                       } else {
-                               // Normal text display
-                               if (vsDraw.styles[styleMain].visible) {
-                                       if (twoPhaseDraw) {
-                                               surface->DrawTextTransparent(rcSegment, textFont,
-                                                       rcSegment.top + vsDraw.maxAscent, ll->chars + 
startseg,
-                                                       i - startseg + 1, textFore);
-                                       } else {
-                                               surface->DrawTextNoClip(rcSegment, textFont,
-                                                       rcSegment.top + vsDraw.maxAscent, ll->chars + 
startseg,
-                                                       i - startseg + 1, textFore, textBack);
-                                       }
-                               }
-                               if (vsDraw.viewWhitespace != wsInvisible ||
-                                       (inIndentation && vsDraw.viewIndentationGuides != ivNone)) {
-                                       for (int cpos = 0; cpos <= i - startseg; cpos++) {
-                                               if (ll->chars[cpos + startseg] == ' ') {
-                                                       if (vsDraw.viewWhitespace != wsInvisible) {
-                                                               if (vsDraw.whitespaceForegroundSet)
-                                                                       textFore = 
vsDraw.whitespaceForeground;
-                                                               if (!inIndentation || vsDraw.viewWhitespace 
== wsVisibleAlways) {
-                                                                       XYPOSITION xmid = (ll->positions[cpos 
+ startseg] + ll->positions[cpos + startseg + 1]) / 2;
-                                                                       if (!twoPhaseDraw && 
drawWhitespaceBackground &&
-                                                                               (!inIndentation || 
vsDraw.viewWhitespace == wsVisibleAlways)) {
-                                                                               textBack = 
vsDraw.whitespaceBackground;
-                                                                               PRectangle 
rcSpace(ll->positions[cpos + startseg] + xStart - subLineStart,
-                                                                                       rcSegment.top,
-                                                                                       ll->positions[cpos + 
startseg + 1] + xStart - subLineStart,
-                                                                                       rcSegment.bottom);
-                                                                               
surface->FillRectangle(rcSpace, textBack);
-                                                                       }
-                                                                       PRectangle rcDot(xmid + xStart - 
subLineStart, rcSegment.top + vsDraw.lineHeight / 2, 0, 0);
-                                                                       rcDot.right = rcDot.left + 
vs.whitespaceSize;
-                                                                       rcDot.bottom = rcDot.top + 
vs.whitespaceSize;
-                                                                       surface->FillRectangle(rcDot, 
textFore);
-                                                               }
-                                                       }
-                                                       if (inIndentation && vsDraw.viewIndentationGuides == 
ivReal) {
-                                                               for (int indentCount = (ll->positions[cpos + 
startseg] + epsilon) / indentWidth;
-                                                                       indentCount <= (ll->positions[cpos + 
startseg + 1] - epsilon) / indentWidth;
-                                                                       indentCount++) {
-                                                                       if (indentCount > 0) {
-                                                                               int xIndent = indentCount * 
indentWidth;
-                                                                               DrawIndentGuide(surface, 
lineVisible, vsDraw.lineHeight, xIndent + xStart, rcSegment,
-                                                                                               
(ll->xHighlightGuide == xIndent));
-                                                                       }
-                                                               }
-                                                       }
-                                               } else {
-                                                       inIndentation = false;
-                                               }
-                                       }
-                               }
-                       }
-                       if (ll->hsStart != -1 && vsDraw.hotspotUnderline && iDoc >= ll->hsStart && iDoc < 
ll->hsEnd) {
-                               PRectangle rcUL = rcSegment;
-                               rcUL.top = rcUL.top + vsDraw.maxAscent + 1;
-                               rcUL.bottom = rcUL.top + 1;
-                               if (vsDraw.hotspotForegroundSet)
-                                       surface->FillRectangle(rcUL, vsDraw.hotspotForeground);
-                               else
-                                       surface->FillRectangle(rcUL, textFore);
-                       } else if (vsDraw.styles[styleMain].underline) {
-                               PRectangle rcUL = rcSegment;
-                               rcUL.top = rcUL.top + vsDraw.maxAscent + 1;
-                               rcUL.bottom = rcUL.top + 1;
-                               surface->FillRectangle(rcUL, textFore);
-                       }
-               } else if (rcSegment.left > rcLine.right) {
-                       break;
-               }
-       }
-       if ((vsDraw.viewIndentationGuides == ivLookForward || vsDraw.viewIndentationGuides == ivLookBoth)
-               && (subLine == 0)) {
-               int indentSpace = pdoc->GetLineIndentation(line);
-               int xStartText = ll->positions[pdoc->GetLineIndentPosition(line) - posLineStart];
-
-               // Find the most recent line with some text
-
-               int lineLastWithText = line;
-               while (lineLastWithText > Platform::Maximum(line-20, 0) && 
pdoc->IsWhiteLine(lineLastWithText)) {
-                       lineLastWithText--;
-               }
-               if (lineLastWithText < line) {
-                       xStartText = 100000;    // Don't limit to visible indentation on empty line
-                       // This line is empty, so use indentation of last line with text
-                       int indentLastWithText = pdoc->GetLineIndentation(lineLastWithText);
-                       int isFoldHeader = pdoc->GetLevel(lineLastWithText) & SC_FOLDLEVELHEADERFLAG;
-                       if (isFoldHeader) {
-                               // Level is one more level than parent
-                               indentLastWithText += pdoc->IndentSize();
-                       }
-                       if (vsDraw.viewIndentationGuides == ivLookForward) {
-                               // In viLookForward mode, previous line only used if it is a fold header
-                               if (isFoldHeader) {
-                                       indentSpace = Platform::Maximum(indentSpace, indentLastWithText);
-                               }
-                       } else {        // viLookBoth
-                               indentSpace = Platform::Maximum(indentSpace, indentLastWithText);
-                       }
-               }
-
-               int lineNextWithText = line;
-               while (lineNextWithText < Platform::Minimum(line+20, pdoc->LinesTotal()) && 
pdoc->IsWhiteLine(lineNextWithText)) {
-                       lineNextWithText++;
-               }
-               if (lineNextWithText > line) {
-                       xStartText = 100000;    // Don't limit to visible indentation on empty line
-                       // This line is empty, so use indentation of first next line with text
-                       indentSpace = Platform::Maximum(indentSpace,
-                               pdoc->GetLineIndentation(lineNextWithText));
-               }
-
-               for (int indentPos = pdoc->IndentSize(); indentPos < indentSpace; indentPos += 
pdoc->IndentSize()) {
-                       int xIndent = indentPos * vsDraw.spaceWidth;
-                       if (xIndent < xStartText) {
-                               DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIndent + xStart, 
rcSegment,
-                                       (ll->xHighlightGuide == xIndent));
-                       }
-               }
-       }
-
-       DrawIndicators(surface, vsDraw, line, xStart, rcLine, ll, subLine, lineEnd, false);
-
-       // End of the drawing of the current line
-       if (!twoPhaseDraw) {
-               DrawEOL(surface, vsDraw, rcLine, ll, line, lineEnd,
-                       xStart, subLine, subLineStart, overrideBackground, background,
-                       drawWrapMarkEnd, wrapColour);
-       }
-       if (!hideSelection && ((vsDraw.selAlpha != SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha != 
SC_ALPHA_NOALPHA))) {
-               // For each selection draw
-               int virtualSpaces = 0;
-               if (subLine == (ll->lines - 1)) {
-                       virtualSpaces = sel.VirtualSpaceFor(pdoc->LineEnd(line));
-               }
-               SelectionPosition posStart(posLineStart + lineStart);
-               SelectionPosition posEnd(posLineStart + lineEnd, virtualSpaces);
-               SelectionSegment virtualSpaceRange(posStart, posEnd);
-               for (size_t r=0; r<sel.Count(); r++) {
-                       int alpha = (r == sel.Main()) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
-                       if (alpha != SC_ALPHA_NOALPHA) {
-                               SelectionSegment portion = sel.Range(r).Intersect(virtualSpaceRange);
-                               if (!portion.Empty()) {
-                                       const XYPOSITION spaceWidth = 
vsDraw.styles[ll->EndLineStyle()].spaceWidth;
-                                       rcSegment.left = xStart + ll->positions[portion.start.Position() - 
posLineStart] - subLineStart + portion.start.VirtualSpace() * spaceWidth;
-                                       rcSegment.right = xStart + ll->positions[portion.end.Position() - 
posLineStart] - subLineStart + portion.end.VirtualSpace() * spaceWidth;
-                                       if ((ll->wrapIndent != 0) && (lineStart != 0)) {
-                                               if ((portion.start.Position() - posLineStart) == lineStart && 
sel.Range(r).ContainsCharacter(portion.start.Position() - 1))
-                                                       rcSegment.left -= static_cast<int>(ll->wrapIndent); 
// indentation added to xStart was truncated to int, so we do the same here
-                                       }
-                                       rcSegment.left = (rcSegment.left > rcLine.left) ? rcSegment.left : 
rcLine.left;
-                                       rcSegment.right = (rcSegment.right < rcLine.right) ? rcSegment.right 
: rcLine.right;
-                                       if (rcSegment.right > rcLine.left)
-                                               SimpleAlphaRectangle(surface, rcSegment, 
SelectionBackground(vsDraw, r == sel.Main()), alpha);
-                               }
-                       }
-               }
-       }
-
-       // Draw any translucent whole line states
-       rcSegment = rcLine;
-       if ((caret.active || vsDraw.alwaysShowCaretLineBackground) && vsDraw.showCaretLineBackground && 
ll->containsCaret) {
-               SimpleAlphaRectangle(surface, rcSegment, vsDraw.caretLineBackground, vsDraw.caretLineAlpha);
-       }
-       marks = pdoc->GetMark(line);
-       for (markBit = 0; (markBit < 32) && marks; markBit++) {
-               if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_BACKGROUND)) {
-                       SimpleAlphaRectangle(surface, rcSegment, vsDraw.markers[markBit].back, 
vsDraw.markers[markBit].alpha);
-               } else if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_UNDERLINE)) {
-                       PRectangle rcUnderline = rcSegment;
-                       rcUnderline.top = rcUnderline.bottom - 2;
-                       SimpleAlphaRectangle(surface, rcUnderline, vsDraw.markers[markBit].back, 
vsDraw.markers[markBit].alpha);
-               }
-               marks >>= 1;
-       }
-       if (vsDraw.maskInLine) {
-               int marksMasked = pdoc->GetMark(line) & vsDraw.maskInLine;
-               if (marksMasked) {
-                       for (markBit = 0; (markBit < 32) && marksMasked; markBit++) {
-                               if ((marksMasked & 1) && (vsDraw.markers[markBit].markType != SC_MARK_EMPTY)) 
{
-                                       SimpleAlphaRectangle(surface, rcSegment, 
vsDraw.markers[markBit].back, vsDraw.markers[markBit].alpha);
-                               }
-                               marksMasked >>= 1;
-                       }
-               }
-       }
-}
-
-void Editor::DrawBlockCaret(Surface *surface, ViewStyle &vsDraw, LineLayout *ll, int subLine,
-                                                       int xStart, int offset, int posCaret, PRectangle 
rcCaret, ColourDesired caretColour) {
-
-       int lineStart = ll->LineStart(subLine);
-       int posBefore = posCaret;
-       int posAfter = MovePositionOutsideChar(posCaret + 1, 1);
-       int numCharsToDraw = posAfter - posCaret;
-
-       // Work out where the starting and ending offsets are. We need to
-       // see if the previous character shares horizontal space, such as a
-       // glyph / combining character. If so we'll need to draw that too.
-       int offsetFirstChar = offset;
-       int offsetLastChar = offset + (posAfter - posCaret);
-       while ((posBefore > 0) && ((offsetLastChar - numCharsToDraw) >= lineStart)) {
-               if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - numCharsToDraw]) > 0) {
-                       // The char does not share horizontal space
-                       break;
-               }
-               // Char shares horizontal space, update the numChars to draw
-               // Update posBefore to point to the prev char
-               posBefore = MovePositionOutsideChar(posBefore - 1, -1);
-               numCharsToDraw = posAfter - posBefore;
-               offsetFirstChar = offset - (posCaret - posBefore);
-       }
-
-       // See if the next character shares horizontal space, if so we'll
-       // need to draw that too.
-       if (offsetFirstChar < 0)
-               offsetFirstChar = 0;
-       numCharsToDraw = offsetLastChar - offsetFirstChar;
-       while ((offsetLastChar < ll->LineStart(subLine + 1)) && (offsetLastChar <= ll->numCharsInLine)) {
-               // Update posAfter to point to the 2nd next char, this is where
-               // the next character ends, and 2nd next begins. We'll need
-               // to compare these two
-               posBefore = posAfter;
-               posAfter = MovePositionOutsideChar(posAfter + 1, 1);
-               offsetLastChar = offset + (posAfter - posCaret);
-               if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - (posAfter - posBefore)]) 
0) {
-                       // The char does not share horizontal space
-                       break;
-               }
-               // Char shares horizontal space, update the numChars to draw
-               numCharsToDraw = offsetLastChar - offsetFirstChar;
-       }
-
-       // We now know what to draw, update the caret drawing rectangle
-       rcCaret.left = ll->positions[offsetFirstChar] - ll->positions[lineStart] + xStart;
-       rcCaret.right = ll->positions[offsetFirstChar+numCharsToDraw] - ll->positions[lineStart] + xStart;
-
-       // Adjust caret position to take into account any word wrapping symbols.
-       if ((ll->wrapIndent != 0) && (lineStart != 0)) {
-               XYPOSITION wordWrapCharWidth = ll->wrapIndent;
-               rcCaret.left += wordWrapCharWidth;
-               rcCaret.right += wordWrapCharWidth;
-       }
-
-       // This character is where the caret block is, we override the colours
-       // (inversed) for drawing the caret here.
-       int styleMain = ll->styles[offsetFirstChar];
-       surface->DrawTextClipped(rcCaret, vsDraw.styles[styleMain].font,
-               rcCaret.top + vsDraw.maxAscent, ll->chars + offsetFirstChar,
-               numCharsToDraw, vsDraw.styles[styleMain].back,
-               caretColour);
-}
-
 void Editor::RefreshPixMaps(Surface *surfaceWindow) {
-       if (!pixmapSelPattern->Initialised()) {
-               const int patternSize = 8;
-               pixmapSelPattern->InitPixMap(patternSize, patternSize, surfaceWindow, wMain.GetID());
-               pixmapSelPatternOffset1->InitPixMap(patternSize, patternSize, surfaceWindow, wMain.GetID());
-               // This complex procedure is to reproduce the checkerboard dithered pattern used by windows
-               // for scroll bars and Visual Studio for its selection margin. The colour of this pattern is 
half
-               // way between the chrome colour and the chrome highlight colour making a nice transition
-               // between the window chrome and the content area. And it works in low colour depths.
-               PRectangle rcPattern(0, 0, patternSize, patternSize);
-
-               // Initialize default colours based on the chrome colour scheme.  Typically the highlight is 
white.
-               ColourDesired colourFMFill = vs.selbar;
-               ColourDesired colourFMStripes = vs.selbarlight;
-
-               if (!(vs.selbarlight == ColourDesired(0xff, 0xff, 0xff))) {
-                       // User has chosen an unusual chrome colour scheme so just use the highlight edge 
colour.
-                       // (Typically, the highlight colour is white.)
-                       colourFMFill = vs.selbarlight;
-               }
-
-               if (vs.foldmarginColourSet) {
-                       // override default fold margin colour
-                       colourFMFill = vs.foldmarginColour;
-               }
-               if (vs.foldmarginHighlightColourSet) {
-                       // override default fold margin highlight colour
-                       colourFMStripes = vs.foldmarginHighlightColour;
-               }
-
-               pixmapSelPattern->FillRectangle(rcPattern, colourFMFill);
-               pixmapSelPatternOffset1->FillRectangle(rcPattern, colourFMStripes);
-               for (int y = 0; y < patternSize; y++) {
-                       for (int x = y % 2; x < patternSize; x+=2) {
-                               PRectangle rcPixel(x, y, x+1, y+1);
-                               pixmapSelPattern->FillRectangle(rcPixel, colourFMStripes);
-                               pixmapSelPatternOffset1->FillRectangle(rcPixel, colourFMFill);
-                       }
-               }
-       }
-
-       if (!pixmapIndentGuide->Initialised()) {
-               // 1 extra pixel in height so can handle odd/even positions and so produce a continuous line
-               pixmapIndentGuide->InitPixMap(1, vs.lineHeight + 1, surfaceWindow, wMain.GetID());
-               pixmapIndentGuideHighlight->InitPixMap(1, vs.lineHeight + 1, surfaceWindow, wMain.GetID());
-               PRectangle rcIG(0, 0, 1, vs.lineHeight);
-               pixmapIndentGuide->FillRectangle(rcIG, vs.styles[STYLE_INDENTGUIDE].back);
-               pixmapIndentGuide->PenColour(vs.styles[STYLE_INDENTGUIDE].fore);
-               pixmapIndentGuideHighlight->FillRectangle(rcIG, vs.styles[STYLE_BRACELIGHT].back);
-               pixmapIndentGuideHighlight->PenColour(vs.styles[STYLE_BRACELIGHT].fore);
-               for (int stripe = 1; stripe < vs.lineHeight + 1; stripe += 2) {
-                       PRectangle rcPixel(0, stripe, 1, stripe+1);
-                       pixmapIndentGuide->FillRectangle(rcPixel, vs.styles[STYLE_INDENTGUIDE].fore);
-                       pixmapIndentGuideHighlight->FillRectangle(rcPixel, vs.styles[STYLE_BRACELIGHT].fore);
-               }
-       }
+       view.RefreshPixMaps(surfaceWindow, wMain.GetID(), vs);
+       marginView.RefreshPixMaps(surfaceWindow, wMain.GetID(), vs);
+       if (view.bufferedDraw) {
+               const PRectangle rcClient = GetClientRectangle();
+               if (!view.pixmapLine->Initialised()) {
 
-       if (bufferedDraw) {
-               if (!pixmapLine->Initialised()) {
-                       PRectangle rcClient = GetClientRectangle();
-                       pixmapLine->InitPixMap(rcClient.Width(), vs.lineHeight,
+                       view.pixmapLine->InitPixMap(static_cast<int>(rcClient.Width()), vs.lineHeight,
                                surfaceWindow, wMain.GetID());
-                       pixmapSelMargin->InitPixMap(vs.fixedColumnWidth,
-                               rcClient.Height(), surfaceWindow, wMain.GetID());
                }
-       }
-}
-
-void Editor::DrawCarets(Surface *surface, ViewStyle &vsDraw, int lineDoc, int xStart,
-        PRectangle rcLine, LineLayout *ll, int subLine) {
-       // When drag is active it is the only caret drawn
-       bool drawDrag = posDrag.IsValid();
-       if (hideSelection && !drawDrag)
-               return;
-       const int posLineStart = pdoc->LineStart(lineDoc);
-       // For each selection draw
-       for (size_t r=0; (r<sel.Count()) || drawDrag; r++) {
-               const bool mainCaret = r == sel.Main();
-               const SelectionPosition posCaret = (drawDrag ? posDrag : sel.Range(r).caret);
-               const int offset = posCaret.Position() - posLineStart;
-               const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
-               const XYPOSITION virtualOffset = posCaret.VirtualSpace() * spaceWidth;
-               if (ll->InLine(offset, subLine) && offset <= ll->numCharsBeforeEOL) {
-                       XYPOSITION xposCaret = ll->positions[offset] + virtualOffset - 
ll->positions[ll->LineStart(subLine)];
-                       if (ll->wrapIndent != 0) {
-                               int lineStart = ll->LineStart(subLine);
-                               if (lineStart != 0)     // Wrapped
-                                       xposCaret += ll->wrapIndent;
-                       }
-                       bool caretBlinkState = (caret.active && caret.on) || (!additionalCaretsBlink && 
!mainCaret);
-                       bool caretVisibleState = additionalCaretsVisible || mainCaret;
-                       if ((xposCaret >= 0) && (vsDraw.caretWidth > 0) && (vsDraw.caretStyle != 
CARETSTYLE_INVISIBLE) &&
-                               ((posDrag.IsValid()) || (caretBlinkState && caretVisibleState))) {
-                               bool caretAtEOF = false;
-                               bool caretAtEOL = false;
-                               bool drawBlockCaret = false;
-                               XYPOSITION widthOverstrikeCaret;
-                               int caretWidthOffset = 0;
-                               PRectangle rcCaret = rcLine;
-
-                               if (posCaret.Position() == pdoc->Length())      {   // At end of document
-                                       caretAtEOF = true;
-                                       widthOverstrikeCaret = vsDraw.aveCharWidth;
-                               } else if ((posCaret.Position() - posLineStart) >= ll->numCharsInLine) {      
  // At end of line
-                                       caretAtEOL = true;
-                                       widthOverstrikeCaret = vsDraw.aveCharWidth;
-                               } else {
-                                       widthOverstrikeCaret = ll->positions[offset + 1] - 
ll->positions[offset];
-                               }
-                               if (widthOverstrikeCaret < 3)   // Make sure its visible
-                                       widthOverstrikeCaret = 3;
-
-                               if (xposCaret > 0)
-                                       caretWidthOffset = 1;   // Move back so overlaps both character cells.
-                               xposCaret += xStart;
-                               if (posDrag.IsValid()) {
-                                       /* Dragging text, use a line caret */
-                                       rcCaret.left = xposCaret - caretWidthOffset;
-                                       rcCaret.right = rcCaret.left + vsDraw.caretWidth;
-                               } else if (inOverstrike && drawOverstrikeCaret) {
-                                       /* Overstrike (insert mode), use a modified bar caret */
-                                       rcCaret.top = rcCaret.bottom - 2;
-                                       rcCaret.left = xposCaret + 1;
-                                       rcCaret.right = rcCaret.left + widthOverstrikeCaret - 1;
-                               } else if (vsDraw.caretStyle == CARETSTYLE_BLOCK) {
-                                       /* Block caret */
-                                       rcCaret.left = xposCaret;
-                                       if (!caretAtEOL && !caretAtEOF && (ll->chars[offset] != '\t') && 
!(IsControlCharacter(ll->chars[offset]))) {
-                                               drawBlockCaret = true;
-                                               rcCaret.right = xposCaret + widthOverstrikeCaret;
-                                       } else {
-                                               rcCaret.right = xposCaret + vsDraw.aveCharWidth;
-                                       }
-                               } else {
-                                       /* Line caret */
-                                       rcCaret.left = xposCaret - caretWidthOffset;
-                                       rcCaret.right = rcCaret.left + vsDraw.caretWidth;
-                               }
-                               ColourDesired caretColour = mainCaret ? vsDraw.caretcolour : 
vsDraw.additionalCaretColour;
-                               if (drawBlockCaret) {
-                                       DrawBlockCaret(surface, vsDraw, ll, subLine, xStart, offset, 
posCaret.Position(), rcCaret, caretColour);
-                               } else {
-                                       surface->FillRectangle(rcCaret, caretColour);
-                               }
-                       }
+               if (!marginView.pixmapSelMargin->Initialised()) {
+                       marginView.pixmapSelMargin->InitPixMap(vs.fixedColumnWidth,
+                               static_cast<int>(rcClient.Height()), surfaceWindow, wMain.GetID());
                }
-               if (drawDrag)
-                       break;
        }
 }
 
@@ -3522,28 +1702,19 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 
        paintAbandonedByStyling = false;
 
-       StyleToPositionInView(PositionAfterArea(rcArea));
+       StyleAreaBounded(rcArea, false);
 
        PRectangle rcClient = GetClientRectangle();
-       Point ptOrigin = GetVisibleOriginInMain();
        //Platform::DebugPrintf("Client: (%3d,%3d) ... (%3d,%3d)   %d\n",
        //      rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
 
-       int screenLinePaintFirst = rcArea.top / vs.lineHeight;
-
-       int xStart = vs.textStart - xOffset + ptOrigin.x;
-       int ypos = 0;
-       if (!bufferedDraw)
-               ypos += screenLinePaintFirst * vs.lineHeight;
-       int yposScreen = screenLinePaintFirst * vs.lineHeight;
-
        if (NotifyUpdateUI()) {
                RefreshStyleData();
                RefreshPixMaps(surfaceWindow);
        }
 
        // Wrap the visible lines if needed.
-       if (WrapLines(wsVisible)) {
+       if (WrapLines(WrapScope::wsVisible)) {
                // The wrapping process has changed the height of some lines so
                // abandon this paint for a complete repaint.
                if (AbandonPaint()) {
@@ -3551,9 +1722,9 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
                }
                RefreshPixMaps(surfaceWindow);  // In case pixmaps invalidated by scrollbar change
        }
-       PLATFORM_ASSERT(pixmapSelPattern->Initialised());
+       PLATFORM_ASSERT(marginView.pixmapSelPattern->Initialised());
 
-       if (!bufferedDraw)
+       if (!view.bufferedDraw)
                surfaceWindow->SetClip(rcArea);
 
        if (paintState != paintAbandoned) {
@@ -3578,7 +1749,7 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
                // Either styling or NotifyUpdateUI noticed that painting is needed
                // outside the current painting rectangle
                //Platform::DebugPrintf("Abandoning paint\n");
-               if (wrapState != eWrapNone) {
+               if (Wrapping()) {
                        if (paintAbandonedByStyling) {
                                // Styling has spilled over a line end, such as occurs by starting a multiline
                                // comment. The width of subsequent text may have changed, so rewrap.
@@ -3587,194 +1758,19 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
                }
                return;
        }
-       //Platform::DebugPrintf("start display %d, offset = %d\n", pdoc->Length(), xOffset);
-
-       // Allow text at start of line to overlap 1 pixel into the margin as this displays
-       // serifs and italic stems for aliased text.
-       const int leftTextOverlap = ((xOffset == 0) && (vs.leftMarginWidth > 0)) ? 1 : 0;
-
-       // Do the painting
-       if (rcArea.right > vs.textStart - leftTextOverlap) {
 
-               Surface *surface = surfaceWindow;
-               if (bufferedDraw) {
-                       surface = pixmapLine;
-                       PLATFORM_ASSERT(pixmapLine->Initialised());
-               }
-               surface->SetUnicodeMode(IsUnicodeMode());
-               surface->SetDBCSMode(CodePage());
+       view.PaintText(surfaceWindow, *this, rcArea, rcClient, vs);
 
-               int visibleLine = TopLineOfMain() + screenLinePaintFirst;
-
-               SelectionPosition posCaret = sel.RangeMain().caret;
-               if (posDrag.IsValid())
-                       posCaret = posDrag;
-               int lineCaret = pdoc->LineFromPosition(posCaret.Position());
-
-               PRectangle rcTextArea = rcClient;
-               if (vs.marginInside) {
-                       rcTextArea.left += vs.textStart;
-                       rcTextArea.right -= vs.rightMarginWidth;
-               } else {
-                       rcTextArea = rcArea;
-               }
-
-               // Remove selection margin from drawing area so text will not be drawn
-               // on it in unbuffered mode.
-               if (!bufferedDraw && vs.marginInside) {
-                       PRectangle rcClipText = rcTextArea;
-                       rcClipText.left -= leftTextOverlap;
-                       surfaceWindow->SetClip(rcClipText);
-               }
-
-               // Loop on visible lines
-               //double durLayout = 0.0;
-               //double durPaint = 0.0;
-               //double durCopy = 0.0;
-               //ElapsedTime etWhole;
-               int lineDocPrevious = -1;       // Used to avoid laying out one document line multiple times
-               AutoLineLayout ll(llc, 0);
-               while (visibleLine < cs.LinesDisplayed() && yposScreen < rcArea.bottom) {
-
-                       int lineDoc = cs.DocFromDisplay(visibleLine);
-                       // Only visible lines should be handled by the code within the loop
-                       PLATFORM_ASSERT(cs.GetVisible(lineDoc));
-                       int lineStartSet = cs.DisplayFromDoc(lineDoc);
-                       int subLine = visibleLine - lineStartSet;
-
-                       // Copy this line and its styles from the document into local arrays
-                       // and determine the x position at which each character starts.
-                       //ElapsedTime et;
-                       if (lineDoc != lineDocPrevious) {
-                               ll.Set(0);
-                               ll.Set(RetrieveLineLayout(lineDoc));
-                               LayoutLine(lineDoc, surface, vs, ll, wrapWidth);
-                               lineDocPrevious = lineDoc;
-                       }
-                       //durLayout += et.Duration(true);
-
-                       if (ll) {
-                               ll->containsCaret = lineDoc == lineCaret;
-                               if (hideSelection) {
-                                       ll->containsCaret = false;
-                               }
-
-                               GetHotSpotRange(ll->hsStart, ll->hsEnd);
-
-                               PRectangle rcLine = rcTextArea;
-                               rcLine.top = ypos;
-                               rcLine.bottom = ypos + vs.lineHeight;
-
-                               bool bracesIgnoreStyle = false;
-                               if ((vs.braceHighlightIndicatorSet && (bracesMatchStyle == STYLE_BRACELIGHT)) 
||
-                                       (vs.braceBadLightIndicatorSet && (bracesMatchStyle == 
STYLE_BRACEBAD))) {
-                                       bracesIgnoreStyle = true;
-                               }
-                               Range rangeLine(pdoc->LineStart(lineDoc), pdoc->LineStart(lineDoc + 1));
-                               // Highlight the current braces if any
-                               ll->SetBracesHighlight(rangeLine, braces, static_cast<char>(bracesMatchStyle),
-                                       highlightGuideColumn * vs.spaceWidth, bracesIgnoreStyle);
-
-                               if (leftTextOverlap && bufferedDraw) {
-                                       PRectangle rcSpacer = rcLine;
-                                       rcSpacer.right = rcSpacer.left;
-                                       rcSpacer.left -= 1;
-                                       surface->FillRectangle(rcSpacer, vs.styles[STYLE_DEFAULT].back);
-                               }
-
-                               // Draw the line
-                               DrawLine(surface, vs, lineDoc, visibleLine, xStart, rcLine, ll, subLine);
-                               //durPaint += et.Duration(true);
-
-                               // Restore the previous styles for the brace highlights in case layout is in 
cache.
-                               ll->RestoreBracesHighlight(rangeLine, braces, bracesIgnoreStyle);
-
-                               bool expanded = cs.GetExpanded(lineDoc);
-                               const int level = pdoc->GetLevel(lineDoc);
-                               const int levelNext = pdoc->GetLevel(lineDoc + 1);
-                               if ((level & SC_FOLDLEVELHEADERFLAG) &&
-                                       ((level & SC_FOLDLEVELNUMBERMASK) < (levelNext & 
SC_FOLDLEVELNUMBERMASK))) {
-                                       // Paint the line above the fold
-                                       if ((expanded && (foldFlags & SC_FOLDFLAG_LINEBEFORE_EXPANDED))
-                                               ||
-                                               (!expanded && (foldFlags & 
SC_FOLDFLAG_LINEBEFORE_CONTRACTED))) {
-                                               PRectangle rcFoldLine = rcLine;
-                                               rcFoldLine.bottom = rcFoldLine.top + 1;
-                                               surface->FillRectangle(rcFoldLine, 
vs.styles[STYLE_DEFAULT].fore);
-                                       }
-                                       // Paint the line below the fold
-                                       if ((expanded && (foldFlags & SC_FOLDFLAG_LINEAFTER_EXPANDED))
-                                               ||
-                                               (!expanded && (foldFlags & 
SC_FOLDFLAG_LINEAFTER_CONTRACTED))) {
-                                               PRectangle rcFoldLine = rcLine;
-                                               rcFoldLine.top = rcFoldLine.bottom - 1;
-                                               surface->FillRectangle(rcFoldLine, 
vs.styles[STYLE_DEFAULT].fore);
-                                       }
-                               }
-
-                               DrawCarets(surface, vs, lineDoc, xStart, rcLine, ll, subLine);
-
-                               if (bufferedDraw) {
-                                       Point from(vs.textStart-leftTextOverlap, 0);
-                                       PRectangle rcCopyArea(vs.textStart-leftTextOverlap, yposScreen,
-                                               rcClient.right - vs.rightMarginWidth, yposScreen + 
vs.lineHeight);
-                                       surfaceWindow->Copy(rcCopyArea, from, *pixmapLine);
-                               }
-
-                               lineWidthMaxSeen = Platform::Maximum(
-                                           lineWidthMaxSeen, ll->positions[ll->numCharsInLine]);
-                               //durCopy += et.Duration(true);
-                       }
-
-                       if (!bufferedDraw) {
-                               ypos += vs.lineHeight;
-                       }
-
-                       yposScreen += vs.lineHeight;
-                       visibleLine++;
-
-                       //gdk_flush();
-               }
-               ll.Set(0);
-               //if (durPaint < 0.00000001)
-               //      durPaint = 0.00000001;
-
-               // Right column limit indicator
-               PRectangle rcBeyondEOF = (vs.marginInside) ? rcClient : rcArea;
-               rcBeyondEOF.left = vs.textStart;
-               rcBeyondEOF.right = rcBeyondEOF.right - ((vs.marginInside) ? vs.rightMarginWidth : 0);
-               rcBeyondEOF.top = (cs.LinesDisplayed() - TopLineOfMain()) * vs.lineHeight;
-               if (rcBeyondEOF.top < rcBeyondEOF.bottom) {
-                       surfaceWindow->FillRectangle(rcBeyondEOF, vs.styles[STYLE_DEFAULT].back);
-                       if (vs.edgeState == EDGE_LINE) {
-                               int edgeX = theEdge * vs.spaceWidth;
-                               rcBeyondEOF.left = edgeX + xStart;
-                               rcBeyondEOF.right = rcBeyondEOF.left + 1;
-                               surfaceWindow->FillRectangle(rcBeyondEOF, vs.edgecolour);
+       if (horizontalScrollBarVisible && trackLineWidth && (view.lineWidthMaxSeen > scrollWidth)) {
+               if (FineTickerAvailable()) {
+                       scrollWidth = view.lineWidthMaxSeen;
+                       if (!FineTickerRunning(tickWiden)) {
+                               FineTickerStart(tickWiden, 50, 5);
                        }
                }
-               //Platform::DebugPrintf(
-               //"Layout:%9.6g    Paint:%9.6g    Ratio:%9.6g   Copy:%9.6g   Total:%9.6g\n",
-               //durLayout, durPaint, durLayout / durPaint, durCopy, etWhole.Duration());
-               NotifyPainted();
        }
-}
 
-// Space (3 space characters) between line numbers and text when printing.
-#define lineNumberPrintSpace "   "
-
-ColourDesired InvertedLight(ColourDesired orig) {
-       unsigned int r = orig.GetRed();
-       unsigned int g = orig.GetGreen();
-       unsigned int b = orig.GetBlue();
-       unsigned int l = (r + g + b) / 3;       // There is a better calculation for this that matches human 
eye
-       unsigned int il = 0xff - l;
-       if (l == 0)
-               return ColourDesired(0xff, 0xff, 0xff);
-       r = r * il / l;
-       g = g * il / l;
-       b = b * il / l;
-       return ColourDesired(Platform::Minimum(r, 0xff), Platform::Minimum(g, 0xff), Platform::Minimum(b, 
0xff));
+       NotifyPainted();
 }
 
 // This is mostly copied from the Paint method but with some things omitted
@@ -3791,191 +1787,14 @@ long Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
        if (!surfaceMeasure) {
                return 0;
        }
-
-       // Can't use measurements cached for screen
-       posCache.Clear();
-
-       ViewStyle vsPrint(vs);
-       vsPrint.technology = SC_TECHNOLOGY_DEFAULT;
-
-       // Modify the view style for printing as do not normally want any of the transient features to be 
printed
-       // Printing supports only the line number margin.
-       int lineNumberIndex = -1;
-       for (int margin = 0; margin <= SC_MAX_MARGIN; margin++) {
-               if ((vsPrint.ms[margin].style == SC_MARGIN_NUMBER) && (vsPrint.ms[margin].width > 0)) {
-                       lineNumberIndex = margin;
-               } else {
-                       vsPrint.ms[margin].width = 0;
-               }
-       }
-       vsPrint.fixedColumnWidth = 0;
-       vsPrint.zoomLevel = printMagnification;
-       // Don't show indentation guides
-       // If this ever gets changed, cached pixmap would need to be recreated if technology != 
SC_TECHNOLOGY_DEFAULT
-       vsPrint.viewIndentationGuides = ivNone;
-       // Don't show the selection when printing
-       vsPrint.selbackset = false;
-       vsPrint.selforeset = false;
-       vsPrint.selAlpha = SC_ALPHA_NOALPHA;
-       vsPrint.selAdditionalAlpha = SC_ALPHA_NOALPHA;
-       vsPrint.whitespaceBackgroundSet = false;
-       vsPrint.whitespaceForegroundSet = false;
-       vsPrint.showCaretLineBackground = false;
-       vsPrint.alwaysShowCaretLineBackground = false;
-       // Don't highlight matching braces using indicators
-       vsPrint.braceHighlightIndicatorSet = false;
-       vsPrint.braceBadLightIndicatorSet = false;
-
-       // Set colours for printing according to users settings
-       for (size_t sty = 0; sty < vsPrint.styles.size(); sty++) {
-               if (printColourMode == SC_PRINT_INVERTLIGHT) {
-                       vsPrint.styles[sty].fore = InvertedLight(vsPrint.styles[sty].fore);
-                       vsPrint.styles[sty].back = InvertedLight(vsPrint.styles[sty].back);
-               } else if (printColourMode == SC_PRINT_BLACKONWHITE) {
-                       vsPrint.styles[sty].fore = ColourDesired(0, 0, 0);
-                       vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
-               } else if (printColourMode == SC_PRINT_COLOURONWHITE) {
-                       vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
-               } else if (printColourMode == SC_PRINT_COLOURONWHITEDEFAULTBG) {
-                       if (sty <= STYLE_DEFAULT) {
-                               vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
-                       }
-               }
-       }
-       // White background for the line numbers
-       vsPrint.styles[STYLE_LINENUMBER].back = ColourDesired(0xff, 0xff, 0xff);
-
-       // Printing uses different margins, so reset screen margins
-       vsPrint.leftMarginWidth = 0;
-       vsPrint.rightMarginWidth = 0;
-
-       vsPrint.Refresh(*surfaceMeasure);
-       // Determining width must hapen after fonts have been realised in Refresh
-       int lineNumberWidth = 0;
-       if (lineNumberIndex >= 0) {
-               lineNumberWidth = surfaceMeasure->WidthText(vsPrint.styles[STYLE_LINENUMBER].font,
-                       "99999" lineNumberPrintSpace, 5 + istrlen(lineNumberPrintSpace));
-               vsPrint.ms[lineNumberIndex].width = lineNumberWidth;
-               vsPrint.Refresh(*surfaceMeasure);       // Recalculate fixedColumnWidth
-       }
-
-       int linePrintStart = pdoc->LineFromPosition(pfr->chrg.cpMin);
-       int linePrintLast = linePrintStart + (pfr->rc.bottom - pfr->rc.top) / vsPrint.lineHeight - 1;
-       if (linePrintLast < linePrintStart)
-               linePrintLast = linePrintStart;
-       int linePrintMax = pdoc->LineFromPosition(pfr->chrg.cpMax);
-       if (linePrintLast > linePrintMax)
-               linePrintLast = linePrintMax;
-       //Platform::DebugPrintf("Formatting lines=[%0d,%0d,%0d] top=%0d bottom=%0d line=%0d %0d\n",
-       //      linePrintStart, linePrintLast, linePrintMax, pfr->rc.top, pfr->rc.bottom, vsPrint.lineHeight,
-       //      surfaceMeasure->Height(vsPrint.styles[STYLE_LINENUMBER].font));
-       int endPosPrint = pdoc->Length();
-       if (linePrintLast < pdoc->LinesTotal())
-               endPosPrint = pdoc->LineStart(linePrintLast + 1);
-
-       // Ensure we are styled to where we are formatting.
-       pdoc->EnsureStyledTo(endPosPrint);
-
-       int xStart = vsPrint.fixedColumnWidth + pfr->rc.left;
-       int ypos = pfr->rc.top;
-
-       int lineDoc = linePrintStart;
-
-       int nPrintPos = pfr->chrg.cpMin;
-       int visibleLine = 0;
-       int widthPrint = pfr->rc.right - pfr->rc.left - vsPrint.fixedColumnWidth;
-       if (printWrapState == eWrapNone)
-               widthPrint = LineLayout::wrapWidthInfinite;
-
-       while (lineDoc <= linePrintLast && ypos < pfr->rc.bottom) {
-
-               // When printing, the hdc and hdcTarget may be the same, so
-               // changing the state of surfaceMeasure may change the underlying
-               // state of surface. Therefore, any cached state is discarded before
-               // using each surface.
-               surfaceMeasure->FlushCachedState();
-
-               // Copy this line and its styles from the document into local arrays
-               // and determine the x position at which each character starts.
-               LineLayout ll(pdoc->LineStart(lineDoc+1)-pdoc->LineStart(lineDoc)+1);
-               LayoutLine(lineDoc, surfaceMeasure, vsPrint, &ll, widthPrint);
-
-               ll.containsCaret = false;
-
-               PRectangle rcLine;
-               rcLine.left = pfr->rc.left;
-               rcLine.top = ypos;
-               rcLine.right = pfr->rc.right - 1;
-               rcLine.bottom = ypos + vsPrint.lineHeight;
-
-               // When document line is wrapped over multiple display lines, find where
-               // to start printing from to ensure a particular position is on the first
-               // line of the page.
-               if (visibleLine == 0) {
-                       int startWithinLine = nPrintPos - pdoc->LineStart(lineDoc);
-                       for (int iwl = 0; iwl < ll.lines - 1; iwl++) {
-                               if (ll.LineStart(iwl) <= startWithinLine && ll.LineStart(iwl + 1) >= 
startWithinLine) {
-                                       visibleLine = -iwl;
-                               }
-                       }
-
-                       if (ll.lines > 1 && startWithinLine >= ll.LineStart(ll.lines - 1)) {
-                               visibleLine = -(ll.lines - 1);
-                       }
-               }
-
-               if (draw && lineNumberWidth &&
-                       (ypos + vsPrint.lineHeight <= pfr->rc.bottom) &&
-                       (visibleLine >= 0)) {
-                       char number[100];
-                       sprintf(number, "%d" lineNumberPrintSpace, lineDoc + 1);
-                       PRectangle rcNumber = rcLine;
-                       rcNumber.right = rcNumber.left + lineNumberWidth;
-                       // Right justify
-                       rcNumber.left = rcNumber.right - surfaceMeasure->WidthText(
-                                   vsPrint.styles[STYLE_LINENUMBER].font, number, istrlen(number));
-                       surface->FlushCachedState();
-                       surface->DrawTextNoClip(rcNumber, vsPrint.styles[STYLE_LINENUMBER].font,
-                               ypos + vsPrint.maxAscent, number, istrlen(number),
-                               vsPrint.styles[STYLE_LINENUMBER].fore,
-                               vsPrint.styles[STYLE_LINENUMBER].back);
-               }
-
-               // Draw the line
-               surface->FlushCachedState();
-
-               for (int iwl = 0; iwl < ll.lines; iwl++) {
-                       if (ypos + vsPrint.lineHeight <= pfr->rc.bottom) {
-                               if (visibleLine >= 0) {
-                                       if (draw) {
-                                               rcLine.top = ypos;
-                                               rcLine.bottom = ypos + vsPrint.lineHeight;
-                                               DrawLine(surface, vsPrint, lineDoc, visibleLine, xStart, 
rcLine, &ll, iwl);
-                                       }
-                                       ypos += vsPrint.lineHeight;
-                               }
-                               visibleLine++;
-                               if (iwl == ll.lines - 1)
-                                       nPrintPos = pdoc->LineStart(lineDoc + 1);
-                               else
-                                       nPrintPos += ll.LineStart(iwl + 1) - ll.LineStart(iwl);
-                       }
-               }
-
-               ++lineDoc;
-       }
-
-       // Clear cache so measurements are not used for screen
-       posCache.Clear();
-
-       return nPrintPos;
+       return view.FormatRange(draw, pfr, surface, surfaceMeasure, *this, vs);
 }
 
 int Editor::TextWidth(int style, const char *text) {
        RefreshStyleData();
        AutoSurface surface(this);
        if (surface) {
-               return surface->WidthText(vs.styles[style].font, text, istrlen(text));
+               return static_cast<int>(surface->WidthText(vs.styles[style].font, text, istrlen(text)));
        } else {
                return 1;
        }
@@ -3987,9 +1806,9 @@ void Editor::ReconfigureScrollBars() {}
 void Editor::SetScrollBars() {
        RefreshStyleData();
 
-       int nMax = MaxScrollPos();
-       int nPage = LinesOnScreen();
-       bool modified = ModifyScrollBars(nMax + nPage - 1, nPage);
+       const Sci::Line nMax = MaxScrollPos();
+       const Sci::Line nPage = LinesOnScreen();
+       const bool modified = ModifyScrollBars(nMax + nPage - 1, nPage);
        if (modified) {
                DwellEnd(true);
        }
@@ -4011,9 +1830,9 @@ void Editor::SetScrollBars() {
 void Editor::ChangeSize() {
        DropGraphics(false);
        SetScrollBars();
-       if (wrapState != eWrapNone) {
+       if (Wrapping()) {
                PRectangle rcTextArea = GetClientRectangle();
-               rcTextArea.left = vs.textStart;
+               rcTextArea.left = static_cast<XYPOSITION>(vs.textStart);
                rcTextArea.right -= vs.rightMarginWidth;
                if (wrapWidth != rcTextArea.Width()) {
                        NeedWrapping();
@@ -4022,15 +1841,26 @@ void Editor::ChangeSize() {
        }
 }
 
-int Editor::InsertSpace(int position, unsigned int spaces) {
-       if (spaces > 0) {
-               std::string spaceText(spaces, ' ');
-               pdoc->InsertString(position, spaceText.c_str(), spaces);
-               position += spaces;
+Sci::Position Editor::RealizeVirtualSpace(Sci::Position position, Sci::Position virtualSpace) {
+       if (virtualSpace > 0) {
+               const Sci::Line line = pdoc->LineFromPosition(position);
+               const Sci::Position indent = pdoc->GetLineIndentPosition(line);
+               if (indent == position) {
+                       return pdoc->SetLineIndentation(line, pdoc->GetLineIndentation(line) + virtualSpace);
+               } else {
+                       std::string spaceText(virtualSpace, ' ');
+                       const Sci::Position lengthInserted = pdoc->InsertString(position, spaceText.c_str(), 
virtualSpace);
+                       position += lengthInserted;
+               }
        }
        return position;
 }
 
+SelectionPosition Editor::RealizeVirtualSpace(const SelectionPosition &position) {
+       // Return the new position with no virtual space
+       return SelectionPosition(RealizeVirtualSpace(position.Position(), position.VirtualSpace()));
+}
+
 void Editor::AddChar(char ch) {
        char s[2];
        s[0] = ch;
@@ -4040,34 +1870,33 @@ void Editor::AddChar(char ch) {
 
 void Editor::FilterSelections() {
        if (!additionalSelectionTyping && (sel.Count() > 1)) {
-               SelectionRange rangeOnly = sel.RangeMain();
-               InvalidateSelection(rangeOnly, true);
-               sel.SetSelection(rangeOnly);
+               InvalidateWholeSelection();
+               sel.DropAdditionalRanges();
        }
 }
 
-static bool cmpSelPtrs(const SelectionRange *a, const SelectionRange *b) {
-       return *a < *b;
-}
-
 // AddCharUTF inserts an array of bytes which may or may not be in UTF-8.
-void Editor::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
+void Editor::AddCharUTF(const char *s, unsigned int len, bool treatAsDBCS) {
        FilterSelections();
        {
                UndoGroup ug(pdoc, (sel.Count() > 1) || !sel.Empty() || inOverstrike);
 
+               // Vector elements point into selection in order to change selection.
                std::vector<SelectionRange *> selPtrs;
                for (size_t r = 0; r < sel.Count(); r++) {
                        selPtrs.push_back(&sel.Range(r));
                }
-               std::sort(selPtrs.begin(), selPtrs.end(), cmpSelPtrs);
+               // Order selections by position in document.
+               std::sort(selPtrs.begin(), selPtrs.end(),
+                       [](const SelectionRange *a, const SelectionRange *b) {return *a < *b;});
 
+               // Loop in reverse to avoid disturbing positions of selections yet to be processed.
                for (std::vector<SelectionRange *>::reverse_iterator rit = selPtrs.rbegin();
                        rit != selPtrs.rend(); ++rit) {
                        SelectionRange *currentSel = *rit;
                        if (!RangeContainsProtected(currentSel->Start().Position(),
                                currentSel->End().Position())) {
-                               int positionInsert = currentSel->Start().Position();
+                               Sci::Position positionInsert = currentSel->Start().Position();
                                if (!currentSel->Empty()) {
                                        if (currentSel->Length()) {
                                                pdoc->DeleteChars(positionInsert, currentSel->Length());
@@ -4084,14 +1913,15 @@ void Editor::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
                                                }
                                        }
                                }
-                               positionInsert = InsertSpace(positionInsert, 
currentSel->caret.VirtualSpace());
-                               if (pdoc->InsertString(positionInsert, s, len)) {
-                                       currentSel->caret.SetPosition(positionInsert + len);
-                                       currentSel->anchor.SetPosition(positionInsert + len);
+                               positionInsert = RealizeVirtualSpace(positionInsert, 
currentSel->caret.VirtualSpace());
+                               const Sci::Position lengthInserted = pdoc->InsertString(positionInsert, s, 
len);
+                               if (lengthInserted > 0) {
+                                       currentSel->caret.SetPosition(positionInsert + lengthInserted);
+                                       currentSel->anchor.SetPosition(positionInsert + lengthInserted);
                                }
                                currentSel->ClearVirtualSpace();
                                // If in wrap mode rewrap current line so EnsureCaretVisible has accurate 
information
-                               if (wrapState != eWrapNone) {
+                               if (Wrapping()) {
                                        AutoSurface surface(this);
                                        if (surface) {
                                                if (WrapOneLine(surface, 
pdoc->LineFromPosition(positionInsert))) {
@@ -4104,7 +1934,7 @@ void Editor::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
                        }
                }
        }
-       if (wrapState != eWrapNone) {
+       if (Wrapping()) {
                SetScrollBars();
        }
        ThinRectangularRange();
@@ -4128,28 +1958,9 @@ void Editor::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
                        // Also treats \0 and naked trail bytes 0x80 to 0xBF as valid
                        // characters representing themselves.
                } else {
-                       // Unroll 1 to 3 byte UTF-8 sequences.  See reference data at:
-                       // http://www.cl.cam.ac.uk/~mgk25/unicode.html
-                       // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
-                       if (byte < 0xE0) {
-                               int byte2 = static_cast<unsigned char>(s[1]);
-                               if ((byte2 & 0xC0) == 0x80) {
-                                       // Two-byte-character lead-byte followed by a trail-byte.
-                                       byte = (((byte & 0x1F) << 6) | (byte2 & 0x3F));
-                               }
-                               // A two-byte-character lead-byte not followed by trail-byte
-                               // represents itself.
-                       } else if (byte < 0xF0) {
-                               int byte2 = static_cast<unsigned char>(s[1]);
-                               int byte3 = static_cast<unsigned char>(s[2]);
-                               if (((byte2 & 0xC0) == 0x80) && ((byte3 & 0xC0) == 0x80)) {
-                                       // Three-byte-character lead byte followed by two trail bytes.
-                                       byte = (((byte & 0x0F) << 12) | ((byte2 & 0x3F) << 6) |
-                                               (byte3 & 0x3F));
-                               }
-                               // A three-byte-character lead-byte not followed by two trail-bytes
-                               // represents itself.
-                       }
+                       unsigned int utf32[1] = { 0 };
+                       UTF32FromUTF8(s, len, utf32, ELEMENTS(utf32));
+                       byte = utf32[0];
                }
                NotifyChar(byte);
        }
@@ -4159,18 +1970,43 @@ void Editor::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
        }
 }
 
-void Editor::InsertPaste(SelectionPosition selStart, const char *text, int len) {
+void Editor::ClearBeforeTentativeStart() {
+       // Make positions for the first composition string.
+       FilterSelections();
+       UndoGroup ug(pdoc, (sel.Count() > 1) || !sel.Empty() || inOverstrike);
+       for (size_t r = 0; r<sel.Count(); r++) {
+               if (!RangeContainsProtected(sel.Range(r).Start().Position(),
+                       sel.Range(r).End().Position())) {
+                       Sci::Position positionInsert = sel.Range(r).Start().Position();
+                       if (!sel.Range(r).Empty()) {
+                               if (sel.Range(r).Length()) {
+                                       pdoc->DeleteChars(positionInsert, sel.Range(r).Length());
+                                       sel.Range(r).ClearVirtualSpace();
+                               } else {
+                                       // Range is all virtual so collapse to start of virtual space
+                                       sel.Range(r).MinimizeVirtualSpace();
+                               }
+                       }
+                       RealizeVirtualSpace(positionInsert, sel.Range(r).caret.VirtualSpace());
+                       sel.Range(r).ClearVirtualSpace();
+               }
+       }
+}
+
+void Editor::InsertPaste(const char *text, int len) {
        if (multiPasteMode == SC_MULTIPASTE_ONCE) {
-               selStart = SelectionPosition(InsertSpace(selStart.Position(), selStart.VirtualSpace()));
-               if (pdoc->InsertString(selStart.Position(), text, len)) {
-                       SetEmptySelection(selStart.Position() + len);
+               SelectionPosition selStart = sel.Start();
+               selStart = RealizeVirtualSpace(selStart);
+               const Sci::Position lengthInserted = pdoc->InsertString(selStart.Position(), text, len);
+               if (lengthInserted > 0) {
+                       SetEmptySelection(selStart.Position() + lengthInserted);
                }
        } else {
                // SC_MULTIPASTE_EACH
                for (size_t r=0; r<sel.Count(); r++) {
                        if (!RangeContainsProtected(sel.Range(r).Start().Position(),
                                sel.Range(r).End().Position())) {
-                               int positionInsert = sel.Range(r).Start().Position();
+                               Sci::Position positionInsert = sel.Range(r).Start().Position();
                                if (!sel.Range(r).Empty()) {
                                        if (sel.Range(r).Length()) {
                                                pdoc->DeleteChars(positionInsert, sel.Range(r).Length());
@@ -4180,10 +2016,11 @@ void Editor::InsertPaste(SelectionPosition selStart, const char *text, int len)
                                                sel.Range(r).MinimizeVirtualSpace();
                                        }
                                }
-                               positionInsert = InsertSpace(positionInsert, 
sel.Range(r).caret.VirtualSpace());
-                               if (pdoc->InsertString(positionInsert, text, len)) {
-                                       sel.Range(r).caret.SetPosition(positionInsert + len);
-                                       sel.Range(r).anchor.SetPosition(positionInsert + len);
+                               positionInsert = RealizeVirtualSpace(positionInsert, 
sel.Range(r).caret.VirtualSpace());
+                               const Sci::Position lengthInserted = pdoc->InsertString(positionInsert, text, 
len);
+                               if (lengthInserted > 0) {
+                                       sel.Range(r).caret.SetPosition(positionInsert + lengthInserted);
+                                       sel.Range(r).anchor.SetPosition(positionInsert + lengthInserted);
                                }
                                sel.Range(r).ClearVirtualSpace();
                        }
@@ -4191,6 +2028,35 @@ void Editor::InsertPaste(SelectionPosition selStart, const char *text, int len)
        }
 }
 
+void Editor::InsertPasteShape(const char *text, int len, PasteShape shape) {
+       std::string convertedText;
+       if (convertPastes) {
+               // Convert line endings of the paste into our local line-endings mode
+               convertedText = Document::TransformLineEnds(text, len, pdoc->eolMode);
+               len = static_cast<int>(convertedText.length());
+               text = convertedText.c_str();
+       }
+       if (shape == pasteRectangular) {
+               PasteRectangular(sel.Start(), text, len);
+       } else {
+               if (shape == pasteLine) {
+                       Sci::Position insertPos = pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret()));
+                       Sci::Position lengthInserted = pdoc->InsertString(insertPos, text, len);
+                       // add the newline if necessary
+                       if ((len > 0) && (text[len - 1] != '\n' && text[len - 1] != '\r')) {
+                               const char *endline = StringFromEOLMode(pdoc->eolMode);
+                               int length = static_cast<int>(strlen(endline));
+                               lengthInserted += pdoc->InsertString(insertPos + lengthInserted, endline, 
length);
+                       }
+                       if (sel.MainCaret() == insertPos) {
+                               SetEmptySelection(sel.MainCaret() + lengthInserted);
+                       }
+               } else {
+                       InsertPaste(text, len);
+               }
+       }
+}
+
 void Editor::ClearSelection(bool retainMultipleSelections) {
        if (!sel.IsRectangular() && !retainMultipleSelections)
                FilterSelections();
@@ -4201,13 +2067,14 @@ void Editor::ClearSelection(bool retainMultipleSelections) {
                                sel.Range(r).End().Position())) {
                                pdoc->DeleteChars(sel.Range(r).Start().Position(),
                                        sel.Range(r).Length());
-                               sel.Range(r) = sel.Range(r).Start();
+                               sel.Range(r) = SelectionRange(sel.Range(r).Start());
                        }
                }
        }
        ThinRectangularRange();
        sel.RemoveDuplicates();
        ClaimSelection();
+       SetHoverIndicatorPosition(sel.MainCaret());
 }
 
 void Editor::ClearAll() {
@@ -4222,6 +2089,9 @@ void Editor::ClearAll() {
                        pdoc->MarginClearAll();
                }
        }
+
+       view.ClearAllTabstops();
+
        sel.Clear();
        SetTopLine(0);
        SetVerticalScrollPos();
@@ -4229,19 +2099,11 @@ void Editor::ClearAll() {
 }
 
 void Editor::ClearDocumentStyle() {
-       Decoration *deco = pdoc->decorations.root;
-       while (deco) {
-               // Save next in case deco deleted
-               Decoration *decoNext = deco->next;
-               if (deco->indicator < INDIC_CONTAINER) {
-                       pdoc->decorations.SetCurrentIndicator(deco->indicator);
-                       pdoc->DecorationFillRange(0, 0, pdoc->Length());
-               }
-               deco = decoNext;
-       }
+       pdoc->decorations.DeleteLexerDecorations();
        pdoc->StartStyling(0, '\377');
        pdoc->SetStyleFor(pdoc->Length(), 0);
        cs.ShowAll();
+       SetAnnotationHeights(0, pdoc->LinesTotal());
        pdoc->ClearLevels();
 }
 
@@ -4259,42 +2121,42 @@ void Editor::Cut() {
        }
 }
 
-void Editor::PasteRectangular(SelectionPosition pos, const char *ptr, int len) {
+void Editor::PasteRectangular(SelectionPosition pos, const char *ptr, Sci::Position len) {
        if (pdoc->IsReadOnly() || SelectionContainsProtected()) {
                return;
        }
        sel.Clear();
        sel.RangeMain() = SelectionRange(pos);
-       int line = pdoc->LineFromPosition(sel.MainCaret());
+       Sci::Line line = pdoc->LineFromPosition(sel.MainCaret());
        UndoGroup ug(pdoc);
-       sel.RangeMain().caret = SelectionPosition(
-               InsertSpace(sel.RangeMain().caret.Position(), sel.RangeMain().caret.VirtualSpace()));
+       sel.RangeMain().caret = RealizeVirtualSpace(sel.RangeMain().caret);
        int xInsert = XFromPosition(sel.RangeMain().caret);
        bool prevCr = false;
        while ((len > 0) && IsEOLChar(ptr[len-1]))
                len--;
-       for (int i = 0; i < len; i++) {
+       for (Sci::Position i = 0; i < len; i++) {
                if (IsEOLChar(ptr[i])) {
                        if ((ptr[i] == '\r') || (!prevCr))
                                line++;
                        if (line >= pdoc->LinesTotal()) {
                                if (pdoc->eolMode != SC_EOL_LF)
-                                       pdoc->InsertChar(pdoc->Length(), '\r');
+                                       pdoc->InsertString(pdoc->Length(), "\r", 1);
                                if (pdoc->eolMode != SC_EOL_CR)
-                                       pdoc->InsertChar(pdoc->Length(), '\n');
+                                       pdoc->InsertString(pdoc->Length(), "\n", 1);
                        }
                        // Pad the end of lines with spaces if required
                        sel.RangeMain().caret.SetPosition(PositionFromLineX(line, xInsert));
                        if ((XFromPosition(sel.MainCaret()) < xInsert) && (i + 1 < len)) {
                                while (XFromPosition(sel.MainCaret()) < xInsert) {
-                                       pdoc->InsertChar(sel.MainCaret(), ' ');
-                                       sel.RangeMain().caret.Add(1);
+                                       assert(pdoc);
+                                       const Sci::Position lengthInserted = 
pdoc->InsertString(sel.MainCaret(), " ", 1);
+                                       sel.RangeMain().caret.Add(lengthInserted);
                                }
                        }
                        prevCr = ptr[i] == '\r';
                } else {
-                       pdoc->InsertString(sel.MainCaret(), ptr + i, 1);
-                       sel.RangeMain().caret.Add(1);
+                       const Sci::Position lengthInserted = pdoc->InsertString(sel.MainCaret(), ptr + i, 1);
+                       sel.RangeMain().caret.Add(lengthInserted);
                        prevCr = false;
                }
        }
@@ -4319,9 +2181,9 @@ void Editor::Clear() {
                        if (!RangeContainsProtected(sel.Range(r).caret.Position(), 
sel.Range(r).caret.Position() + 1)) {
                                if (sel.Range(r).Start().VirtualSpace()) {
                                        if (sel.Range(r).anchor < sel.Range(r).caret)
-                                               sel.Range(r) = 
SelectionPosition(InsertSpace(sel.Range(r).anchor.Position(), sel.Range(r).anchor.VirtualSpace()));
+                                               sel.Range(r) = 
SelectionRange(RealizeVirtualSpace(sel.Range(r).anchor.Position(), sel.Range(r).anchor.VirtualSpace()));
                                        else
-                                               sel.Range(r) = 
SelectionPosition(InsertSpace(sel.Range(r).caret.Position(), sel.Range(r).caret.VirtualSpace()));
+                                               sel.Range(r) = 
SelectionRange(RealizeVirtualSpace(sel.Range(r).caret.Position(), sel.Range(r).caret.VirtualSpace()));
                                }
                                if ((sel.Count() == 1) || 
!pdoc->IsPositionInLineEnd(sel.Range(r).caret.Position())) {
                                        pdoc->DelChar(sel.Range(r).caret.Position());
@@ -4335,6 +2197,7 @@ void Editor::Clear() {
                ClearSelection();
        }
        sel.RemoveDuplicates();
+       ShowCaretAtCurrentPosition();           // Avoid blinking
 }
 
 void Editor::SelectAll() {
@@ -4346,7 +2209,7 @@ void Editor::SelectAll() {
 void Editor::Undo() {
        if (pdoc->CanUndo()) {
                InvalidateCaret();
-               int newPos = pdoc->Undo();
+               Sci::Position newPos = pdoc->Undo();
                if (newPos >= 0)
                        SetEmptySelection(newPos);
                EnsureCaretVisible();
@@ -4355,22 +2218,15 @@ void Editor::Undo() {
 
 void Editor::Redo() {
        if (pdoc->CanRedo()) {
-               int newPos = pdoc->Redo();
+               Sci::Position newPos = pdoc->Redo();
                if (newPos >= 0)
                        SetEmptySelection(newPos);
                EnsureCaretVisible();
        }
 }
 
-void Editor::DelChar() {
-       if (!RangeContainsProtected(sel.MainCaret(), sel.MainCaret() + 1)) {
-               pdoc->DelChar(sel.MainCaret());
-       }
-       // Avoid blinking during rapid typing:
-       ShowCaretAtCurrentPosition();
-}
-
 void Editor::DelCharBack(bool allowLineStartDeletion) {
+       RefreshStyleData();
        if (!sel.IsRectangular())
                FilterSelections();
        if (sel.IsRectangular())
@@ -4383,21 +2239,19 @@ void Editor::DelCharBack(bool allowLineStartDeletion) {
                                        sel.Range(r).caret.SetVirtualSpace(sel.Range(r).caret.VirtualSpace() 
- 1);
                                        
sel.Range(r).anchor.SetVirtualSpace(sel.Range(r).caret.VirtualSpace());
                                } else {
-                                       int lineCurrentPos = 
pdoc->LineFromPosition(sel.Range(r).caret.Position());
+                                       Sci::Line lineCurrentPos = 
pdoc->LineFromPosition(sel.Range(r).caret.Position());
                                        if (allowLineStartDeletion || (pdoc->LineStart(lineCurrentPos) != 
sel.Range(r).caret.Position())) {
                                                if (pdoc->GetColumn(sel.Range(r).caret.Position()) <= 
pdoc->GetLineIndentation(lineCurrentPos) &&
                                                                
pdoc->GetColumn(sel.Range(r).caret.Position()) > 0 && pdoc->backspaceUnindents) {
                                                        UndoGroup ugInner(pdoc, !ug.Needed());
-                                                       int indentation = 
pdoc->GetLineIndentation(lineCurrentPos);
-                                                       int indentationStep = pdoc->IndentSize();
-                                                       if (indentation % indentationStep == 0) {
-                                                               pdoc->SetLineIndentation(lineCurrentPos, 
indentation - indentationStep);
-                                                       } else {
-                                                               pdoc->SetLineIndentation(lineCurrentPos, 
indentation - (indentation % indentationStep));
-                                                       }
+                                                       const int indentation = 
pdoc->GetLineIndentation(lineCurrentPos);
+                                                       const int indentationStep = pdoc->IndentSize();
+                                                       int indentationChange = indentation % indentationStep;
+                                                       if (indentationChange == 0)
+                                                               indentationChange = indentationStep;
+                                                       const Sci::Position posSelect = 
pdoc->SetLineIndentation(lineCurrentPos, indentation - indentationChange);
                                                        // SetEmptySelection
-                                                       sel.Range(r) = 
SelectionRange(pdoc->GetLineIndentPosition(lineCurrentPos),
-                                                               pdoc->GetLineIndentPosition(lineCurrentPos));
+                                                       sel.Range(r) = SelectionRange(posSelect);
                                                } else {
                                                        pdoc->DelCharBack(sel.Range(r).caret.Position());
                                                }
@@ -4417,20 +2271,33 @@ void Editor::DelCharBack(bool allowLineStartDeletion) {
        ShowCaretAtCurrentPosition();
 }
 
-void Editor::NotifyFocus(bool) {}
+int Editor::ModifierFlags(bool shift, bool ctrl, bool alt, bool meta, bool super) {
+       return
+               (shift ? SCI_SHIFT : 0) |
+               (ctrl ? SCI_CTRL : 0) |
+               (alt ? SCI_ALT : 0) |
+               (meta ? SCI_META : 0) |
+               (super ? SCI_SUPER : 0);
+}
+
+void Editor::NotifyFocus(bool focus) {
+       SCNotification scn = {};
+       scn.nmhdr.code = focus ? SCN_FOCUSIN : SCN_FOCUSOUT;
+       NotifyParent(scn);
+}
 
 void Editor::SetCtrlID(int identifier) {
        ctrlID = identifier;
 }
 
-void Editor::NotifyStyleToNeeded(int endStyleNeeded) {
-       SCNotification scn = {0};
+void Editor::NotifyStyleToNeeded(Sci::Position endStyleNeeded) {
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_STYLENEEDED;
        scn.position = endStyleNeeded;
        NotifyParent(scn);
 }
 
-void Editor::NotifyStyleNeeded(Document *, void *, int endStyleNeeded) {
+void Editor::NotifyStyleNeeded(Document *, void *, Sci::Position endStyleNeeded) {
        NotifyStyleToNeeded(endStyleNeeded);
 }
 
@@ -4442,14 +2309,14 @@ void Editor::NotifyErrorOccurred(Document *, void *, int status) {
 }
 
 void Editor::NotifyChar(int ch) {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_CHARADDED;
        scn.ch = ch;
        NotifyParent(scn);
 }
 
 void Editor::NotifySavePoint(bool isSavePoint) {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        if (isSavePoint) {
                scn.nmhdr.code = SCN_SAVEPOINTREACHED;
        } else {
@@ -4459,51 +2326,63 @@ void Editor::NotifySavePoint(bool isSavePoint) {
 }
 
 void Editor::NotifyModifyAttempt() {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_MODIFYATTEMPTRO;
        NotifyParent(scn);
 }
 
-void Editor::NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt) {
-       SCNotification scn = {0};
+void Editor::NotifyDoubleClick(Point pt, int modifiers) {
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_DOUBLECLICK;
        scn.line = LineFromLocation(pt);
        scn.position = PositionFromLocation(pt, true);
-       scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) |
-               (alt ? SCI_ALT : 0);
+       scn.modifiers = modifiers;
        NotifyParent(scn);
 }
 
-void Editor::NotifyHotSpotDoubleClicked(int position, bool shift, bool ctrl, bool alt) {
-       SCNotification scn = {0};
+void Editor::NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt) {
+       NotifyDoubleClick(pt, ModifierFlags(shift, ctrl, alt));
+}
+
+void Editor::NotifyHotSpotDoubleClicked(Sci::Position position, int modifiers) {
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_HOTSPOTDOUBLECLICK;
        scn.position = position;
-       scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) |
-               (alt ? SCI_ALT : 0);
+       scn.modifiers = modifiers;
        NotifyParent(scn);
 }
 
-void Editor::NotifyHotSpotClicked(int position, bool shift, bool ctrl, bool alt) {
-       SCNotification scn = {0};
+void Editor::NotifyHotSpotDoubleClicked(Sci::Position position, bool shift, bool ctrl, bool alt) {
+       NotifyHotSpotDoubleClicked(position, ModifierFlags(shift, ctrl, alt));
+}
+
+void Editor::NotifyHotSpotClicked(Sci::Position position, int modifiers) {
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_HOTSPOTCLICK;
        scn.position = position;
-       scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) |
-               (alt ? SCI_ALT : 0);
+       scn.modifiers = modifiers;
        NotifyParent(scn);
 }
 
-void Editor::NotifyHotSpotReleaseClick(int position, bool shift, bool ctrl, bool alt) {
-       SCNotification scn = {0};
+void Editor::NotifyHotSpotClicked(Sci::Position position, bool shift, bool ctrl, bool alt) {
+       NotifyHotSpotClicked(position, ModifierFlags(shift, ctrl, alt));
+}
+
+void Editor::NotifyHotSpotReleaseClick(Sci::Position position, int modifiers) {
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_HOTSPOTRELEASECLICK;
        scn.position = position;
-       scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) |
-               (alt ? SCI_ALT : 0);
+       scn.modifiers = modifiers;
        NotifyParent(scn);
 }
 
+void Editor::NotifyHotSpotReleaseClick(Sci::Position position, bool shift, bool ctrl, bool alt) {
+       NotifyHotSpotReleaseClick(position, ModifierFlags(shift, ctrl, alt));
+}
+
 bool Editor::NotifyUpdateUI() {
        if (needUpdateUI) {
-               SCNotification scn = {0};
+               SCNotification scn = {};
                scn.nmhdr.code = SCN_UPDATEUI;
                scn.updated = needUpdateUI;
                NotifyParent(scn);
@@ -4514,35 +2393,35 @@ bool Editor::NotifyUpdateUI() {
 }
 
 void Editor::NotifyPainted() {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_PAINTED;
        NotifyParent(scn);
 }
 
-void Editor::NotifyIndicatorClick(bool click, int position, bool shift, bool ctrl, bool alt) {
-       int mask = pdoc->decorations.AllOnFor(position);
-       if ((click && mask) || pdoc->decorations.clickNotified) {
-               SCNotification scn = {0};
-               pdoc->decorations.clickNotified = click;
+void Editor::NotifyIndicatorClick(bool click, Sci::Position position, int modifiers) {
+       const int mask = pdoc->decorations.AllOnFor(position);
+       if ((click && mask) || pdoc->decorations.ClickNotified()) {
+               SCNotification scn = {};
+               pdoc->decorations.SetClickNotified(click);
                scn.nmhdr.code = click ? SCN_INDICATORCLICK : SCN_INDICATORRELEASE;
-               scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | (alt ? SCI_ALT : 0);
+               scn.modifiers = modifiers;
                scn.position = position;
                NotifyParent(scn);
        }
 }
 
-bool Editor::NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt) {
-       int marginClicked = -1;
-       int x = vs.textStart - vs.fixedColumnWidth;
-       for (int margin = 0; margin <= SC_MAX_MARGIN; margin++) {
-               if ((pt.x >= x) && (pt.x < x + vs.ms[margin].width))
-                       marginClicked = margin;
-               x += vs.ms[margin].width;
-       }
+void Editor::NotifyIndicatorClick(bool click, Sci::Position position, bool shift, bool ctrl, bool alt) {
+       NotifyIndicatorClick(click, position, ModifierFlags(shift, ctrl, alt));
+}
+
+bool Editor::NotifyMarginClick(Point pt, int modifiers) {
+       const int marginClicked = vs.MarginFromLocation(pt);
        if ((marginClicked >= 0) && vs.ms[marginClicked].sensitive) {
-               int position = pdoc->LineStart(LineFromLocation(pt));
+               Sci::Position position = pdoc->LineStart(LineFromLocation(pt));
                if ((vs.ms[marginClicked].mask & SC_MASK_FOLDERS) && (foldAutomatic & 
SC_AUTOMATICFOLD_CLICK)) {
-                       int lineClick = pdoc->LineFromPosition(position);
+                       const bool ctrl = (modifiers & SCI_CTRL) != 0;
+                       const bool shift = (modifiers & SCI_SHIFT) != 0;
+                       Sci::Line lineClick = pdoc->LineFromPosition(position);
                        if (shift && ctrl) {
                                FoldAll(SC_FOLDACTION_TOGGLE);
                        } else {
@@ -4561,10 +2440,9 @@ bool Editor::NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt) {
                        }
                        return true;
                }
-               SCNotification scn = {0};
+               SCNotification scn = {};
                scn.nmhdr.code = SCN_MARGINCLICK;
-               scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) |
-                       (alt ? SCI_ALT : 0);
+               scn.modifiers = modifiers;
                scn.position = position;
                scn.margin = marginClicked;
                NotifyParent(scn);
@@ -4574,8 +2452,28 @@ bool Editor::NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt) {
        }
 }
 
-void Editor::NotifyNeedShown(int pos, int len) {
-       SCNotification scn = {0};
+bool Editor::NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt) {
+       return NotifyMarginClick(pt, ModifierFlags(shift, ctrl, alt));
+}
+
+bool Editor::NotifyMarginRightClick(Point pt, int modifiers) {
+       int marginRightClicked = vs.MarginFromLocation(pt);
+       if ((marginRightClicked >= 0) && vs.ms[marginRightClicked].sensitive) {
+               Sci::Position position = pdoc->LineStart(LineFromLocation(pt));
+               SCNotification scn = {};
+               scn.nmhdr.code = SCN_MARGINRIGHTCLICK;
+               scn.modifiers = modifiers;
+               scn.position = position;
+               scn.margin = marginRightClicked;
+               NotifyParent(scn);
+               return true;
+       } else {
+               return false;
+       }
+}
+
+void Editor::NotifyNeedShown(Sci::Position pos, Sci::Position len) {
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_NEEDSHOWN;
        scn.position = pos;
        scn.length = len;
@@ -4583,16 +2481,16 @@ void Editor::NotifyNeedShown(int pos, int len) {
 }
 
 void Editor::NotifyDwelling(Point pt, bool state) {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = state ? SCN_DWELLSTART : SCN_DWELLEND;
        scn.position = PositionFromLocation(pt, true);
-       scn.x = pt.x;
-       scn.y = pt.y;
+       scn.x = static_cast<int>(pt.x + vs.ExternalMarginWidth());
+       scn.y = static_cast<int>(pt.y);
        NotifyParent(scn);
 }
 
 void Editor::NotifyZoom() {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_ZOOM;
        NotifyParent(scn);
 }
@@ -4610,10 +2508,10 @@ void Editor::NotifySavePoint(Document *, void *, bool atSavePoint) {
 
 void Editor::CheckModificationForWrap(DocModification mh) {
        if (mh.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) {
-               llc.Invalidate(LineLayout::llCheckTextAndStyle);
-               int lineDoc = pdoc->LineFromPosition(mh.position);
-               int lines = Platform::Maximum(0, mh.linesAdded);
-               if (wrapState != eWrapNone) {
+               view.llc.Invalidate(LineLayout::llCheckTextAndStyle);
+               Sci::Line lineDoc = pdoc->LineFromPosition(mh.position);
+               Sci::Line lines = std::max(static_cast<Sci::Line>(0), mh.linesAdded);
+               if (Wrapping()) {
                        NeedWrapping(lineDoc, lineDoc + lines + 1);
                }
                RefreshStyleData();
@@ -4623,7 +2521,7 @@ void Editor::CheckModificationForWrap(DocModification mh) {
 }
 
 // Move a position so it is still after the same character as before the insertion.
-static inline int MovePositionForInsertion(int position, int startInsertion, int length) {
+static inline Sci::Position MovePositionForInsertion(Sci::Position position, Sci::Position startInsertion, 
Sci::Position length) {
        if (position > startInsertion) {
                return position + length;
        }
@@ -4632,9 +2530,9 @@ static inline int MovePositionForInsertion(int position, int startInsertion, int
 
 // Move a position so it is still after the same character as before the deletion if that
 // character is still present else after the previous surviving character.
-static inline int MovePositionForDeletion(int position, int startDeletion, int length) {
+static inline Sci::Position MovePositionForDeletion(Sci::Position position, Sci::Position startDeletion, 
Sci::Position length) {
        if (position > startDeletion) {
-               int endDeletion = startDeletion + length;
+               const Sci::Position endDeletion = startDeletion + length;
                if (position > endDeletion) {
                        return position - length;
                } else {
@@ -4659,6 +2557,9 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                        Redraw();
                }
        }
+       if (mh.modificationType & SC_MOD_CHANGETABSTOPS) {
+               Redraw();
+       }
        if (mh.modificationType & SC_MOD_LEXERSTATE) {
                if (paintState == painting) {
                        CheckForChangeOutsidePaint(
@@ -4680,7 +2581,7 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                        }
                }
                if (mh.modificationType & SC_MOD_CHANGESTYLE) {
-                       llc.Invalidate(LineLayout::llCheckTextAndStyle);
+                       view.llc.Invalidate(LineLayout::llCheckTextAndStyle);
                }
        } else {
                // Move selection and brace highlights
@@ -4695,26 +2596,29 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                }
                if ((mh.modificationType & (SC_MOD_BEFOREINSERT | SC_MOD_BEFOREDELETE)) && cs.HiddenLines()) {
                        // Some lines are hidden so may need shown.
-                       // TODO: check if the modified area is hidden.
+                       const Sci::Line lineOfPos = pdoc->LineFromPosition(mh.position);
+                       Sci::Position endNeedShown = mh.position;
                        if (mh.modificationType & SC_MOD_BEFOREINSERT) {
-                               int lineOfPos = pdoc->LineFromPosition(mh.position);
-                               bool insertingNewLine = false;
-                               for (int i=0; i < mh.length; i++) {
-                                       if ((mh.text[i] == '\n') || (mh.text[i] == '\r'))
-                                               insertingNewLine = true;
-                               }
-                               if (insertingNewLine && (mh.position != pdoc->LineStart(lineOfPos)))
-                                       NeedShown(mh.position, pdoc->LineStart(lineOfPos+1) - mh.position);
-                               else
-                                       NeedShown(mh.position, 0);
+                               if (pdoc->ContainsLineEnd(mh.text, mh.length) && (mh.position != 
pdoc->LineStart(lineOfPos)))
+                                       endNeedShown = pdoc->LineStart(lineOfPos+1);
                        } else if (mh.modificationType & SC_MOD_BEFOREDELETE) {
-                               NeedShown(mh.position, mh.length);
+                               // If the deletion includes any EOL then we extend the need shown area.
+                               endNeedShown = mh.position + mh.length;
+                               Sci::Line lineLast = pdoc->LineFromPosition(mh.position+mh.length);
+                               for (Sci::Line line = lineOfPos + 1; line <= lineLast; line++) {
+                                       const Sci::Line lineMaxSubord = pdoc->GetLastChild(line, -1, -1);
+                                       if (lineLast < lineMaxSubord) {
+                                               lineLast = lineMaxSubord;
+                                               endNeedShown = pdoc->LineEnd(lineLast);
+                                       }
+                               }
                        }
+                       NeedShown(mh.position, endNeedShown - mh.position);
                }
                if (mh.linesAdded != 0) {
                        // Update contraction state for inserted and removed lines
                        // lineOfPos should be calculated in context of state before modification, shouldn't 
it
-                       int lineOfPos = pdoc->LineFromPosition(mh.position);
+                       Sci::Line lineOfPos = pdoc->LineFromPosition(mh.position);
                        if (mh.position > pdoc->LineStart(lineOfPos))
                                lineOfPos++;    // Affecting subsequent lines
                        if (mh.linesAdded > 0) {
@@ -4722,11 +2626,14 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                        } else {
                                cs.DeleteLines(lineOfPos, -mh.linesAdded);
                        }
+                       view.LinesAddedOrRemoved(lineOfPos, mh.linesAdded);
                }
                if (mh.modificationType & SC_MOD_CHANGEANNOTATION) {
-                       int lineDoc = pdoc->LineFromPosition(mh.position);
+                       Sci::Line lineDoc = pdoc->LineFromPosition(mh.position);
                        if (vs.annotationVisible) {
-                               cs.SetHeight(lineDoc, cs.GetHeight(lineDoc) + mh.annotationLinesAdded);
+                               if (cs.SetHeight(lineDoc, cs.GetHeight(lineDoc) + mh.annotationLinesAdded)) {
+                                       SetScrollBars();
+                               }
                                Redraw();
                        }
                }
@@ -4734,7 +2641,7 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                if (mh.linesAdded != 0) {
                        // Avoid scrolling of display if change before current display
                        if (mh.position < posTopLine && !CanDeferToLastStep(mh)) {
-                               int newTop = Platform::Clamp(topLine + mh.linesAdded, 0, MaxScrollPos());
+                               Sci::Line newTop = Platform::Clamp(topLine + mh.linesAdded, 0, 
MaxScrollPos());
                                if (newTop != topLine) {
                                        SetTopLine(newTop);
                                        SetVerticalScrollPos();
@@ -4761,7 +2668,7 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                if ((!willRedrawAll) && ((paintState == notPainting) || !PaintContainsMargin())) {
                        if (mh.modificationType & SC_MOD_CHANGEFOLD) {
                                // Fold changes can affect the drawing of following lines so redraw whole 
margin
-                               RedrawSelMargin(highlightDelimiter.isEnabled ? -1 : mh.line-1, true);
+                               RedrawSelMargin(marginView.highlightDelimiter.isEnabled ? -1 : mh.line - 1, 
true);
                        } else {
                                RedrawSelMargin(mh.line);
                        }
@@ -4784,7 +2691,7 @@ void Editor::NotifyModified(Document *, DocModification mh, void *) {
                        NotifyChange(); // Send EN_CHANGE
                }
 
-               SCNotification scn = {0};
+               SCNotification scn = {};
                scn.nmhdr.code = SCN_MODIFIED;
                scn.position = mh.position;
                scn.modificationType = mh.modificationType;
@@ -4888,6 +2795,7 @@ void Editor::NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lPar
        case SCI_LINECUT:
        case SCI_LINEDELETE:
        case SCI_LINETRANSPOSE:
+       case SCI_LINEREVERSE:
        case SCI_LINEDUPLICATE:
        case SCI_LOWERCASE:
        case SCI_UPPERCASE:
@@ -4922,11 +2830,11 @@ void Editor::NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lPar
        case SCI_NEWLINE:
        default:
                //              printf("Filtered out %ld of macro recording\n", iMessage);
-               return ;
+               return;
        }
 
        // Send notification
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_MACRORECORD;
        scn.message = iMessage;
        scn.wParam = wParam;
@@ -4946,24 +2854,24 @@ void Editor::ContainerNeedsUpdate(int flags) {
  * If stuttered = true and already at first/last row, scroll as normal.
  */
 void Editor::PageMove(int direction, Selection::selTypes selt, bool stuttered) {
-       int topLineNew;
+       Sci::Line topLineNew;
        SelectionPosition newPos;
 
-       int currentLine = pdoc->LineFromPosition(sel.MainCaret());
-       int topStutterLine = topLine + caretYSlop;
-       int bottomStutterLine =
+       const Sci::Line currentLine = pdoc->LineFromPosition(sel.MainCaret());
+       const Sci::Line topStutterLine = topLine + caretYSlop;
+       const Sci::Line bottomStutterLine =
            pdoc->LineFromPosition(PositionFromLocation(
-                       Point(lastXChosen - xOffset, direction * vs.lineHeight * LinesToScroll())))
+                       Point::FromInts(lastXChosen - xOffset, direction * vs.lineHeight * LinesToScroll())))
            - caretYSlop - 1;
 
        if (stuttered && (direction < 0 && currentLine > topStutterLine)) {
                topLineNew = topLine;
-               newPos = SPositionFromLocation(Point(lastXChosen - xOffset, vs.lineHeight * caretYSlop),
+               newPos = SPositionFromLocation(Point::FromInts(lastXChosen - xOffset, vs.lineHeight * 
caretYSlop),
                        false, false, UserVirtualSpace());
 
        } else if (stuttered && (direction > 0 && currentLine < bottomStutterLine)) {
                topLineNew = topLine;
-               newPos = SPositionFromLocation(Point(lastXChosen - xOffset, vs.lineHeight * (LinesToScroll() 
- caretYSlop)),
+               newPos = SPositionFromLocation(Point::FromInts(lastXChosen - xOffset, vs.lineHeight * 
(LinesToScroll() - caretYSlop)),
                        false, false, UserVirtualSpace());
 
        } else {
@@ -4972,7 +2880,7 @@ void Editor::PageMove(int direction, Selection::selTypes selt, bool stuttered) {
                topLineNew = Platform::Clamp(
                            topLine + direction * LinesToScroll(), 0, MaxScrollPos());
                newPos = SPositionFromLocation(
-                       Point(lastXChosen - xOffset, pt.y + direction * (vs.lineHeight * LinesToScroll())),
+                       Point::FromInts(lastXChosen - xOffset, static_cast<int>(pt.y) + direction * 
(vs.lineHeight * LinesToScroll())),
                        false, false, UserVirtualSpace());
        }
 
@@ -5010,14 +2918,15 @@ void Editor::ChangeCaseOfSelection(int caseMapping) {
                                }
                                size_t endDifferenceText = sText.size() - 1 - lastDifferenceText;
                                pdoc->DeleteChars(
-                                       static_cast<int>(currentNoVS.Start().Position() + firstDifference),
-                                       static_cast<int>(rangeBytes - firstDifference - endDifferenceText));
-                               pdoc->InsertString(
+                                       static_cast<Sci::Position>(currentNoVS.Start().Position() + 
firstDifference),
+                                       static_cast<Sci::Position>(rangeBytes - firstDifference - 
endDifferenceText));
+                               const Sci::Position lengthChange = 
static_cast<Sci::Position>(lastDifferenceMapped - firstDifference + 1);
+                               const Sci::Position lengthInserted = pdoc->InsertString(
                                        static_cast<int>(currentNoVS.Start().Position() + firstDifference),
                                        sMapped.c_str() + firstDifference,
-                                       static_cast<int>(lastDifferenceMapped - firstDifference + 1));
+                                       lengthChange);
                                // Automatic movement changes selection so reset to exactly the same as it 
was.
-                               int diffSizes = static_cast<int>(sMapped.size() - sText.size());
+                               Sci::Position diffSizes = static_cast<Sci::Position>(sMapped.size() - 
sText.size()) + lengthInserted - lengthChange;
                                if (diffSizes != 0) {
                                        if (current.anchor > current.caret)
                                                current.anchor.Add(diffSizes);
@@ -5031,25 +2940,55 @@ void Editor::ChangeCaseOfSelection(int caseMapping) {
 }
 
 void Editor::LineTranspose() {
-       int line = pdoc->LineFromPosition(sel.MainCaret());
+       Sci::Line line = pdoc->LineFromPosition(sel.MainCaret());
        if (line > 0) {
                UndoGroup ug(pdoc);
-               int startPrev = pdoc->LineStart(line - 1);
-               int endPrev = pdoc->LineEnd(line - 1);
-               int start = pdoc->LineStart(line);
-               int end = pdoc->LineEnd(line);
-               std::string line1 = RangeText(startPrev, endPrev);
-               int len1 = endPrev - startPrev;
-               std::string line2 = RangeText(start, end);
-               int len2 = end - start;
-               pdoc->DeleteChars(start, len2);
-               pdoc->DeleteChars(startPrev, len1);
-               pdoc->InsertString(startPrev, line2.c_str(), len2);
-               pdoc->InsertString(start - len1 + len2, line1.c_str(), len1);
-               MovePositionTo(SelectionPosition(start - len1 + len2));
+
+               const Sci::Position startPrevious = pdoc->LineStart(line - 1);
+               const std::string linePrevious = RangeText(startPrevious, pdoc->LineEnd(line - 1));
+
+               Sci::Position startCurrent = pdoc->LineStart(line);
+               const std::string lineCurrent = RangeText(startCurrent, pdoc->LineEnd(line));
+
+               pdoc->DeleteChars(startCurrent, static_cast<Sci::Position>(lineCurrent.length()));
+               pdoc->DeleteChars(startPrevious, static_cast<Sci::Position>(linePrevious.length()));
+               startCurrent -= static_cast<Sci::Position>(linePrevious.length());
+
+               startCurrent += pdoc->InsertString(startPrevious, lineCurrent.c_str(),
+                       static_cast<Sci::Position>(lineCurrent.length()));
+               pdoc->InsertString(startCurrent, linePrevious.c_str(),
+                       static_cast<Sci::Position>(linePrevious.length()));
+               // Move caret to start of current line
+               MovePositionTo(SelectionPosition(startCurrent));
        }
 }
 
+void Editor::LineReverse() {
+       const Sci::Line lineStart = pdoc->LineFromPosition(sel.RangeMain().Start().Position());
+       const Sci::Line lineEnd = pdoc->LineFromPosition(sel.RangeMain().End().Position()-1);
+       const Sci::Line lineDiff = lineEnd - lineStart;
+       if (lineDiff <= 0)
+               return;
+       UndoGroup ug(pdoc);
+       for (Sci::Line i=(lineDiff+1)/2-1; i>=0; --i) {
+               const Sci::Line lineNum2 = lineEnd - i;
+               const Sci::Line lineNum1 = lineStart + i;
+               Sci::Position lineStart2 = pdoc->LineStart(lineNum2);
+               const Sci::Position lineStart1 = pdoc->LineStart(lineNum1);
+               const std::string line2 = RangeText(lineStart2, pdoc->LineEnd(lineNum2));
+               const std::string line1 = RangeText(lineStart1, pdoc->LineEnd(lineNum1));
+               const Sci::Position lineLen2 = static_cast<Sci::Position>(line2.length());
+               const Sci::Position lineLen1 = static_cast<Sci::Position>(line1.length());
+               pdoc->DeleteChars(lineStart2, lineLen2);
+               pdoc->DeleteChars(lineStart1, lineLen1);
+               lineStart2 -= lineLen1;
+               pdoc->InsertString(lineStart2, line1.c_str(), lineLen1);
+               pdoc->InsertString(lineStart1, line2.c_str(), lineLen2);
+       }
+       // Wholly select all affected lines
+       sel.RangeMain() = SelectionRange(pdoc->LineStart(lineStart), pdoc->LineStart(lineEnd+1));
+}
+
 void Editor::Duplicate(bool forLine) {
        if (sel.Empty()) {
                forLine = true;
@@ -5065,19 +3004,20 @@ void Editor::Duplicate(bool forLine) {
                SelectionPosition start = sel.Range(r).Start();
                SelectionPosition end = sel.Range(r).End();
                if (forLine) {
-                       int line = pdoc->LineFromPosition(sel.Range(r).caret.Position());
+                       Sci::Line line = pdoc->LineFromPosition(sel.Range(r).caret.Position());
                        start = SelectionPosition(pdoc->LineStart(line));
                        end = SelectionPosition(pdoc->LineEnd(line));
                }
                std::string text = RangeText(start.Position(), end.Position());
+               Sci::Position lengthInserted = eolLen;
                if (forLine)
-                       pdoc->InsertString(end.Position(), eol, eolLen);
-               pdoc->InsertString(end.Position() + eolLen, text.c_str(), SelectionRange(end, 
start).Length());
+                       lengthInserted = pdoc->InsertString(end.Position(), eol, eolLen);
+               pdoc->InsertString(end.Position() + lengthInserted, text.c_str(), 
static_cast<Sci::Position>(text.length()));
        }
        if (sel.Count() && sel.IsRectangular()) {
                SelectionPosition last = sel.Last();
                if (forLine) {
-                       int line = pdoc->LineFromPosition(last.Position());
+                       Sci::Line line = pdoc->LineFromPosition(last.Position());
                        last = SelectionPosition(last.Position() + pdoc->LineStart(line+1) - 
pdoc->LineStart(line));
                }
                if (sel.Rectangular().anchor > sel.Rectangular().caret)
@@ -5093,29 +3033,36 @@ void Editor::CancelModes() {
 }
 
 void Editor::NewLine() {
-       // Remove non-main ranges
-       InvalidateSelection(sel.RangeMain(), true);
-       sel.SetSelection(sel.RangeMain());
+       InvalidateWholeSelection();
+       if (sel.IsRectangular() || !additionalSelectionTyping) {
+               // Remove non-main ranges
+               sel.DropAdditionalRanges();
+       }
 
-       // Clear main range and insert line end
-       bool needGroupUndo = !sel.Empty();
-       if (needGroupUndo)
-               pdoc->BeginUndoAction();
+       UndoGroup ug(pdoc, !sel.Empty() || (sel.Count() > 1));
 
-       if (!sel.Empty())
+       // Clear each range
+       if (!sel.Empty()) {
                ClearSelection();
-       const char *eol = "\n";
-       if (pdoc->eolMode == SC_EOL_CRLF) {
-               eol = "\r\n";
-       } else if (pdoc->eolMode == SC_EOL_CR) {
-               eol = "\r";
-       } // else SC_EOL_LF -> "\n" already set
-       bool inserted = pdoc->InsertCString(sel.MainCaret(), eol);
-       // Want to end undo group before NotifyChar as applications often modify text here
-       if (needGroupUndo)
-               pdoc->EndUndoAction();
-       if (inserted) {
-               SetEmptySelection(sel.MainCaret() + istrlen(eol));
+       }
+
+       // Insert each line end
+       size_t countInsertions = 0;
+       for (size_t r = 0; r < sel.Count(); r++) {
+               sel.Range(r).ClearVirtualSpace();
+               const char *eol = StringFromEOLMode(pdoc->eolMode);
+               const Sci::Position positionInsert = sel.Range(r).caret.Position();
+               const Sci::Position insertLength = pdoc->InsertString(positionInsert, eol, istrlen(eol));
+               if (insertLength > 0) {
+                       sel.Range(r) = SelectionRange(positionInsert + insertLength);
+                       countInsertions++;
+               }
+       }
+
+       // Perform notifications after all the changes as the application may change the
+       // selections in response to the characters.
+       for (size_t i = 0; i < countInsertions; i++) {
+               const char *eol = StringFromEOLMode(pdoc->eolMode);
                while (*eol) {
                        NotifyChar(*eol);
                        if (recordingMacro) {
@@ -5127,6 +3074,7 @@ void Editor::NewLine() {
                        eol++;
                }
        }
+
        SetLastXChosen();
        SetScrollBars();
        EnsureCaretVisible();
@@ -5134,26 +3082,17 @@ void Editor::NewLine() {
        ShowCaretAtCurrentPosition();
 }
 
-void Editor::CursorUpOrDown(int direction, Selection::selTypes selt) {
-       SelectionPosition caretToUse = sel.Range(sel.Main()).caret;
-       if (sel.IsRectangular()) {
-               if (selt ==  Selection::noSel) {
-                       caretToUse = (direction > 0) ? sel.Limits().end : sel.Limits().start;
-               } else {
-                       caretToUse = sel.Rectangular().caret;
-               }
-       }
-
-       Point pt = LocationFromPosition(caretToUse);
+SelectionPosition Editor::PositionUpOrDown(SelectionPosition spStart, int direction, int lastX) {
+       const Point pt = LocationFromPosition(spStart);
        int skipLines = 0;
 
        if (vs.annotationVisible) {
-               int lineDoc = pdoc->LineFromPosition(caretToUse.Position());
-               Point ptStartLine = LocationFromPosition(pdoc->LineStart(lineDoc));
-               int subLine = (pt.y - ptStartLine.y) / vs.lineHeight;
+               const Sci::Line lineDoc = pdoc->LineFromPosition(spStart.Position());
+               const Point ptStartLine = LocationFromPosition(pdoc->LineStart(lineDoc));
+               const int subLine = static_cast<int>(pt.y - ptStartLine.y) / vs.lineHeight;
 
                if (direction < 0 && subLine == 0) {
-                       int lineDisplay = cs.DisplayFromDoc(lineDoc);
+                       const Sci::Line lineDisplay = cs.DisplayFromDoc(lineDoc);
                        if (lineDisplay > 0) {
                                skipLines = pdoc->AnnotationLines(cs.DocFromDisplay(lineDisplay - 1));
                        }
@@ -5162,9 +3101,12 @@ void Editor::CursorUpOrDown(int direction, Selection::selTypes selt) {
                }
        }
 
-       int newY = pt.y + (1 + skipLines) * direction * vs.lineHeight;
+       const Sci::Line newY = static_cast<Sci::Line>(pt.y) + (1 + skipLines) * direction * vs.lineHeight;
+       if (lastX < 0) {
+               lastX = static_cast<Sci::Position>(pt.x) + xOffset;
+       }
        SelectionPosition posNew = SPositionFromLocation(
-                   Point(lastXChosen - xOffset, newY), false, false, UserVirtualSpace());
+               Point::FromInts(lastX - xOffset, newY), false, false, UserVirtualSpace());
 
        if (direction < 0) {
                // Line wrapping may lead to a location on the same line, so
@@ -5179,18 +3121,61 @@ void Editor::CursorUpOrDown(int direction, Selection::selTypes selt) {
                // There is an equivalent case when moving down which skips
                // over a line.
                Point ptNew = LocationFromPosition(posNew.Position());
-               while ((posNew.Position() > caretToUse.Position()) && (ptNew.y > newY)) {
+               while ((posNew.Position() > spStart.Position()) && (ptNew.y > newY)) {
                        posNew.Add(-1);
                        posNew.SetVirtualSpace(0);
                        ptNew = LocationFromPosition(posNew.Position());
                }
        }
+       return posNew;
+}
 
-       MovePositionTo(MovePositionSoVisible(posNew, direction), selt);
+void Editor::CursorUpOrDown(int direction, Selection::selTypes selt) {
+       if ((selt == Selection::noSel) && sel.MoveExtends()) {
+               selt = Selection::selStream;
+       }
+       SelectionPosition caretToUse = sel.Range(sel.Main()).caret;
+       if (sel.IsRectangular()) {
+               if (selt ==  Selection::noSel) {
+                       caretToUse = (direction > 0) ? sel.Limits().end : sel.Limits().start;
+               } else {
+                       caretToUse = sel.Rectangular().caret;
+               }
+       }
+       if (selt == Selection::selRectangle) {
+               const SelectionRange rangeBase = sel.IsRectangular() ? sel.Rectangular() : sel.RangeMain();
+               if (!sel.IsRectangular()) {
+                       InvalidateWholeSelection();
+                       sel.DropAdditionalRanges();
+               }
+               const SelectionPosition posNew = MovePositionSoVisible(
+                       PositionUpOrDown(caretToUse, direction, lastXChosen), direction);
+               sel.selType = Selection::selRectangle;
+               sel.Rectangular() = SelectionRange(posNew, rangeBase.anchor);
+               SetRectangularRange();
+               MovedCaret(posNew, caretToUse, true);
+       } else {
+               InvalidateWholeSelection();
+               if (!additionalSelectionTyping || (sel.IsRectangular())) {
+                       sel.DropAdditionalRanges();
+               }
+               sel.selType = Selection::selStream;
+               for (size_t r = 0; r < sel.Count(); r++) {
+                       const int lastX = (r == sel.Main()) ? lastXChosen : -1;
+                       const SelectionPosition spCaretNow = sel.Range(r).caret;
+                       const SelectionPosition posNew = MovePositionSoVisible(
+                               PositionUpOrDown(spCaretNow, direction, lastX), direction);
+                       sel.Range(r) = selt == Selection::selStream ?
+                               SelectionRange(posNew, sel.Range(r).anchor) : SelectionRange(posNew);
+               }
+               sel.RemoveDuplicates();
+               MovedCaret(sel.RangeMain().caret, caretToUse, true);
+       }
 }
 
 void Editor::ParaUpOrDown(int direction, Selection::selTypes selt) {
-       int lineDoc, savedPos = sel.MainCaret();
+       Sci::Line lineDoc;
+       Sci::Position savedPos = sel.MainCaret();
        do {
                MovePositionTo(SelectionPosition(direction > 0 ? pdoc->ParaDown(sel.MainCaret()) : 
pdoc->ParaUp(sel.MainCaret())), selt);
                lineDoc = pdoc->LineFromPosition(sel.MainCaret());
@@ -5205,31 +3190,16 @@ void Editor::ParaUpOrDown(int direction, Selection::selTypes selt) {
        } while (!cs.GetVisible(lineDoc));
 }
 
-int Editor::StartEndDisplayLine(int pos, bool start) {
+Range Editor::RangeDisplayLine(Sci::Line lineVisible) {
        RefreshStyleData();
-       int line = pdoc->LineFromPosition(pos);
        AutoSurface surface(this);
-       AutoLineLayout ll(llc, RetrieveLineLayout(line));
-       int posRet = INVALID_POSITION;
-       if (surface && ll) {
-               unsigned int posLineStart = pdoc->LineStart(line);
-               LayoutLine(line, surface, vs, ll, wrapWidth);
-               int posInLine = pos - posLineStart;
-               if (posInLine <= ll->maxLineLength) {
-                       for (int subLine = 0; subLine < ll->lines; subLine++) {
-                               if ((posInLine >= ll->LineStart(subLine)) && (posInLine <= 
ll->LineStart(subLine + 1))) {
-                                       if (start) {
-                                               posRet = ll->LineStart(subLine) + posLineStart;
-                                       } else {
-                                               if (subLine == ll->lines - 1)
-                                                       posRet = ll->LineStart(subLine + 1) + posLineStart;
-                                               else
-                                                       posRet = ll->LineStart(subLine + 1) + posLineStart - 
1;
-                                       }
-                               }
-                       }
-               }
-       }
+       return view.RangeDisplayLine(surface, *this, lineVisible, vs);
+}
+
+Sci::Position Editor::StartEndDisplayLine(Sci::Position pos, bool start) {
+       RefreshStyleData();
+       AutoSurface surface(this);
+       Sci::Position posRet = view.StartEndDisplayLine(surface, *this, pos, start, vs);
        if (posRet == INVALID_POSITION) {
                return pos;
        } else {
@@ -5237,10 +3207,406 @@ int Editor::StartEndDisplayLine(int pos, bool start) {
        }
 }
 
+namespace {
+
+unsigned int WithExtends(unsigned int iMessage) {
+       switch (iMessage) {
+       case SCI_CHARLEFT: return SCI_CHARLEFTEXTEND;
+       case SCI_CHARRIGHT: return SCI_CHARRIGHTEXTEND;
+
+       case SCI_WORDLEFT: return SCI_WORDLEFTEXTEND;
+       case SCI_WORDRIGHT: return SCI_WORDRIGHTEXTEND;
+       case SCI_WORDLEFTEND: return SCI_WORDLEFTENDEXTEND;
+       case SCI_WORDRIGHTEND: return SCI_WORDRIGHTENDEXTEND;
+       case SCI_WORDPARTLEFT: return SCI_WORDPARTLEFTEXTEND;
+       case SCI_WORDPARTRIGHT: return SCI_WORDPARTRIGHTEXTEND;
+
+       case SCI_HOME: return SCI_HOMEEXTEND;
+       case SCI_HOMEDISPLAY: return SCI_HOMEDISPLAYEXTEND;
+       case SCI_HOMEWRAP: return SCI_HOMEWRAPEXTEND;
+       case SCI_VCHOME: return SCI_VCHOMEEXTEND;
+       case SCI_VCHOMEDISPLAY: return SCI_VCHOMEDISPLAYEXTEND;
+       case SCI_VCHOMEWRAP: return SCI_VCHOMEWRAPEXTEND;
+
+       case SCI_LINEEND: return SCI_LINEENDEXTEND;
+       case SCI_LINEENDDISPLAY: return SCI_LINEENDDISPLAYEXTEND;
+       case SCI_LINEENDWRAP: return SCI_LINEENDWRAPEXTEND;
+
+       default:        return iMessage;
+       }
+}
+
+int NaturalDirection(unsigned int iMessage) {
+       switch (iMessage) {
+       case SCI_CHARLEFT:
+       case SCI_CHARLEFTEXTEND:
+       case SCI_CHARLEFTRECTEXTEND:
+       case SCI_WORDLEFT:
+       case SCI_WORDLEFTEXTEND:
+       case SCI_WORDLEFTEND:
+       case SCI_WORDLEFTENDEXTEND:
+       case SCI_WORDPARTLEFT:
+       case SCI_WORDPARTLEFTEXTEND:
+       case SCI_HOME:
+       case SCI_HOMEEXTEND:
+       case SCI_HOMEDISPLAY:
+       case SCI_HOMEDISPLAYEXTEND:
+       case SCI_HOMEWRAP:
+       case SCI_HOMEWRAPEXTEND:
+               // VC_HOME* mostly goes back
+       case SCI_VCHOME:
+       case SCI_VCHOMEEXTEND:
+       case SCI_VCHOMEDISPLAY:
+       case SCI_VCHOMEDISPLAYEXTEND:
+       case SCI_VCHOMEWRAP:
+       case SCI_VCHOMEWRAPEXTEND:
+               return -1;
+
+       default:
+               return 1;
+       }
+}
+
+bool IsRectExtend(unsigned int iMessage) {
+       switch (iMessage) {
+       case SCI_CHARLEFTRECTEXTEND:
+       case SCI_CHARRIGHTRECTEXTEND:
+       case SCI_HOMERECTEXTEND:
+       case SCI_VCHOMERECTEXTEND:
+       case SCI_LINEENDRECTEXTEND:
+               return true;
+       default:
+               return false;
+       }
+}
+
+}
+
+Sci::Position Editor::VCHomeDisplayPosition(Sci::Position position) {
+       const Sci::Position homePos = pdoc->VCHomePosition(position);
+       const Sci::Position viewLineStart = StartEndDisplayLine(position, true);
+       if (viewLineStart > homePos)
+               return viewLineStart;
+       else
+               return homePos;
+}
+
+Sci::Position Editor::VCHomeWrapPosition(Sci::Position position) {
+       const Sci::Position homePos = pdoc->VCHomePosition(position);
+       const Sci::Position viewLineStart = StartEndDisplayLine(position, true);
+       if ((viewLineStart < position) && (viewLineStart > homePos))
+               return viewLineStart;
+       else
+               return homePos;
+}
+
+Sci::Position Editor::LineEndWrapPosition(Sci::Position position) {
+       const Sci::Position endPos = StartEndDisplayLine(position, false);
+       const Sci::Position realEndPos = pdoc->LineEndPosition(position);
+       if (endPos > realEndPos      // if moved past visible EOLs
+               || position >= endPos) // if at end of display line already
+               return realEndPos;
+       else
+               return endPos;
+}
+
+int Editor::HorizontalMove(unsigned int iMessage) {
+       if (sel.MoveExtends()) {
+               iMessage = WithExtends(iMessage);
+       }
+
+       if (!multipleSelection && !sel.IsRectangular()) {
+               // Simplify selection down to 1
+               sel.SetSelection(sel.RangeMain());
+       }
+
+       // Invalidate each of the current selections
+       InvalidateWholeSelection();
+
+       if (IsRectExtend(iMessage)) {
+               const SelectionRange rangeBase = sel.IsRectangular() ? sel.Rectangular() : sel.RangeMain();
+               if (!sel.IsRectangular()) {
+                       sel.DropAdditionalRanges();
+               }
+               // Will change to rectangular if not currently rectangular
+               SelectionPosition spCaret = rangeBase.caret;
+               switch (iMessage) {
+               case SCI_CHARLEFTRECTEXTEND:
+                       if (pdoc->IsLineEndPosition(spCaret.Position()) && spCaret.VirtualSpace()) {
+                               spCaret.SetVirtualSpace(spCaret.VirtualSpace() - 1);
+                       } else if ((virtualSpaceOptions & SCVS_NOWRAPLINESTART) == 0 || 
pdoc->GetColumn(spCaret.Position()) > 0) {
+                               spCaret = SelectionPosition(spCaret.Position() - 1);
+                       }
+                       break;
+               case SCI_CHARRIGHTRECTEXTEND:
+                       if ((virtualSpaceOptions & SCVS_RECTANGULARSELECTION) && 
pdoc->IsLineEndPosition(sel.MainCaret())) {
+                               spCaret.SetVirtualSpace(spCaret.VirtualSpace() + 1);
+                       } else {
+                               spCaret = SelectionPosition(spCaret.Position() + 1);
+                       }
+                       break;
+               case SCI_HOMERECTEXTEND:
+                       spCaret = 
SelectionPosition(pdoc->LineStart(pdoc->LineFromPosition(spCaret.Position())));
+                       break;
+               case SCI_VCHOMERECTEXTEND:
+                       spCaret = SelectionPosition(pdoc->VCHomePosition(spCaret.Position()));
+                       break;
+               case SCI_LINEENDRECTEXTEND:
+                       spCaret = SelectionPosition(pdoc->LineEndPosition(spCaret.Position()));
+                       break;
+               }
+               const int directionMove = (spCaret < rangeBase.caret) ? -1 : 1;
+               spCaret = MovePositionSoVisible(spCaret, directionMove);
+               sel.selType = Selection::selRectangle;
+               sel.Rectangular() = SelectionRange(spCaret, rangeBase.anchor);
+               SetRectangularRange();
+       } else if (sel.IsRectangular()) {
+               // Not a rectangular extension so switch to stream.
+               const SelectionPosition selAtLimit = 
+                       (NaturalDirection(iMessage) > 0) ? sel.Limits().end : sel.Limits().start;
+               sel.selType = Selection::selStream;
+               sel.SetSelection(SelectionRange(selAtLimit));
+       } else {
+               if (!additionalSelectionTyping) {
+                       InvalidateWholeSelection();
+                       sel.DropAdditionalRanges();
+               }
+               for (size_t r = 0; r < sel.Count(); r++) {
+                       const SelectionPosition spCaretNow = sel.Range(r).caret;
+                       SelectionPosition spCaret = spCaretNow;
+                       switch (iMessage) {
+                       case SCI_CHARLEFT:
+                       case SCI_CHARLEFTEXTEND:
+                               if (spCaret.VirtualSpace()) {
+                                       spCaret.SetVirtualSpace(spCaret.VirtualSpace() - 1);
+                               } else if ((virtualSpaceOptions & SCVS_NOWRAPLINESTART) == 0 || 
pdoc->GetColumn(spCaret.Position()) > 0) {
+                                       spCaret = SelectionPosition(spCaret.Position() - 1);
+                               }
+                               break;
+                       case SCI_CHARRIGHT:
+                       case SCI_CHARRIGHTEXTEND:
+                               if ((virtualSpaceOptions & SCVS_USERACCESSIBLE) && 
pdoc->IsLineEndPosition(spCaret.Position())) {
+                                       spCaret.SetVirtualSpace(spCaret.VirtualSpace() + 1);
+                               } else {
+                                       spCaret = SelectionPosition(spCaret.Position() + 1);
+                               }
+                               break;
+                       case SCI_WORDLEFT:
+                       case SCI_WORDLEFTEXTEND:
+                               spCaret = SelectionPosition(pdoc->NextWordStart(spCaret.Position(), -1));
+                               break;
+                       case SCI_WORDRIGHT:
+                       case SCI_WORDRIGHTEXTEND:
+                               spCaret = SelectionPosition(pdoc->NextWordStart(spCaret.Position(), 1));
+                               break;
+                       case SCI_WORDLEFTEND:
+                       case SCI_WORDLEFTENDEXTEND:
+                               spCaret = SelectionPosition(pdoc->NextWordEnd(spCaret.Position(), -1));
+                               break;
+                       case SCI_WORDRIGHTEND:
+                       case SCI_WORDRIGHTENDEXTEND:
+                               spCaret = SelectionPosition(pdoc->NextWordEnd(spCaret.Position(), 1));
+                               break;
+                       case SCI_WORDPARTLEFT:
+                       case SCI_WORDPARTLEFTEXTEND:
+                               spCaret = SelectionPosition(pdoc->WordPartLeft(spCaret.Position()));
+                               break;
+                       case SCI_WORDPARTRIGHT:
+                       case SCI_WORDPARTRIGHTEXTEND:
+                               spCaret = SelectionPosition(pdoc->WordPartRight(spCaret.Position()));
+                               break;
+                       case SCI_HOME:
+                       case SCI_HOMEEXTEND:
+                               spCaret = 
SelectionPosition(pdoc->LineStart(pdoc->LineFromPosition(spCaret.Position())));
+                               break;
+                       case SCI_HOMEDISPLAY:
+                       case SCI_HOMEDISPLAYEXTEND:
+                               spCaret = SelectionPosition(StartEndDisplayLine(spCaret.Position(), true));
+                               break;
+                       case SCI_HOMEWRAP:
+                       case SCI_HOMEWRAPEXTEND:
+                               spCaret = MovePositionSoVisible(StartEndDisplayLine(spCaret.Position(), 
true), -1);
+                               if (spCaretNow <= spCaret)
+                                       spCaret = 
SelectionPosition(pdoc->LineStart(pdoc->LineFromPosition(spCaret.Position())));
+                               break;
+                       case SCI_VCHOME:
+                       case SCI_VCHOMEEXTEND:
+                               // VCHome alternates between beginning of line and beginning of text so may 
move back or forwards
+                               spCaret = SelectionPosition(pdoc->VCHomePosition(spCaret.Position()));
+                               break;
+                       case SCI_VCHOMEDISPLAY:
+                       case SCI_VCHOMEDISPLAYEXTEND:
+                               spCaret = SelectionPosition(VCHomeDisplayPosition(spCaret.Position()));
+                               break;
+                       case SCI_VCHOMEWRAP:
+                       case SCI_VCHOMEWRAPEXTEND:
+                               spCaret = SelectionPosition(VCHomeWrapPosition(spCaret.Position()));
+                               break;
+                       case SCI_LINEEND:
+                       case SCI_LINEENDEXTEND:
+                               spCaret = SelectionPosition(pdoc->LineEndPosition(spCaret.Position()));
+                               break;
+                       case SCI_LINEENDDISPLAY:
+                       case SCI_LINEENDDISPLAYEXTEND:
+                               spCaret = SelectionPosition(StartEndDisplayLine(spCaret.Position(), false));
+                               break;
+                       case SCI_LINEENDWRAP:
+                       case SCI_LINEENDWRAPEXTEND:
+                               spCaret = SelectionPosition(LineEndWrapPosition(spCaret.Position()));
+                               break;
+
+                       default:
+                               PLATFORM_ASSERT(false);
+                       }
+
+                       const int directionMove = (spCaret < spCaretNow) ? -1 : 1;
+                       spCaret = MovePositionSoVisible(spCaret, directionMove);
+
+                       // Handle move versus extend, and special behaviour for non-empty left/right
+                       switch (iMessage) {
+                       case SCI_CHARLEFT:
+                       case SCI_CHARRIGHT:
+                               if (sel.Range(r).Empty()) {
+                                       sel.Range(r) = SelectionRange(spCaret);
+                               } else {
+                                       sel.Range(r) = SelectionRange(
+                                               (iMessage == SCI_CHARLEFT) ? sel.Range(r).Start() : 
sel.Range(r).End());
+                               }
+                               break;
+
+                       case SCI_WORDLEFT:
+                       case SCI_WORDRIGHT:
+                       case SCI_WORDLEFTEND:
+                       case SCI_WORDRIGHTEND:
+                       case SCI_WORDPARTLEFT:
+                       case SCI_WORDPARTRIGHT:
+                       case SCI_HOME:
+                       case SCI_HOMEDISPLAY:
+                       case SCI_HOMEWRAP:
+                       case SCI_VCHOME:
+                       case SCI_VCHOMEDISPLAY:
+                       case SCI_VCHOMEWRAP:
+                       case SCI_LINEEND:
+                       case SCI_LINEENDDISPLAY:
+                       case SCI_LINEENDWRAP:
+                               sel.Range(r) = SelectionRange(spCaret);
+                               break;
+
+                       case SCI_CHARLEFTEXTEND:
+                       case SCI_CHARRIGHTEXTEND:
+                       case SCI_WORDLEFTEXTEND:
+                       case SCI_WORDRIGHTEXTEND:
+                       case SCI_WORDLEFTENDEXTEND:
+                       case SCI_WORDRIGHTENDEXTEND:
+                       case SCI_WORDPARTLEFTEXTEND:
+                       case SCI_WORDPARTRIGHTEXTEND:
+                       case SCI_HOMEEXTEND:
+                       case SCI_HOMEDISPLAYEXTEND:
+                       case SCI_HOMEWRAPEXTEND:
+                       case SCI_VCHOMEEXTEND:
+                       case SCI_VCHOMEDISPLAYEXTEND:
+                       case SCI_VCHOMEWRAPEXTEND:
+                       case SCI_LINEENDEXTEND:
+                       case SCI_LINEENDDISPLAYEXTEND:
+                       case SCI_LINEENDWRAPEXTEND: {
+                               SelectionRange rangeNew = SelectionRange(spCaret, sel.Range(r).anchor);
+                               sel.TrimOtherSelections(r, SelectionRange(rangeNew));
+                               sel.Range(r) = rangeNew;
+                               }
+                               break;
+
+                       default:
+                               PLATFORM_ASSERT(false);
+                       }
+               }
+       }
+
+       sel.RemoveDuplicates();
+
+       MovedCaret(sel.RangeMain().caret, SelectionPosition(INVALID_POSITION), true);
+
+       // Invalidate the new state of the selection
+       InvalidateWholeSelection();
+
+       SetLastXChosen();
+       // Need the line moving and so forth from MovePositionTo
+       return 0;
+}
+
+int Editor::DelWordOrLine(unsigned int iMessage) {
+       // Virtual space may be realised for SCI_DELWORDRIGHT or SCI_DELWORDRIGHTEND
+       // which means 2 actions so wrap in an undo group.
+
+       // Rightwards and leftwards deletions differ in treatment of virtual space.
+       // Clear virtual space for leftwards, realise for rightwards.
+       const bool leftwards = (iMessage == SCI_DELWORDLEFT) || (iMessage == SCI_DELLINELEFT);
+
+       if (!additionalSelectionTyping) {
+               InvalidateWholeSelection();
+               sel.DropAdditionalRanges();
+       }
+
+       UndoGroup ug0(pdoc, (sel.Count() > 1) || !leftwards);
+
+       for (size_t r = 0; r < sel.Count(); r++) {
+               if (leftwards) {
+                       // Delete to the left so first clear the virtual space.
+                       sel.Range(r).ClearVirtualSpace();
+               } else {
+                       // Delete to the right so first realise the virtual space.
+                       sel.Range(r) = SelectionRange(
+                               RealizeVirtualSpace(sel.Range(r).caret));
+               }
+
+               Range rangeDelete;
+               switch (iMessage) {
+               case SCI_DELWORDLEFT:
+                       rangeDelete = Range(
+                               pdoc->NextWordStart(sel.Range(r).caret.Position(), -1),
+                               sel.Range(r).caret.Position());
+                       break;
+               case SCI_DELWORDRIGHT:
+                       rangeDelete = Range(
+                               sel.Range(r).caret.Position(),
+                               pdoc->NextWordStart(sel.Range(r).caret.Position(), 1));
+                       break;
+               case SCI_DELWORDRIGHTEND:
+                       rangeDelete = Range(
+                               sel.Range(r).caret.Position(),
+                               pdoc->NextWordEnd(sel.Range(r).caret.Position(), 1));
+                       break;
+               case SCI_DELLINELEFT:
+                       rangeDelete = Range(
+                               pdoc->LineStart(pdoc->LineFromPosition(sel.Range(r).caret.Position())),
+                               sel.Range(r).caret.Position());
+                       break;
+               case SCI_DELLINERIGHT:
+                       rangeDelete = Range(
+                               sel.Range(r).caret.Position(),
+                               pdoc->LineEnd(pdoc->LineFromPosition(sel.Range(r).caret.Position())));
+                       break;
+               }
+               if (!RangeContainsProtected(rangeDelete.start, rangeDelete.end)) {
+                       pdoc->DeleteChars(rangeDelete.start, rangeDelete.end - rangeDelete.start);
+               }
+       }
+
+       // May need something stronger here: can selections overlap at this point?
+       sel.RemoveDuplicates();
+
+       MovedCaret(sel.RangeMain().caret, SelectionPosition(INVALID_POSITION), true);
+
+       // Invalidate the new state of the selection
+       InvalidateWholeSelection();
+
+       SetLastXChosen();
+       return 0;
+}
+
 int Editor::KeyCommand(unsigned int iMessage) {
        switch (iMessage) {
        case SCI_LINEDOWN:
-               CursorUpOrDown(1);
+               CursorUpOrDown(1, Selection::noSel);
                break;
        case SCI_LINEDOWNEXTEND:
                CursorUpOrDown(1, Selection::selStream);
@@ -5249,7 +3615,7 @@ int Editor::KeyCommand(unsigned int iMessage) {
                CursorUpOrDown(1, Selection::selRectangle);
                break;
        case SCI_PARADOWN:
-               ParaUpOrDown(1);
+               ParaUpOrDown(1, Selection::noSel);
                break;
        case SCI_PARADOWNEXTEND:
                ParaUpOrDown(1, Selection::selStream);
@@ -5259,7 +3625,7 @@ int Editor::KeyCommand(unsigned int iMessage) {
                MoveCaretInsideView(false);
                break;
        case SCI_LINEUP:
-               CursorUpOrDown(-1);
+               CursorUpOrDown(-1, Selection::noSel);
                break;
        case SCI_LINEUPEXTEND:
                CursorUpOrDown(-1, Selection::selStream);
@@ -5268,7 +3634,7 @@ int Editor::KeyCommand(unsigned int iMessage) {
                CursorUpOrDown(-1, Selection::selRectangle);
                break;
        case SCI_PARAUP:
-               ParaUpOrDown(-1);
+               ParaUpOrDown(-1, Selection::noSel);
                break;
        case SCI_PARAUPEXTEND:
                ParaUpOrDown(-1, Selection::selStream);
@@ -5277,174 +3643,48 @@ int Editor::KeyCommand(unsigned int iMessage) {
                ScrollTo(topLine - 1);
                MoveCaretInsideView(false);
                break;
+
        case SCI_CHARLEFT:
-               if (SelectionEmpty() || sel.MoveExtends()) {
-                       if ((sel.Count() == 1) && pdoc->IsLineEndPosition(sel.MainCaret()) && 
sel.RangeMain().caret.VirtualSpace()) {
-                               SelectionPosition spCaret = sel.RangeMain().caret;
-                               spCaret.SetVirtualSpace(spCaret.VirtualSpace() - 1);
-                               MovePositionTo(spCaret);
-                       } else if (sel.MoveExtends() && sel.selType == Selection::selStream) {
-                               MovePositionTo(MovePositionSoVisible(SelectionPosition(sel.MainCaret() - 1), 
-1));
-                       } else {
-                               MovePositionTo(MovePositionSoVisible(
-                                       
SelectionPosition((sel.LimitsForRectangularElseMain().start).Position() - 1), -1));
-                       }
-               } else {
-                       MovePositionTo(sel.LimitsForRectangularElseMain().start);
-               }
-               SetLastXChosen();
-               break;
        case SCI_CHARLEFTEXTEND:
-               if (pdoc->IsLineEndPosition(sel.MainCaret()) && sel.RangeMain().caret.VirtualSpace()) {
-                       SelectionPosition spCaret = sel.RangeMain().caret;
-                       spCaret.SetVirtualSpace(spCaret.VirtualSpace() - 1);
-                       MovePositionTo(spCaret, Selection::selStream);
-               } else {
-                       MovePositionTo(MovePositionSoVisible(SelectionPosition(sel.MainCaret() - 1), -1), 
Selection::selStream);
-               }
-               SetLastXChosen();
-               break;
        case SCI_CHARLEFTRECTEXTEND:
-               if (pdoc->IsLineEndPosition(sel.MainCaret()) && sel.RangeMain().caret.VirtualSpace()) {
-                       SelectionPosition spCaret = sel.RangeMain().caret;
-                       spCaret.SetVirtualSpace(spCaret.VirtualSpace() - 1);
-                       MovePositionTo(spCaret, Selection::selRectangle);
-               } else {
-                       MovePositionTo(MovePositionSoVisible(SelectionPosition(sel.MainCaret() - 1), -1), 
Selection::selRectangle);
-               }
-               SetLastXChosen();
-               break;
        case SCI_CHARRIGHT:
-               if (SelectionEmpty() || sel.MoveExtends()) {
-                       if ((virtualSpaceOptions & SCVS_USERACCESSIBLE) && 
pdoc->IsLineEndPosition(sel.MainCaret())) {
-                               SelectionPosition spCaret = sel.RangeMain().caret;
-                               spCaret.SetVirtualSpace(spCaret.VirtualSpace() + 1);
-                               MovePositionTo(spCaret);
-                       } else if (sel.MoveExtends() && sel.selType == Selection::selStream) {
-                               MovePositionTo(MovePositionSoVisible(SelectionPosition(sel.MainCaret() + 1), 
1));
-                       } else {
-                               MovePositionTo(MovePositionSoVisible(
-                                       SelectionPosition((sel.LimitsForRectangularElseMain().end).Position() 
+ 1), 1));
-                       }
-               } else {
-                       MovePositionTo(sel.LimitsForRectangularElseMain().end);
-               }
-               SetLastXChosen();
-               break;
        case SCI_CHARRIGHTEXTEND:
-               if ((virtualSpaceOptions & SCVS_USERACCESSIBLE) && pdoc->IsLineEndPosition(sel.MainCaret())) {
-                       SelectionPosition spCaret = sel.RangeMain().caret;
-                       spCaret.SetVirtualSpace(spCaret.VirtualSpace() + 1);
-                       MovePositionTo(spCaret, Selection::selStream);
-               } else {
-                       MovePositionTo(MovePositionSoVisible(SelectionPosition(sel.MainCaret() + 1), 1), 
Selection::selStream);
-               }
-               SetLastXChosen();
-               break;
        case SCI_CHARRIGHTRECTEXTEND:
-               if ((virtualSpaceOptions & SCVS_RECTANGULARSELECTION) && 
pdoc->IsLineEndPosition(sel.MainCaret())) {
-                       SelectionPosition spCaret = sel.RangeMain().caret;
-                       spCaret.SetVirtualSpace(spCaret.VirtualSpace() + 1);
-                       MovePositionTo(spCaret, Selection::selRectangle);
-               } else {
-                       MovePositionTo(MovePositionSoVisible(SelectionPosition(sel.MainCaret() + 1), 1), 
Selection::selRectangle);
-               }
-               SetLastXChosen();
-               break;
        case SCI_WORDLEFT:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(sel.MainCaret(), -1), -1));
-               SetLastXChosen();
-               break;
        case SCI_WORDLEFTEXTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(sel.MainCaret(), -1), -1), 
Selection::selStream);
-               SetLastXChosen();
-               break;
        case SCI_WORDRIGHT:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(sel.MainCaret(), 1), 1));
-               SetLastXChosen();
-               break;
        case SCI_WORDRIGHTEXTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(sel.MainCaret(), 1), 1), 
Selection::selStream);
-               SetLastXChosen();
-               break;
-
        case SCI_WORDLEFTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(sel.MainCaret(), -1), -1));
-               SetLastXChosen();
-               break;
        case SCI_WORDLEFTENDEXTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(sel.MainCaret(), -1), -1), 
Selection::selStream);
-               SetLastXChosen();
-               break;
        case SCI_WORDRIGHTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(sel.MainCaret(), 1), 1));
-               SetLastXChosen();
-               break;
        case SCI_WORDRIGHTENDEXTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(sel.MainCaret(), 1), 1), 
Selection::selStream);
-               SetLastXChosen();
-               break;
-
+       case SCI_WORDPARTLEFT:
+       case SCI_WORDPARTLEFTEXTEND:
+       case SCI_WORDPARTRIGHT:
+       case SCI_WORDPARTRIGHTEXTEND:
        case SCI_HOME:
-               MovePositionTo(pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret())));
-               SetLastXChosen();
-               break;
        case SCI_HOMEEXTEND:
-               MovePositionTo(pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret())), 
Selection::selStream);
-               SetLastXChosen();
-               break;
        case SCI_HOMERECTEXTEND:
-               MovePositionTo(pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret())), 
Selection::selRectangle);
-               SetLastXChosen();
-               break;
+       case SCI_HOMEDISPLAY:
+       case SCI_HOMEDISPLAYEXTEND:
+       case SCI_HOMEWRAP:
+       case SCI_HOMEWRAPEXTEND:
+       case SCI_VCHOME:
+       case SCI_VCHOMEEXTEND:
+       case SCI_VCHOMERECTEXTEND:
+       case SCI_VCHOMEDISPLAY:
+       case SCI_VCHOMEDISPLAYEXTEND:
+       case SCI_VCHOMEWRAP:
+       case SCI_VCHOMEWRAPEXTEND:
        case SCI_LINEEND:
-               MovePositionTo(pdoc->LineEndPosition(sel.MainCaret()));
-               SetLastXChosen();
-               break;
        case SCI_LINEENDEXTEND:
-               MovePositionTo(pdoc->LineEndPosition(sel.MainCaret()), Selection::selStream);
-               SetLastXChosen();
-               break;
        case SCI_LINEENDRECTEXTEND:
-               MovePositionTo(pdoc->LineEndPosition(sel.MainCaret()), Selection::selRectangle);
-               SetLastXChosen();
-               break;
-       case SCI_HOMEWRAP: {
-                       SelectionPosition homePos = 
MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), true), -1);
-                       if (sel.RangeMain().caret <= homePos)
-                               homePos = 
SelectionPosition(pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret())));
-                       MovePositionTo(homePos);
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_HOMEWRAPEXTEND: {
-                       SelectionPosition homePos = 
MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), true), -1);
-                       if (sel.RangeMain().caret <= homePos)
-                               homePos = 
SelectionPosition(pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret())));
-                       MovePositionTo(homePos, Selection::selStream);
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_LINEENDWRAP: {
-                       SelectionPosition endPos = MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), 
false), 1);
-                       SelectionPosition realEndPos = 
SelectionPosition(pdoc->LineEndPosition(sel.MainCaret()));
-                       if (endPos > realEndPos      // if moved past visible EOLs
-                               || sel.RangeMain().caret >= endPos) // if at end of display line already
-                               endPos = realEndPos;
-                       MovePositionTo(endPos);
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_LINEENDWRAPEXTEND: {
-                       SelectionPosition endPos = MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), 
false), 1);
-                       SelectionPosition realEndPos = 
SelectionPosition(pdoc->LineEndPosition(sel.MainCaret()));
-                       if (endPos > realEndPos      // if moved past visible EOLs
-                               || sel.RangeMain().caret >= endPos) // if at end of display line already
-                               endPos = realEndPos;
-                       MovePositionTo(endPos, Selection::selStream);
-                       SetLastXChosen();
-               }
-               break;
+       case SCI_LINEENDDISPLAY:
+       case SCI_LINEENDDISPLAYEXTEND:
+       case SCI_LINEENDWRAP:
+       case SCI_LINEENDWRAPEXTEND:
+               return HorizontalMove(iMessage);
+
        case SCI_DOCUMENTSTART:
                MovePositionTo(0);
                SetLastXChosen();
@@ -5493,7 +3733,6 @@ int Editor::KeyCommand(unsigned int iMessage) {
                break;
        case SCI_EDITTOGGLEOVERTYPE:
                inOverstrike = !inOverstrike;
-               DropCaret();
                ShowCaretAtCurrentPosition();
                ContainerNeedsUpdate(SC_UPDATE_CONTENT);
                NotifyUpdateUI();
@@ -5501,6 +3740,11 @@ int Editor::KeyCommand(unsigned int iMessage) {
        case SCI_CANCEL:                // Cancel any modes - handled in subclass
                // Also unselect text
                CancelModes();
+               if ((sel.Count() > 1) && !sel.IsRectangular()) {
+                       // Drop additional selections
+                       InvalidateWholeSelection();
+                       sel.DropAdditionalRanges();
+               }
                break;
        case SCI_DELETEBACK:
                DelCharBack(true);
@@ -5538,38 +3782,6 @@ int Editor::KeyCommand(unsigned int iMessage) {
        case SCI_FORMFEED:
                AddChar('\f');
                break;
-       case SCI_VCHOME:
-               MovePositionTo(pdoc->VCHomePosition(sel.MainCaret()));
-               SetLastXChosen();
-               break;
-       case SCI_VCHOMEEXTEND:
-               MovePositionTo(pdoc->VCHomePosition(sel.MainCaret()), Selection::selStream);
-               SetLastXChosen();
-               break;
-       case SCI_VCHOMERECTEXTEND:
-               MovePositionTo(pdoc->VCHomePosition(sel.MainCaret()), Selection::selRectangle);
-               SetLastXChosen();
-               break;
-       case SCI_VCHOMEWRAP: {
-                       SelectionPosition homePos = SelectionPosition(pdoc->VCHomePosition(sel.MainCaret()));
-                       SelectionPosition viewLineStart = 
MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), true), -1);
-                       if ((viewLineStart < sel.RangeMain().caret) && (viewLineStart > homePos))
-                               homePos = viewLineStart;
-
-                       MovePositionTo(homePos);
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_VCHOMEWRAPEXTEND: {
-                       SelectionPosition homePos = SelectionPosition(pdoc->VCHomePosition(sel.MainCaret()));
-                       SelectionPosition viewLineStart = 
MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), true), -1);
-                       if ((viewLineStart < sel.RangeMain().caret) && (viewLineStart > homePos))
-                               homePos = viewLineStart;
-
-                       MovePositionTo(homePos, Selection::selStream);
-                       SetLastXChosen();
-               }
-               break;
        case SCI_ZOOMIN:
                if (vs.zoomLevel < 20) {
                        vs.zoomLevel++;
@@ -5584,71 +3796,44 @@ int Editor::KeyCommand(unsigned int iMessage) {
                        NotifyZoom();
                }
                break;
-       case SCI_DELWORDLEFT: {
-                       int startWord = pdoc->NextWordStart(sel.MainCaret(), -1);
-                       pdoc->DeleteChars(startWord, sel.MainCaret() - startWord);
-                       sel.RangeMain().ClearVirtualSpace();
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_DELWORDRIGHT: {
-                       UndoGroup ug(pdoc);
-                       sel.RangeMain().caret = SelectionPosition(
-                               InsertSpace(sel.RangeMain().caret.Position(), 
sel.RangeMain().caret.VirtualSpace()));
-                       sel.RangeMain().anchor = sel.RangeMain().caret;
-                       int endWord = pdoc->NextWordStart(sel.MainCaret(), 1);
-                       pdoc->DeleteChars(sel.MainCaret(), endWord - sel.MainCaret());
-               }
-               break;
-       case SCI_DELWORDRIGHTEND: {
-                       UndoGroup ug(pdoc);
-                       sel.RangeMain().caret = SelectionPosition(
-                               InsertSpace(sel.RangeMain().caret.Position(), 
sel.RangeMain().caret.VirtualSpace()));
-                       int endWord = pdoc->NextWordEnd(sel.MainCaret(), 1);
-                       pdoc->DeleteChars(sel.MainCaret(), endWord - sel.MainCaret());
-               }
-               break;
-       case SCI_DELLINELEFT: {
-                       int line = pdoc->LineFromPosition(sel.MainCaret());
-                       int start = pdoc->LineStart(line);
-                       pdoc->DeleteChars(start, sel.MainCaret() - start);
-                       sel.RangeMain().ClearVirtualSpace();
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_DELLINERIGHT: {
-                       int line = pdoc->LineFromPosition(sel.MainCaret());
-                       int end = pdoc->LineEnd(line);
-                       pdoc->DeleteChars(sel.MainCaret(), end - sel.MainCaret());
-               }
-               break;
+
+       case SCI_DELWORDLEFT:
+       case SCI_DELWORDRIGHT:
+       case SCI_DELWORDRIGHTEND:
+       case SCI_DELLINELEFT:
+       case SCI_DELLINERIGHT:
+               return DelWordOrLine(iMessage);
+
        case SCI_LINECOPY: {
-                       int lineStart = pdoc->LineFromPosition(SelectionStart().Position());
-                       int lineEnd = pdoc->LineFromPosition(SelectionEnd().Position());
+                       const Sci::Line lineStart = pdoc->LineFromPosition(SelectionStart().Position());
+                       const Sci::Line lineEnd = pdoc->LineFromPosition(SelectionEnd().Position());
                        CopyRangeToClipboard(pdoc->LineStart(lineStart),
                                pdoc->LineStart(lineEnd + 1));
                }
                break;
        case SCI_LINECUT: {
-                       int lineStart = pdoc->LineFromPosition(SelectionStart().Position());
-                       int lineEnd = pdoc->LineFromPosition(SelectionEnd().Position());
-                       int start = pdoc->LineStart(lineStart);
-                       int end = pdoc->LineStart(lineEnd + 1);
+                       const Sci::Line lineStart = pdoc->LineFromPosition(SelectionStart().Position());
+                       const Sci::Line lineEnd = pdoc->LineFromPosition(SelectionEnd().Position());
+                       const Sci::Position start = pdoc->LineStart(lineStart);
+                       const Sci::Position end = pdoc->LineStart(lineEnd + 1);
                        SetSelection(start, end);
                        Cut();
                        SetLastXChosen();
                }
                break;
        case SCI_LINEDELETE: {
-                       int line = pdoc->LineFromPosition(sel.MainCaret());
-                       int start = pdoc->LineStart(line);
-                       int end = pdoc->LineStart(line + 1);
+                       const Sci::Line line = pdoc->LineFromPosition(sel.MainCaret());
+                       const Sci::Position start = pdoc->LineStart(line);
+                       const Sci::Position end = pdoc->LineStart(line + 1);
                        pdoc->DeleteChars(start, end - start);
                }
                break;
        case SCI_LINETRANSPOSE:
                LineTranspose();
                break;
+       case SCI_LINEREVERSE:
+               LineReverse();
+               break;
        case SCI_LINEDUPLICATE:
                Duplicate(true);
                break;
@@ -5661,62 +3846,6 @@ int Editor::KeyCommand(unsigned int iMessage) {
        case SCI_UPPERCASE:
                ChangeCaseOfSelection(cmUpper);
                break;
-       case SCI_WORDPARTLEFT:
-               MovePositionTo(MovePositionSoVisible(pdoc->WordPartLeft(sel.MainCaret()), -1));
-               SetLastXChosen();
-               break;
-       case SCI_WORDPARTLEFTEXTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->WordPartLeft(sel.MainCaret()), -1), 
Selection::selStream);
-               SetLastXChosen();
-               break;
-       case SCI_WORDPARTRIGHT:
-               MovePositionTo(MovePositionSoVisible(pdoc->WordPartRight(sel.MainCaret()), 1));
-               SetLastXChosen();
-               break;
-       case SCI_WORDPARTRIGHTEXTEND:
-               MovePositionTo(MovePositionSoVisible(pdoc->WordPartRight(sel.MainCaret()), 1), 
Selection::selStream);
-               SetLastXChosen();
-               break;
-       case SCI_HOMEDISPLAY:
-               MovePositionTo(MovePositionSoVisible(
-                           StartEndDisplayLine(sel.MainCaret(), true), -1));
-               SetLastXChosen();
-               break;
-       case SCI_VCHOMEDISPLAY: {
-                       SelectionPosition homePos = SelectionPosition(pdoc->VCHomePosition(sel.MainCaret()));
-                       SelectionPosition viewLineStart = 
MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), true), -1);
-                       if (viewLineStart > homePos)
-                               homePos = viewLineStart;
-
-                       MovePositionTo(homePos);
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_HOMEDISPLAYEXTEND:
-               MovePositionTo(MovePositionSoVisible(
-                           StartEndDisplayLine(sel.MainCaret(), true), -1), Selection::selStream);
-               SetLastXChosen();
-               break;
-       case SCI_VCHOMEDISPLAYEXTEND: {
-                       SelectionPosition homePos = SelectionPosition(pdoc->VCHomePosition(sel.MainCaret()));
-                       SelectionPosition viewLineStart = 
MovePositionSoVisible(StartEndDisplayLine(sel.MainCaret(), true), -1);
-                       if (viewLineStart > homePos)
-                               homePos = viewLineStart;
-
-                       MovePositionTo(homePos, Selection::selStream);
-                       SetLastXChosen();
-               }
-               break;
-       case SCI_LINEENDDISPLAY:
-               MovePositionTo(MovePositionSoVisible(
-                           StartEndDisplayLine(sel.MainCaret(), false), 1));
-               SetLastXChosen();
-               break;
-       case SCI_LINEENDDISPLAYEXTEND:
-               MovePositionTo(MovePositionSoVisible(
-                           StartEndDisplayLine(sel.MainCaret(), false), 1), Selection::selStream);
-               SetLastXChosen();
-               break;
        case SCI_SCROLLTOSTART:
                ScrollTo(0);
                break;
@@ -5737,7 +3866,7 @@ int Editor::KeyDownWithModifiers(int key, int modifiers, bool *consumed) {
        if (msg) {
                if (consumed)
                        *consumed = true;
-               return WndProc(msg, 0, 0);
+               return static_cast<int>(WndProc(msg, 0, 0));
        } else {
                if (consumed)
                        *consumed = false;
@@ -5746,17 +3875,15 @@ int Editor::KeyDownWithModifiers(int key, int modifiers, bool *consumed) {
 }
 
 int Editor::KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed) {
-       int modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) |
-               (alt ? SCI_ALT : 0);
-       return KeyDownWithModifiers(key, modifiers, consumed);
+       return KeyDownWithModifiers(key, ModifierFlags(shift, ctrl, alt), consumed);
 }
 
 void Editor::Indent(bool forwards) {
        UndoGroup ug(pdoc);
        for (size_t r=0; r<sel.Count(); r++) {
-               int lineOfAnchor = pdoc->LineFromPosition(sel.Range(r).anchor.Position());
-               int caretPosition = sel.Range(r).caret.Position();
-               int lineCurrentPos = pdoc->LineFromPosition(caretPosition);
+               Sci::Line lineOfAnchor = pdoc->LineFromPosition(sel.Range(r).anchor.Position());
+               Sci::Position caretPosition = sel.Range(r).caret.Position();
+               Sci::Line lineCurrentPos = pdoc->LineFromPosition(caretPosition);
                if (lineOfAnchor == lineCurrentPos) {
                        if (forwards) {
                                pdoc->DeleteChars(sel.Range(r).Start().Position(), sel.Range(r).Length());
@@ -5765,47 +3892,48 @@ void Editor::Indent(bool forwards) {
                                                pdoc->tabIndents) {
                                        int indentation = pdoc->GetLineIndentation(lineCurrentPos);
                                        int indentationStep = pdoc->IndentSize();
-                                       pdoc->SetLineIndentation(lineCurrentPos, indentation + 
indentationStep - indentation % indentationStep);
-                                       sel.Range(r) = 
SelectionRange(pdoc->GetLineIndentPosition(lineCurrentPos));
+                                       const Sci::Position posSelect = pdoc->SetLineIndentation(
+                                               lineCurrentPos, indentation + indentationStep - indentation % 
indentationStep);
+                                       sel.Range(r) = SelectionRange(posSelect);
                                } else {
                                        if (pdoc->useTabs) {
-                                               pdoc->InsertChar(caretPosition, '\t');
-                                               sel.Range(r) = SelectionRange(caretPosition+1);
+                                               const Sci::Position lengthInserted = 
pdoc->InsertString(caretPosition, "\t", 1);
+                                               sel.Range(r) = SelectionRange(caretPosition + lengthInserted);
                                        } else {
                                                int numSpaces = (pdoc->tabInChars) -
                                                                (pdoc->GetColumn(caretPosition) % 
(pdoc->tabInChars));
                                                if (numSpaces < 1)
                                                        numSpaces = pdoc->tabInChars;
-                                               for (int i = 0; i < numSpaces; i++) {
-                                                       pdoc->InsertChar(caretPosition + i, ' ');
-                                               }
-                                               sel.Range(r) = SelectionRange(caretPosition+numSpaces);
+                                               const std::string spaceText(numSpaces, ' ');
+                                               const Sci::Position lengthInserted = 
pdoc->InsertString(caretPosition, spaceText.c_str(),
+                                                       static_cast<Sci::Position>(spaceText.length()));
+                                               sel.Range(r) = SelectionRange(caretPosition + lengthInserted);
                                        }
                                }
                        } else {
                                if (pdoc->GetColumn(caretPosition) <= 
pdoc->GetLineIndentation(lineCurrentPos) &&
                                                pdoc->tabIndents) {
-                                       int indentation = pdoc->GetLineIndentation(lineCurrentPos);
-                                       int indentationStep = pdoc->IndentSize();
-                                       pdoc->SetLineIndentation(lineCurrentPos, indentation - 
indentationStep);
-                                       sel.Range(r) = 
SelectionRange(pdoc->GetLineIndentPosition(lineCurrentPos));
+                                       const int indentation = pdoc->GetLineIndentation(lineCurrentPos);
+                                       const int indentationStep = pdoc->IndentSize();
+                                       const Sci::Position posSelect = 
pdoc->SetLineIndentation(lineCurrentPos, indentation - indentationStep);
+                                       sel.Range(r) = SelectionRange(posSelect);
                                } else {
-                                       int newColumn = ((pdoc->GetColumn(caretPosition) - 1) / 
pdoc->tabInChars) *
+                                       Sci::Position newColumn = ((pdoc->GetColumn(caretPosition) - 1) / 
pdoc->tabInChars) *
                                                        pdoc->tabInChars;
                                        if (newColumn < 0)
                                                newColumn = 0;
-                                       int newPos = caretPosition;
+                                       Sci::Position newPos = caretPosition;
                                        while (pdoc->GetColumn(newPos) > newColumn)
                                                newPos--;
                                        sel.Range(r) = SelectionRange(newPos);
                                }
                        }
                } else {        // Multiline
-                       int anchorPosOnLine = sel.Range(r).anchor.Position() - pdoc->LineStart(lineOfAnchor);
-                       int currentPosPosOnLine = caretPosition - pdoc->LineStart(lineCurrentPos);
+                       const Sci::Position anchorPosOnLine = sel.Range(r).anchor.Position() - 
pdoc->LineStart(lineOfAnchor);
+                       const Sci::Position currentPosPosOnLine = caretPosition - 
pdoc->LineStart(lineCurrentPos);
                        // Multiple lines selected so indent / dedent
-                       int lineTopSel = Platform::Minimum(lineOfAnchor, lineCurrentPos);
-                       int lineBottomSel = Platform::Maximum(lineOfAnchor, lineCurrentPos);
+                       const Sci::Line lineTopSel = std::min(lineOfAnchor, lineCurrentPos);
+                       Sci::Line lineBottomSel = std::max(lineOfAnchor, lineCurrentPos);
                        if (pdoc->LineStart(lineBottomSel) == sel.Range(r).anchor.Position() || 
pdoc->LineStart(lineBottomSel) == caretPosition)
                                lineBottomSel--;        // If not selecting any characters on a line, do not 
indent
                        pdoc->Indent(forwards, lineBottomSel, lineTopSel);
@@ -5822,6 +3950,7 @@ void Editor::Indent(bool forwards) {
                        }
                }
        }
+       ContainerNeedsUpdate(SC_UPDATE_SELECTION);
 }
 
 class CaseFolderASCII : public CaseFolderTable {
@@ -5829,7 +3958,7 @@ public:
        CaseFolderASCII() {
                StandardASCII();
        }
-       ~CaseFolderASCII() {
+       ~CaseFolderASCII() override {
        }
 };
 
@@ -5846,24 +3975,28 @@ CaseFolder *Editor::CaseFolderForEncoding() {
 long Editor::FindText(
     uptr_t wParam,             ///< Search modes : @c SCFIND_MATCHCASE, @c SCFIND_WHOLEWORD,
     ///< @c SCFIND_WORDSTART, @c SCFIND_REGEXP or @c SCFIND_POSIX.
-    sptr_t lParam) {   ///< @c TextToFind structure: The text to search for in the given range.
+    sptr_t lParam) {   ///< @c Sci_TextToFind structure: The text to search for in the given range.
 
        Sci_TextToFind *ft = reinterpret_cast<Sci_TextToFind *>(lParam);
-       int lengthFound = istrlen(ft->lpstrText);
+       Sci::Position lengthFound = istrlen(ft->lpstrText);
        if (!pdoc->HasCaseFolder())
                pdoc->SetCaseFolder(CaseFolderForEncoding());
-       int pos = pdoc->FindText(ft->chrg.cpMin, ft->chrg.cpMax, ft->lpstrText,
-               (wParam & SCFIND_MATCHCASE) != 0,
-               (wParam & SCFIND_WHOLEWORD) != 0,
-               (wParam & SCFIND_WORDSTART) != 0,
-               (wParam & SCFIND_REGEXP) != 0,
-               wParam,
-               &lengthFound);
-       if (pos != -1) {
-               ft->chrgText.cpMin = pos;
-               ft->chrgText.cpMax = pos + lengthFound;
+       try {
+               long pos = pdoc->FindText(
+                       static_cast<Sci::Position>(ft->chrg.cpMin),
+                       static_cast<Sci::Position>(ft->chrg.cpMax),
+                       ft->lpstrText,
+                       static_cast<int>(wParam),
+                       &lengthFound);
+               if (pos != -1) {
+                       ft->chrgText.cpMin = pos;
+                       ft->chrgText.cpMax = pos + lengthFound;
+               }
+               return static_cast<int>(pos);
+       } catch (RegexError &) {
+               errorStatus = SC_STATUS_WARN_REGEX;
+               return -1;
        }
-       return pos;
 }
 
 /**
@@ -5893,29 +4026,26 @@ long Editor::SearchText(
     sptr_t lParam) {                   ///< The text to search for.
 
        const char *txt = reinterpret_cast<char *>(lParam);
-       int pos;
-       int lengthFound = istrlen(txt);
+       long pos;
+       Sci::Position lengthFound = istrlen(txt);
        if (!pdoc->HasCaseFolder())
                pdoc->SetCaseFolder(CaseFolderForEncoding());
-       if (iMessage == SCI_SEARCHNEXT) {
-               pos = pdoc->FindText(searchAnchor, pdoc->Length(), txt,
-                       (wParam & SCFIND_MATCHCASE) != 0,
-                       (wParam & SCFIND_WHOLEWORD) != 0,
-                       (wParam & SCFIND_WORDSTART) != 0,
-                       (wParam & SCFIND_REGEXP) != 0,
-                       wParam,
-                       &lengthFound);
-       } else {
-               pos = pdoc->FindText(searchAnchor, 0, txt,
-                       (wParam & SCFIND_MATCHCASE) != 0,
-                       (wParam & SCFIND_WHOLEWORD) != 0,
-                       (wParam & SCFIND_WORDSTART) != 0,
-                       (wParam & SCFIND_REGEXP) != 0,
-                       wParam,
-                       &lengthFound);
+       try {
+               if (iMessage == SCI_SEARCHNEXT) {
+                       pos = pdoc->FindText(searchAnchor, pdoc->Length(), txt,
+                                       static_cast<int>(wParam),
+                                       &lengthFound);
+               } else {
+                       pos = pdoc->FindText(searchAnchor, 0, txt,
+                                       static_cast<int>(wParam),
+                                       &lengthFound);
+               }
+       } catch (RegexError &) {
+               errorStatus = SC_STATUS_WARN_REGEX;
+               return -1;
        }
        if (pos != -1) {
-               SetSelection(pos, pos + lengthFound);
+               SetSelection(static_cast<int>(pos), static_cast<int>(pos + lengthFound));
        }
 
        return pos;
@@ -5923,15 +4053,15 @@ long Editor::SearchText(
 
 std::string Editor::CaseMapString(const std::string &s, int caseMapping) {
        std::string ret(s);
-       for (size_t i=0; i<ret.size(); i++) {
+       for (char &ch : ret) {
                switch (caseMapping) {
                        case cmUpper:
-                               if (ret[i] >= 'a' && ret[i] <= 'z')
-                                       ret[i] = static_cast<char>(ret[i] - 'a' + 'A');
+                               if (ch >= 'a' && ch <= 'z')
+                                       ch = static_cast<char>(ch - 'a' + 'A');
                                break;
                        case cmLower:
-                               if (ret[i] >= 'A' && ret[i] <= 'Z')
-                                       ret[i] = static_cast<char>(ret[i] - 'A' + 'a');
+                               if (ch >= 'A' && ch <= 'Z')
+                                       ch = static_cast<char>(ch - 'A' + 'a');
                                break;
                }
        }
@@ -5942,26 +4072,27 @@ std::string Editor::CaseMapString(const std::string &s, int caseMapping) {
  * Search for text in the target range of the document.
  * @return The position of the found text, -1 if not found.
  */
-long Editor::SearchInTarget(const char *text, int length) {
-       int lengthFound = length;
+long Editor::SearchInTarget(const char *text, Sci::Position length) {
+       Sci::Position lengthFound = length;
 
        if (!pdoc->HasCaseFolder())
                pdoc->SetCaseFolder(CaseFolderForEncoding());
-       int pos = pdoc->FindText(targetStart, targetEnd, text,
-               (searchFlags & SCFIND_MATCHCASE) != 0,
-               (searchFlags & SCFIND_WHOLEWORD) != 0,
-               (searchFlags & SCFIND_WORDSTART) != 0,
-               (searchFlags & SCFIND_REGEXP) != 0,
-               searchFlags,
-               &lengthFound);
-       if (pos != -1) {
-               targetStart = pos;
-               targetEnd = pos + lengthFound;
+       try {
+               long pos = pdoc->FindText(targetStart, targetEnd, text,
+                               searchFlags,
+                               &lengthFound);
+               if (pos != -1) {
+                       targetStart = static_cast<int>(pos);
+                       targetEnd = static_cast<int>(pos + lengthFound);
+               }
+               return pos;
+       } catch (RegexError &) {
+               errorStatus = SC_STATUS_WARN_REGEX;
+               return -1;
        }
-       return pos;
 }
 
-void Editor::GoToLine(int lineNo) {
+void Editor::GoToLine(Sci::Line lineNo) {
        if (lineNo > pdoc->LinesTotal())
                lineNo = pdoc->LinesTotal();
        if (lineNo < 0)
@@ -5971,17 +4102,17 @@ void Editor::GoToLine(int lineNo) {
        EnsureCaretVisible();
 }
 
-static bool Close(Point pt1, Point pt2) {
-       if (abs(pt1.x - pt2.x) > 3)
+static bool Close(Point pt1, Point pt2, Point threshold) {
+       if (std::abs(pt1.x - pt2.x) > threshold.x)
                return false;
-       if (abs(pt1.y - pt2.y) > 3)
+       if (std::abs(pt1.y - pt2.y) > threshold.y)
                return false;
        return true;
 }
 
-std::string Editor::RangeText(int start, int end) const {
+std::string Editor::RangeText(Sci::Position start, Sci::Position end) const {
        if (start < end) {
-               int len = end - start;
+               Sci::Position len = end - start;
                std::string ret(len, '\0');
                for (int i = 0; i < len; i++) {
                        ret[i] = pdoc->CharAt(start + i);
@@ -5994,9 +4125,9 @@ std::string Editor::RangeText(int start, int end) const {
 void Editor::CopySelectionRange(SelectionText *ss, bool allowLineCopy) {
        if (sel.Empty()) {
                if (allowLineCopy) {
-                       int currentLine = pdoc->LineFromPosition(sel.MainCaret());
-                       int start = pdoc->LineStart(currentLine);
-                       int end = pdoc->LineEnd(currentLine);
+                       Sci::Line currentLine = pdoc->LineFromPosition(sel.MainCaret());
+                       Sci::Position start = pdoc->LineStart(currentLine);
+                       Sci::Position end = pdoc->LineEnd(currentLine);
 
                        std::string text = RangeText(start, end);
                        if (pdoc->eolMode != SC_EOL_LF)
@@ -6011,9 +4142,8 @@ void Editor::CopySelectionRange(SelectionText *ss, bool allowLineCopy) {
                std::vector<SelectionRange> rangesInOrder = sel.RangesCopy();
                if (sel.selType == Selection::selRectangle)
                        std::sort(rangesInOrder.begin(), rangesInOrder.end());
-               for (size_t r=0; r<rangesInOrder.size(); r++) {
-                       SelectionRange current = rangesInOrder[r];
-                       text.append(RangeText(current.Start().Position(), current.End().Position()));
+               for (const SelectionRange &current : rangesInOrder) {
+                               text.append(RangeText(current.Start().Position(), current.End().Position()));
                        if (sel.selType == Selection::selRectangle) {
                                if (pdoc->eolMode != SC_EOL_LF)
                                        text.push_back('\r');
@@ -6026,7 +4156,7 @@ void Editor::CopySelectionRange(SelectionText *ss, bool allowLineCopy) {
        }
 }
 
-void Editor::CopyRangeToClipboard(int start, int end) {
+void Editor::CopyRangeToClipboard(Sci::Position start, Sci::Position end) {
        start = pdoc->ClampPositionIntoDocument(start);
        end = pdoc->ClampPositionIntoDocument(end);
        SelectionText selectedText;
@@ -6050,7 +4180,13 @@ void Editor::SetDragPosition(SelectionPosition newPos) {
        }
        if (!(posDrag == newPos)) {
                caret.on = true;
-               SetTicking(true);
+               if (FineTickerAvailable()) {
+                       FineTickerCancel(tickCaret);
+                       if ((caret.active) && (caret.period > 0) && (newPos.Position() < 0))
+                               FineTickerStart(tickCaret, caret.period, caret.period/10);
+               } else {
+                       SetTicking(true);
+               }
                InvalidateCaret();
                posDrag = newPos;
                InvalidateCaret();
@@ -6065,9 +4201,9 @@ void Editor::DisplayCursor(Window::Cursor c) {
 }
 
 bool Editor::DragThreshold(Point ptStart, Point ptNow) {
-       int xMove = ptStart.x - ptNow.x;
-       int yMove = ptStart.y - ptNow.y;
-       int distanceSquared = xMove * xMove + yMove * yMove;
+       const int xMove = static_cast<int>(ptStart.x - ptNow.x);
+       const int yMove = static_cast<int>(ptStart.y - ptNow.y);
+       const int distanceSquared = xMove * xMove + yMove * yMove;
        return distanceSquared > 16;
 }
 
@@ -6082,9 +4218,9 @@ void Editor::DropAt(SelectionPosition position, const char *value, size_t length
        if (inDragDrop == ddDragging)
                dropWentOutside = false;
 
-       bool positionWasInSelection = PositionInSelection(position.Position());
+       const bool positionWasInSelection = PositionInSelection(position.Position());
 
-       bool positionOnEdgeOfSelection =
+       const bool positionOnEdgeOfSelection =
            (position == SelectionStart()) || (position == SelectionEnd());
 
        if ((inDragDrop != ddDragging) || !(positionWasInSelection) ||
@@ -6117,16 +4253,20 @@ void Editor::DropAt(SelectionPosition position, const char *value, size_t length
                }
                position = positionAfterDeletion;
 
+               std::string convertedText = Document::TransformLineEnds(value, lengthValue, pdoc->eolMode);
+
                if (rectangular) {
-                       PasteRectangular(position, value, static_cast<int>(lengthValue));
+                       PasteRectangular(position, convertedText.c_str(), 
static_cast<Sci::Position>(convertedText.length()));
                        // Should try to select new rectangle but it may not be a rectangle now so just 
select the drop position
                        SetEmptySelection(position);
                } else {
                        position = MovePositionOutsideChar(position, sel.MainCaret() - position.Position());
-                       position = SelectionPosition(InsertSpace(position.Position(), 
position.VirtualSpace()));
-                       if (pdoc->InsertString(position.Position(), value, static_cast<int>(lengthValue))) {
+                       position = RealizeVirtualSpace(position);
+                       const Sci::Position lengthInserted = pdoc->InsertString(
+                               position.Position(), convertedText.c_str(), 
static_cast<int>(convertedText.length()));
+                       if (lengthInserted > 0) {
                                SelectionPosition posAfterInsertion = position;
-                               posAfterInsertion.Add(static_cast<int>(lengthValue));
+                               posAfterInsertion.Add(lengthInserted);
                                SetSelection(posAfterInsertion, position);
                        }
                }
@@ -6142,7 +4282,7 @@ void Editor::DropAt(SelectionPosition position, const char *value, bool moving,
 /**
  * @return true if given position is inside the selection,
  */
-bool Editor::PositionInSelection(int pos) {
+bool Editor::PositionInSelection(Sci::Position pos) {
        pos = MovePositionOutsideChar(pos, sel.MainCaret() - pos);
        for (size_t r=0; r<sel.Count(); r++) {
                if (sel.Range(r).Contains(pos))
@@ -6152,10 +4292,10 @@ bool Editor::PositionInSelection(int pos) {
 }
 
 bool Editor::PointInSelection(Point pt) {
-       SelectionPosition pos = SPositionFromLocation(pt, false, true);
-       Point ptPos = LocationFromPosition(pos);
+       const SelectionPosition pos = SPositionFromLocation(pt, false, true);
+       const Point ptPos = LocationFromPosition(pos);
        for (size_t r=0; r<sel.Count(); r++) {
-               SelectionRange range = sel.Range(r);
+               const SelectionRange &range = sel.Range(r);
                if (range.Contains(pos)) {
                        bool hit = true;
                        if (pos == range.Start()) {
@@ -6177,13 +4317,13 @@ bool Editor::PointInSelection(Point pt) {
        return false;
 }
 
-bool Editor::PointInSelMargin(Point pt) {
+bool Editor::PointInSelMargin(Point pt) const {
        // Really means: "Point in a margin"
        if (vs.fixedColumnWidth > 0) {  // There is a margin
                PRectangle rcSelMargin = GetClientRectangle();
-               rcSelMargin.right = vs.textStart - vs.leftMarginWidth;
-               rcSelMargin.left = vs.textStart - vs.fixedColumnWidth;
-               return rcSelMargin.Contains(pt);
+               rcSelMargin.right = static_cast<XYPOSITION>(vs.textStart - vs.leftMarginWidth);
+               rcSelMargin.left = static_cast<XYPOSITION>(vs.textStart - vs.fixedColumnWidth);
+               return rcSelMargin.ContainsWholePixel(pt);
        } else {
                return false;
        }
@@ -6191,24 +4331,24 @@ bool Editor::PointInSelMargin(Point pt) {
 
 Window::Cursor Editor::GetMarginCursor(Point pt) const {
        int x = 0;
-       for (int margin = 0; margin <= SC_MAX_MARGIN; margin++) {
-               if ((pt.x >= x) && (pt.x < x + vs.ms[margin].width))
-                       return static_cast<Window::Cursor>(vs.ms[margin].cursor);
-               x += vs.ms[margin].width;
+       for (const MarginStyle &m : vs.ms) {
+               if ((pt.x >= x) && (pt.x < x + m.width))
+                       return static_cast<Window::Cursor>(m.cursor);
+               x += m.width;
        }
        return Window::cursorReverseArrow;
 }
 
-void Editor::TrimAndSetSelection(int currentPos_, int anchor_) {
+void Editor::TrimAndSetSelection(Sci::Position currentPos_, Sci::Position anchor_) {
        sel.TrimSelection(SelectionRange(currentPos_, anchor_));
        SetSelection(currentPos_, anchor_);
 }
 
-void Editor::LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLine) {
-       int selCurrentPos, selAnchorPos;
+void Editor::LineSelection(Sci::Position lineCurrentPos_, Sci::Position lineAnchorPos_, bool wholeLine) {
+       Sci::Position selCurrentPos, selAnchorPos;
        if (wholeLine) {
-               int lineCurrent_ = pdoc->LineFromPosition(lineCurrentPos_);
-               int lineAnchor_ = pdoc->LineFromPosition(lineAnchorPos_);
+               Sci::Line lineCurrent_ = pdoc->LineFromPosition(lineCurrentPos_);
+               Sci::Line lineAnchor_ = pdoc->LineFromPosition(lineAnchorPos_);
                if (lineAnchorPos_ < lineCurrentPos_) {
                        selCurrentPos = pdoc->LineStart(lineCurrent_ + 1);
                        selAnchorPos = pdoc->LineStart(lineAnchor_);
@@ -6237,7 +4377,7 @@ void Editor::LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLi
        TrimAndSetSelection(selCurrentPos, selAnchorPos);
 }
 
-void Editor::WordSelection(int pos) {
+void Editor::WordSelection(Sci::Position pos) {
        if (pos < wordSelectAnchorStartPos) {
                // Extend backward to the word containing pos.
                // Skip ExtendWordSelect if the line is empty or if pos is after the last character.
@@ -6270,6 +4410,12 @@ void Editor::DwellEnd(bool mouseMoved) {
                dwelling = false;
                NotifyDwelling(ptMouseLast, dwelling);
        }
+       if (FineTickerAvailable()) {
+               FineTickerCancel(tickDwell);
+               if (mouseMoved && (dwellDelay < SC_TIME_FOREVER)) {
+                       //FineTickerStart(tickDwell, dwellDelay, dwellDelay/10);
+               }
+       }
 }
 
 void Editor::MouseLeave() {
@@ -6285,20 +4431,26 @@ static bool AllowVirtualSpace(int virtualSpaceOptions, bool rectangular) {
                || (rectangular && ((virtualSpaceOptions & SCVS_RECTANGULARSELECTION) != 0));
 }
 
-void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) {
+void Editor::ButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) {
+       SetHoverIndicatorPoint(pt);
        //Platform::DebugPrintf("ButtonDown %d %d = %d alt=%d %d\n", curTime, lastClickTime, curTime - 
lastClickTime, alt, inDragDrop);
        ptMouseLast = pt;
+       const bool ctrl = (modifiers & SCI_CTRL) != 0;
+       const bool shift = (modifiers & SCI_SHIFT) != 0;
+       const bool alt = (modifiers & SCI_ALT) != 0;
        SelectionPosition newPos = SPositionFromLocation(pt, false, false, 
AllowVirtualSpace(virtualSpaceOptions, alt));
        newPos = MovePositionOutsideChar(newPos, sel.MainCaret() - newPos.Position());
+       SelectionPosition newCharPos = SPositionFromLocation(pt, false, true, false);
+       newCharPos = MovePositionOutsideChar(newCharPos, -1);
        inDragDrop = ddNone;
        sel.SetMoveExtends(false);
 
-       if (NotifyMarginClick(pt, shift, ctrl, alt))
+       if (NotifyMarginClick(pt, modifiers))
                return;
 
-       NotifyIndicatorClick(true, newPos.Position(), shift, ctrl, alt);
+       NotifyIndicatorClick(true, newPos.Position(), modifiers);
 
-       bool inSelMargin = PointInSelMargin(pt);
+       const bool inSelMargin = PointInSelMargin(pt);
        // In margin ctrl+(double)click should always select everything
        if (ctrl && inSelMargin) {
                SelectAll();
@@ -6309,9 +4461,12 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
        if (shift && !inSelMargin) {
                SetSelection(newPos);
        }
-       if (((curTime - lastClickTime) < Platform::DoubleClickTime()) && Close(pt, lastClick)) {
+       if (((curTime - lastClickTime) < Platform::DoubleClickTime()) && Close(pt, lastClick, 
doubleClickCloseThreshold)) {
                //Platform::DebugPrintf("Double click %d %d = %d\n", curTime, lastClickTime, curTime - 
lastClickTime);
                SetMouseCapture(true);
+               if (FineTickerAvailable()) {
+                       FineTickerStart(tickScroll, 100, 10);
+               }
                if (!ctrl || !multipleSelection || (selectionType != selChar && selectionType != selWord))
                        SetEmptySelection(newPos.Position());
                bool doubleClick = false;
@@ -6325,7 +4480,7 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
                                        selectionType = selWholeLine;
                                } else if (selectionType != selSubLine && selectionType != selWholeLine) {
                                        // If it is neither, reset selection type to line selection.
-                                       selectionType = ((wrapState != eWrapNone) && (marginOptions & 
SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
+                                       selectionType = (Wrapping() && (marginOptions & 
SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
                                }
                        } else {
                                if (selectionType == selChar) {
@@ -6333,7 +4488,7 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
                                        doubleClick = true;
                                } else if (selectionType == selWord) {
                                        // Since we ended up here, we're inside a *triple* click, which 
should always select
-                                       // whole line irregardless of word wrap being enabled or not.
+                                       // whole line regardless of word wrap being enabled or not.
                                        selectionType = selWholeLine;
                                } else {
                                        selectionType = selChar;
@@ -6343,13 +4498,13 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
                }
 
                if (selectionType == selWord) {
-                       int charPos = originalAnchorPos;
+                       Sci::Position charPos = originalAnchorPos;
                        if (sel.MainCaret() == originalAnchorPos) {
                                charPos = PositionFromLocation(pt, false, true);
                                charPos = MovePositionOutsideChar(charPos, -1);
                        }
 
-                       int startWord, endWord;
+                       Sci::Position startWord, endWord;
                        if ((sel.MainCaret() >= originalAnchorPos) && !pdoc->IsLineEndPosition(charPos)) {
                                startWord = pdoc->ExtendWordSelect(pdoc->MovePositionOutsideChar(charPos + 1, 
1), -1);
                                endWord = pdoc->ExtendWordSelect(charPos, 1);
@@ -6379,17 +4534,21 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
                }
                //Platform::DebugPrintf("Double click: %d - %d\n", anchor, currentPos);
                if (doubleClick) {
-                       NotifyDoubleClick(pt, shift, ctrl, alt);
-                       if (PositionIsHotspot(newPos.Position()))
-                               NotifyHotSpotDoubleClicked(newPos.Position(), shift, ctrl, alt);
+                       NotifyDoubleClick(pt, modifiers);
+                       if (PositionIsHotspot(newCharPos.Position()))
+                               NotifyHotSpotDoubleClicked(newCharPos.Position(), modifiers);
                }
        } else {        // Single click
                if (inSelMargin) {
+                       if (sel.IsRectangular() || (sel.Count() > 1)) {
+                               InvalidateWholeSelection();
+                               sel.Clear();
+                       }
                        sel.selType = Selection::selStream;
                        if (!shift) {
                                // Single click in margin: select whole line or only subline if word wrap is 
enabled
                                lineAnchorPos = newPos.Position();
-                               selectionType = ((wrapState != eWrapNone) && (marginOptions & 
SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
+                               selectionType = (Wrapping() && (marginOptions & 
SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
                                LineSelection(lineAnchorPos, lineAnchorPos, selectionType == selWholeLine);
                        } else {
                                // Single shift+click in margin: select from line anchor to clicked line
@@ -6402,16 +4561,19 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
                                // Otherwise, if there's a non empty selection, reset selection type only if 
it differs from selSubLine and selWholeLine.
                                // This ensures that we continue selecting in the same selection mode.
                                if (sel.Empty() || (selectionType != selSubLine && selectionType != 
selWholeLine))
-                                       selectionType = ((wrapState != eWrapNone) && (marginOptions & 
SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
+                                       selectionType = (Wrapping() && (marginOptions & 
SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
                                LineSelection(newPos.Position(), lineAnchorPos, selectionType == 
selWholeLine);
                        }
 
-                       SetDragPosition(SelectionPosition(invalidPosition));
+                       SetDragPosition(SelectionPosition(Sci::invalidPosition));
                        SetMouseCapture(true);
+                       if (FineTickerAvailable()) {
+                               FineTickerStart(tickScroll, 100, 10);
+                       }
                } else {
                        if (PointIsHotspot(pt)) {
-                               NotifyHotSpotClicked(newPos.Position(), shift, ctrl, alt);
-                               hotSpotClickPos = PositionFromLocation(pt,true,false);
+                               NotifyHotSpotClicked(newCharPos.Position(), modifiers);
+                               hotSpotClickPos = newCharPos.Position();
                        }
                        if (!shift) {
                                if (PointInSelection(pt) && !SelectionEmpty())
@@ -6420,8 +4582,11 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
                                        inDragDrop = ddNone;
                        }
                        SetMouseCapture(true);
+                       if (FineTickerAvailable()) {
+                               FineTickerStart(tickScroll, 100, 10);
+                       }
                        if (inDragDrop != ddInitial) {
-                               SetDragPosition(SelectionPosition(invalidPosition));
+                               SetDragPosition(SelectionPosition(Sci::invalidPosition));
                                if (!shift) {
                                        if (ctrl && multipleSelection) {
                                                SelectionRange range(newPos);
@@ -6451,60 +4616,89 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
        }
        lastClickTime = curTime;
        lastClick = pt;
-       lastXChosen = pt.x + xOffset;
+       lastXChosen = static_cast<int>(pt.x) + xOffset;
        ShowCaretAtCurrentPosition();
 }
 
-bool Editor::PositionIsHotspot(int position) const {
-       return vs.styles[pdoc->StyleAt(position) & pdoc->stylingBitsMask].hotspot;
+void Editor::RightButtonDownWithModifiers(Point pt, unsigned int, int modifiers) {
+       if (NotifyMarginRightClick(pt, modifiers))
+               return;
+}
+
+void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) {
+       return ButtonDownWithModifiers(pt, curTime, ModifierFlags(shift, ctrl, alt));
+}
+
+bool Editor::PositionIsHotspot(Sci::Position position) const {
+       return vs.styles[pdoc->StyleIndexAt(position)].hotspot;
 }
 
 bool Editor::PointIsHotspot(Point pt) {
-       int pos = PositionFromLocation(pt, true);
+       Sci::Position pos = PositionFromLocation(pt, true, true);
        if (pos == INVALID_POSITION)
                return false;
        return PositionIsHotspot(pos);
 }
 
+void Editor::SetHoverIndicatorPosition(Sci::Position position) {
+       const Sci::Position hoverIndicatorPosPrev = hoverIndicatorPos;
+       hoverIndicatorPos = INVALID_POSITION;
+       if (!vs.indicatorsDynamic)
+               return;
+       if (position != INVALID_POSITION) {
+               for (const Decoration *deco : pdoc->decorations.View()) {
+                       if (vs.indicators[deco->Indicator()].IsDynamic()) {
+                               if (pdoc->decorations.ValueAt(deco->Indicator(), position)) {
+                                       hoverIndicatorPos = position;
+                               }
+                       }
+               }
+       }
+       if (hoverIndicatorPosPrev != hoverIndicatorPos) {
+               Redraw();
+       }
+}
+
+void Editor::SetHoverIndicatorPoint(Point pt) {
+       if (!vs.indicatorsDynamic) {
+               SetHoverIndicatorPosition(INVALID_POSITION);
+       } else {
+               SetHoverIndicatorPosition(PositionFromLocation(pt, true, true));
+       }
+}
+
 void Editor::SetHotSpotRange(Point *pt) {
        if (pt) {
-               int pos = PositionFromLocation(*pt);
+               Sci::Position pos = PositionFromLocation(*pt, false, true);
 
                // If we don't limit this to word characters then the
                // range can encompass more than the run range and then
                // the underline will not be drawn properly.
-               int hsStart_ = pdoc->ExtendStyleRange(pos, -1, vs.hotspotSingleLine);
-               int hsEnd_ = pdoc->ExtendStyleRange(pos, 1, vs.hotspotSingleLine);
+               Range hsNew;
+               hsNew.start = pdoc->ExtendStyleRange(pos, -1, vs.hotspotSingleLine);
+               hsNew.end = pdoc->ExtendStyleRange(pos, 1, vs.hotspotSingleLine);
 
                // Only invalidate the range if the hotspot range has changed...
-               if (hsStart_ != hsStart || hsEnd_ != hsEnd) {
-                       if (hsStart != -1) {
-                               InvalidateRange(hsStart, hsEnd);
+               if (!(hsNew == hotspot)) {
+                       if (hotspot.Valid()) {
+                               InvalidateRange(hotspot.start, hotspot.end);
                        }
-                       hsStart = hsStart_;
-                       hsEnd = hsEnd_;
-                       InvalidateRange(hsStart, hsEnd);
+                       hotspot = hsNew;
+                       InvalidateRange(hotspot.start, hotspot.end);
                }
        } else {
-               if (hsStart != -1) {
-                       int hsStart_ = hsStart;
-                       int hsEnd_ = hsEnd;
-                       hsStart = -1;
-                       hsEnd = -1;
-                       InvalidateRange(hsStart_, hsEnd_);
-               } else {
-                       hsStart = -1;
-                       hsEnd = -1;
+               if (hotspot.Valid()) {
+                       InvalidateRange(hotspot.start, hotspot.end);
                }
+               hotspot = Range(Sci::invalidPosition);
        }
 }
 
-void Editor::GetHotSpotRange(int &hsStart_, int &hsEnd_) const {
-       hsStart_ = hsStart;
-       hsEnd_ = hsEnd;
+Range Editor::GetHotSpotRange() const {
+       return hotspot;
 }
 
-void Editor::ButtonMove(Point pt) {
+void Editor::ButtonMoveWithModifiers(Point pt, int modifiers) {
        if ((ptMouseLast.x != pt.x) || (ptMouseLast.y != pt.y)) {
                DwellEnd(true);
        }
@@ -6516,6 +4710,9 @@ void Editor::ButtonMove(Point pt) {
        if (inDragDrop == ddInitial) {
                if (DragThreshold(ptMouseLast, pt)) {
                        SetMouseCapture(false);
+                       if (FineTickerAvailable()) {
+                               FineTickerCancel(tickScroll);
+                       }
                        SetDragPosition(movePos);
                        CopySelectionRange(&drag);
                        StartDrag();
@@ -6524,6 +4721,12 @@ void Editor::ButtonMove(Point pt) {
        }
 
        ptMouseLast = pt;
+       PRectangle rcClient = GetClientRectangle();
+       Point ptOrigin = GetVisibleOriginInMain();
+       rcClient.Move(0, -ptOrigin.y);
+       if (FineTickerAvailable() && (dwellDelay < SC_TIME_FOREVER) && rcClient.Contains(pt)) {
+               FineTickerStart(tickDwell, dwellDelay, dwellDelay/10);
+       }
        //Platform::DebugPrintf("Move %d %d\n", pt.x, pt.y);
        if (HaveMouseCapture()) {
 
@@ -6538,10 +4741,14 @@ void Editor::ButtonMove(Point pt) {
                        SetDragPosition(movePos);
                } else {
                        if (selectionType == selChar) {
+                               if (sel.selType == Selection::selStream && (modifiers & SCI_ALT) && 
mouseSelectionRectangularSwitch) {
+                                       sel.selType = Selection::selRectangle;
+                               }
                                if (sel.IsRectangular()) {
                                        sel.Rectangular() = SelectionRange(movePos, sel.Rectangular().anchor);
                                        SetSelection(movePos, sel.RangeMain().anchor);
                                } else if (sel.Count() > 1) {
+                                       InvalidateSelection(sel.RangeMain(), false);
                                        SelectionRange range(movePos, sel.RangeMain().anchor);
                                        sel.TentativeSelection(range);
                                        InvalidateSelection(range, true);
@@ -6571,10 +4778,7 @@ void Editor::ButtonMove(Point pt) {
                }
 
                // Autoscroll
-               PRectangle rcClient = GetClientRectangle();
-               Point ptOrigin = GetVisibleOriginInMain();
-               rcClient.Move(0, -ptOrigin.y);
-               int lineMove = DisplayFromPosition(movePos.Position());
+               Sci::Line lineMove = DisplayFromPosition(movePos.Position());
                if (pt.y > rcClient.bottom) {
                        ScrollTo(lineMove - LinesOnScreen() + 1);
                        Redraw();
@@ -6584,10 +4788,10 @@ void Editor::ButtonMove(Point pt) {
                }
                EnsureCaretVisible(false, false, true);
 
-               if (hsStart != -1 && !PositionIsHotspot(movePos.Position()))
+               if (hotspot.Valid() && !PointIsHotspot(pt))
                        SetHotSpotRange(NULL);
 
-               if (hotSpotClickPos != INVALID_POSITION && PositionFromLocation(pt,true,false) != 
hotSpotClickPos) {
+               if (hotSpotClickPos != INVALID_POSITION && PositionFromLocation(pt,true,true) != 
hotSpotClickPos) {
                        if (inDragDrop == ddNone) {
                                DisplayCursor(Window::cursorText);
                        }
@@ -6605,20 +4809,32 @@ void Editor::ButtonMove(Point pt) {
                // Display regular (drag) cursor over selection
                if (PointInSelection(pt) && !SelectionEmpty()) {
                        DisplayCursor(Window::cursorArrow);
-               } else if (PointIsHotspot(pt)) {
-                       DisplayCursor(Window::cursorHand);
-                       SetHotSpotRange(&pt);
                } else {
-                       DisplayCursor(Window::cursorText);
-                       SetHotSpotRange(NULL);
+                       SetHoverIndicatorPoint(pt);
+                       if (PointIsHotspot(pt)) {
+                               DisplayCursor(Window::cursorHand);
+                               SetHotSpotRange(&pt);
+                       } else {
+                               if (hoverIndicatorPos != Sci::invalidPosition)
+                                       DisplayCursor(Window::cursorHand);
+                               else
+                                       DisplayCursor(Window::cursorText);
+                               SetHotSpotRange(NULL);
+                       }
                }
        }
 }
 
+void Editor::ButtonMove(Point pt) {
+       ButtonMoveWithModifiers(pt, 0);
+}
+
 void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) {
        //Platform::DebugPrintf("ButtonUp %d %d\n", HaveMouseCapture(), inDragDrop);
        SelectionPosition newPos = SPositionFromLocation(pt, false, false,
                AllowVirtualSpace(virtualSpaceOptions, sel.IsRectangular()));
+       if (hoverIndicatorPos != INVALID_POSITION)
+               InvalidateRange(newPos.Position(), newPos.Position() + 1);
        newPos = MovePositionOutsideChar(newPos, sel.MainCaret() - newPos.Position());
        if (inDragDrop == ddInitial) {
                inDragDrop = ddNone;
@@ -6628,7 +4844,9 @@ void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) {
        }
        if (hotSpotClickPos != INVALID_POSITION && PointIsHotspot(pt)) {
                hotSpotClickPos = INVALID_POSITION;
-               NotifyHotSpotReleaseClick(newPos.Position(), false, ctrl, false);
+               SelectionPosition newCharPos = SPositionFromLocation(pt, false, true, false);
+               newCharPos = MovePositionOutsideChar(newCharPos, -1);
+               NotifyHotSpotReleaseClick(newCharPos.Position(), ctrl ? SCI_CTRL : 0);
        }
        if (HaveMouseCapture()) {
                if (PointInSelMargin(pt)) {
@@ -6639,26 +4857,36 @@ void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) {
                }
                ptMouseLast = pt;
                SetMouseCapture(false);
-               NotifyIndicatorClick(false, newPos.Position(), false, false, false);
+               if (FineTickerAvailable()) {
+                       FineTickerCancel(tickScroll);
+               }
+               NotifyIndicatorClick(false, newPos.Position(), 0);
                if (inDragDrop == ddDragging) {
                        SelectionPosition selStart = SelectionStart();
                        SelectionPosition selEnd = SelectionEnd();
                        if (selStart < selEnd) {
                                if (drag.Length()) {
+                                       const int length = static_cast<int>(drag.Length());
                                        if (ctrl) {
-                                               if (pdoc->InsertString(newPos.Position(), drag.Data(), 
static_cast<int>(drag.Length()))) {
-                                                       SetSelection(newPos.Position(), newPos.Position() + 
static_cast<int>(drag.Length()));
+                                               const Sci::Position lengthInserted = pdoc->InsertString(
+                                                       newPos.Position(), drag.Data(), length);
+                                               if (lengthInserted > 0) {
+                                                       SetSelection(newPos.Position(), newPos.Position() + 
lengthInserted);
                                                }
                                        } else if (newPos < selStart) {
                                                pdoc->DeleteChars(selStart.Position(), 
static_cast<int>(drag.Length()));
-                                               if (pdoc->InsertString(newPos.Position(), drag.Data(), 
static_cast<int>(drag.Length()))) {
-                                                       SetSelection(newPos.Position(), newPos.Position() + 
static_cast<int>(drag.Length()));
+                                               const Sci::Position lengthInserted = pdoc->InsertString(
+                                                       newPos.Position(), drag.Data(), length);
+                                               if (lengthInserted > 0) {
+                                                       SetSelection(newPos.Position(), newPos.Position() + 
lengthInserted);
                                                }
                                        } else if (newPos > selEnd) {
                                                pdoc->DeleteChars(selStart.Position(), 
static_cast<int>(drag.Length()));
                                                newPos.Add(-static_cast<int>(drag.Length()));
-                                               if (pdoc->InsertString(newPos.Position(), drag.Data(), 
static_cast<int>(drag.Length()))) {
-                                                       SetSelection(newPos.Position(), newPos.Position() + 
static_cast<int>(drag.Length()));
+                                               const Sci::Position lengthInserted = pdoc->InsertString(
+                                                       newPos.Position(), drag.Data(), length);
+                                               if (lengthInserted > 0) {
+                                                       SetSelection(newPos.Position(), newPos.Position() + 
lengthInserted);
                                                }
                                        } else {
                                                SetEmptySelection(newPos.Position());
@@ -6672,7 +4900,7 @@ void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) {
                                if (sel.Count() > 1) {
                                        sel.RangeMain() =
                                                SelectionRange(newPos, sel.Range(sel.Count() - 1).anchor);
-                                       InvalidateSelection(sel.RangeMain(), true);
+                                       InvalidateWholeSelection();
                                } else {
                                        SetSelection(newPos, sel.RangeMain().anchor);
                                }
@@ -6682,7 +4910,7 @@ void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) {
                SetRectangularRange();
                lastClickTime = curTime;
                lastClick = pt;
-               lastXChosen = pt.x + xOffset;
+               lastXChosen = static_cast<int>(pt.x) + xOffset;
                if (sel.selType == Selection::selStream) {
                        SetLastXChosen();
                }
@@ -6708,8 +4936,8 @@ void Editor::Tick() {
                        }
                }
        }
-       if (horizontalScrollBarVisible && trackLineWidth && (lineWidthMaxSeen > scrollWidth)) {
-               scrollWidth = lineWidthMaxSeen;
+       if (horizontalScrollBarVisible && trackLineWidth && (view.lineWidthMaxSeen > scrollWidth)) {
+               scrollWidth = view.lineWidthMaxSeen;
                SetScrollBars();
        }
        if ((dwellDelay < SC_TIME_FOREVER) &&
@@ -6725,45 +4953,101 @@ void Editor::Tick() {
 }
 
 bool Editor::Idle() {
+       bool needWrap = Wrapping() && wrapPending.NeedsWrap();
 
-       bool idleDone;
-
-       bool wrappingDone = wrapState == eWrapNone;
-
-       if (!wrappingDone) {
+       if (needWrap) {
                // Wrap lines during idle.
-               WrapLines(wsIdle);
+               WrapLines(WrapScope::wsIdle);
                // No more wrapping
-               if (!wrapPending.NeedsWrap())
-                       wrappingDone = true;
+               needWrap = wrapPending.NeedsWrap();
+       } else if (needIdleStyling) {
+               IdleStyling();
        }
 
        // Add more idle things to do here, but make sure idleDone is
        // set correctly before the function returns. returning
-       // false will stop calling this idle funtion until SetIdle() is
+       // false will stop calling this idle function until SetIdle() is
        // called again.
 
-       idleDone = wrappingDone; // && thatDone && theOtherThingDone...
+       const bool idleDone = !needWrap && !needIdleStyling; // && thatDone && theOtherThingDone...
 
        return !idleDone;
 }
 
+void Editor::SetTicking(bool) {
+       // SetTicking is deprecated. In the past it was pure virtual and was overridden in each
+       // derived platform class but fine grained timers should now be implemented.
+       // Either way, execution should not arrive here so assert failure.
+       assert(false);
+}
+
+void Editor::TickFor(TickReason reason) {
+       switch (reason) {
+               case tickCaret:
+                       caret.on = !caret.on;
+                       if (caret.active) {
+                               InvalidateCaret();
+                       }
+                       break;
+               case tickScroll:
+                       // Auto scroll
+                       ButtonMove(ptMouseLast);
+                       break;
+               case tickWiden:
+                       SetScrollBars();
+                       FineTickerCancel(tickWiden);
+                       break;
+               case tickDwell:
+                       if ((!HaveMouseCapture()) &&
+                               (ptMouseLast.y >= 0)) {
+                               dwelling = true;
+                               NotifyDwelling(ptMouseLast, dwelling);
+                       }
+                       FineTickerCancel(tickDwell);
+                       break;
+               default:
+                       // tickPlatform handled by subclass
+                       break;
+       }
+}
+
+bool Editor::FineTickerAvailable() {
+       return false;
+}
+
+// FineTickerStart is be overridden by subclasses that support fine ticking so
+// this method should never be called.
+bool Editor::FineTickerRunning(TickReason) {
+       assert(false);
+       return false;
+}
+
+// FineTickerStart is be overridden by subclasses that support fine ticking so
+// this method should never be called.
+void Editor::FineTickerStart(TickReason, int, int) {
+       assert(false);
+}
+
+// FineTickerCancel is be overridden by subclasses that support fine ticking so
+// this method should never be called.
+void Editor::FineTickerCancel(TickReason) {
+       assert(false);
+}
+
 void Editor::SetFocusState(bool focusState) {
        hasFocus = focusState;
        NotifyFocus(hasFocus);
-       if (hasFocus) {
-               ShowCaretAtCurrentPosition();
-       } else {
+       if (!hasFocus) {
                CancelModes();
-               DropCaret();
        }
+       ShowCaretAtCurrentPosition();
 }
 
-int Editor::PositionAfterArea(PRectangle rcArea) const {
+Sci::Position Editor::PositionAfterArea(PRectangle rcArea) const {
        // The start of the document line after the display line after the area
        // This often means that the line after a modification is restyled which helps
        // detect multiline comment additions and heals single line comments
-       int lineAfter = topLine + (rcArea.bottom - 1) / vs.lineHeight + 1;
+       Sci::Line lineAfter = TopLineOfMain() + static_cast<Sci::Line>(rcArea.bottom - 1) / vs.lineHeight + 1;
        if (lineAfter < cs.LinesDisplayed())
                return pdoc->LineStart(cs.DocFromDisplay(lineAfter) + 1);
        else
@@ -6772,30 +5056,92 @@ int Editor::PositionAfterArea(PRectangle rcArea) const {
 
 // Style to a position within the view. If this causes a change at end of last line then
 // affects later lines so style all the viewed text.
-void Editor::StyleToPositionInView(Position pos) {
-       int endWindow = (vs.marginInside) ? (PositionAfterArea(GetClientRectangle())) : (pdoc->Length());
+void Editor::StyleToPositionInView(Sci::Position pos) {
+       Sci::Position endWindow = PositionAfterArea(GetClientDrawingRectangle());
        if (pos > endWindow)
                pos = endWindow;
-       int styleAtEnd = pdoc->StyleAt(pos-1);
+       const int styleAtEnd = pdoc->StyleIndexAt(pos-1);
        pdoc->EnsureStyledTo(pos);
-       if ((endWindow > pos) && (styleAtEnd != pdoc->StyleAt(pos-1))) {
+       if ((endWindow > pos) && (styleAtEnd != pdoc->StyleIndexAt(pos-1))) {
                // Style at end of line changed so is multi-line change like starting a comment
                // so require rest of window to be styled.
+               DiscardOverdraw();      // Prepared bitmaps may be invalid
+               // DiscardOverdraw may have truncated client drawing area so recalculate endWindow
+               endWindow = PositionAfterArea(GetClientDrawingRectangle());
                pdoc->EnsureStyledTo(endWindow);
        }
 }
 
+Sci::Position Editor::PositionAfterMaxStyling(Sci::Position posMax, bool scrolling) const {
+       if ((idleStyling == SC_IDLESTYLING_NONE) || (idleStyling == SC_IDLESTYLING_AFTERVISIBLE)) {
+               // Both states do not limit styling
+               return posMax;
+       }
+
+       // Try to keep time taken by styling reasonable so interaction remains smooth.
+       // When scrolling, allow less time to ensure responsive
+       const double secondsAllowed = scrolling ? 0.005 : 0.02;
+
+       const Sci::Line linesToStyle = Platform::Clamp(static_cast<int>(secondsAllowed / 
pdoc->durationStyleOneLine),
+               10, 0x10000);
+       const Sci::Line stylingMaxLine = std::min(
+               static_cast<Sci::Line>(pdoc->LineFromPosition(pdoc->GetEndStyled()) + linesToStyle),
+               pdoc->LinesTotal());
+       return std::min(static_cast<Sci::Position>(pdoc->LineStart(stylingMaxLine)), posMax);
+}
+
+void Editor::StartIdleStyling(bool truncatedLastStyling) {
+       if ((idleStyling == SC_IDLESTYLING_ALL) || (idleStyling == SC_IDLESTYLING_AFTERVISIBLE)) {
+               if (pdoc->GetEndStyled() < pdoc->Length()) {
+                       // Style remainder of document in idle time
+                       needIdleStyling = true;
+               }
+       } else if (truncatedLastStyling) {
+               needIdleStyling = true;
+       }
+
+       if (needIdleStyling) {
+               SetIdle(true);
+       }
+}
+
+// Style for an area but bound the amount of styling to remain responsive
+void Editor::StyleAreaBounded(PRectangle rcArea, bool scrolling) {
+       const Sci::Position posAfterArea = PositionAfterArea(rcArea);
+       const Sci::Position posAfterMax = PositionAfterMaxStyling(posAfterArea, scrolling);
+       if (posAfterMax < posAfterArea) {
+               // Idle styling may be performed before current visible area
+               // Style a bit now then style further in idle time
+               pdoc->StyleToAdjustingLineDuration(posAfterMax);
+       } else {
+               // Can style all wanted now.
+               StyleToPositionInView(posAfterArea);
+       }
+       StartIdleStyling(posAfterMax < posAfterArea);
+}
+
+void Editor::IdleStyling() {
+       const Sci::Position posAfterArea = PositionAfterArea(GetClientRectangle());
+       const Sci::Position endGoal = (idleStyling >= SC_IDLESTYLING_AFTERVISIBLE) ?
+               pdoc->Length() : posAfterArea;
+       const Sci::Position posAfterMax = PositionAfterMaxStyling(endGoal, false);
+       pdoc->StyleToAdjustingLineDuration(posAfterMax);
+       if (pdoc->GetEndStyled() >= endGoal) {
+               needIdleStyling = false;
+       }
+}
+
 void Editor::IdleWork() {
        // Style the line after the modification as this allows modifications that change just the
        // line of the modification to heal instead of propagating to the rest of the window.
-       if (workNeeded.items & WorkNeeded::workStyle)
+       if (workNeeded.items & WorkNeeded::workStyle) {
                StyleToPositionInView(pdoc->LineStart(pdoc->LineFromPosition(workNeeded.upTo) + 2));
-
+       }
        NotifyUpdateUI();
        workNeeded.Reset();
 }
 
-void Editor::QueueIdleWork(WorkNeeded::workItems items, int upTo) {
+void Editor::QueueIdleWork(WorkNeeded::workItems items, Sci::Position upTo) {
        workNeeded.Need(items, upTo);
 }
 
@@ -6814,7 +5160,7 @@ bool Editor::PaintContainsMargin() {
                return false;
        }
        PRectangle rcSelMargin = GetClientRectangle();
-       rcSelMargin.right = vs.textStart;
+       rcSelMargin.right = static_cast<XYPOSITION>(vs.textStart);
        return PaintContains(rcSelMargin);
 }
 
@@ -6824,7 +5170,7 @@ void Editor::CheckForChangeOutsidePaint(Range r) {
                if (!r.Valid())
                        return;
 
-               PRectangle rcRange = RectangleFromRange(r.start, r.end);
+               PRectangle rcRange = RectangleFromRange(r, 0);
                PRectangle rcText = GetTextRectangle();
                if (rcRange.top < rcText.top) {
                        rcRange.top = rcText.top;
@@ -6840,7 +5186,7 @@ void Editor::CheckForChangeOutsidePaint(Range r) {
        }
 }
 
-void Editor::SetBraceHighlight(Position pos0, Position pos1, int matchStyle) {
+void Editor::SetBraceHighlight(Sci::Position pos0, Sci::Position pos1, int matchStyle) {
        if ((pos0 != braces[0]) || (pos1 != braces[1]) || (matchStyle != bracesMatchStyle)) {
                if ((braces[0] != pos0) || (matchStyle != bracesMatchStyle)) {
                        CheckForChangeOutsidePaint(Range(braces[0]));
@@ -6859,16 +5205,17 @@ void Editor::SetBraceHighlight(Position pos0, Position pos1, int matchStyle) {
        }
 }
 
-void Editor::SetAnnotationHeights(int start, int end) {
+void Editor::SetAnnotationHeights(Sci::Line start, Sci::Line end) {
        if (vs.annotationVisible) {
+               RefreshStyleData();
                bool changedHeight = false;
-               for (int line=start; line<end && line<pdoc->LinesTotal(); line++) {
+               for (Sci::Line line=start; line<end && line<pdoc->LinesTotal(); line++) {
                        int linesWrapped = 1;
-                       if (wrapState != eWrapNone) {
+                       if (Wrapping()) {
                                AutoSurface surface(this);
-                               AutoLineLayout ll(llc, RetrieveLineLayout(line));
+                               AutoLineLayout ll(view.llc, view.RetrieveLineLayout(line, *this));
                                if (surface && ll) {
-                                       LayoutLine(line, surface, vs, ll, wrapWidth);
+                                       view.LayoutLine(*this, line, surface, vs, ll, wrapWidth);
                                        linesWrapped = ll->lines;
                                }
                        }
@@ -6897,18 +5244,25 @@ void Editor::SetDocPointer(Document *document) {
        targetStart = 0;
        targetEnd = 0;
 
-       braces[0] = invalidPosition;
-       braces[1] = invalidPosition;
+       braces[0] = Sci::invalidPosition;
+       braces[1] = Sci::invalidPosition;
 
        vs.ReleaseAllExtendedStyles();
 
+       SetRepresentations();
+
        // Reset the contraction state to fully shown.
        cs.Clear();
        cs.InsertLines(0, pdoc->LinesTotal() - 1);
        SetAnnotationHeights(0, pdoc->LinesTotal());
-       llc.Deallocate();
+       view.llc.Deallocate();
        NeedWrapping();
 
+       hotspot = Range(Sci::invalidPosition);
+       hoverIndicatorPos = Sci::invalidPosition;
+
+       view.ClearAllTabstops();
+
        pdoc->AddWatcher(this, 0);
        SetScrollBars();
        Redraw();
@@ -6916,16 +5270,17 @@ void Editor::SetDocPointer(Document *document) {
 
 void Editor::SetAnnotationVisible(int visible) {
        if (vs.annotationVisible != visible) {
-               bool changedFromOrToHidden = ((vs.annotationVisible != 0) != (visible != 0));
+               const bool changedFromOrToHidden = ((vs.annotationVisible != 0) != (visible != 0));
                vs.annotationVisible = visible;
                if (changedFromOrToHidden) {
                        int dir = vs.annotationVisible ? 1 : -1;
-                       for (int line=0; line<pdoc->LinesTotal(); line++) {
+                       for (Sci::Line line=0; line<pdoc->LinesTotal(); line++) {
                                int annotationLines = pdoc->AnnotationLines(line);
                                if (annotationLines > 0) {
                                        cs.SetHeight(line, cs.GetHeight(line) + annotationLines * dir);
                                }
                        }
+                       SetScrollBars();
                }
                Redraw();
        }
@@ -6934,12 +5289,12 @@ void Editor::SetAnnotationVisible(int visible) {
 /**
  * Recursively expand a fold, making lines visible except where they have an unexpanded parent.
  */
-int Editor::ExpandLine(int line) {
-       int lineMaxSubord = pdoc->GetLastChild(line);
+Sci::Line Editor::ExpandLine(Sci::Line line) {
+       Sci::Line lineMaxSubord = pdoc->GetLastChild(line);
        line++;
        while (line <= lineMaxSubord) {
                cs.SetVisible(line, line, true);
-               int level = pdoc->GetLevel(line);
+               const int level = pdoc->GetLevel(line);
                if (level & SC_FOLDLEVELHEADERFLAG) {
                        if (cs.GetExpanded(line)) {
                                line = ExpandLine(line);
@@ -6952,16 +5307,16 @@ int Editor::ExpandLine(int line) {
        return lineMaxSubord;
 }
 
-void Editor::SetFoldExpanded(int lineDoc, bool expanded) {
+void Editor::SetFoldExpanded(Sci::Line lineDoc, bool expanded) {
        if (cs.SetExpanded(lineDoc, expanded)) {
                RedrawSelMargin();
        }
 }
 
-void Editor::FoldLine(int line, int action) {
+void Editor::FoldLine(Sci::Line line, int action) {
        if (line >= 0) {
                if (action == SC_FOLDACTION_TOGGLE) {
-                       if ((pdoc->GetLevel(line) & SC_FOLDLEVELHEADERFLAG) == 0) {
+                       if ((pdoc->GetLevel(line) & SC_FOLDLEVELHEADERFLAG) == 0) {
                                line = pdoc->GetFoldParent(line);
                                if (line < 0)
                                        return;
@@ -6970,12 +5325,12 @@ void Editor::FoldLine(int line, int action) {
                }
 
                if (action == SC_FOLDACTION_CONTRACT) {
-                       int lineMaxSubord = pdoc->GetLastChild(line);
+                       const Sci::Line lineMaxSubord = pdoc->GetLastChild(line);
                        if (lineMaxSubord > line) {
-                               cs.SetExpanded(line, 0);
+                               cs.SetExpanded(line, false);
                                cs.SetVisible(line + 1, lineMaxSubord, false);
 
-                               int lineCurrent = pdoc->LineFromPosition(sel.MainCaret());
+                               const Sci::Line lineCurrent = pdoc->LineFromPosition(sel.MainCaret());
                                if (lineCurrent > line && lineCurrent <= lineMaxSubord) {
                                        // This does not re-expand the fold
                                        EnsureCaretVisible();
@@ -6987,7 +5342,7 @@ void Editor::FoldLine(int line, int action) {
                                EnsureLineVisible(line, false);
                                GoToLine(line);
                        }
-                       cs.SetExpanded(line, 1);
+                       cs.SetExpanded(line, true);
                        ExpandLine(line);
                }
 
@@ -6996,20 +5351,23 @@ void Editor::FoldLine(int line, int action) {
        }
 }
 
-void Editor::FoldExpand(int line, int action, int level) {
+void Editor::FoldExpand(Sci::Line line, int action, int level) {
        bool expanding = action == SC_FOLDACTION_EXPAND;
        if (action == SC_FOLDACTION_TOGGLE) {
                expanding = !cs.GetExpanded(line);
        }
+       // Ensure child lines lexed and fold information extracted before
+       // flipping the state.
+       pdoc->GetLastChild(line, LevelNumber(level));
        SetFoldExpanded(line, expanding);
        if (expanding && (cs.HiddenLines() == 0))
                // Nothing to do
                return;
-       int lineMaxSubord = pdoc->GetLastChild(line, level & SC_FOLDLEVELNUMBERMASK);
+       Sci::Line lineMaxSubord = pdoc->GetLastChild(line, LevelNumber(level));
        line++;
        cs.SetVisible(line, lineMaxSubord, expanding);
        while (line <= lineMaxSubord) {
-               int levelLine = pdoc->GetLevel(line);
+               const int levelLine = pdoc->GetLevel(line);
                if (levelLine & SC_FOLDLEVELHEADERFLAG) {
                        SetFoldExpanded(line, expanding);
                }
@@ -7019,8 +5377,8 @@ void Editor::FoldExpand(int line, int action, int level) {
        Redraw();
 }
 
-int Editor::ContractedFoldNext(int lineStart) const {
-       for (int line = lineStart; line<pdoc->LinesTotal();) {
+Sci::Line Editor::ContractedFoldNext(Sci::Line lineStart) const {
+       for (Sci::Line line = lineStart; line<pdoc->LinesTotal();) {
                if (!cs.GetExpanded(line) && (pdoc->GetLevel(line) & SC_FOLDLEVELHEADERFLAG))
                        return line;
                line = cs.ContractedNext(line+1);
@@ -7035,20 +5393,20 @@ int Editor::ContractedFoldNext(int lineStart) const {
  * Recurse up from this line to find any folds that prevent this line from being visible
  * and unfold them all.
  */
-void Editor::EnsureLineVisible(int lineDoc, bool enforcePolicy) {
+void Editor::EnsureLineVisible(Sci::Line lineDoc, bool enforcePolicy) {
 
        // In case in need of wrapping to ensure DisplayFromDoc works.
        if (lineDoc >= wrapPending.start)
-               WrapLines(wsAll);
+               WrapLines(WrapScope::wsAll);
 
        if (!cs.GetVisible(lineDoc)) {
                // Back up to find a non-blank line
-               int lookLine = lineDoc;
+               Sci::Line lookLine = lineDoc;
                int lookLineLevel = pdoc->GetLevel(lookLine);
                while ((lookLine > 0) && (lookLineLevel & SC_FOLDLEVELWHITEFLAG)) {
                        lookLineLevel = pdoc->GetLevel(--lookLine);
                }
-               int lineParent = pdoc->GetFoldParent(lookLine);
+               Sci::Line lineParent = pdoc->GetFoldParent(lookLine);
                if (lineParent < 0) {
                        // Backed up to a top level line, so try to find parent of initial line
                        lineParent = pdoc->GetFoldParent(lineDoc);
@@ -7057,7 +5415,7 @@ void Editor::EnsureLineVisible(int lineDoc, bool enforcePolicy) {
                        if (lineDoc != lineParent)
                                EnsureLineVisible(lineParent, enforcePolicy);
                        if (!cs.GetExpanded(lineParent)) {
-                               cs.SetExpanded(lineParent, 1);
+                               cs.SetExpanded(lineParent, true);
                                ExpandLine(lineParent);
                        }
                }
@@ -7065,7 +5423,7 @@ void Editor::EnsureLineVisible(int lineDoc, bool enforcePolicy) {
                Redraw();
        }
        if (enforcePolicy) {
-               int lineDisplay = cs.DisplayFromDoc(lineDoc);
+               const Sci::Line lineDisplay = cs.DisplayFromDoc(lineDoc);
                if (visiblePolicy & VISIBLE_SLOP) {
                        if ((topLine > lineDisplay) || ((visiblePolicy & VISIBLE_STRICT) && (topLine + 
visibleSlop > lineDisplay))) {
                                SetTopLine(Platform::Clamp(lineDisplay - visibleSlop, 0, MaxScrollPos()));
@@ -7089,7 +5447,7 @@ void Editor::EnsureLineVisible(int lineDoc, bool enforcePolicy) {
 
 void Editor::FoldAll(int action) {
        pdoc->EnsureStyledTo(pdoc->Length());
-       int maxLine = pdoc->LinesTotal();
+       Sci::Line maxLine = pdoc->LinesTotal();
        bool expanding = action == SC_FOLDACTION_EXPAND;
        if (action == SC_FOLDACTION_TOGGLE) {
                // Discover current state
@@ -7103,18 +5461,18 @@ void Editor::FoldAll(int action) {
        if (expanding) {
                cs.SetVisible(0, maxLine-1, true);
                for (int line = 0; line < maxLine; line++) {
-                       int levelLine = pdoc->GetLevel(line);
+                       const int levelLine = pdoc->GetLevel(line);
                        if (levelLine & SC_FOLDLEVELHEADERFLAG) {
                                SetFoldExpanded(line, true);
                        }
                }
        } else {
                for (int line = 0; line < maxLine; line++) {
-                       int level = pdoc->GetLevel(line);
+                       const int level = pdoc->GetLevel(line);
                        if ((level & SC_FOLDLEVELHEADERFLAG) &&
-                                       (SC_FOLDLEVELBASE == (level & SC_FOLDLEVELNUMBERMASK))) {
+                                       (SC_FOLDLEVELBASE == LevelNumber(level))) {
                                SetFoldExpanded(line, false);
-                               int lineMaxSubord = pdoc->GetLastChild(line, -1);
+                               Sci::Line lineMaxSubord = pdoc->GetLastChild(line, -1);
                                if (lineMaxSubord > line) {
                                        cs.SetVisible(line + 1, lineMaxSubord, false);
                                }
@@ -7125,7 +5483,7 @@ void Editor::FoldAll(int action) {
        Redraw();
 }
 
-void Editor::FoldChanged(int line, int levelNow, int levelPrev) {
+void Editor::FoldChanged(Sci::Line line, int levelNow, int levelPrev) {
        if (levelNow & SC_FOLDLEVELHEADERFLAG) {
                if (!(levelPrev & SC_FOLDLEVELHEADERFLAG)) {
                        // Adding a fold point.
@@ -7135,20 +5493,28 @@ void Editor::FoldChanged(int line, int levelNow, int levelPrev) {
                        FoldExpand(line, SC_FOLDACTION_EXPAND, levelPrev);
                }
        } else if (levelPrev & SC_FOLDLEVELHEADERFLAG) {
+               const Sci::Line prevLine = line - 1;
+               const int prevLineLevel = pdoc->GetLevel(prevLine);
+
+               // Combining two blocks where the first block is collapsed (e.g. by deleting the line(s) 
which separate(s) the two blocks)
+               if ((LevelNumber(prevLineLevel) == LevelNumber(levelNow)) && !cs.GetVisible(prevLine))
+                       FoldLine(pdoc->GetFoldParent(prevLine), SC_FOLDACTION_EXPAND);
+
                if (!cs.GetExpanded(line)) {
                        // Removing the fold from one that has been contracted so should expand
                        // otherwise lines are left invisible with no way to make them visible
                        if (cs.SetExpanded(line, true)) {
                                RedrawSelMargin();
                        }
+                       // Combining two blocks where the second one is collapsed (e.g. by adding characters 
in the line which separates the two blocks)
                        FoldExpand(line, SC_FOLDACTION_EXPAND, levelPrev);
                }
        }
        if (!(levelNow & SC_FOLDLEVELWHITEFLAG) &&
-               ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK))) {
+               (LevelNumber(levelPrev) > LevelNumber(levelNow))) {
                if (cs.HiddenLines()) {
                        // See if should still be hidden
-                       int parentLine = pdoc->GetFoldParent(line);
+                       Sci::Line parentLine = pdoc->GetFoldParent(line);
                        if ((parentLine < 0) || (cs.GetExpanded(parentLine) && cs.GetVisible(parentLine))) {
                                cs.SetVisible(line, line, true);
                                SetScrollBars();
@@ -7156,13 +5522,22 @@ void Editor::FoldChanged(int line, int levelNow, int levelPrev) {
                        }
                }
        }
+
+       // Combining two blocks where the first one is collapsed (e.g. by adding characters in the line which 
separates the two blocks)
+       if (!(levelNow & SC_FOLDLEVELWHITEFLAG) && (LevelNumber(levelPrev) < LevelNumber(levelNow))) {
+               if (cs.HiddenLines()) {
+                       const Sci::Line parentLine = pdoc->GetFoldParent(line);
+                       if (!cs.GetExpanded(parentLine) && cs.GetVisible(line))
+                               FoldLine(parentLine, SC_FOLDACTION_EXPAND);
+               }
+       }
 }
 
-void Editor::NeedShown(int pos, int len) {
+void Editor::NeedShown(Sci::Position pos, Sci::Position len) {
        if (foldAutomatic & SC_AUTOMATICFOLD_SHOW) {
-               int lineStart = pdoc->LineFromPosition(pos);
-               int lineEnd = pdoc->LineFromPosition(pos+len);
-               for (int line = lineStart; line <= lineEnd; line++) {
+               const Sci::Line lineStart = pdoc->LineFromPosition(pos);
+               const Sci::Line lineEnd = pdoc->LineFromPosition(pos+len);
+               for (Sci::Line line = lineStart; line <= lineEnd; line++) {
                        EnsureLineVisible(line, false);
                }
        } else {
@@ -7170,9 +5545,9 @@ void Editor::NeedShown(int pos, int len) {
        }
 }
 
-int Editor::GetTag(char *tagValue, int tagNumber) {
+Sci::Position Editor::GetTag(char *tagValue, int tagNumber) {
        const char *text = 0;
-       int length = 0;
+       Sci::Position length = 0;
        if ((tagNumber >= 1) && (tagNumber <= 9)) {
                char name[3] = "\\?";
                name[1] = static_cast<char>(tagNumber + '0');
@@ -7188,7 +5563,7 @@ int Editor::GetTag(char *tagValue, int tagNumber) {
        return length;
 }
 
-int Editor::ReplaceTarget(bool replacePatterns, const char *text, int length) {
+Sci::Position Editor::ReplaceTarget(bool replacePatterns, const char *text, Sci::Position length) {
        UndoGroup ug(pdoc);
        if (length == -1)
                length = istrlen(text);
@@ -7201,8 +5576,8 @@ int Editor::ReplaceTarget(bool replacePatterns, const char *text, int length) {
        if (targetStart != targetEnd)
                pdoc->DeleteChars(targetStart, targetEnd - targetStart);
        targetEnd = targetStart;
-       pdoc->InsertString(targetStart, text, length);
-       targetEnd = targetStart + length;
+       const Sci::Position lengthInserted = pdoc->InsertString(targetStart, text, length);
+       targetEnd = targetStart + lengthInserted;
        return length;
 }
 
@@ -7219,35 +5594,35 @@ int Editor::CodePage() const {
 
 int Editor::WrapCount(int line) {
        AutoSurface surface(this);
-       AutoLineLayout ll(llc, RetrieveLineLayout(line));
+       AutoLineLayout ll(view.llc, view.RetrieveLineLayout(line, *this));
 
        if (surface && ll) {
-               LayoutLine(line, surface, vs, ll, wrapWidth);
+               view.LayoutLine(*this, line, surface, vs, ll, wrapWidth);
                return ll->lines;
        } else {
                return 1;
        }
 }
 
-void Editor::AddStyledText(char *buffer, int appendLength) {
+void Editor::AddStyledText(char *buffer, Sci::Position appendLength) {
        // The buffer consists of alternating character bytes and style bytes
-       int textLength = appendLength / 2;
+       Sci::Position textLength = appendLength / 2;
        std::string text(textLength, '\0');
-       int i;
+       Sci::Position i;
        for (i = 0; i < textLength; i++) {
                text[i] = buffer[i*2];
        }
-       pdoc->InsertString(CurrentPosition(), text.c_str(), textLength);
+       const Sci::Position lengthInserted = pdoc->InsertString(CurrentPosition(), text.c_str(), textLength);
        for (i = 0; i < textLength; i++) {
                text[i] = buffer[i*2+1];
        }
-       pdoc->StartStyling(CurrentPosition(), static_cast<char>(0xff));
+       pdoc->StartStyling(CurrentPosition(), static_cast<unsigned char>(0xff));
        pdoc->SetStyles(textLength, text.c_str());
-       SetEmptySelection(sel.MainCaret() + textLength);
+       SetEmptySelection(sel.MainCaret() + lengthInserted);
 }
 
-static bool ValidMargin(unsigned long wParam) {
-       return wParam <= SC_MAX_MARGIN;
+bool Editor::ValidMargin(uptr_t wParam) const {
+       return wParam < vs.ms.size();
 }
 
 static char *CharPtrFromSPtr(sptr_t lParam) {
@@ -7258,16 +5633,16 @@ void Editor::StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam
        vs.EnsureStyle(wParam);
        switch (iMessage) {
        case SCI_STYLESETFORE:
-               vs.styles[wParam].fore = ColourDesired(lParam);
+               vs.styles[wParam].fore = ColourDesired(static_cast<long>(lParam));
                break;
        case SCI_STYLESETBACK:
-               vs.styles[wParam].back = ColourDesired(lParam);
+               vs.styles[wParam].back = ColourDesired(static_cast<long>(lParam));
                break;
        case SCI_STYLESETBOLD:
                vs.styles[wParam].weight = lParam != 0 ? SC_WEIGHT_BOLD : SC_WEIGHT_NORMAL;
                break;
        case SCI_STYLESETWEIGHT:
-               vs.styles[wParam].weight = lParam;
+               vs.styles[wParam].weight = static_cast<int>(lParam);
                break;
        case SCI_STYLESETITALIC:
                vs.styles[wParam].italic = lParam != 0;
@@ -7276,14 +5651,14 @@ void Editor::StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam
                vs.styles[wParam].eolFilled = lParam != 0;
                break;
        case SCI_STYLESETSIZE:
-               vs.styles[wParam].size = lParam * SC_FONT_SIZE_MULTIPLIER;
+               vs.styles[wParam].size = static_cast<int>(lParam * SC_FONT_SIZE_MULTIPLIER);
                break;
        case SCI_STYLESETSIZEFRACTIONAL:
-               vs.styles[wParam].size = lParam;
+               vs.styles[wParam].size = static_cast<int>(lParam);
                break;
        case SCI_STYLESETFONT:
                if (lParam != 0) {
-                       vs.SetStyleFontName(wParam, CharPtrFromSPtr(lParam));
+                       vs.SetStyleFontName(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
                }
                break;
        case SCI_STYLESETUNDERLINE:
@@ -7293,8 +5668,8 @@ void Editor::StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam
                vs.styles[wParam].caseForce = static_cast<Style::ecaseForced>(lParam);
                break;
        case SCI_STYLESETCHARACTERSET:
-               vs.styles[wParam].characterSet = lParam;
-               pdoc->SetCaseFolder(NULL);
+               vs.styles[wParam].characterSet = static_cast<int>(lParam);
+               pdoc->SetCaseFolder(nullptr);
                break;
        case SCI_STYLESETVISIBLE:
                vs.styles[wParam].visible = lParam != 0;
@@ -7329,11 +5704,7 @@ sptr_t Editor::StyleGetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lPar
        case SCI_STYLEGETSIZEFRACTIONAL:
                return vs.styles[wParam].size;
        case SCI_STYLEGETFONT:
-               if (!vs.styles[wParam].fontName)
-                       return 0;
-               if (lParam != 0)
-                       strcpy(CharPtrFromSPtr(lParam), vs.styles[wParam].fontName);
-               return strlen(vs.styles[wParam].fontName);
+               return StringResult(lParam, vs.styles[wParam].fontName);
        case SCI_STYLEGETUNDERLINE:
                return vs.styles[wParam].underline ? 1 : 0;
        case SCI_STYLEGETCASE:
@@ -7350,13 +5721,61 @@ sptr_t Editor::StyleGetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lPar
        return 0;
 }
 
+void Editor::SetSelectionNMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
+       InvalidateRange(sel.Range(wParam).Start().Position(), sel.Range(wParam).End().Position());
+
+       switch (iMessage) {
+       case SCI_SETSELECTIONNCARET:
+               sel.Range(wParam).caret.SetPosition(static_cast<int>(lParam));
+               break;
+
+       case SCI_SETSELECTIONNANCHOR:
+               sel.Range(wParam).anchor.SetPosition(static_cast<int>(lParam));
+               break;
+
+       case SCI_SETSELECTIONNCARETVIRTUALSPACE:
+               sel.Range(wParam).caret.SetVirtualSpace(static_cast<int>(lParam));
+               break;
+
+       case SCI_SETSELECTIONNANCHORVIRTUALSPACE:
+               sel.Range(wParam).anchor.SetVirtualSpace(static_cast<int>(lParam));
+               break;
+
+       case SCI_SETSELECTIONNSTART:
+               sel.Range(wParam).anchor.SetPosition(static_cast<int>(lParam));
+               break;
+
+       case SCI_SETSELECTIONNEND:
+               sel.Range(wParam).caret.SetPosition(static_cast<int>(lParam));
+               break;
+       }
+
+       InvalidateRange(sel.Range(wParam).Start().Position(), sel.Range(wParam).End().Position());
+       ContainerNeedsUpdate(SC_UPDATE_SELECTION);
+}
+
 sptr_t Editor::StringResult(sptr_t lParam, const char *val) {
-       const size_t n = strlen(val);
-       if (lParam != 0) {
-               char *ptr = reinterpret_cast<char *>(lParam);
-               strcpy(ptr, val);
+       const size_t len = val ? strlen(val) : 0;
+       if (lParam) {
+               char *ptr = CharPtrFromSPtr(lParam);
+               if (val)
+                       memcpy(ptr, val, len+1);
+               else
+                       *ptr = 0;
        }
-       return n;       // Not including NUL
+       return len;     // Not including NUL
+}
+
+sptr_t Editor::BytesResult(sptr_t lParam, const unsigned char *val, size_t len) {
+       // No NUL termination: len is number of valid/displayed bytes
+       if ((lParam) && (len > 0)) {
+               char *ptr = CharPtrFromSPtr(lParam);
+               if (val)
+                       memcpy(ptr, val, len);
+               else
+                       *ptr = 0;
+       }
+       return val ? len : 0;
 }
 
 sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
@@ -7387,7 +5806,8 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                        UndoGroup ug(pdoc);
                        pdoc->DeleteChars(0, pdoc->Length());
                        SetEmptySelection(0);
-                       pdoc->InsertCString(0, CharPtrFromSPtr(lParam));
+                       const char *text = CharPtrFromSPtr(lParam);
+                       pdoc->InsertString(0, text, istrlen(text));
                        return 1;
                }
 
@@ -7420,11 +5840,11 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_COPYRANGE:
-               CopyRangeToClipboard(wParam, lParam);
+               CopyRangeToClipboard(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_COPYTEXT:
-               CopyText(wParam, CharPtrFromSPtr(lParam));
+               CopyText(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
                break;
 
        case SCI_PASTE:
@@ -7457,18 +5877,18 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return topLine;
 
        case SCI_SETFIRSTVISIBLELINE:
-               ScrollTo(wParam);
+               ScrollTo(static_cast<int>(wParam));
                break;
 
        case SCI_GETLINE: {     // Risk of overwriting the end of the buffer
-                       int lineStart = pdoc->LineStart(wParam);
-                       int lineEnd = pdoc->LineStart(wParam + 1);
+                       Sci::Position lineStart = pdoc->LineStart(static_cast<Sci::Line>(wParam));
+                       Sci::Position lineEnd = pdoc->LineStart(static_cast<Sci::Line>(wParam + 1));
                        if (lParam == 0) {
                                return lineEnd - lineStart;
                        }
                        char *ptr = CharPtrFromSPtr(lParam);
-                       int iPlace = 0;
-                       for (int iChar = lineStart; iChar < lineEnd; iChar++) {
+                       Sci::Position iPlace = 0;
+                       for (Sci::Position iChar = lineStart; iChar < lineEnd; iChar++) {
                                ptr[iPlace++] = pdoc->CharAt(iChar);
                        }
                        return iPlace;
@@ -7484,8 +5904,8 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return !pdoc->IsSavePoint();
 
        case SCI_SETSEL: {
-                       int nStart = static_cast<int>(wParam);
-                       int nEnd = static_cast<int>(lParam);
+                       Sci::Position nStart = static_cast<Sci::Position>(wParam);
+                       Sci::Position nEnd = static_cast<Sci::Position>(lParam);
                        if (nEnd < 0)
                                nEnd = pdoc->Length();
                        if (nStart < 0)
@@ -7519,25 +5939,25 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_LINEFROMPOSITION:
                if (static_cast<int>(wParam) < 0)
                        return 0;
-               return pdoc->LineFromPosition(wParam);
+               return pdoc->LineFromPosition(static_cast<int>(wParam));
 
        case SCI_POSITIONFROMLINE:
                if (static_cast<int>(wParam) < 0)
                        wParam = pdoc->LineFromPosition(SelectionStart().Position());
                if (wParam == 0)
                        return 0;       // Even if there is no text, there is a first line that starts at 0
-               if (static_cast<int>(wParam) > pdoc->LinesTotal())
+               if (static_cast<Sci::Line>(wParam) > pdoc->LinesTotal())
                        return -1;
                //if (wParam > pdoc->LineFromPosition(pdoc->Length()))  // Useful test, anyway...
                //      return -1;
-               return pdoc->LineStart(wParam);
+               return pdoc->LineStart(static_cast<int>(wParam));
 
                // Replacement of the old Scintilla interpretation of EM_LINELENGTH
        case SCI_LINELENGTH:
                if ((static_cast<int>(wParam) < 0) ||
                        (static_cast<int>(wParam) > pdoc->LineFromPosition(pdoc->Length())))
                        return 0;
-               return pdoc->LineStart(wParam + 1) - pdoc->LineStart(wParam);
+               return pdoc->LineStart(static_cast<int>(wParam) + 1) - 
pdoc->LineStart(static_cast<int>(wParam));
 
        case SCI_REPLACESEL: {
                        if (lParam == 0)
@@ -7545,26 +5965,37 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                        UndoGroup ug(pdoc);
                        ClearSelection();
                        char *replacement = CharPtrFromSPtr(lParam);
-                       pdoc->InsertCString(sel.MainCaret(), replacement);
-                       SetEmptySelection(sel.MainCaret() + istrlen(replacement));
+                       const Sci::Position lengthInserted = pdoc->InsertString(
+                               sel.MainCaret(), replacement, istrlen(replacement));
+                       SetEmptySelection(sel.MainCaret() + lengthInserted);
                        EnsureCaretVisible();
                }
                break;
 
        case SCI_SETTARGETSTART:
-               targetStart = wParam;
+               targetStart = static_cast<int>(wParam);
                break;
 
        case SCI_GETTARGETSTART:
                return targetStart;
 
        case SCI_SETTARGETEND:
-               targetEnd = wParam;
+               targetEnd = static_cast<int>(wParam);
                break;
 
        case SCI_GETTARGETEND:
                return targetEnd;
 
+       case SCI_SETTARGETRANGE:
+               targetStart = static_cast<int>(wParam);
+               targetEnd = static_cast<int>(lParam);
+               break;
+
+       case SCI_TARGETWHOLEDOCUMENT:
+               targetStart = 0;
+               targetEnd = pdoc->Length();
+               break;
+
        case SCI_TARGETFROMSELECTION:
                if (sel.MainCaret() < sel.MainAnchor()) {
                        targetStart = sel.MainCaret();
@@ -7575,41 +6006,49 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                }
                break;
 
+       case SCI_GETTARGETTEXT: {
+                       std::string text = RangeText(targetStart, targetEnd);
+                       return BytesResult(lParam, reinterpret_cast<const unsigned char *>(text.c_str()), 
text.length());
+               }
+
        case SCI_REPLACETARGET:
                PLATFORM_ASSERT(lParam);
-               return ReplaceTarget(false, CharPtrFromSPtr(lParam), wParam);
+               return ReplaceTarget(false, CharPtrFromSPtr(lParam), static_cast<Sci::Position>(wParam));
 
        case SCI_REPLACETARGETRE:
                PLATFORM_ASSERT(lParam);
-               return ReplaceTarget(true, CharPtrFromSPtr(lParam), wParam);
+               return ReplaceTarget(true, CharPtrFromSPtr(lParam), static_cast<Sci::Position>(wParam));
 
        case SCI_SEARCHINTARGET:
                PLATFORM_ASSERT(lParam);
-               return SearchInTarget(CharPtrFromSPtr(lParam), wParam);
+               return SearchInTarget(CharPtrFromSPtr(lParam), static_cast<Sci::Position>(wParam));
 
        case SCI_SETSEARCHFLAGS:
-               searchFlags = wParam;
+               searchFlags = static_cast<int>(wParam);
                break;
 
        case SCI_GETSEARCHFLAGS:
                return searchFlags;
 
        case SCI_GETTAG:
-               return GetTag(CharPtrFromSPtr(lParam), wParam);
+               return GetTag(CharPtrFromSPtr(lParam), static_cast<int>(wParam));
 
        case SCI_POSITIONBEFORE:
-               return pdoc->MovePositionOutsideChar(wParam - 1, -1, true);
+               return pdoc->MovePositionOutsideChar(static_cast<int>(wParam) - 1, -1, true);
 
        case SCI_POSITIONAFTER:
-               return pdoc->MovePositionOutsideChar(wParam + 1, 1, true);
+               return pdoc->MovePositionOutsideChar(static_cast<int>(wParam) + 1, 1, true);
+
+       case SCI_POSITIONRELATIVE:
+               return Platform::Clamp(pdoc->GetRelativePosition(static_cast<int>(wParam), 
static_cast<int>(lParam)), 0, pdoc->Length());
 
        case SCI_LINESCROLL:
-               ScrollTo(topLine + lParam);
-               HorizontalScrollTo(xOffset + static_cast<int>(wParam) * vs.spaceWidth);
+               ScrollTo(topLine + static_cast<Sci::Line>(lParam));
+               HorizontalScrollTo(xOffset + static_cast<int>(wParam) * static_cast<int>(vs.spaceWidth));
                return 1;
 
        case SCI_SETXOFFSET:
-               xOffset = wParam;
+               xOffset = static_cast<int>(wParam);
                ContainerNeedsUpdate(SC_UPDATE_H_SCROLL);
                SetHorizontalScrollPos();
                Redraw();
@@ -7640,17 +6079,17 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (lParam < 0) {
                        return 0;
                } else {
-                       Point pt = LocationFromPosition(lParam);
+                       Point pt = LocationFromPosition(static_cast<int>(lParam));
                        // Convert to view-relative
-                       return pt.x - vs.textStart + vs.fixedColumnWidth;
+                       return static_cast<int>(pt.x) - vs.textStart + vs.fixedColumnWidth;
                }
 
        case SCI_POINTYFROMPOSITION:
                if (lParam < 0) {
                        return 0;
                } else {
-                       Point pt = LocationFromPosition(lParam);
-                       return pt.y;
+                       Point pt = LocationFromPosition(static_cast<int>(lParam));
+                       return static_cast<int>(pt.y);
                }
 
        case SCI_FINDTEXT:
@@ -7660,19 +6099,19 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                        if (lParam == 0)
                                return 0;
                        Sci_TextRange *tr = reinterpret_cast<Sci_TextRange *>(lParam);
-                       int cpMax = tr->chrg.cpMax;
+                       Sci::Position cpMax = static_cast<Sci::Position>(tr->chrg.cpMax);
                        if (cpMax == -1)
                                cpMax = pdoc->Length();
                        PLATFORM_ASSERT(cpMax <= pdoc->Length());
-                       int len = cpMax - tr->chrg.cpMin;       // No -1 as cpMin and cpMax are referring to 
inter character positions
-                       pdoc->GetCharRange(tr->lpstrText, tr->chrg.cpMin, len);
+                       int len = static_cast<int>(cpMax - tr->chrg.cpMin);     // No -1 as cpMin and cpMax 
are referring to inter character positions
+                       pdoc->GetCharRange(tr->lpstrText, static_cast<int>(tr->chrg.cpMin), len);
                        // Spec says copied text is terminated with a NUL
                        tr->lpstrText[len] = '\0';
                        return len;     // Not including NUL
                }
 
        case SCI_HIDESELECTION:
-               hideSelection = wParam != 0;
+               view.hideSelection = wParam != 0;
                Redraw();
                break;
 
@@ -7686,12 +6125,13 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.rightMarginWidth;
 
        case SCI_SETMARGINLEFT:
-               vs.leftMarginWidth = lParam;
+               lastXChosen += static_cast<int>(lParam) - vs.leftMarginWidth;
+               vs.leftMarginWidth = static_cast<int>(lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETMARGINRIGHT:
-               vs.rightMarginWidth = lParam;
+               vs.rightMarginWidth = static_cast<int>(lParam);
                InvalidateStyleRedraw();
                break;
 
@@ -7700,33 +6140,39 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_ADDTEXT: {
                        if (lParam == 0)
                                return 0;
-                       pdoc->InsertString(CurrentPosition(), CharPtrFromSPtr(lParam), wParam);
-                       SetEmptySelection(sel.MainCaret() + wParam);
+                       const Sci::Position lengthInserted = pdoc->InsertString(
+                               CurrentPosition(), CharPtrFromSPtr(lParam), 
static_cast<Sci::Position>(wParam));
+                       SetEmptySelection(sel.MainCaret() + lengthInserted);
                        return 0;
                }
 
        case SCI_ADDSTYLEDTEXT:
                if (lParam)
-                       AddStyledText(CharPtrFromSPtr(lParam), wParam);
+                       AddStyledText(CharPtrFromSPtr(lParam), static_cast<Sci::Position>(wParam));
                return 0;
 
        case SCI_INSERTTEXT: {
                        if (lParam == 0)
                                return 0;
-                       int insertPos = wParam;
+                       Sci::Position insertPos = static_cast<Sci::Position>(wParam);
                        if (static_cast<int>(wParam) == -1)
                                insertPos = CurrentPosition();
-                       int newCurrent = CurrentPosition();
+                       Sci::Position newCurrent = CurrentPosition();
                        char *sz = CharPtrFromSPtr(lParam);
-                       pdoc->InsertCString(insertPos, sz);
+                       const Sci::Position lengthInserted = pdoc->InsertString(insertPos, sz, istrlen(sz));
                        if (newCurrent > insertPos)
-                               newCurrent += istrlen(sz);
+                               newCurrent += lengthInserted;
                        SetEmptySelection(newCurrent);
                        return 0;
                }
 
+       case SCI_CHANGEINSERTION:
+               PLATFORM_ASSERT(lParam);
+               pdoc->ChangeInsertion(CharPtrFromSPtr(lParam), static_cast<int>(wParam));
+               return 0;
+
        case SCI_APPENDTEXT:
-               pdoc->InsertString(pdoc->Length(), CharPtrFromSPtr(lParam), wParam);
+               pdoc->InsertString(pdoc->Length(), CharPtrFromSPtr(lParam), static_cast<int>(wParam));
                return 0;
 
        case SCI_CLEARALL:
@@ -7734,7 +6180,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return 0;
 
        case SCI_DELETERANGE:
-               pdoc->DeleteChars(wParam, lParam);
+               pdoc->DeleteChars(static_cast<int>(wParam), static_cast<int>(lParam));
                return 0;
 
        case SCI_CLEARDOCUMENTSTYLE:
@@ -7760,7 +6206,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return caret.period;
 
        case SCI_SETCARETPERIOD:
-               caret.period = wParam;
+               CaretSetPeriod(static_cast<int>(wParam));
                break;
 
        case SCI_GETWORDCHARS:
@@ -7802,19 +6248,19 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return pdoc->Length();
 
        case SCI_ALLOCATE:
-               pdoc->Allocate(wParam);
+               pdoc->Allocate(static_cast<Sci::Position>(wParam));
                break;
 
        case SCI_GETCHARAT:
-               return pdoc->CharAt(wParam);
+               return pdoc->CharAt(static_cast<Sci::Position>(wParam));
 
        case SCI_SETCURRENTPOS:
                if (sel.IsRectangular()) {
-                       sel.Rectangular().caret.SetPosition(wParam);
+                       sel.Rectangular().caret.SetPosition(static_cast<int>(wParam));
                        SetRectangularRange();
                        Redraw();
                } else {
-                       SetSelection(wParam, sel.MainAnchor());
+                       SetSelection(static_cast<Sci::Position>(wParam), sel.MainAnchor());
                }
                break;
 
@@ -7823,11 +6269,11 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_SETANCHOR:
                if (sel.IsRectangular()) {
-                       sel.Rectangular().anchor.SetPosition(wParam);
+                       sel.Rectangular().anchor.SetPosition(static_cast<Sci::Position>(wParam));
                        SetRectangularRange();
                        Redraw();
                } else {
-                       SetSelection(sel.MainCaret(), wParam);
+                       SetSelection(sel.MainCaret(), static_cast<Sci::Position>(wParam));
                }
                break;
 
@@ -7835,49 +6281,49 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return sel.IsRectangular() ? sel.Rectangular().anchor.Position() : sel.MainAnchor();
 
        case SCI_SETSELECTIONSTART:
-               SetSelection(Platform::Maximum(sel.MainCaret(), wParam), wParam);
+               SetSelection(std::max(sel.MainCaret(), static_cast<Sci::Position>(wParam)), 
static_cast<Sci::Position>(wParam));
                break;
 
        case SCI_GETSELECTIONSTART:
                return sel.LimitsForRectangularElseMain().start.Position();
 
        case SCI_SETSELECTIONEND:
-               SetSelection(wParam, Platform::Minimum(sel.MainAnchor(), wParam));
+               SetSelection(static_cast<Sci::Position>(wParam), std::min(sel.MainAnchor(), 
static_cast<Sci::Position>(wParam)));
                break;
 
        case SCI_GETSELECTIONEND:
                return sel.LimitsForRectangularElseMain().end.Position();
 
        case SCI_SETEMPTYSELECTION:
-               SetEmptySelection(wParam);
+               SetEmptySelection(static_cast<int>(wParam));
                break;
 
        case SCI_SETPRINTMAGNIFICATION:
-               printMagnification = wParam;
+               view.printParameters.magnification = static_cast<int>(wParam);
                break;
 
        case SCI_GETPRINTMAGNIFICATION:
-               return printMagnification;
+               return view.printParameters.magnification;
 
        case SCI_SETPRINTCOLOURMODE:
-               printColourMode = wParam;
+               view.printParameters.colourMode = static_cast<int>(wParam);
                break;
 
        case SCI_GETPRINTCOLOURMODE:
-               return printColourMode;
+               return view.printParameters.colourMode;
 
        case SCI_SETPRINTWRAPMODE:
-               printWrapState = (wParam == SC_WRAP_WORD) ? eWrapWord : eWrapNone;
+               view.printParameters.wrapState = (wParam == SC_WRAP_WORD) ? eWrapWord : eWrapNone;
                break;
 
        case SCI_GETPRINTWRAPMODE:
-               return printWrapState;
+               return view.printParameters.wrapState;
 
        case SCI_GETSTYLEAT:
                if (static_cast<int>(wParam) >= pdoc->Length())
                        return 0;
                else
-                       return pdoc->StyleAt(wParam);
+                       return pdoc->StyleAt(static_cast<int>(wParam));
 
        case SCI_REDO:
                Redo();
@@ -7896,9 +6342,9 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                                return 0;
                        Sci_TextRange *tr = reinterpret_cast<Sci_TextRange *>(lParam);
                        int iPlace = 0;
-                       for (int iChar = tr->chrg.cpMin; iChar < tr->chrg.cpMax; iChar++) {
-                               tr->lpstrText[iPlace++] = pdoc->CharAt(iChar);
-                               tr->lpstrText[iPlace++] = pdoc->StyleAt(iChar);
+                       for (long iChar = tr->chrg.cpMin; iChar < tr->chrg.cpMax; iChar++) {
+                               tr->lpstrText[iPlace++] = pdoc->CharAt(static_cast<int>(iChar));
+                               tr->lpstrText[iPlace++] = pdoc->StyleAt(static_cast<int>(iChar));
                        }
                        tr->lpstrText[iPlace] = '\0';
                        tr->lpstrText[iPlace + 1] = '\0';
@@ -7909,10 +6355,10 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return (pdoc->CanRedo() && !pdoc->IsReadOnly()) ? 1 : 0;
 
        case SCI_MARKERLINEFROMHANDLE:
-               return pdoc->LineFromHandle(wParam);
+               return pdoc->LineFromHandle(static_cast<int>(wParam));
 
        case SCI_MARKERDELETEHANDLE:
-               pdoc->DeleteMarkFromHandle(wParam);
+               pdoc->DeleteMarkFromHandle(static_cast<int>(wParam));
                break;
 
        case SCI_GETVIEWWS:
@@ -7923,6 +6369,14 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                Redraw();
                break;
 
+       case SCI_GETTABDRAWMODE:
+               return vs.tabDrawMode;
+
+       case SCI_SETTABDRAWMODE:
+               vs.tabDrawMode = static_cast<TabDrawMode>(wParam);
+               Redraw();
+               break;
+
        case SCI_GETWHITESPACESIZE:
                return vs.whitespaceSize;
 
@@ -7932,37 +6386,41 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_POSITIONFROMPOINT:
-               return PositionFromLocation(Point(wParam, lParam), false, false);
+               return PositionFromLocation(Point::FromInts(static_cast<int>(wParam) - 
vs.ExternalMarginWidth(), static_cast<int>(lParam)),
+                                           false, false);
 
        case SCI_POSITIONFROMPOINTCLOSE:
-               return PositionFromLocation(Point(wParam, lParam), true, false);
+               return PositionFromLocation(Point::FromInts(static_cast<int>(wParam) - 
vs.ExternalMarginWidth(), static_cast<int>(lParam)),
+                                           true, false);
 
        case SCI_CHARPOSITIONFROMPOINT:
-               return PositionFromLocation(Point(wParam, lParam), false, true);
+               return PositionFromLocation(Point::FromInts(static_cast<int>(wParam) - 
vs.ExternalMarginWidth(), static_cast<int>(lParam)),
+                                           false, true);
 
        case SCI_CHARPOSITIONFROMPOINTCLOSE:
-               return PositionFromLocation(Point(wParam, lParam), true, true);
+               return PositionFromLocation(Point::FromInts(static_cast<int>(wParam) - 
vs.ExternalMarginWidth(), static_cast<int>(lParam)),
+                                           true, true);
 
        case SCI_GOTOLINE:
-               GoToLine(wParam);
+               GoToLine(static_cast<int>(wParam));
                break;
 
        case SCI_GOTOPOS:
-               SetEmptySelection(wParam);
+               SetEmptySelection(static_cast<int>(wParam));
                EnsureCaretVisible();
                break;
 
        case SCI_GETCURLINE: {
-                       int lineCurrentPos = pdoc->LineFromPosition(sel.MainCaret());
-                       int lineStart = pdoc->LineStart(lineCurrentPos);
-                       unsigned int lineEnd = pdoc->LineStart(lineCurrentPos + 1);
+                       const Sci::Line lineCurrentPos = pdoc->LineFromPosition(sel.MainCaret());
+                       const Sci::Position lineStart = pdoc->LineStart(lineCurrentPos);
+                       const Sci::Position lineEnd = pdoc->LineStart(lineCurrentPos + 1);
                        if (lParam == 0) {
                                return 1 + lineEnd - lineStart;
                        }
                        PLATFORM_ASSERT(wParam > 0);
                        char *ptr = CharPtrFromSPtr(lParam);
                        unsigned int iPlace = 0;
-                       for (unsigned int iChar = lineStart; iChar < lineEnd && iPlace < wParam - 1; iChar++) 
{
+                       for (Sci::Position iChar = lineStart; iChar < lineEnd && iPlace < wParam - 1; 
iChar++) {
                                ptr[iPlace++] = pdoc->CharAt(iChar);
                        }
                        ptr[iPlace] = '\0';
@@ -7976,11 +6434,11 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return pdoc->eolMode;
 
        case SCI_SETEOLMODE:
-               pdoc->eolMode = wParam;
+               pdoc->eolMode = static_cast<int>(wParam);
                break;
 
        case SCI_SETLINEENDTYPESALLOWED:
-               if (pdoc->SetLineEndTypesAllowed(wParam)) {
+               if (pdoc->SetLineEndTypesAllowed(static_cast<int>(wParam))) {
                        cs.Clear();
                        cs.InsertLines(0, pdoc->LinesTotal() - 1);
                        SetAnnotationHeights(0, pdoc->LinesTotal());
@@ -7995,32 +6453,43 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return pdoc->GetLineEndTypesActive();
 
        case SCI_STARTSTYLING:
-               pdoc->StartStyling(wParam, static_cast<char>(lParam));
+               pdoc->StartStyling(static_cast<int>(wParam), static_cast<char>(lParam));
                break;
 
        case SCI_SETSTYLING:
-               pdoc->SetStyleFor(wParam, static_cast<char>(lParam));
+               if (static_cast<int>(wParam) < 0)
+                       errorStatus = SC_STATUS_FAILURE;
+               else
+                       pdoc->SetStyleFor(static_cast<int>(wParam), static_cast<char>(lParam));
                break;
 
        case SCI_SETSTYLINGEX:             // Specify a complete styling buffer
                if (lParam == 0)
                        return 0;
-               pdoc->SetStyles(wParam, CharPtrFromSPtr(lParam));
+               pdoc->SetStyles(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
                break;
 
        case SCI_SETBUFFEREDDRAW:
-               bufferedDraw = wParam != 0;
+               view.bufferedDraw = wParam != 0;
                break;
 
        case SCI_GETBUFFEREDDRAW:
-               return bufferedDraw;
+               return view.bufferedDraw;
 
        case SCI_GETTWOPHASEDRAW:
-               return twoPhaseDraw;
+               return view.phasesDraw == EditView::phasesTwo;
 
        case SCI_SETTWOPHASEDRAW:
-               twoPhaseDraw = wParam != 0;
-               InvalidateStyleRedraw();
+               if (view.SetTwoPhaseDraw(wParam != 0))
+                       InvalidateStyleRedraw();
+               break;
+
+       case SCI_GETPHASESDRAW:
+               return view.phasesDraw;
+
+       case SCI_SETPHASESDRAW:
+               if (view.SetPhasesDraw(static_cast<int>(wParam)))
+                       InvalidateStyleRedraw();
                break;
 
        case SCI_SETFONTQUALITY:
@@ -8034,7 +6503,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_SETTABWIDTH:
                if (wParam > 0) {
-                       pdoc->tabInChars = wParam;
+                       pdoc->tabInChars = static_cast<int>(wParam);
                        if (pdoc->indentInChars == 0)
                                pdoc->actualIndentInChars = pdoc->tabInChars;
                }
@@ -8044,8 +6513,25 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_GETTABWIDTH:
                return pdoc->tabInChars;
 
+       case SCI_CLEARTABSTOPS:
+               if (view.ClearTabstops(static_cast<int>(wParam))) {
+                       DocModification mh(SC_MOD_CHANGETABSTOPS, 0, 0, 0, 0, static_cast<int>(wParam));
+                       NotifyModified(pdoc, mh, NULL);
+               }
+               break;
+
+       case SCI_ADDTABSTOP:
+               if (view.AddTabstop(static_cast<int>(wParam), static_cast<int>(lParam))) {
+                       DocModification mh(SC_MOD_CHANGETABSTOPS, 0, 0, 0, 0, static_cast<int>(wParam));
+                       NotifyModified(pdoc, mh, NULL);
+               }
+               break;
+
+       case SCI_GETNEXTTABSTOP:
+               return view.GetNextTabstop(static_cast<int>(wParam), static_cast<int>(lParam));
+
        case SCI_SETINDENT:
-               pdoc->indentInChars = wParam;
+               pdoc->indentInChars = static_cast<int>(wParam);
                if (pdoc->indentInChars != 0)
                        pdoc->actualIndentInChars = pdoc->indentInChars;
                else
@@ -8065,14 +6551,14 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return pdoc->useTabs;
 
        case SCI_SETLINEINDENTATION:
-               pdoc->SetLineIndentation(wParam, lParam);
+               pdoc->SetLineIndentation(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_GETLINEINDENTATION:
-               return pdoc->GetLineIndentation(wParam);
+               return pdoc->GetLineIndentation(static_cast<int>(wParam));
 
        case SCI_GETLINEINDENTPOSITION:
-               return pdoc->GetLineIndentPosition(wParam);
+               return pdoc->GetLineIndentPosition(static_cast<int>(wParam));
 
        case SCI_SETTABINDENTS:
                pdoc->tabIndents = wParam != 0;
@@ -8089,7 +6575,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return pdoc->backspaceUnindents;
 
        case SCI_SETMOUSEDWELLTIME:
-               dwellDelay = wParam;
+               dwellDelay = static_cast<int>(wParam);
                ticksToDwell = dwellDelay;
                break;
 
@@ -8097,92 +6583,91 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return dwellDelay;
 
        case SCI_WORDSTARTPOSITION:
-               return pdoc->ExtendWordSelect(wParam, -1, lParam != 0);
+               return pdoc->ExtendWordSelect(static_cast<int>(wParam), -1, lParam != 0);
 
        case SCI_WORDENDPOSITION:
-               return pdoc->ExtendWordSelect(wParam, 1, lParam != 0);
+               return pdoc->ExtendWordSelect(static_cast<int>(wParam), 1, lParam != 0);
+
+       case SCI_ISRANGEWORD:
+               return pdoc->IsWordAt(static_cast<int>(wParam), static_cast<int>(lParam));
+
+       case SCI_SETIDLESTYLING:
+               idleStyling = static_cast<int>(wParam);
+               break;
+
+       case SCI_GETIDLESTYLING:
+               return idleStyling;
 
        case SCI_SETWRAPMODE:
-               switch (wParam) {
-               case SC_WRAP_WORD:
-                       wrapState = eWrapWord;
-                       break;
-               case SC_WRAP_CHAR:
-                       wrapState = eWrapChar;
-                       break;
-               default:
-                       wrapState = eWrapNone;
-                       break;
+               if (vs.SetWrapState(static_cast<int>(wParam))) {
+                       xOffset = 0;
+                       ContainerNeedsUpdate(SC_UPDATE_H_SCROLL);
+                       InvalidateStyleRedraw();
+                       ReconfigureScrollBars();
                }
-               xOffset = 0;
-               ContainerNeedsUpdate(SC_UPDATE_H_SCROLL);
-               InvalidateStyleRedraw();
-               ReconfigureScrollBars();
                break;
 
        case SCI_GETWRAPMODE:
-               return wrapState;
+               return vs.wrapState;
 
        case SCI_SETWRAPVISUALFLAGS:
-               if (wrapVisualFlags != static_cast<int>(wParam)) {
-                       wrapVisualFlags = wParam;
+               if (vs.SetWrapVisualFlags(static_cast<int>(wParam))) {
                        InvalidateStyleRedraw();
                        ReconfigureScrollBars();
                }
                break;
 
        case SCI_GETWRAPVISUALFLAGS:
-               return wrapVisualFlags;
+               return vs.wrapVisualFlags;
 
        case SCI_SETWRAPVISUALFLAGSLOCATION:
-               wrapVisualFlagsLocation = wParam;
-               InvalidateStyleRedraw();
+               if (vs.SetWrapVisualFlagsLocation(static_cast<int>(wParam))) {
+                       InvalidateStyleRedraw();
+               }
                break;
 
        case SCI_GETWRAPVISUALFLAGSLOCATION:
-               return wrapVisualFlagsLocation;
+               return vs.wrapVisualFlagsLocation;
 
        case SCI_SETWRAPSTARTINDENT:
-               if (wrapVisualStartIndent != static_cast<int>(wParam)) {
-                       wrapVisualStartIndent = wParam;
+               if (vs.SetWrapVisualStartIndent(static_cast<int>(wParam))) {
                        InvalidateStyleRedraw();
                        ReconfigureScrollBars();
                }
                break;
 
        case SCI_GETWRAPSTARTINDENT:
-               return wrapVisualStartIndent;
+               return vs.wrapVisualStartIndent;
 
        case SCI_SETWRAPINDENTMODE:
-               if (wrapIndentMode != static_cast<int>(wParam)) {
-                       wrapIndentMode = wParam;
+               if (vs.SetWrapIndentMode(static_cast<int>(wParam))) {
                        InvalidateStyleRedraw();
                        ReconfigureScrollBars();
                }
                break;
 
        case SCI_GETWRAPINDENTMODE:
-               return wrapIndentMode;
+               return vs.wrapIndentMode;
 
        case SCI_SETLAYOUTCACHE:
-               llc.SetLevel(wParam);
+               view.llc.SetLevel(static_cast<int>(wParam));
                break;
 
        case SCI_GETLAYOUTCACHE:
-               return llc.GetLevel();
+               return view.llc.GetLevel();
 
        case SCI_SETPOSITIONCACHE:
-               posCache.SetSize(wParam);
+               view.posCache.SetSize(wParam);
                break;
 
        case SCI_GETPOSITIONCACHE:
-               return posCache.GetSize();
+               return view.posCache.GetSize();
 
        case SCI_SETSCROLLWIDTH:
                PLATFORM_ASSERT(wParam > 0);
                if ((wParam > 0) && (wParam != static_cast<unsigned int >(scrollWidth))) {
-                       lineWidthMaxSeen = 0;
-                       scrollWidth = wParam;
+                       view.lineWidthMaxSeen = 0;
+                       scrollWidth = static_cast<int>(wParam);
                        SetScrollBars();
                }
                break;
@@ -8202,15 +6687,16 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_LINESSPLIT:
-               LinesSplit(wParam);
+               LinesSplit(static_cast<int>(wParam));
                break;
 
        case SCI_TEXTWIDTH:
                PLATFORM_ASSERT(wParam < vs.styles.size());
                PLATFORM_ASSERT(lParam);
-               return TextWidth(wParam, CharPtrFromSPtr(lParam));
+               return TextWidth(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
 
        case SCI_TEXTHEIGHT:
+               RefreshStyleData();
                return vs.lineHeight;
 
        case SCI_SETENDATLASTLINE:
@@ -8227,7 +6713,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_SETCARETSTICKY:
                PLATFORM_ASSERT(wParam <= SC_CARETSTICKY_WHITESPACE);
                if (wParam <= SC_CARETSTICKY_WHITESPACE) {
-                       caretSticky = wParam;
+                       caretSticky = static_cast<int>(wParam);
                }
                break;
 
@@ -8239,10 +6725,10 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_GETCOLUMN:
-               return pdoc->GetColumn(wParam);
+               return pdoc->GetColumn(static_cast<int>(wParam));
 
        case SCI_FINDCOLUMN:
-               return pdoc->FindColumn(wParam, lParam);
+               return pdoc->FindColumn(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_SETHSCROLLBAR :
                if (horizontalScrollBarVisible != (wParam != 0)) {
@@ -8278,7 +6764,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_SETHIGHLIGHTGUIDE:
                if ((highlightGuideColumn != static_cast<int>(wParam)) || (wParam > 0)) {
-                       highlightGuideColumn = wParam;
+                       highlightGuideColumn = static_cast<int>(wParam);
                        Redraw();
                }
                break;
@@ -8287,15 +6773,16 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return highlightGuideColumn;
 
        case SCI_GETLINEENDPOSITION:
-               return pdoc->LineEnd(wParam);
+               return pdoc->LineEnd(static_cast<int>(wParam));
 
        case SCI_SETCODEPAGE:
-               if (ValidCodePage(wParam)) {
-                       if (pdoc->SetDBCSCodePage(wParam)) {
+               if (ValidCodePage(static_cast<int>(wParam))) {
+                       if (pdoc->SetDBCSCodePage(static_cast<int>(wParam))) {
                                cs.Clear();
                                cs.InsertLines(0, pdoc->LinesTotal() - 1);
                                SetAnnotationHeights(0, pdoc->LinesTotal());
                                InvalidateStyleRedraw();
+                               SetRepresentations();
                        }
                }
                break;
@@ -8303,19 +6790,17 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_GETCODEPAGE:
                return pdoc->dbcsCodePage;
 
-#ifdef INCLUDE_DEPRECATED_FEATURES
-       case SCI_SETUSEPALETTE:
-               InvalidateStyleRedraw();
+       case SCI_SETIMEINTERACTION:
+               imeInteraction = static_cast<EditModel::IMEInteraction>(wParam);
                break;
 
-       case SCI_GETUSEPALETTE:
-               return 0;
-#endif
+       case SCI_GETIMEINTERACTION:
+               return imeInteraction;
 
                // Marker definition and setting
        case SCI_MARKERDEFINE:
                if (wParam <= MARKER_MAX) {
-                       vs.markers[wParam].markType = lParam;
+                       vs.markers[wParam].markType = static_cast<int>(lParam);
                        vs.CalcLargestMarkerHeight();
                }
                InvalidateStyleData();
@@ -8330,42 +6815,42 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_MARKERSETFORE:
                if (wParam <= MARKER_MAX)
-                       vs.markers[wParam].fore = ColourDesired(lParam);
+                       vs.markers[wParam].fore = ColourDesired(static_cast<long>(lParam));
                InvalidateStyleData();
                RedrawSelMargin();
                break;
        case SCI_MARKERSETBACKSELECTED:
                if (wParam <= MARKER_MAX)
-                       vs.markers[wParam].backSelected = ColourDesired(lParam);
+                       vs.markers[wParam].backSelected = ColourDesired(static_cast<long>(lParam));
                InvalidateStyleData();
                RedrawSelMargin();
                break;
        case SCI_MARKERENABLEHIGHLIGHT:
-               highlightDelimiter.isEnabled = wParam == 1;
+               marginView.highlightDelimiter.isEnabled = wParam == 1;
                RedrawSelMargin();
                break;
        case SCI_MARKERSETBACK:
                if (wParam <= MARKER_MAX)
-                       vs.markers[wParam].back = ColourDesired(lParam);
+                       vs.markers[wParam].back = ColourDesired(static_cast<long>(lParam));
                InvalidateStyleData();
                RedrawSelMargin();
                break;
        case SCI_MARKERSETALPHA:
                if (wParam <= MARKER_MAX)
-                       vs.markers[wParam].alpha = lParam;
+                       vs.markers[wParam].alpha = static_cast<int>(lParam);
                InvalidateStyleRedraw();
                break;
        case SCI_MARKERADD: {
-                       int markerID = pdoc->AddMark(wParam, lParam);
+                       int markerID = pdoc->AddMark(static_cast<int>(wParam), static_cast<int>(lParam));
                        return markerID;
                }
        case SCI_MARKERADDSET:
                if (lParam != 0)
-                       pdoc->AddMarkSet(wParam, lParam);
+                       pdoc->AddMarkSet(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_MARKERDELETE:
-               pdoc->DeleteMark(wParam, lParam);
+               pdoc->DeleteMark(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_MARKERDELETEALL:
@@ -8373,13 +6858,13 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_MARKERGET:
-               return pdoc->GetMark(wParam);
+               return pdoc->GetMark(static_cast<int>(wParam));
 
        case SCI_MARKERNEXT:
-               return pdoc->MarkerNext(wParam, lParam);
+               return pdoc->MarkerNext(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_MARKERPREVIOUS: {
-                       for (int iLine = wParam; iLine >= 0; iLine--) {
+                       for (int iLine = static_cast<int>(wParam); iLine >= 0; iLine--) {
                                if ((pdoc->GetMark(iLine) & lParam) != 0)
                                        return iLine;
                        }
@@ -8390,35 +6875,35 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (wParam <= MARKER_MAX) {
                        vs.markers[wParam].SetXPM(CharPtrFromSPtr(lParam));
                        vs.CalcLargestMarkerHeight();
-               };
+               }
                InvalidateStyleData();
                RedrawSelMargin();
                break;
 
        case SCI_RGBAIMAGESETWIDTH:
-               sizeRGBAImage.x = wParam;
+               sizeRGBAImage.x = static_cast<XYPOSITION>(wParam);
                break;
 
        case SCI_RGBAIMAGESETHEIGHT:
-               sizeRGBAImage.y = wParam;
+               sizeRGBAImage.y = static_cast<XYPOSITION>(wParam);
                break;
 
        case SCI_RGBAIMAGESETSCALE:
-               scaleRGBAImage = wParam;
+               scaleRGBAImage = static_cast<float>(wParam);
                break;
 
        case SCI_MARKERDEFINERGBAIMAGE:
                if (wParam <= MARKER_MAX) {
-                       vs.markers[wParam].SetRGBAImage(sizeRGBAImage, scaleRGBAImage / 100.0, 
reinterpret_cast<unsigned char *>(lParam));
+                       vs.markers[wParam].SetRGBAImage(sizeRGBAImage, scaleRGBAImage / 100.0f, 
reinterpret_cast<unsigned char *>(lParam));
                        vs.CalcLargestMarkerHeight();
-               };
+               }
                InvalidateStyleData();
                RedrawSelMargin();
                break;
 
        case SCI_SETMARGINTYPEN:
                if (ValidMargin(wParam)) {
-                       vs.ms[wParam].style = lParam;
+                       vs.ms[wParam].style = static_cast<int>(lParam);
                        InvalidateStyleRedraw();
                }
                break;
@@ -8433,7 +6918,8 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (ValidMargin(wParam)) {
                        // Short-circuit if the width is unchanged, to avoid unnecessary redraw.
                        if (vs.ms[wParam].width != lParam) {
-                               vs.ms[wParam].width = lParam;
+                               lastXChosen += static_cast<int>(lParam) - vs.ms[wParam].width;
+                               vs.ms[wParam].width = static_cast<int>(lParam);
                                InvalidateStyleRedraw();
                        }
                }
@@ -8447,7 +6933,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_SETMARGINMASKN:
                if (ValidMargin(wParam)) {
-                       vs.ms[wParam].mask = lParam;
+                       vs.ms[wParam].mask = static_cast<int>(lParam);
                        InvalidateStyleRedraw();
                }
                break;
@@ -8473,7 +6959,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_SETMARGINCURSORN:
                if (ValidMargin(wParam))
-                       vs.ms[wParam].cursor = lParam;
+                       vs.ms[wParam].cursor = static_cast<int>(lParam);
                break;
 
        case SCI_GETMARGINCURSORN:
@@ -8482,6 +6968,27 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                else
                        return 0;
 
+       case SCI_SETMARGINBACKN:
+               if (ValidMargin(wParam)) {
+                       vs.ms[wParam].back = ColourDesired(static_cast<long>(lParam));
+                       InvalidateStyleRedraw();
+               }
+               break;
+
+       case SCI_GETMARGINBACKN:
+               if (ValidMargin(wParam))
+                       return vs.ms[wParam].back.AsLong();
+               else
+                       return 0;
+
+       case SCI_SETMARGINS:
+               if (wParam < 1000)
+                       vs.ms.resize(wParam);
+               break;
+
+       case SCI_GETMARGINS:
+               return vs.ms.size();
+
        case SCI_STYLECLEARALL:
                vs.ClearStyles();
                InvalidateStyleRedraw();
@@ -8527,18 +7034,17 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                InvalidateStyleRedraw();
                break;
        case SCI_SETSTYLEBITS:
-               vs.EnsureStyle((1 << wParam) - 1);
-               pdoc->SetStylingBits(wParam);
+               vs.EnsureStyle(0xff);
                break;
 
        case SCI_GETSTYLEBITS:
-               return pdoc->stylingBits;
+               return 8;
 
        case SCI_SETLINESTATE:
-               return pdoc->SetLineState(wParam, lParam);
+               return pdoc->SetLineState(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_GETLINESTATE:
-               return pdoc->GetLineState(wParam);
+               return pdoc->GetLineState(static_cast<int>(wParam));
 
        case SCI_GETMAXLINESTATE:
                return pdoc->GetMaxLineState();
@@ -8556,117 +7062,133 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                InvalidateStyleRedraw();
                break;
 
+       case SCI_GETCARETLINEFRAME:
+               return vs.caretLineFrame;
+       case SCI_SETCARETLINEFRAME:
+               vs.caretLineFrame = static_cast<int>(wParam);
+               InvalidateStyleRedraw();
+               break;
        case SCI_GETCARETLINEBACK:
                return vs.caretLineBackground.AsLong();
        case SCI_SETCARETLINEBACK:
-               vs.caretLineBackground = wParam;
+               vs.caretLineBackground = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
        case SCI_GETCARETLINEBACKALPHA:
                return vs.caretLineAlpha;
        case SCI_SETCARETLINEBACKALPHA:
-               vs.caretLineAlpha = wParam;
+               vs.caretLineAlpha = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
                // Folding messages
 
        case SCI_VISIBLEFROMDOCLINE:
-               return cs.DisplayFromDoc(wParam);
+               return cs.DisplayFromDoc(static_cast<int>(wParam));
 
        case SCI_DOCLINEFROMVISIBLE:
-               return cs.DocFromDisplay(wParam);
+               return cs.DocFromDisplay(static_cast<int>(wParam));
 
        case SCI_WRAPCOUNT:
-               return WrapCount(wParam);
+               return WrapCount(static_cast<int>(wParam));
 
        case SCI_SETFOLDLEVEL: {
-                       int prev = pdoc->SetLevel(wParam, lParam);
-                       if (prev != lParam)
+                       int prev = pdoc->SetLevel(static_cast<int>(wParam), static_cast<int>(lParam));
+                       if (prev != static_cast<int>(lParam))
                                RedrawSelMargin();
                        return prev;
                }
 
        case SCI_GETFOLDLEVEL:
-               return pdoc->GetLevel(wParam);
+               return pdoc->GetLevel(static_cast<int>(wParam));
 
        case SCI_GETLASTCHILD:
-               return pdoc->GetLastChild(wParam, lParam);
+               return pdoc->GetLastChild(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_GETFOLDPARENT:
-               return pdoc->GetFoldParent(wParam);
+               return pdoc->GetFoldParent(static_cast<int>(wParam));
 
        case SCI_SHOWLINES:
-               cs.SetVisible(wParam, lParam, true);
+               cs.SetVisible(static_cast<int>(wParam), static_cast<int>(lParam), true);
                SetScrollBars();
                Redraw();
                break;
 
        case SCI_HIDELINES:
                if (wParam > 0)
-                       cs.SetVisible(wParam, lParam, false);
+                       cs.SetVisible(static_cast<int>(wParam), static_cast<int>(lParam), false);
                SetScrollBars();
                Redraw();
                break;
 
        case SCI_GETLINEVISIBLE:
-               return cs.GetVisible(wParam);
+               return cs.GetVisible(static_cast<int>(wParam));
 
        case SCI_GETALLLINESVISIBLE:
                return cs.HiddenLines() ? 0 : 1;
 
        case SCI_SETFOLDEXPANDED:
-               SetFoldExpanded(wParam, lParam != 0);
+               SetFoldExpanded(static_cast<int>(wParam), lParam != 0);
                break;
 
        case SCI_GETFOLDEXPANDED:
-               return cs.GetExpanded(wParam);
+               return cs.GetExpanded(static_cast<int>(wParam));
 
        case SCI_SETAUTOMATICFOLD:
-               foldAutomatic = wParam;
+               foldAutomatic = static_cast<int>(wParam);
                break;
 
        case SCI_GETAUTOMATICFOLD:
                return foldAutomatic;
 
        case SCI_SETFOLDFLAGS:
-               foldFlags = wParam;
+               foldFlags = static_cast<int>(wParam);
+               Redraw();
+               break;
+
+       case SCI_TOGGLEFOLDSHOWTEXT:
+               cs.SetFoldDisplayText(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
+               FoldLine(static_cast<int>(wParam), SC_FOLDACTION_TOGGLE);
+               break;
+
+       case SCI_FOLDDISPLAYTEXTSETSTYLE:
+               foldDisplayTextStyle = static_cast<int>(wParam);
                Redraw();
                break;
 
        case SCI_TOGGLEFOLD:
-               FoldLine(wParam, SC_FOLDACTION_TOGGLE);
+               FoldLine(static_cast<int>(wParam), SC_FOLDACTION_TOGGLE);
                break;
 
        case SCI_FOLDLINE:
-               FoldLine(wParam, lParam);
+               FoldLine(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_FOLDCHILDREN:
-               FoldExpand(wParam, lParam, pdoc->GetLevel(wParam));
+               FoldExpand(static_cast<int>(wParam), static_cast<int>(lParam), 
pdoc->GetLevel(static_cast<int>(wParam)));
                break;
 
        case SCI_FOLDALL:
-               FoldAll(wParam);
+               FoldAll(static_cast<int>(wParam));
                break;
 
        case SCI_EXPANDCHILDREN:
-               FoldExpand(wParam, SC_FOLDACTION_EXPAND, lParam);
+               FoldExpand(static_cast<int>(wParam), SC_FOLDACTION_EXPAND, static_cast<int>(lParam));
                break;
 
        case SCI_CONTRACTEDFOLDNEXT:
-               return ContractedFoldNext(wParam);
+               return ContractedFoldNext(static_cast<int>(wParam));
 
        case SCI_ENSUREVISIBLE:
-               EnsureLineVisible(wParam, false);
+               EnsureLineVisible(static_cast<int>(wParam), false);
                break;
 
        case SCI_ENSUREVISIBLEENFORCEPOLICY:
-               EnsureLineVisible(wParam, true);
+               EnsureLineVisible(static_cast<int>(wParam), true);
                break;
 
        case SCI_SCROLLRANGE:
-               ScrollRange(SelectionRange(lParam, wParam));
+               ScrollRange(SelectionRange(static_cast<int>(wParam), static_cast<int>(lParam)));
                break;
 
        case SCI_SEARCHANCHOR:
@@ -8678,40 +7200,38 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return SearchText(iMessage, wParam, lParam);
 
        case SCI_SETXCARETPOLICY:
-               caretXPolicy = wParam;
-               caretXSlop = lParam;
+               caretXPolicy = static_cast<int>(wParam);
+               caretXSlop = static_cast<int>(lParam);
                break;
 
        case SCI_SETYCARETPOLICY:
-               caretYPolicy = wParam;
-               caretYSlop = lParam;
+               caretYPolicy = static_cast<int>(wParam);
+               caretYSlop = static_cast<int>(lParam);
                break;
 
        case SCI_SETVISIBLEPOLICY:
-               visiblePolicy = wParam;
-               visibleSlop = lParam;
+               visiblePolicy = static_cast<int>(wParam);
+               visibleSlop = static_cast<int>(lParam);
                break;
 
        case SCI_LINESONSCREEN:
                return LinesOnScreen();
 
        case SCI_SETSELFORE:
-               vs.selforeset = wParam != 0;
-               vs.selforeground = ColourDesired(lParam);
-               vs.selAdditionalForeground = ColourDesired(lParam);
+               vs.selColours.fore = ColourOptional(wParam, lParam);
+               vs.selAdditionalForeground = ColourDesired(static_cast<long>(lParam));
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETSELBACK:
-               vs.selbackset = wParam != 0;
-               vs.selbackground = ColourDesired(lParam);
-               vs.selAdditionalBackground = ColourDesired(lParam);
+               vs.selColours.back = ColourOptional(wParam, lParam);
+               vs.selAdditionalBackground = ColourDesired(static_cast<long>(lParam));
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETSELALPHA:
-               vs.selAlpha = wParam;
-               vs.selAdditionalAlpha = wParam;
+               vs.selAlpha = static_cast<int>(wParam);
+               vs.selAdditionalAlpha = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -8727,19 +7247,17 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_SETWHITESPACEFORE:
-               vs.whitespaceForegroundSet = wParam != 0;
-               vs.whitespaceForeground = ColourDesired(lParam);
+               vs.whitespaceColours.fore = ColourOptional(wParam, lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETWHITESPACEBACK:
-               vs.whitespaceBackgroundSet = wParam != 0;
-               vs.whitespaceBackground = ColourDesired(lParam);
+               vs.whitespaceColours.back = ColourOptional(wParam, lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETCARETFORE:
-               vs.caretcolour = ColourDesired(wParam);
+               vs.caretcolour = ColourDesired(static_cast<long>(wParam));
                InvalidateStyleRedraw();
                break;
 
@@ -8748,7 +7266,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_SETCARETSTYLE:
                if (wParam <= CARETSTYLE_BLOCK)
-                       vs.caretStyle = wParam;
+                       vs.caretStyle = static_cast<int>(wParam);
                else
                        /* Default to the line caret */
                        vs.caretStyle = CARETSTYLE_LINE;
@@ -8764,7 +7282,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                else if (wParam >= 3)
                        vs.caretWidth = 3;
                else
-                       vs.caretWidth = wParam;
+                       vs.caretWidth = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -8772,13 +7290,13 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.caretWidth;
 
        case SCI_ASSIGNCMDKEY:
-               kmap.AssignCmdKey(Platform::LowShortFromLong(wParam),
-                       Platform::HighShortFromLong(wParam), lParam);
+               kmap.AssignCmdKey(Platform::LowShortFromLong(static_cast<long>(wParam)),
+                       Platform::HighShortFromLong(static_cast<long>(wParam)), static_cast<unsigned 
int>(lParam));
                break;
 
        case SCI_CLEARCMDKEY:
-               kmap.AssignCmdKey(Platform::LowShortFromLong(wParam),
-                       Platform::HighShortFromLong(wParam), SCI_NULL);
+               kmap.AssignCmdKey(Platform::LowShortFromLong(static_cast<long>(wParam)),
+                       Platform::HighShortFromLong(static_cast<long>(wParam)), SCI_NULL);
                break;
 
        case SCI_CLEARALLCMDKEYS:
@@ -8787,23 +7305,55 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_INDICSETSTYLE:
                if (wParam <= INDIC_MAX) {
-                       vs.indicators[wParam].style = lParam;
+                       vs.indicators[wParam].sacNormal.style = static_cast<int>(lParam);
+                       vs.indicators[wParam].sacHover.style = static_cast<int>(lParam);
                        InvalidateStyleRedraw();
                }
                break;
 
        case SCI_INDICGETSTYLE:
-               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].style : 0;
+               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].sacNormal.style : 0;
 
        case SCI_INDICSETFORE:
                if (wParam <= INDIC_MAX) {
-                       vs.indicators[wParam].fore = ColourDesired(lParam);
+                       vs.indicators[wParam].sacNormal.fore = ColourDesired(static_cast<long>(lParam));
+                       vs.indicators[wParam].sacHover.fore = ColourDesired(static_cast<long>(lParam));
                        InvalidateStyleRedraw();
                }
                break;
 
        case SCI_INDICGETFORE:
-               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].fore.AsLong() : 0;
+               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].sacNormal.fore.AsLong() : 0;
+
+       case SCI_INDICSETHOVERSTYLE:
+               if (wParam <= INDIC_MAX) {
+                       vs.indicators[wParam].sacHover.style = static_cast<int>(lParam);
+                       InvalidateStyleRedraw();
+               }
+               break;
+
+       case SCI_INDICGETHOVERSTYLE:
+               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].sacHover.style : 0;
+
+       case SCI_INDICSETHOVERFORE:
+               if (wParam <= INDIC_MAX) {
+                       vs.indicators[wParam].sacHover.fore = ColourDesired(static_cast<long>(lParam));
+                       InvalidateStyleRedraw();
+               }
+               break;
+
+       case SCI_INDICGETHOVERFORE:
+               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].sacHover.fore.AsLong() : 0;
+
+       case SCI_INDICSETFLAGS:
+               if (wParam <= INDIC_MAX) {
+                       vs.indicators[wParam].SetFlags(static_cast<int>(lParam));
+                       InvalidateStyleRedraw();
+               }
+               break;
+
+       case SCI_INDICGETFLAGS:
+               return (wParam <= INDIC_MAX) ? vs.indicators[wParam].Flags() : 0;
 
        case SCI_INDICSETUNDER:
                if (wParam <= INDIC_MAX) {
@@ -8817,7 +7367,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_INDICSETALPHA:
                if (wParam <= INDIC_MAX && lParam >=0 && lParam <= 255) {
-                       vs.indicators[wParam].fillAlpha = lParam;
+                       vs.indicators[wParam].fillAlpha = static_cast<int>(lParam);
                        InvalidateStyleRedraw();
                }
                break;
@@ -8827,7 +7377,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_INDICSETOUTLINEALPHA:
                if (wParam <= INDIC_MAX && lParam >=0 && lParam <= 255) {
-                       vs.indicators[wParam].outlineAlpha = lParam;
+                       vs.indicators[wParam].outlineAlpha = static_cast<int>(lParam);
                        InvalidateStyleRedraw();
                }
                break;
@@ -8836,35 +7386,35 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return (wParam <= INDIC_MAX) ? vs.indicators[wParam].outlineAlpha : 0;
 
        case SCI_SETINDICATORCURRENT:
-               pdoc->decorations.SetCurrentIndicator(wParam);
+               pdoc->DecorationSetCurrentIndicator(static_cast<int>(wParam));
                break;
        case SCI_GETINDICATORCURRENT:
                return pdoc->decorations.GetCurrentIndicator();
        case SCI_SETINDICATORVALUE:
-               pdoc->decorations.SetCurrentValue(wParam);
+               pdoc->decorations.SetCurrentValue(static_cast<int>(wParam));
                break;
        case SCI_GETINDICATORVALUE:
                return pdoc->decorations.GetCurrentValue();
 
        case SCI_INDICATORFILLRANGE:
-               pdoc->DecorationFillRange(wParam, pdoc->decorations.GetCurrentValue(), lParam);
+               pdoc->DecorationFillRange(static_cast<int>(wParam), pdoc->decorations.GetCurrentValue(), 
static_cast<int>(lParam));
                break;
 
        case SCI_INDICATORCLEARRANGE:
-               pdoc->DecorationFillRange(wParam, 0, lParam);
+               pdoc->DecorationFillRange(static_cast<int>(wParam), 0, static_cast<int>(lParam));
                break;
 
        case SCI_INDICATORALLONFOR:
-               return pdoc->decorations.AllOnFor(wParam);
+               return pdoc->decorations.AllOnFor(static_cast<int>(wParam));
 
        case SCI_INDICATORVALUEAT:
-               return pdoc->decorations.ValueAt(wParam, lParam);
+               return pdoc->decorations.ValueAt(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_INDICATORSTART:
-               return pdoc->decorations.Start(wParam, lParam);
+               return pdoc->decorations.Start(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_INDICATOREND:
-               return pdoc->decorations.End(wParam, lParam);
+               return pdoc->decorations.End(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_LINEDOWN:
        case SCI_LINEDOWNEXTEND:
@@ -8934,6 +7484,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_LINECUT:
        case SCI_LINEDELETE:
        case SCI_LINETRANSPOSE:
+       case SCI_LINEREVERSE:
        case SCI_LINEDUPLICATE:
        case SCI_LOWERCASE:
        case SCI_UPPERCASE:
@@ -8961,13 +7512,13 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return KeyCommand(iMessage);
 
        case SCI_BRACEHIGHLIGHT:
-               SetBraceHighlight(static_cast<int>(wParam), lParam, STYLE_BRACELIGHT);
+               SetBraceHighlight(static_cast<int>(wParam), static_cast<int>(lParam), STYLE_BRACELIGHT);
                break;
 
        case SCI_BRACEHIGHLIGHTINDICATOR:
                if (lParam >= 0 && lParam <= INDIC_MAX) {
                        vs.braceHighlightIndicatorSet = wParam != 0;
-                       vs.braceHighlightIndicator = lParam;
+                       vs.braceHighlightIndicator = static_cast<int>(lParam);
                }
                break;
 
@@ -8978,14 +7529,14 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_BRACEBADLIGHTINDICATOR:
                if (lParam >= 0 && lParam <= INDIC_MAX) {
                        vs.braceBadLightIndicatorSet = wParam != 0;
-                       vs.braceBadLightIndicator = lParam;
+                       vs.braceBadLightIndicator = static_cast<int>(lParam);
                }
                break;
 
        case SCI_BRACEMATCH:
                // wParam is position of char to find brace for,
                // lParam is maximum amount of text to restyle to find it
-               return pdoc->BraceMatch(wParam, lParam);
+               return pdoc->BraceMatch(static_cast<int>(wParam), static_cast<int>(lParam));
 
        case SCI_GETVIEWEOL:
                return vs.viewEOL;
@@ -8996,7 +7547,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_SETZOOM:
-               vs.zoomLevel = wParam;
+               vs.zoomLevel = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                NotifyZoom();
                break;
@@ -9005,10 +7556,10 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.zoomLevel;
 
        case SCI_GETEDGECOLUMN:
-               return theEdge;
+               return vs.theEdge.column;
 
        case SCI_SETEDGECOLUMN:
-               theEdge = wParam;
+               vs.theEdge.column = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -9016,18 +7567,35 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.edgeState;
 
        case SCI_SETEDGEMODE:
-               vs.edgeState = wParam;
+               vs.edgeState = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_GETEDGECOLOUR:
-               return vs.edgecolour.AsLong();
+               return vs.theEdge.colour.AsLong();
 
        case SCI_SETEDGECOLOUR:
-               vs.edgecolour = ColourDesired(wParam);
+               vs.theEdge.colour = ColourDesired(static_cast<long>(wParam));
                InvalidateStyleRedraw();
                break;
 
+       case SCI_MULTIEDGEADDLINE:
+               vs.theMultiEdge.push_back(EdgeProperties(wParam, lParam));
+               InvalidateStyleRedraw();
+               break;
+
+       case SCI_MULTIEDGECLEARALL:
+               std::vector<EdgeProperties>().swap(vs.theMultiEdge); // Free vector and memory, C++03 
compatible
+               InvalidateStyleRedraw();
+               break;
+       
+       case SCI_GETACCESSIBILITY:
+               return SC_ACCESSIBILITY_DISABLED;
+
+       case SCI_SETACCESSIBILITY:
+               // May be implemented by platform code.
+               break;
+
        case SCI_GETDOCPOINTER:
                return reinterpret_cast<sptr_t>(pdoc);
 
@@ -9053,25 +7621,25 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_CREATELOADER: {
                        Document *doc = new Document();
                        doc->AddRef();
-                       doc->Allocate(wParam);
+                       doc->Allocate(static_cast<int>(wParam));
                        doc->SetUndoCollection(false);
                        return reinterpret_cast<sptr_t>(static_cast<ILoader *>(doc));
                }
 
        case SCI_SETMODEVENTMASK:
-               modEventMask = wParam;
+               modEventMask = static_cast<int>(wParam);
                return 0;
 
        case SCI_GETMODEVENTMASK:
                return modEventMask;
 
        case SCI_CONVERTEOLS:
-               pdoc->ConvertLineEnds(wParam);
+               pdoc->ConvertLineEnds(static_cast<int>(wParam));
                SetSelection(sel.MainCaret(), sel.MainAnchor());        // Ensure selection inside document
                return 0;
 
        case SCI_SETLENGTHFORENCODE:
-               lengthForEncode = wParam;
+               lengthForEncode = static_cast<int>(wParam);
                return 0;
 
        case SCI_SELECTIONISRECTANGLE:
@@ -9099,7 +7667,8 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                                sel.SetMoveExtends(!sel.MoveExtends() || (sel.selType != 
Selection::selStream));
                                sel.selType = Selection::selStream;
                        }
-                       InvalidateSelection(sel.RangeMain(), true);
+                       InvalidateWholeSelection();
+                       break;
                }
        case SCI_GETSELECTIONMODE:
                switch (sel.selType) {
@@ -9116,10 +7685,10 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                }
        case SCI_GETLINESELSTARTPOSITION:
        case SCI_GETLINESELENDPOSITION: {
-                       SelectionSegment segmentLine(SelectionPosition(pdoc->LineStart(wParam)),
-                               SelectionPosition(pdoc->LineEnd(wParam)));
+                       SelectionSegment 
segmentLine(SelectionPosition(pdoc->LineStart(static_cast<int>(wParam))),
+                               SelectionPosition(pdoc->LineEnd(static_cast<int>(wParam))));
                        for (size_t r=0; r<sel.Count(); r++) {
-                               SelectionSegment portion = sel.Range(r).Intersect(segmentLine);
+                               const SelectionSegment portion = sel.Range(r).Intersect(segmentLine);
                                if (portion.start.IsValid()) {
                                        return (iMessage == SCI_GETLINESELSTARTPOSITION) ? 
portion.start.Position() : portion.end.Position();
                                }
@@ -9142,7 +7711,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return hasFocus;
 
        case SCI_SETSTATUS:
-               errorStatus = wParam;
+               errorStatus = static_cast<int>(wParam);
                break;
 
        case SCI_GETSTATUS:
@@ -9155,8 +7724,15 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
        case SCI_GETMOUSEDOWNCAPTURES:
                return mouseDownCaptures;
 
+       case SCI_SETMOUSEWHEELCAPTURES:
+               mouseWheelCaptures = wParam != 0;
+               break;
+
+       case SCI_GETMOUSEWHEELCAPTURES:
+               return mouseWheelCaptures;
+
        case SCI_SETCURSOR:
-               cursorMode = wParam;
+               cursorMode = static_cast<int>(wParam);
                DisplayCursor(Window::cursorText);
                break;
 
@@ -9164,11 +7740,29 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return cursorMode;
 
        case SCI_SETCONTROLCHARSYMBOL:
-               controlCharSymbol = wParam;
+               vs.controlCharSymbol = static_cast<int>(wParam);
+               InvalidateStyleRedraw();
                break;
 
        case SCI_GETCONTROLCHARSYMBOL:
-               return controlCharSymbol;
+               return vs.controlCharSymbol;
+
+       case SCI_SETREPRESENTATION:
+               reprs.SetRepresentation(reinterpret_cast<const char *>(wParam), CharPtrFromSPtr(lParam));
+               break;
+
+       case SCI_GETREPRESENTATION: {
+                       const Representation *repr = reprs.RepresentationFromCharacter(
+                               reinterpret_cast<const char *>(wParam), UTF8MaxBytes);
+                       if (repr) {
+                               return StringResult(lParam, repr->stringRep.c_str());
+                       }
+                       return 0;
+               }
+
+       case SCI_CLEARREPRESENTATION:
+               reprs.ClearRepresentation(reinterpret_cast<const char *>(wParam));
+               break;
 
        case SCI_STARTRECORD:
                recordingMacro = true;
@@ -9183,34 +7777,30 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_SETFOLDMARGINCOLOUR:
-               vs.foldmarginColourSet = wParam != 0;
-               vs.foldmarginColour = ColourDesired(lParam);
+               vs.foldmarginColour = ColourOptional(wParam, lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETFOLDMARGINHICOLOUR:
-               vs.foldmarginHighlightColourSet = wParam != 0;
-               vs.foldmarginHighlightColour = ColourDesired(lParam);
+               vs.foldmarginHighlightColour = ColourOptional(wParam, lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETHOTSPOTACTIVEFORE:
-               vs.hotspotForegroundSet = wParam != 0;
-               vs.hotspotForeground = ColourDesired(lParam);
+               vs.hotspotColours.fore = ColourOptional(wParam, lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_GETHOTSPOTACTIVEFORE:
-               return vs.hotspotForeground.AsLong();
+               return vs.hotspotColours.fore.AsLong();
 
        case SCI_SETHOTSPOTACTIVEBACK:
-               vs.hotspotBackgroundSet = wParam != 0;
-               vs.hotspotBackground = ColourDesired(lParam);
+               vs.hotspotColours.back = ColourOptional(wParam, lParam);
                InvalidateStyleRedraw();
                break;
 
        case SCI_GETHOTSPOTACTIVEBACK:
-               return vs.hotspotBackground.AsLong();
+               return vs.hotspotColours.back.AsLong();
 
        case SCI_SETHOTSPOTACTIVEUNDERLINE:
                vs.hotspotUnderline = wParam != 0;
@@ -9239,13 +7829,13 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return reinterpret_cast<sptr_t>(pdoc->BufferPointer());
 
        case SCI_GETRANGEPOINTER:
-               return reinterpret_cast<sptr_t>(pdoc->RangePointer(wParam, lParam));
+               return reinterpret_cast<sptr_t>(pdoc->RangePointer(static_cast<int>(wParam), 
static_cast<int>(lParam)));
 
        case SCI_GETGAPPOSITION:
                return pdoc->GapPosition();
 
        case SCI_SETEXTRAASCENT:
-               vs.extraAscent = wParam;
+               vs.extraAscent = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -9253,7 +7843,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.extraAscent;
 
        case SCI_SETEXTRADESCENT:
-               vs.extraDescent = wParam;
+               vs.extraDescent = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -9261,7 +7851,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.extraDescent;
 
        case SCI_MARGINSETSTYLEOFFSET:
-               vs.marginStyleOffset = wParam;
+               vs.marginStyleOffset = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -9269,49 +7859,37 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.marginStyleOffset;
 
        case SCI_SETMARGINOPTIONS:
-               marginOptions = wParam;
+               marginOptions = static_cast<int>(wParam);
                break;
 
        case SCI_GETMARGINOPTIONS:
                return marginOptions;
 
        case SCI_MARGINSETTEXT:
-               pdoc->MarginSetText(wParam, CharPtrFromSPtr(lParam));
+               pdoc->MarginSetText(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
                break;
 
        case SCI_MARGINGETTEXT: {
-                       const StyledText st = pdoc->MarginStyledText(wParam);
-                       if (lParam) {
-                               if (st.text)
-                                       memcpy(CharPtrFromSPtr(lParam), st.text, st.length);
-                               else
-                                       strcpy(CharPtrFromSPtr(lParam), "");
-                       }
-                       return st.length;
+                       const StyledText st = pdoc->MarginStyledText(static_cast<int>(wParam));
+                       return BytesResult(lParam, reinterpret_cast<const unsigned char *>(st.text), 
st.length);
                }
 
        case SCI_MARGINSETSTYLE:
-               pdoc->MarginSetStyle(wParam, lParam);
+               pdoc->MarginSetStyle(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_MARGINGETSTYLE: {
-                       const StyledText st = pdoc->MarginStyledText(wParam);
+                       const StyledText st = pdoc->MarginStyledText(static_cast<int>(wParam));
                        return st.style;
                }
 
        case SCI_MARGINSETSTYLES:
-               pdoc->MarginSetStyles(wParam, reinterpret_cast<const unsigned char *>(lParam));
+               pdoc->MarginSetStyles(static_cast<int>(wParam), reinterpret_cast<const unsigned char 
*>(lParam));
                break;
 
        case SCI_MARGINGETSTYLES: {
-                       const StyledText st = pdoc->MarginStyledText(wParam);
-                       if (lParam) {
-                               if (st.styles)
-                                       memcpy(CharPtrFromSPtr(lParam), st.styles, st.length);
-                               else
-                                       strcpy(CharPtrFromSPtr(lParam), "");
-                       }
-                       return st.styles ? st.length : 0;
+                       const StyledText st = pdoc->MarginStyledText(static_cast<int>(wParam));
+                       return BytesResult(lParam, st.styles, st.length);
                }
 
        case SCI_MARGINTEXTCLEARALL:
@@ -9319,60 +7897,48 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_ANNOTATIONSETTEXT:
-               pdoc->AnnotationSetText(wParam, CharPtrFromSPtr(lParam));
+               pdoc->AnnotationSetText(static_cast<int>(wParam), CharPtrFromSPtr(lParam));
                break;
 
        case SCI_ANNOTATIONGETTEXT: {
-                       const StyledText st = pdoc->AnnotationStyledText(wParam);
-                       if (lParam) {
-                               if (st.text)
-                                       memcpy(CharPtrFromSPtr(lParam), st.text, st.length);
-                               else
-                                       strcpy(CharPtrFromSPtr(lParam), "");
-                       }
-                       return st.length;
+                       const StyledText st = pdoc->AnnotationStyledText(static_cast<int>(wParam));
+                       return BytesResult(lParam, reinterpret_cast<const unsigned char *>(st.text), 
st.length);
                }
 
        case SCI_ANNOTATIONGETSTYLE: {
-                       const StyledText st = pdoc->AnnotationStyledText(wParam);
+                       const StyledText st = pdoc->AnnotationStyledText(static_cast<int>(wParam));
                        return st.style;
                }
 
        case SCI_ANNOTATIONSETSTYLE:
-               pdoc->AnnotationSetStyle(wParam, lParam);
+               pdoc->AnnotationSetStyle(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_ANNOTATIONSETSTYLES:
-               pdoc->AnnotationSetStyles(wParam, reinterpret_cast<const unsigned char *>(lParam));
+               pdoc->AnnotationSetStyles(static_cast<int>(wParam), reinterpret_cast<const unsigned char 
*>(lParam));
                break;
 
        case SCI_ANNOTATIONGETSTYLES: {
-                       const StyledText st = pdoc->AnnotationStyledText(wParam);
-                       if (lParam) {
-                               if (st.styles)
-                                       memcpy(CharPtrFromSPtr(lParam), st.styles, st.length);
-                               else
-                                       strcpy(CharPtrFromSPtr(lParam), "");
-                       }
-                       return st.styles ? st.length : 0;
+                       const StyledText st = pdoc->AnnotationStyledText(static_cast<int>(wParam));
+                       return BytesResult(lParam, st.styles, st.length);
                }
 
        case SCI_ANNOTATIONGETLINES:
-               return pdoc->AnnotationLines(wParam);
+               return pdoc->AnnotationLines(static_cast<int>(wParam));
 
        case SCI_ANNOTATIONCLEARALL:
                pdoc->AnnotationClearAll();
                break;
 
        case SCI_ANNOTATIONSETVISIBLE:
-               SetAnnotationVisible(wParam);
+               SetAnnotationVisible(static_cast<int>(wParam));
                break;
 
        case SCI_ANNOTATIONGETVISIBLE:
                return vs.annotationVisible;
 
        case SCI_ANNOTATIONSETSTYLEOFFSET:
-               vs.annotationStyleOffset = wParam;
+               vs.annotationStyleOffset = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -9384,12 +7950,19 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                break;
 
        case SCI_ALLOCATEEXTENDEDSTYLES:
-               return vs.AllocateExtendedStyles(wParam);
+               return vs.AllocateExtendedStyles(static_cast<int>(wParam));
 
        case SCI_ADDUNDOACTION:
-               pdoc->AddUndoAction(wParam, lParam & UNDO_MAY_COALESCE);
+               pdoc->AddUndoAction(static_cast<int>(wParam), lParam & UNDO_MAY_COALESCE);
+               break;
+
+       case SCI_SETMOUSESELECTIONRECTANGULARSWITCH:
+               mouseSelectionRectangularSwitch = wParam != 0;
                break;
 
+       case SCI_GETMOUSESELECTIONRECTANGULARSWITCH:
+               return mouseSelectionRectangularSwitch;
+
        case SCI_SETMULTIPLESELECTION:
                multipleSelection = wParam != 0;
                InvalidateCaret();
@@ -9407,27 +7980,27 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return additionalSelectionTyping;
 
        case SCI_SETMULTIPASTE:
-               multiPasteMode = wParam;
+               multiPasteMode = static_cast<int>(wParam);
                break;
 
        case SCI_GETMULTIPASTE:
                return multiPasteMode;
 
        case SCI_SETADDITIONALCARETSBLINK:
-               additionalCaretsBlink = wParam != 0;
+               view.additionalCaretsBlink = wParam != 0;
                InvalidateCaret();
                break;
 
        case SCI_GETADDITIONALCARETSBLINK:
-               return additionalCaretsBlink;
+               return view.additionalCaretsBlink;
 
        case SCI_SETADDITIONALCARETSVISIBLE:
-               additionalCaretsVisible = wParam != 0;
+               view.additionalCaretsVisible = wParam != 0;
                InvalidateCaret();
                break;
 
        case SCI_GETADDITIONALCARETSVISIBLE:
-               return additionalCaretsVisible;
+               return view.additionalCaretsVisible;
 
        case SCI_GETSELECTIONS:
                return sel.Count();
@@ -9437,21 +8010,30 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_CLEARSELECTIONS:
                sel.Clear();
+               ContainerNeedsUpdate(SC_UPDATE_SELECTION);
                Redraw();
                break;
 
        case SCI_SETSELECTION:
-               sel.SetSelection(SelectionRange(wParam, lParam));
+               sel.SetSelection(SelectionRange(static_cast<int>(wParam), static_cast<int>(lParam)));
                Redraw();
                break;
 
        case SCI_ADDSELECTION:
-               sel.AddSelection(SelectionRange(wParam, lParam));
+               sel.AddSelection(SelectionRange(static_cast<int>(wParam), static_cast<int>(lParam)));
+               ContainerNeedsUpdate(SC_UPDATE_SELECTION);
+               Redraw();
+               break;
+
+       case SCI_DROPSELECTIONN:
+               sel.DropSelection(static_cast<int>(wParam));
+               ContainerNeedsUpdate(SC_UPDATE_SELECTION);
                Redraw();
                break;
 
        case SCI_SETMAINSELECTION:
-               sel.SetMain(wParam);
+               sel.SetMain(static_cast<int>(wParam));
+               ContainerNeedsUpdate(SC_UPDATE_SELECTION);
                Redraw();
                break;
 
@@ -9459,49 +8041,29 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return sel.Main();
 
        case SCI_SETSELECTIONNCARET:
-               sel.Range(wParam).caret.SetPosition(lParam);
-               Redraw();
+       case SCI_SETSELECTIONNANCHOR:
+       case SCI_SETSELECTIONNCARETVIRTUALSPACE:
+       case SCI_SETSELECTIONNANCHORVIRTUALSPACE:
+       case SCI_SETSELECTIONNSTART:
+       case SCI_SETSELECTIONNEND:
+               SetSelectionNMessage(iMessage, wParam, lParam);
                break;
 
        case SCI_GETSELECTIONNCARET:
                return sel.Range(wParam).caret.Position();
 
-       case SCI_SETSELECTIONNANCHOR:
-               sel.Range(wParam).anchor.SetPosition(lParam);
-               Redraw();
-               break;
        case SCI_GETSELECTIONNANCHOR:
                return sel.Range(wParam).anchor.Position();
 
-       case SCI_SETSELECTIONNCARETVIRTUALSPACE:
-               sel.Range(wParam).caret.SetVirtualSpace(lParam);
-               Redraw();
-               break;
-
        case SCI_GETSELECTIONNCARETVIRTUALSPACE:
                return sel.Range(wParam).caret.VirtualSpace();
 
-       case SCI_SETSELECTIONNANCHORVIRTUALSPACE:
-               sel.Range(wParam).anchor.SetVirtualSpace(lParam);
-               Redraw();
-               break;
-
        case SCI_GETSELECTIONNANCHORVIRTUALSPACE:
                return sel.Range(wParam).anchor.VirtualSpace();
 
-       case SCI_SETSELECTIONNSTART:
-               sel.Range(wParam).anchor.SetPosition(lParam);
-               Redraw();
-               break;
-
        case SCI_GETSELECTIONNSTART:
                return sel.Range(wParam).Start().Position();
 
-       case SCI_SETSELECTIONNEND:
-               sel.Range(wParam).caret.SetPosition(lParam);
-               Redraw();
-               break;
-
        case SCI_GETSELECTIONNEND:
                return sel.Range(wParam).End().Position();
 
@@ -9509,7 +8071,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (!sel.IsRectangular())
                        sel.Clear();
                sel.selType = Selection::selRectangle;
-               sel.Rectangular().caret.SetPosition(wParam);
+               sel.Rectangular().caret.SetPosition(static_cast<int>(wParam));
                SetRectangularRange();
                Redraw();
                break;
@@ -9521,7 +8083,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (!sel.IsRectangular())
                        sel.Clear();
                sel.selType = Selection::selRectangle;
-               sel.Rectangular().anchor.SetPosition(wParam);
+               sel.Rectangular().anchor.SetPosition(static_cast<int>(wParam));
                SetRectangularRange();
                Redraw();
                break;
@@ -9533,7 +8095,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (!sel.IsRectangular())
                        sel.Clear();
                sel.selType = Selection::selRectangle;
-               sel.Rectangular().caret.SetVirtualSpace(wParam);
+               sel.Rectangular().caret.SetVirtualSpace(static_cast<int>(wParam));
                SetRectangularRange();
                Redraw();
                break;
@@ -9545,7 +8107,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                if (!sel.IsRectangular())
                        sel.Clear();
                sel.selType = Selection::selRectangle;
-               sel.Rectangular().anchor.SetVirtualSpace(wParam);
+               sel.Rectangular().anchor.SetVirtualSpace(static_cast<int>(wParam));
                SetRectangularRange();
                Redraw();
                break;
@@ -9554,24 +8116,24 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return sel.Rectangular().anchor.VirtualSpace();
 
        case SCI_SETVIRTUALSPACEOPTIONS:
-               virtualSpaceOptions = wParam;
+               virtualSpaceOptions = static_cast<int>(wParam);
                break;
 
        case SCI_GETVIRTUALSPACEOPTIONS:
                return virtualSpaceOptions;
 
        case SCI_SETADDITIONALSELFORE:
-               vs.selAdditionalForeground = ColourDesired(wParam);
+               vs.selAdditionalForeground = ColourDesired(static_cast<long>(wParam));
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETADDITIONALSELBACK:
-               vs.selAdditionalBackground = ColourDesired(wParam);
+               vs.selAdditionalBackground = ColourDesired(static_cast<long>(wParam));
                InvalidateStyleRedraw();
                break;
 
        case SCI_SETADDITIONALSELALPHA:
-               vs.selAdditionalAlpha = wParam;
+               vs.selAdditionalAlpha = static_cast<int>(wParam);
                InvalidateStyleRedraw();
                break;
 
@@ -9579,7 +8141,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return vs.selAdditionalAlpha;
 
        case SCI_SETADDITIONALCARETFORE:
-               vs.additionalCaretColour = ColourDesired(wParam);
+               vs.additionalCaretColour = ColourDesired(static_cast<long>(wParam));
                InvalidateStyleRedraw();
                break;
 
@@ -9588,20 +8150,28 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
        case SCI_ROTATESELECTION:
                sel.RotateMain();
-               InvalidateSelection(sel.RangeMain(), true);
+               InvalidateWholeSelection();
                break;
 
        case SCI_SWAPMAINANCHORCARET:
                InvalidateSelection(sel.RangeMain());
-               sel.RangeMain() = SelectionRange(sel.RangeMain().anchor, sel.RangeMain().caret);
+               sel.RangeMain().Swap();
+               break;
+
+       case SCI_MULTIPLESELECTADDNEXT:
+               MultipleSelectAdd(addOne);
+               break;
+
+       case SCI_MULTIPLESELECTADDEACH:
+               MultipleSelectAdd(addEach);
                break;
 
        case SCI_CHANGELEXERSTATE:
-               pdoc->ChangeLexerState(wParam, lParam);
+               pdoc->ChangeLexerState(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_SETIDENTIFIER:
-               SetCtrlID(wParam);
+               SetCtrlID(static_cast<int>(wParam));
                break;
 
        case SCI_GETIDENTIFIER:
@@ -9615,7 +8185,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
                return technology;
 
        case SCI_COUNTCHARACTERS:
-               return pdoc->CountCharacters(wParam, lParam);
+               return pdoc->CountCharacters(static_cast<int>(wParam), static_cast<int>(lParam));
 
        default:
                return DefWndProc(iMessage, wParam, lParam);
diff --git a/plugins/scintilla/scintilla/src/Editor.h b/plugins/scintilla/scintilla/src/Editor.h
index 3a1456a..69c8162 100644
--- a/plugins/scintilla/scintilla/src/Editor.h
+++ b/plugins/scintilla/scintilla/src/Editor.h
@@ -14,17 +14,6 @@ namespace Scintilla {
 
 /**
  */
-class Caret {
-public:
-       bool active;
-       bool on;
-       int period;
-
-       Caret();
-};
-
-/**
- */
 class Timer {
 public:
        bool ticking;
@@ -47,7 +36,7 @@ public:
 
 /**
  * When platform has a way to generate an event before painting,
- * accumulate needed styling range and other work items in 
+ * accumulate needed styling range and other work items in
  * WorkNeeded to avoid unnecessary work inside paint handler
  */
 class WorkNeeded {
@@ -57,17 +46,15 @@ public:
                workStyle=1,
                workUpdateUI=2
        };
-       bool active;
        enum workItems items;
-       Position upTo;
+       Sci::Position upTo;
 
-       WorkNeeded() : active(false), items(workNone), upTo(0) {}
+       WorkNeeded() : items(workNone), upTo(0) {}
        void Reset() {
-               active = false;
                items = workNone;
                upTo = 0;
        }
-       void Need(workItems items_, Position pos) {
+       void Need(workItems items_, Sci::Position pos) {
                if ((items_ & workStyle) && (upTo < pos))
                        upTo = pos;
                items = static_cast<workItems>(items | items_);
@@ -119,7 +106,7 @@ public:
        }
 private:
        void FixSelectionForClipboard() {
-               // To avoid truncating the contents of the clipboard when pasted where the 
+               // To avoid truncating the contents of the clipboard when pasted where the
                // clipboard contains NUL characters, replace NUL characters by spaces.
                std::replace(s.begin(), s.end(), '\0', ' ');
        }
@@ -128,8 +115,8 @@ private:
 struct WrapPending {
        // The range of lines that need to be wrapped
        enum { lineLarge = 0x7ffffff };
-       int start;      // When there are wraps pending, will be in document range
-       int end;        // May be lineLarge to indicate all of document after start
+       Sci::Line start;        // When there are wraps pending, will be in document range
+       Sci::Line end;  // May be lineLarge to indicate all of document after start
        WrapPending() {
                start = lineLarge;
                end = lineLarge;
@@ -138,14 +125,14 @@ struct WrapPending {
                start = lineLarge;
                end = lineLarge;
        }
-       void Wrapped(int line) {
+       void Wrapped(Sci::Line line) {
                if (start == line)
                        start++;
        }
        bool NeedsWrap() const {
                return start < end;
        }
-       bool AddRange(int lineStart, int lineEnd) {
+       bool AddRange(Sci::Line lineStart, Sci::Line lineEnd) {
                const bool neededWrap = NeedsWrap();
                bool changed = false;
                if (start > lineStart) {
@@ -162,11 +149,7 @@ struct WrapPending {
 
 /**
  */
-class Editor : public DocWatcher {
-       // Private so Editor objects can not be copied
-       Editor(const Editor &);
-       Editor &operator=(const Editor &);
-
+class Editor : public EditModel, public DocWatcher {
 protected:     // ScintillaBase subclass needs access to much of Editor
 
        /** On GTK+, Scintilla is a container widget holding two scroll bars
@@ -182,59 +165,31 @@ protected:        // ScintillaBase subclass needs access to much of Editor
        Point sizeRGBAImage;
        float scaleRGBAImage;
 
-       int printMagnification;
-       int printColourMode;
-       int printWrapState;
-       int cursorMode;
-       int controlCharSymbol;
+       MarginView marginView;
+       EditView view;
 
-       // Highlight current folding block
-       HighlightDelimiter highlightDelimiter;
+       int cursorMode;
 
        bool hasFocus;
-       bool hideSelection;
-       bool inOverstrike;
-       bool drawOverstrikeCaret;
        bool mouseDownCaptures;
+       bool mouseWheelCaptures;
 
-       /** In bufferedDraw mode, graphics operations are drawn to a pixmap and then copied to
-        * the screen. This avoids flashing but is about 30% slower. */
-       bool bufferedDraw;
-       /** In twoPhaseDraw mode, drawing is performed in two phases, first the background
-       * and then the foreground. This avoids chopping off characters that overlap the next run. */
-       bool twoPhaseDraw;
-
-       int xOffset;            ///< Horizontal scrolled amount in pixels
        int xCaretMargin;       ///< Ensure this many pixels visible on both sides of caret
        bool horizontalScrollBarVisible;
        int scrollWidth;
-       bool trackLineWidth;
-       int lineWidthMaxSeen;
        bool verticalScrollBarVisible;
        bool endAtLastLine;
        int caretSticky;
        int marginOptions;
+       bool mouseSelectionRectangularSwitch;
        bool multipleSelection;
        bool additionalSelectionTyping;
        int multiPasteMode;
-       bool additionalCaretsBlink;
-       bool additionalCaretsVisible;
 
        int virtualSpaceOptions;
 
-       Surface *pixmapLine;
-       Surface *pixmapSelMargin;
-       Surface *pixmapSelPattern;
-       Surface *pixmapSelPatternOffset1;
-       Surface *pixmapIndentGuide;
-       Surface *pixmapIndentGuideHighlight;
-
-       LineLayoutCache llc;
-       PositionCache posCache;
-
        KeyMap kmap;
 
-       Caret caret;
        Timer timer;
        Timer autoScrollTimer;
        enum { autoScrollDelay = 200 };
@@ -243,6 +198,7 @@ protected:  // ScintillaBase subclass needs access to much of Editor
 
        Point lastClick;
        unsigned int lastClickTime;
+       Point doubleClickCloseThreshold;
        int dwellDelay;
        int ticksToDwell;
        bool dwelling;
@@ -250,28 +206,22 @@ protected:        // ScintillaBase subclass needs access to much of Editor
        Point ptMouseLast;
        enum { ddNone, ddInitial, ddDragging } inDragDrop;
        bool dropWentOutside;
-       SelectionPosition posDrag;
        SelectionPosition posDrop;
-       int hotSpotClickPos;
+       Sci::Position hotSpotClickPos;
        int lastXChosen;
-       int lineAnchorPos;
-       int originalAnchorPos;
-       int wordSelectAnchorStartPos;
-       int wordSelectAnchorEndPos;
-       int wordSelectInitialCaretPos;
-       int targetStart;
-       int targetEnd;
+       Sci::Position lineAnchorPos;
+       Sci::Position originalAnchorPos;
+       Sci::Position wordSelectAnchorStartPos;
+       Sci::Position wordSelectAnchorEndPos;
+       Sci::Position wordSelectInitialCaretPos;
+       Sci::Position targetStart;
+       Sci::Position targetEnd;
        int searchFlags;
-       int topLine;
-       int posTopLine;
-       int lengthForEncode;
+       Sci::Line topLine;
+       Sci::Position posTopLine;
+       Sci::Position lengthForEncode;
 
        int needUpdateUI;
-       Position braces[2];
-       int bracesMatchStyle;
-       int highlightGuideColumn;
-
-       int theEdge;
 
        enum { notPainting, painting, paintAbandoned } paintState;
        bool paintAbandonedByStyling;
@@ -279,12 +229,12 @@ protected:        // ScintillaBase subclass needs access to much of Editor
        bool paintingAllText;
        bool willRedrawAll;
        WorkNeeded workNeeded;
+       int idleStyling;
+       bool needIdleStyling;
 
        int modEventMask;
 
        SelectionText drag;
-       Selection sel;
-       bool primarySelection;
 
        int caretXPolicy;
        int caretXSlop; ///< Ensure this many pixels visible on both sides of caret
@@ -295,117 +245,109 @@ protected:      // ScintillaBase subclass needs access to much of Editor
        int visiblePolicy;
        int visibleSlop;
 
-       int searchAnchor;
+       Sci::Position searchAnchor;
 
        bool recordingMacro;
 
-       int foldFlags;
        int foldAutomatic;
-       ContractionState cs;
-
-       // Hotspot support
-       int hsStart;
-       int hsEnd;
 
        // Wrapping support
-       enum { eWrapNone, eWrapWord, eWrapChar } wrapState;
-       int wrapWidth;
        WrapPending wrapPending;
-       int wrapVisualFlags;
-       int wrapVisualFlagsLocation;
-       int wrapVisualStartIndent;
-       int wrapIndentMode; // SC_WRAPINDENT_FIXED, _SAME, _INDENT
 
        bool convertPastes;
 
-       int marginNumberPadding; // the right-side padding of the number margin
-       int ctrlCharPadding; // the padding around control character text blobs
-       int lastSegItalicsOffset; // the offset so as not to clip italic characters at EOLs
-
-       Document *pdoc;
-
        Editor();
-       virtual ~Editor();
+       // Deleted so Editor objects can not be copied.
+       explicit Editor(const Editor &) = delete;
+       Editor &operator=(const Editor &) = delete;
+       ~Editor() override;
        virtual void Initialise() = 0;
        virtual void Finalise();
 
        void InvalidateStyleData();
        void InvalidateStyleRedraw();
        void RefreshStyleData();
+       void SetRepresentations();
        void DropGraphics(bool freeObjects);
        void AllocateGraphics();
 
        // The top left visible point in main window coordinates. Will be 0,0 except for
        // scroll views where it will be equivalent to the current scroll position.
-       virtual Point GetVisibleOriginInMain();
-       Point DocumentPointFromView(Point ptView);  // Convert a point from view space to document
-       int TopLineOfMain() const;   // Return the line at Main's y coordinate 0
-       virtual PRectangle GetClientRectangle();
-       PRectangle GetTextRectangle();
-
-       int LinesOnScreen();
-       int LinesToScroll();
-       int MaxScrollPos();
+       virtual Point GetVisibleOriginInMain() const override;
+       PointDocument DocumentPointFromView(Point ptView) const;  // Convert a point from view space to 
document
+       Sci::Line TopLineOfMain() const override;   // Return the line at Main's y coordinate 0
+       virtual PRectangle GetClientRectangle() const;
+       virtual PRectangle GetClientDrawingRectangle();
+       PRectangle GetTextRectangle() const;
+
+       virtual Sci::Line LinesOnScreen() const override;
+       Sci::Line LinesToScroll() const;
+       Sci::Line MaxScrollPos() const;
        SelectionPosition ClampPositionIntoDocument(SelectionPosition sp) const;
-       Point LocationFromPosition(SelectionPosition pos);
-       Point LocationFromPosition(int pos);
-       int XFromPosition(int pos);
+       Point LocationFromPosition(SelectionPosition pos, PointEnd pe=peDefault);
+       Point LocationFromPosition(Sci::Position pos, PointEnd pe=peDefault);
+       int XFromPosition(Sci::Position pos);
        int XFromPosition(SelectionPosition sp);
        SelectionPosition SPositionFromLocation(Point pt, bool canReturnInvalid=false, bool 
charPosition=false, bool virtualSpace=true);
-       int PositionFromLocation(Point pt, bool canReturnInvalid=false, bool charPosition=false);
-       SelectionPosition SPositionFromLineX(int lineDoc, int x);
-       int PositionFromLineX(int line, int x);
-       int LineFromLocation(Point pt) const;
-       void SetTopLine(int topLineNew);
-
-       bool AbandonPaint();
-       void RedrawRect(PRectangle rc);
-       void Redraw();
-       void RedrawSelMargin(int line=-1, bool allAfter=false);
-       PRectangle RectangleFromRange(int start, int end);
-       void InvalidateRange(int start, int end);
+       Sci::Position PositionFromLocation(Point pt, bool canReturnInvalid = false, bool charPosition = 
false);
+       SelectionPosition SPositionFromLineX(Sci::Line lineDoc, int x);
+       Sci::Position PositionFromLineX(Sci::Line lineDoc, int x);
+       Sci::Line LineFromLocation(Point pt) const;
+       void SetTopLine(Sci::Line topLineNew);
+
+       virtual bool AbandonPaint();
+       virtual void RedrawRect(PRectangle rc);
+       virtual void DiscardOverdraw();
+       virtual void Redraw();
+       void RedrawSelMargin(Sci::Line line=-1, bool allAfter=false);
+       PRectangle RectangleFromRange(Range r, int overlap);
+       void InvalidateRange(Sci::Position start, Sci::Position end);
 
        bool UserVirtualSpace() const {
                return ((virtualSpaceOptions & SCVS_USERACCESSIBLE) != 0);
        }
-       int CurrentPosition() const;
+       Sci::Position CurrentPosition() const;
        bool SelectionEmpty() const;
        SelectionPosition SelectionStart();
        SelectionPosition SelectionEnd();
        void SetRectangularRange();
        void ThinRectangularRange();
        void InvalidateSelection(SelectionRange newMain, bool invalidateWholeSelection=false);
+       void InvalidateWholeSelection();
        void SetSelection(SelectionPosition currentPos_, SelectionPosition anchor_);
-       void SetSelection(int currentPos_, int anchor_);
+       void SetSelection(Sci::Position currentPos_, Sci::Position anchor_);
        void SetSelection(SelectionPosition currentPos_);
        void SetSelection(int currentPos_);
        void SetEmptySelection(SelectionPosition currentPos_);
-       void SetEmptySelection(int currentPos_);
-       bool RangeContainsProtected(int start, int end) const;
+       void SetEmptySelection(Sci::Position currentPos_);
+       enum AddNumber { addOne, addEach };
+       void MultipleSelectAdd(AddNumber addNumber);
+       bool RangeContainsProtected(Sci::Position start, Sci::Position end) const;
        bool SelectionContainsProtected();
-       int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true) const;
-       SelectionPosition MovePositionOutsideChar(SelectionPosition pos, int moveDir, bool checkLineEnd=true) 
const;
-       int MovePositionTo(SelectionPosition newPos, Selection::selTypes sel=Selection::noSel, bool 
ensureVisible=true);
-       int MovePositionTo(int newPos, Selection::selTypes sel=Selection::noSel, bool ensureVisible=true);
+       Sci::Position MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool 
checkLineEnd=true) const;
+       SelectionPosition MovePositionOutsideChar(SelectionPosition pos, Sci::Position moveDir, bool 
checkLineEnd=true) const;
+       void MovedCaret(SelectionPosition newPos, SelectionPosition previousPos, bool ensureVisible);
+       void MovePositionTo(SelectionPosition newPos, Selection::selTypes selt=Selection::noSel, bool 
ensureVisible=true);
+       void MovePositionTo(Sci::Position newPos, Selection::selTypes selt=Selection::noSel, bool 
ensureVisible=true);
        SelectionPosition MovePositionSoVisible(SelectionPosition pos, int moveDir);
-       SelectionPosition MovePositionSoVisible(int pos, int moveDir);
+       SelectionPosition MovePositionSoVisible(Sci::Position pos, int moveDir);
        Point PointMainCaret();
        void SetLastXChosen();
 
-       void ScrollTo(int line, bool moveThumb=true);
-       virtual void ScrollText(int linesToMove);
+       void ScrollTo(Sci::Line line, bool moveThumb=true);
+       virtual void ScrollText(Sci::Line linesToMove);
        void HorizontalScrollTo(int xPos);
        void VerticalCentreCaret();
        void MoveSelectedLines(int lineDelta);
        void MoveSelectedLinesUp();
        void MoveSelectedLinesDown();
        void MoveCaretInsideView(bool ensureVisible=true);
-       int DisplayFromPosition(int pos);
+       Sci::Line DisplayFromPosition(Sci::Position pos);
 
        struct XYScrollPosition {
                int xOffset;
-               int topLine;
-               XYScrollPosition(int xOffset_, int topLine_) : xOffset(xOffset_), topLine(topLine_) {}
+               Sci::Line topLine;
+               XYScrollPosition(int xOffset_, Sci::Line topLine_) : xOffset(xOffset_), topLine(topLine_) {}
                bool operator==(const XYScrollPosition &other) const {
                        return (xOffset == other.xOffset) && (topLine == other.topLine);
                }
@@ -415,47 +357,26 @@ protected:        // ScintillaBase subclass needs access to much of Editor
                xysVertical=0x2,
                xysHorizontal=0x4,
                xysDefault=xysUseMargin|xysVertical|xysHorizontal};
-       XYScrollPosition XYScrollToMakeVisible(const SelectionRange range, const XYScrollOptions options);
+       XYScrollPosition XYScrollToMakeVisible(const SelectionRange &range, const XYScrollOptions options);
        void SetXYScroll(XYScrollPosition newXY);
        void EnsureCaretVisible(bool useMargin=true, bool vert=true, bool horiz=true);
        void ScrollRange(SelectionRange range);
        void ShowCaretAtCurrentPosition();
        void DropCaret();
+       void CaretSetPeriod(int period);
        void InvalidateCaret();
+       virtual void NotifyCaretMove();
        virtual void UpdateSystemCaret();
 
-       void NeedWrapping(int docLineStart=0, int docLineEnd=WrapPending::lineLarge);
-       bool WrapOneLine(Surface *surface, int lineToWrap);
-       enum wrapScope {wsAll, wsVisible, wsIdle};
-       bool WrapLines(enum wrapScope ws);
+       bool Wrapping() const;
+       void NeedWrapping(Sci::Line docLineStart=0, Sci::Line docLineEnd=WrapPending::lineLarge);
+       bool WrapOneLine(Surface *surface, Sci::Line lineToWrap);
+       enum class WrapScope {wsAll, wsVisible, wsIdle};
+       bool WrapLines(WrapScope ws);
        void LinesJoin();
        void LinesSplit(int pixelWidth);
 
-       int SubstituteMarkerIfEmpty(int markerCheck, int markerDefault) const;
-       void PaintSelMargin(Surface *surface, PRectangle &rc);
-       LineLayout *RetrieveLineLayout(int lineNumber);
-       void LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayout *ll,
-               int width=LineLayout::wrapWidthInfinite);
-       ColourDesired SelectionBackground(ViewStyle &vsDraw, bool main) const;
-       ColourDesired TextBackground(ViewStyle &vsDraw, bool overrideBackground, ColourDesired background, 
int inSelection, bool inHotspot, int styleMain, int i, LineLayout *ll) const;
-       void DrawIndentGuide(Surface *surface, int lineVisible, int lineHeight, int start, PRectangle 
rcSegment, bool highlight);
-       void DrawWrapMarker(Surface *surface, PRectangle rcPlace, bool isEndMarker, ColourDesired wrapColour);
-       void DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, LineLayout *ll,
-               int line, int lineEnd, int xStart, int subLine, XYACCUMULATOR subLineStart,
-               bool overrideBackground, ColourDesired background,
-               bool drawWrapMark, ColourDesired wrapColour);
-       void DrawIndicator(int indicNum, int startPos, int endPos, Surface *surface, ViewStyle &vsDraw,
-               int xStart, PRectangle rcLine, LineLayout *ll, int subLine);
-       void DrawIndicators(Surface *surface, ViewStyle &vsDraw, int line, int xStart,
-               PRectangle rcLine, LineLayout *ll, int subLine, int lineEnd, bool under);
-       void DrawAnnotation(Surface *surface, ViewStyle &vsDraw, int line, int xStart,
-        PRectangle rcLine, LineLayout *ll, int subLine);
-       void DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVisible, int xStart,
-               PRectangle rcLine, LineLayout *ll, int subLine);
-       void DrawBlockCaret(Surface *surface, ViewStyle &vsDraw, LineLayout *ll, int subLine,
-               int xStart, int offset, int posCaret, PRectangle rcCaret, ColourDesired caretColour);
-       void DrawCarets(Surface *surface, ViewStyle &vsDraw, int line, int xStart,
-               PRectangle rcLine, LineLayout *ll, int subLine);
+       void PaintSelMargin(Surface *surfaceWindow, PRectangle &rc);
        void RefreshPixMaps(Surface *surfaceWindow);
        void Paint(Surface *surfaceWindow, PRectangle rcArea);
        long FormatRange(bool draw, Sci_RangeToFormat *pfr);
@@ -463,76 +384,95 @@ protected:        // ScintillaBase subclass needs access to much of Editor
 
        virtual void SetVerticalScrollPos() = 0;
        virtual void SetHorizontalScrollPos() = 0;
-       virtual bool ModifyScrollBars(int nMax, int nPage) = 0;
+       virtual bool ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) = 0;
        virtual void ReconfigureScrollBars();
        void SetScrollBars();
        void ChangeSize();
 
        void FilterSelections();
-       int InsertSpace(int position, unsigned int spaces);
+       Sci::Position RealizeVirtualSpace(Sci::Position position, Sci::Position virtualSpace);
+       SelectionPosition RealizeVirtualSpace(const SelectionPosition &position);
        void AddChar(char ch);
-       virtual void AddCharUTF(char *s, unsigned int len, bool treatAsDBCS=false);
-       void InsertPaste(SelectionPosition selStart, const char *text, int len);
-       void ClearSelection(bool retainMultipleSelections=false);
+       virtual void AddCharUTF(const char *s, unsigned int len, bool treatAsDBCS=false);
+       void ClearBeforeTentativeStart();
+       void InsertPaste(const char *text, int len);
+       enum PasteShape { pasteStream=0, pasteRectangular = 1, pasteLine = 2 };
+       void InsertPasteShape(const char *text, int len, PasteShape shape);
+       void ClearSelection(bool retainMultipleSelections = false);
        void ClearAll();
        void ClearDocumentStyle();
-       void Cut();
-       void PasteRectangular(SelectionPosition pos, const char *ptr, int len);
+       virtual void Cut();
+       void PasteRectangular(SelectionPosition pos, const char *ptr, Sci::Position len);
        virtual void Copy() = 0;
        virtual void CopyAllowLine();
        virtual bool CanPaste();
        virtual void Paste() = 0;
        void Clear();
-       void SelectAll();
-       void Undo();
-       void Redo();
-       void DelChar();
+       virtual void SelectAll();
+       virtual void Undo();
+       virtual void Redo();
        void DelCharBack(bool allowLineStartDeletion);
        virtual void ClaimSelection() = 0;
 
+       static int ModifierFlags(bool shift, bool ctrl, bool alt, bool meta=false, bool super=false);
        virtual void NotifyChange() = 0;
        virtual void NotifyFocus(bool focus);
        virtual void SetCtrlID(int identifier);
        virtual int GetCtrlID() { return ctrlID; }
        virtual void NotifyParent(SCNotification scn) = 0;
-       virtual void NotifyStyleToNeeded(int endStyleNeeded);
+       virtual void NotifyStyleToNeeded(Sci::Position endStyleNeeded);
        void NotifyChar(int ch);
        void NotifySavePoint(bool isSavePoint);
        void NotifyModifyAttempt();
+       virtual void NotifyDoubleClick(Point pt, int modifiers);
        virtual void NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt);
-       void NotifyHotSpotClicked(int position, bool shift, bool ctrl, bool alt);
-       void NotifyHotSpotDoubleClicked(int position, bool shift, bool ctrl, bool alt);
-       void NotifyHotSpotReleaseClick(int position, bool shift, bool ctrl, bool alt);
+       void NotifyHotSpotClicked(Sci::Position position, int modifiers);
+       void NotifyHotSpotClicked(Sci::Position position, bool shift, bool ctrl, bool alt);
+       void NotifyHotSpotDoubleClicked(Sci::Position position, int modifiers);
+       void NotifyHotSpotDoubleClicked(Sci::Position position, bool shift, bool ctrl, bool alt);
+       void NotifyHotSpotReleaseClick(Sci::Position position, int modifiers);
+       void NotifyHotSpotReleaseClick(Sci::Position position, bool shift, bool ctrl, bool alt);
        bool NotifyUpdateUI();
        void NotifyPainted();
-       void NotifyIndicatorClick(bool click, int position, bool shift, bool ctrl, bool alt);
+       void NotifyIndicatorClick(bool click, Sci::Position position, int modifiers);
+       void NotifyIndicatorClick(bool click, Sci::Position position, bool shift, bool ctrl, bool alt);
+       bool NotifyMarginClick(Point pt, int modifiers);
        bool NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt);
-       void NotifyNeedShown(int pos, int len);
+       bool NotifyMarginRightClick(Point pt, int modifiers);
+       void NotifyNeedShown(Sci::Position pos, Sci::Position len);
        void NotifyDwelling(Point pt, bool state);
        void NotifyZoom();
 
-       void NotifyModifyAttempt(Document *document, void *userData);
-       void NotifySavePoint(Document *document, void *userData, bool atSavePoint);
+       void NotifyModifyAttempt(Document *document, void *userData) override;
+       void NotifySavePoint(Document *document, void *userData, bool atSavePoint) override;
        void CheckModificationForWrap(DocModification mh);
-       void NotifyModified(Document *document, DocModification mh, void *userData);
-       void NotifyDeleted(Document *document, void *userData);
-       void NotifyStyleNeeded(Document *doc, void *userData, int endPos);
-       void NotifyLexerChanged(Document *doc, void *userData);
-       void NotifyErrorOccurred(Document *doc, void *userData, int status);
+       void NotifyModified(Document *document, DocModification mh, void *userData) override;
+       void NotifyDeleted(Document *document, void *userData) override;
+       void NotifyStyleNeeded(Document *doc, void *userData, Sci::Position endStyleNeeded) override;
+       void NotifyLexerChanged(Document *doc, void *userData) override;
+       void NotifyErrorOccurred(Document *doc, void *userData, int status) override;
        void NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
 
        void ContainerNeedsUpdate(int flags);
-       void PageMove(int direction, Selection::selTypes sel=Selection::noSel, bool stuttered = false);
-       enum { cmSame, cmUpper, cmLower } caseMap;
+       void PageMove(int direction, Selection::selTypes selt=Selection::noSel, bool stuttered = false);
+       enum { cmSame, cmUpper, cmLower };
        virtual std::string CaseMapString(const std::string &s, int caseMapping);
        void ChangeCaseOfSelection(int caseMapping);
        void LineTranspose();
+       void LineReverse();
        void Duplicate(bool forLine);
        virtual void CancelModes();
        void NewLine();
-       void CursorUpOrDown(int direction, Selection::selTypes sel=Selection::noSel);
-       void ParaUpOrDown(int direction, Selection::selTypes sel=Selection::noSel);
-       int StartEndDisplayLine(int pos, bool start);
+       SelectionPosition PositionUpOrDown(SelectionPosition spStart, int direction, int lastX);
+       void CursorUpOrDown(int direction, Selection::selTypes selt);
+       void ParaUpOrDown(int direction, Selection::selTypes selt);
+       Range RangeDisplayLine(Sci::Line lineVisible);
+       Sci::Position StartEndDisplayLine(Sci::Position pos, bool start);
+       Sci::Position VCHomeDisplayPosition(Sci::Position position);
+       Sci::Position VCHomeWrapPosition(Sci::Position position);
+       Sci::Position LineEndWrapPosition(Sci::Position position);
+       int HorizontalMove(unsigned int iMessage);
+       int DelWordOrLine(unsigned int iMessage);
        virtual int KeyCommand(unsigned int iMessage);
        virtual int KeyDefault(int /* key */, int /*modifiers*/);
        int KeyDownWithModifiers(int key, int modifiers, bool *consumed);
@@ -544,13 +484,13 @@ protected:        // ScintillaBase subclass needs access to much of Editor
        long FindText(uptr_t wParam, sptr_t lParam);
        void SearchAnchor();
        long SearchText(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
-       long SearchInTarget(const char *text, int length);
-       void GoToLine(int lineNo);
+       long SearchInTarget(const char *text, Sci::Position length);
+       void GoToLine(Sci::Line lineNo);
 
        virtual void CopyToClipboard(const SelectionText &selectedText) = 0;
-       std::string RangeText(int start, int end) const;
+       std::string RangeText(Sci::Position start, Sci::Position end) const;
        void CopySelectionRange(SelectionText *ss, bool allowLineCopy=false);
-       void CopyRangeToClipboard(int start, int end);
+       void CopyRangeToClipboard(Sci::Position start, Sci::Position end);
        void CopyText(int length, const char *text);
        void SetDragPosition(SelectionPosition newPos);
        virtual void DisplayCursor(Window::Cursor c);
@@ -559,72 +499,90 @@ protected:        // ScintillaBase subclass needs access to much of Editor
        void DropAt(SelectionPosition position, const char *value, size_t lengthValue, bool moving, bool 
rectangular);
        void DropAt(SelectionPosition position, const char *value, bool moving, bool rectangular);
        /** PositionInSelection returns true if position in selection. */
-       bool PositionInSelection(int pos);
+       bool PositionInSelection(Sci::Position pos);
        bool PointInSelection(Point pt);
-       bool PointInSelMargin(Point pt);
+       bool PointInSelMargin(Point pt) const;
        Window::Cursor GetMarginCursor(Point pt) const;
-       void TrimAndSetSelection(int currentPos_, int anchor_);
-       void LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLine);
-       void WordSelection(int pos);
+       void TrimAndSetSelection(Sci::Position currentPos_, Sci::Position anchor_);
+       void LineSelection(Sci::Position lineCurrentPos_, Sci::Position lineAnchorPos_, bool wholeLine);
+       void WordSelection(Sci::Position pos);
        void DwellEnd(bool mouseMoved);
        void MouseLeave();
+       virtual void ButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers);
+       virtual void RightButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers);
        virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt);
+       void ButtonMoveWithModifiers(Point pt, int modifiers);
        void ButtonMove(Point pt);
        void ButtonUp(Point pt, unsigned int curTime, bool ctrl);
 
        void Tick();
        bool Idle();
-       virtual void SetTicking(bool on) = 0;
+       virtual void SetTicking(bool on);
+       enum TickReason { tickCaret, tickScroll, tickWiden, tickDwell, tickPlatform };
+       virtual void TickFor(TickReason reason);
+       virtual bool FineTickerAvailable();
+       virtual bool FineTickerRunning(TickReason reason);
+       virtual void FineTickerStart(TickReason reason, int millis, int tolerance);
+       virtual void FineTickerCancel(TickReason reason);
        virtual bool SetIdle(bool) { return false; }
        virtual void SetMouseCapture(bool on) = 0;
        virtual bool HaveMouseCapture() = 0;
        void SetFocusState(bool focusState);
 
-       int PositionAfterArea(PRectangle rcArea) const;
-       void StyleToPositionInView(Position pos);
+       Sci::Position PositionAfterArea(PRectangle rcArea) const;
+       void StyleToPositionInView(Sci::Position pos);
+       Sci::Position PositionAfterMaxStyling(Sci::Position posMax, bool scrolling) const;
+       void StartIdleStyling(bool truncatedLastStyling);
+       void StyleAreaBounded(PRectangle rcArea, bool scrolling);
+       void IdleStyling();
        virtual void IdleWork();
-       virtual void QueueIdleWork(WorkNeeded::workItems items, int upTo=0);
+       virtual void QueueIdleWork(WorkNeeded::workItems items, Sci::Position upTo=0);
 
        virtual bool PaintContains(PRectangle rc);
        bool PaintContainsMargin();
        void CheckForChangeOutsidePaint(Range r);
-       void SetBraceHighlight(Position pos0, Position pos1, int matchStyle);
+       void SetBraceHighlight(Sci::Position pos0, Sci::Position pos1, int matchStyle);
 
-       void SetAnnotationHeights(int start, int end);
+       void SetAnnotationHeights(Sci::Line start, Sci::Line end);
        virtual void SetDocPointer(Document *document);
 
        void SetAnnotationVisible(int visible);
 
-       int ExpandLine(int line);
-       void SetFoldExpanded(int lineDoc, bool expanded);
-       void FoldLine(int line, int action);
-       void FoldExpand(int line, int action, int level);
-       int ContractedFoldNext(int lineStart) const;
-       void EnsureLineVisible(int lineDoc, bool enforcePolicy);
-       void FoldChanged(int line, int levelNow, int levelPrev);
-       void NeedShown(int pos, int len);
+       Sci::Line ExpandLine(Sci::Line line);
+       void SetFoldExpanded(Sci::Line lineDoc, bool expanded);
+       void FoldLine(Sci::Line line, int action);
+       void FoldExpand(Sci::Line line, int action, int level);
+       Sci::Line ContractedFoldNext(Sci::Line lineStart) const;
+       void EnsureLineVisible(Sci::Line lineDoc, bool enforcePolicy);
+       void FoldChanged(Sci::Line line, int levelNow, int levelPrev);
+       void NeedShown(Sci::Position pos, Sci::Position len);
        void FoldAll(int action);
 
-       int GetTag(char *tagValue, int tagNumber);
-       int ReplaceTarget(bool replacePatterns, const char *text, int length=-1);
+       Sci::Position GetTag(char *tagValue, int tagNumber);
+       Sci::Position ReplaceTarget(bool replacePatterns, const char *text, Sci::Position length=-1);
 
-       bool PositionIsHotspot(int position) const;
+       bool PositionIsHotspot(Sci::Position position) const;
        bool PointIsHotspot(Point pt);
        void SetHotSpotRange(Point *pt);
-       void GetHotSpotRange(int &hsStart, int &hsEnd) const;
+       Range GetHotSpotRange() const override;
+       void SetHoverIndicatorPosition(Sci::Position position);
+       void SetHoverIndicatorPoint(Point pt);
 
        int CodePage() const;
        virtual bool ValidCodePage(int /* codePage */) const { return true; }
        int WrapCount(int line);
-       void AddStyledText(char *buffer, int appendLength);
+       void AddStyledText(char *buffer, Sci::Position appendLength);
 
        virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) = 0;
+       bool ValidMargin(uptr_t wParam) const;
        void StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
        sptr_t StyleGetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
+       void SetSelectionNMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
 
        static const char *StringFromEOLMode(int eolMode);
 
        static sptr_t StringResult(sptr_t lParam, const char *val);
+       static sptr_t BytesResult(sptr_t lParam, const unsigned char *val, size_t len);
 
 public:
        // Public so the COM thunks can access it.
@@ -644,36 +602,34 @@ public:
  */
 class AutoSurface {
 private:
-       Surface *surf;
+       std::unique_ptr<Surface> surf;
 public:
-       AutoSurface(Editor *ed, int technology = -1) : surf(0) {
+       AutoSurface(Editor *ed, int technology = -1) {
                if (ed->wMain.GetID()) {
-                       surf = Surface::Allocate(technology != -1 ? technology : ed->technology);
-                       if (surf) {
-                               surf->Init(ed->wMain.GetID());
-                               surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
-                               surf->SetDBCSMode(ed->CodePage());
-                       }
+                       surf.reset(Surface::Allocate(technology != -1 ? technology : ed->technology));
+                       surf->Init(ed->wMain.GetID());
+                       surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
+                       surf->SetDBCSMode(ed->CodePage());
                }
        }
-       AutoSurface(SurfaceID sid, Editor *ed, int technology = -1) : surf(0) {
+       AutoSurface(SurfaceID sid, Editor *ed, int technology = -1) {
                if (ed->wMain.GetID()) {
-                       surf = Surface::Allocate(technology != -1 ? technology : ed->technology);
-                       if (surf) {
-                               surf->Init(sid, ed->wMain.GetID());
-                               surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
-                               surf->SetDBCSMode(ed->CodePage());
-                       }
+                       surf.reset(Surface::Allocate(technology != -1 ? technology : ed->technology));
+                       surf->Init(sid, ed->wMain.GetID());
+                       surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
+                       surf->SetDBCSMode(ed->CodePage());
                }
        }
+       // Deleted so AutoSurface objects can not be copied.
+       AutoSurface(const AutoSurface &) = delete;
+       void operator=(const AutoSurface &) = delete;
        ~AutoSurface() {
-               delete surf;
        }
        Surface *operator->() const {
-               return surf;
+               return surf.get();
        }
        operator Surface *() const {
-               return surf;
+               return surf.get();
        }
 };
 
diff --git a/plugins/scintilla/scintilla/src/ExternalLexer.cxx 
b/plugins/scintilla/scintilla/src/ExternalLexer.cxx
index bb48464..4a2811c 100644
--- a/plugins/scintilla/scintilla/src/ExternalLexer.cxx
+++ b/plugins/scintilla/scintilla/src/ExternalLexer.cxx
@@ -5,13 +5,14 @@
 // Copyright 2001 Simon Steele <ss pnotepad org>, portions copyright Neil Hodgson.
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include <assert.h>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
 
+#include <stdexcept>
 #include <string>
+#include <vector>
+#include <memory>
 
 #include "Platform.h"
 
@@ -27,7 +28,7 @@
 using namespace Scintilla;
 #endif
 
-LexerManager *LexerManager::theInstance = NULL;
+std::unique_ptr<LexerManager> LexerManager::theInstance;
 
 //------------------------------------------
 //
@@ -46,48 +47,30 @@ void ExternalLexerModule::SetExternal(GetLexerFactoryFunction fFactory, int inde
 //
 //------------------------------------------
 
-LexerLibrary::LexerLibrary(const char *ModuleName) {
-       // Initialise some members...
-       first = NULL;
-       last = NULL;
-
+LexerLibrary::LexerLibrary(const char *moduleName_) {
        // Load the DLL
-       lib = DynamicLibrary::Load(ModuleName);
+       lib.reset(DynamicLibrary::Load(moduleName_));
        if (lib->IsValid()) {
-               m_sModuleName = ModuleName;
+               moduleName = moduleName_;
                //Cannot use reinterpret_cast because: ANSI C++ forbids casting between pointers to functions 
and objects
                GetLexerCountFn GetLexerCount = (GetLexerCountFn)(sptr_t)lib->FindFunction("GetLexerCount");
 
                if (GetLexerCount) {
-                       ExternalLexerModule *lex;
-                       LexerMinder *lm;
-
                        // Find functions in the DLL
                        GetLexerNameFn GetLexerName = 
(GetLexerNameFn)(sptr_t)lib->FindFunction("GetLexerName");
                        GetLexerFactoryFunction fnFactory = 
(GetLexerFactoryFunction)(sptr_t)lib->FindFunction("GetLexerFactory");
 
-                       // Assign a buffer for the lexer name.
-                       char lexname[100];
-                       strcpy(lexname, "");
-
-                       int nl = GetLexerCount();
+                       const int nl = GetLexerCount();
 
                        for (int i = 0; i < nl; i++) {
-                               GetLexerName(i, lexname, 100);
-                               lex = new ExternalLexerModule(SCLEX_AUTOMATIC, NULL, lexname, NULL);
+                               // Assign a buffer for the lexer name.
+                               char lexname[100] = "";
+                               GetLexerName(i, lexname, sizeof(lexname));
+                               ExternalLexerModule *lex = new ExternalLexerModule(SCLEX_AUTOMATIC, NULL, 
lexname, NULL);
                                Catalogue::AddLexerModule(lex);
 
-                               // Create a LexerMinder so we don't leak the ExternalLexerModule...
-                               lm = new LexerMinder;
-                               lm->self = lex;
-                               lm->next = NULL;
-                               if (first != NULL) {
-                                       last->next = lm;
-                                       last = lm;
-                               } else {
-                                       first = lm;
-                                       last = lm;
-                               }
+                               // Remember ExternalLexerModule so we don't leak it
+                               modules.push_back(std::unique_ptr<ExternalLexerModule>(lex));
 
                                // The external lexer needs to know how to call into its DLL to
                                // do its lexing and folding, we tell it here.
@@ -95,27 +78,9 @@ LexerLibrary::LexerLibrary(const char *ModuleName) {
                        }
                }
        }
-       next = NULL;
 }
 
 LexerLibrary::~LexerLibrary() {
-       Release();
-       delete lib;
-}
-
-void LexerLibrary::Release() {
-       LexerMinder *lm;
-       LexerMinder *lmNext;
-       lm = first;
-       while (NULL != lm) {
-               lmNext = lm->next;
-               delete lm->self;
-               delete lm;
-               lm = lmNext;
-       }
-
-       first = NULL;
-       last = NULL;
 }
 
 //------------------------------------------
@@ -127,20 +92,17 @@ void LexerLibrary::Release() {
 /// Return the single LexerManager instance...
 LexerManager *LexerManager::GetInstance() {
        if (!theInstance)
-               theInstance = new LexerManager;
-       return theInstance;
+               theInstance.reset(new LexerManager);
+       return theInstance.get();
 }
 
 /// Delete any LexerManager instance...
 void LexerManager::DeleteInstance() {
-       delete theInstance;
-       theInstance = NULL;
+       theInstance.reset();
 }
 
 /// protected constructor - this is a singleton...
 LexerManager::LexerManager() {
-       first = NULL;
-       last = NULL;
 }
 
 LexerManager::~LexerManager() {
@@ -148,41 +110,21 @@ LexerManager::~LexerManager() {
 }
 
 void LexerManager::Load(const char *path) {
-       LoadLexerLibrary(path);
-}
-
-void LexerManager::LoadLexerLibrary(const char *module) {
-       for (LexerLibrary *ll = first; ll; ll= ll->next) {
-               if (strcmp(ll->m_sModuleName.c_str(), module) == 0)
+       for (const std::unique_ptr<LexerLibrary> &ll : libraries) {
+               if (ll->moduleName == path)
                        return;
        }
-       LexerLibrary *lib = new LexerLibrary(module);
-       if (NULL != first) {
-               last->next = lib;
-               last = lib;
-       } else {
-               first = lib;
-               last = lib;
-       }
+       LexerLibrary *lib = new LexerLibrary(path);
+       libraries.push_back(std::unique_ptr<LexerLibrary>(lib));
 }
 
 void LexerManager::Clear() {
-       if (NULL != first) {
-               LexerLibrary *cur = first;
-               LexerLibrary *next;
-               while (cur) {
-                       next = cur->next;
-                       delete cur;
-                       cur = next;
-               }
-               first = NULL;
-               last = NULL;
-       }
+       libraries.clear();
 }
 
 //------------------------------------------
 //
-// LexerManager
+// LMMinder    -- trigger to clean up at exit.
 //
 //------------------------------------------
 
diff --git a/plugins/scintilla/scintilla/src/ExternalLexer.h b/plugins/scintilla/scintilla/src/ExternalLexer.h
index bf175a6..7804c19 100644
--- a/plugins/scintilla/scintilla/src/ExternalLexer.h
+++ b/plugins/scintilla/scintilla/src/ExternalLexer.h
@@ -27,39 +27,26 @@ typedef LexerFactoryFunction(EXT_LEXER_DECL *GetLexerFactoryFunction)(unsigned i
 class ExternalLexerModule : public LexerModule {
 protected:
        GetLexerFactoryFunction fneFactory;
-       char name[100];
+       std::string name;
 public:
        ExternalLexerModule(int language_, LexerFunction fnLexer_,
                const char *languageName_=0, LexerFunction fnFolder_=0) :
                LexerModule(language_, fnLexer_, 0, fnFolder_),
-               fneFactory(0) {
-               strncpy(name, languageName_, sizeof(name));
-               name[sizeof(name)-1] = '\0';
-               languageName = name;
+               fneFactory(0), name(languageName_){
+               languageName = name.c_str();
        }
        virtual void SetExternal(GetLexerFactoryFunction fFactory, int index);
 };
 
-/// LexerMinder points to an ExternalLexerModule - so we don't leak them.
-class LexerMinder {
-public:
-       ExternalLexerModule *self;
-       LexerMinder *next;
-};
-
-/// LexerLibrary exists for every External Lexer DLL, contains LexerMinders.
+/// LexerLibrary exists for every External Lexer DLL, contains ExternalLexerModules.
 class LexerLibrary {
-       DynamicLibrary  *lib;
-       LexerMinder             *first;
-       LexerMinder             *last;
-
+       std::unique_ptr<DynamicLibrary> lib;
+       std::vector<std::unique_ptr<ExternalLexerModule>> modules;
 public:
-       LexerLibrary(const char *ModuleName);
+       explicit LexerLibrary(const char *moduleName_);
        ~LexerLibrary();
-       void Release();
 
-       LexerLibrary    *next;
-       std::string                     m_sModuleName;
+       std::string moduleName;
 };
 
 /// LexerManager manages external lexers, contains LexerLibrarys.
@@ -75,11 +62,8 @@ public:
 
 private:
        LexerManager();
-       static LexerManager *theInstance;
-
-       void LoadLexerLibrary(const char *module);
-       LexerLibrary *first;
-       LexerLibrary *last;
+       static std::unique_ptr<LexerManager> theInstance;
+       std::vector<std::unique_ptr<LexerLibrary>> libraries;
 };
 
 class LMMinder {
diff --git a/plugins/scintilla/scintilla/src/FontQuality.h b/plugins/scintilla/scintilla/src/FontQuality.h
index 45600c3..a0ae207 100644
--- a/plugins/scintilla/scintilla/src/FontQuality.h
+++ b/plugins/scintilla/scintilla/src/FontQuality.h
@@ -1,15 +1,31 @@
 // Scintilla source code edit control
 /** @file FontQuality.h
  ** Definitions to control font anti-aliasing.
+ ** Redefine constants from Scintilla.h to avoid including Scintilla.h in PlatWin.cxx.
  **/
 // Copyright 1998-2009 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+#ifndef FONTQUALITY_H
+#define FONTQUALITY_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+// These definitions match Scintilla.h
 #define SC_EFF_QUALITY_MASK            0xF
 #define SC_EFF_QUALITY_DEFAULT           0
 #define SC_EFF_QUALITY_NON_ANTIALIASED   1
 #define SC_EFF_QUALITY_ANTIALIASED       2
 #define SC_EFF_QUALITY_LCD_OPTIMIZED     3
 
+// These definitions must match SC_TECHNOLOGY_* in Scintilla.h
 #define SCWIN_TECH_GDI 0
 #define SCWIN_TECH_DIRECTWRITE 1
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/Indicator.cxx b/plugins/scintilla/scintilla/src/Indicator.cxx
index ac74351..16fc591 100644
--- a/plugins/scintilla/scintilla/src/Indicator.cxx
+++ b/plugins/scintilla/scintilla/src/Indicator.cxx
@@ -5,14 +5,16 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+#include <stdexcept>
 #include <vector>
 #include <map>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
-#include "XPM.h"
 #include "Indicator.h"
+#include "XPM.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
@@ -20,17 +22,25 @@ using namespace Scintilla;
 
 static PRectangle PixelGridAlign(const PRectangle &rc) {
        // Move left and right side to nearest pixel to avoid blurry visuals
-       return PRectangle(int(rc.left + 0.5), rc.top, int(rc.right + 0.5), rc.bottom);
+       return PRectangle::FromInts(static_cast<int>(rc.left + 0.5), static_cast<int>(rc.top),
+               static_cast<int>(rc.right + 0.5), static_cast<int>(rc.bottom));
 }
 
-void Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine) {
-       surface->PenColour(fore);
-       int ymid = (rc.bottom + rc.top) / 2;
-       if (style == INDIC_SQUIGGLE) {
-               int x = int(rc.left+0.5);
-               int xLast = int(rc.right+0.5);
+void Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine, const PRectangle 
&rcCharacter, DrawState drawState, int value) const {
+       StyleAndColour sacDraw = sacNormal;
+       if (Flags() & SC_INDICFLAG_VALUEFORE) {
+               sacDraw.fore = value & SC_INDICVALUEMASK;
+       }
+       if (drawState == drawHover) {
+               sacDraw = sacHover;
+       }
+       surface->PenColour(sacDraw.fore);
+       int ymid = static_cast<int>(rc.bottom + rc.top) / 2;
+       if (sacDraw.style == INDIC_SQUIGGLE) {
+               int x = static_cast<int>(rc.left+0.5);
+               const int xLast = static_cast<int>(rc.right+0.5);
                int y = 0;
-               surface->MoveTo(x, rc.top + y);
+               surface->MoveTo(x, static_cast<int>(rc.top) + y);
                while (x < xLast) {
                        if ((x + 2) > xLast) {
                                if (xLast > x)
@@ -40,41 +50,41 @@ void Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &r
                                x += 2;
                                y = 2 - y;
                        }
-                       surface->LineTo(x, rc.top + y);
+                       surface->LineTo(x, static_cast<int>(rc.top) + y);
                }
-       } else if (style == INDIC_SQUIGGLEPIXMAP) {
+       } else if (sacDraw.style == INDIC_SQUIGGLEPIXMAP) {
                PRectangle rcSquiggle = PixelGridAlign(rc);
 
-               int width = Platform::Minimum(4000, rcSquiggle.Width());
+               int width = Platform::Minimum(4000, static_cast<int>(rcSquiggle.Width()));
                RGBAImage image(width, 3, 1.0, 0);
                enum { alphaFull = 0xff, alphaSide = 0x2f, alphaSide2=0x5f };
                for (int x = 0; x < width; x++) {
                        if (x%2) {
                                // Two halfway columns have a full pixel in middle flanked by light pixels
-                               image.SetPixel(x, 0, fore, alphaSide);
-                               image.SetPixel(x, 1, fore, alphaFull);
-                               image.SetPixel(x, 2, fore, alphaSide);
+                               image.SetPixel(x, 0, sacDraw.fore, alphaSide);
+                               image.SetPixel(x, 1, sacDraw.fore, alphaFull);
+                               image.SetPixel(x, 2, sacDraw.fore, alphaSide);
                        } else {
                                // Extreme columns have a full pixel at bottom or top and a mid-tone pixel in 
centre
-                               image.SetPixel(x, (x%4) ? 0 : 2, fore, alphaFull);
-                               image.SetPixel(x, 1, fore, alphaSide2);
+                               image.SetPixel(x, (x % 4) ? 0 : 2, sacDraw.fore, alphaFull);
+                               image.SetPixel(x, 1, sacDraw.fore, alphaSide2);
                        }
                }
                surface->DrawRGBAImage(rcSquiggle, image.GetWidth(), image.GetHeight(), image.Pixels());
-       } else if (style == INDIC_SQUIGGLELOW) {
-               surface->MoveTo(rc.left, rc.top);
-               int x = rc.left + 3;
+       } else if (sacDraw.style == INDIC_SQUIGGLELOW) {
+               surface->MoveTo(static_cast<int>(rc.left), static_cast<int>(rc.top));
+               int x = static_cast<int>(rc.left) + 3;
                int y = 0;
                while (x < rc.right) {
-                       surface->LineTo(x-1, rc.top + y);
+                       surface->LineTo(x - 1, static_cast<int>(rc.top) + y);
                        y = 1 - y;
-               surface->LineTo(x, rc.top + y);
+                       surface->LineTo(x, static_cast<int>(rc.top) + y);
                        x += 3;
                }
-               surface->LineTo(rc.right, rc.top + y);  // Finish the line
-       } else if (style == INDIC_TT) {
-               surface->MoveTo(rc.left, ymid);
-               int x = rc.left + 5;
+               surface->LineTo(static_cast<int>(rc.right), static_cast<int>(rc.top) + y);      // Finish the 
line
+       } else if (sacDraw.style == INDIC_TT) {
+               surface->MoveTo(static_cast<int>(rc.left), ymid);
+               int x = static_cast<int>(rc.left) + 5;
                while (x < rc.right) {
                        surface->LineTo(x, ymid);
                        surface->MoveTo(x-3, ymid);
@@ -83,81 +93,104 @@ void Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &r
                        surface->MoveTo(x, ymid);
                        x += 5;
                }
-               surface->LineTo(rc.right, ymid);        // Finish the line
+               surface->LineTo(static_cast<int>(rc.right), ymid);      // Finish the line
                if (x - 3 <= rc.right) {
                        surface->MoveTo(x-3, ymid);
                        surface->LineTo(x-3, ymid+2);
                }
-       } else if (style == INDIC_DIAGONAL) {
-               int x = rc.left;
+       } else if (sacDraw.style == INDIC_DIAGONAL) {
+               int x = static_cast<int>(rc.left);
                while (x < rc.right) {
-                       surface->MoveTo(x, rc.top+2);
+                       surface->MoveTo(x, static_cast<int>(rc.top) + 2);
                        int endX = x+3;
-                       int endY = rc.top - 1;
+                       int endY = static_cast<int>(rc.top) - 1;
                        if (endX > rc.right) {
-                               endY += endX - rc.right;
-                               endX = rc.right;
+                               endY += endX - static_cast<int>(rc.right);
+                               endX = static_cast<int>(rc.right);
                        }
                        surface->LineTo(endX, endY);
                        x += 4;
                }
-       } else if (style == INDIC_STRIKE) {
-               surface->MoveTo(rc.left, rc.top - 4);
-               surface->LineTo(rc.right, rc.top - 4);
-       } else if (style == INDIC_HIDDEN) {
+       } else if (sacDraw.style == INDIC_STRIKE) {
+               surface->MoveTo(static_cast<int>(rc.left), static_cast<int>(rc.top) - 4);
+               surface->LineTo(static_cast<int>(rc.right), static_cast<int>(rc.top) - 4);
+       } else if ((sacDraw.style == INDIC_HIDDEN) || (sacDraw.style == INDIC_TEXTFORE)) {
                // Draw nothing
-       } else if (style == INDIC_BOX) {
-               surface->MoveTo(rc.left, ymid+1);
-               surface->LineTo(rc.right, ymid+1);
-               surface->LineTo(rc.right, rcLine.top+1);
-               surface->LineTo(rc.left, rcLine.top+1);
-               surface->LineTo(rc.left, ymid+1);
-       } else if (style == INDIC_ROUNDBOX || style == INDIC_STRAIGHTBOX) {
+       } else if (sacDraw.style == INDIC_BOX) {
+               surface->MoveTo(static_cast<int>(rc.left), ymid + 1);
+               surface->LineTo(static_cast<int>(rc.right), ymid + 1);
+               surface->LineTo(static_cast<int>(rc.right), static_cast<int>(rcLine.top) + 1);
+               surface->LineTo(static_cast<int>(rc.left), static_cast<int>(rcLine.top) + 1);
+               surface->LineTo(static_cast<int>(rc.left), ymid + 1);
+       } else if (sacDraw.style == INDIC_ROUNDBOX ||
+               sacDraw.style == INDIC_STRAIGHTBOX ||
+               sacDraw.style == INDIC_FULLBOX) {
                PRectangle rcBox = rcLine;
-               rcBox.top = rcLine.top + 1;
+               if (sacDraw.style != INDIC_FULLBOX)
+                       rcBox.top = rcLine.top + 1;
                rcBox.left = rc.left;
                rcBox.right = rc.right;
-               surface->AlphaRectangle(rcBox, (style == INDIC_ROUNDBOX) ? 1 : 0, fore, fillAlpha, fore, 
outlineAlpha, 0);
-       } else if (style == INDIC_DOTBOX) {
+               surface->AlphaRectangle(rcBox, (sacDraw.style == INDIC_ROUNDBOX) ? 1 : 0,
+                       sacDraw.fore, fillAlpha, sacDraw.fore, outlineAlpha, 0);
+       } else if (sacDraw.style == INDIC_DOTBOX) {
                PRectangle rcBox = PixelGridAlign(rc);
                rcBox.top = rcLine.top + 1;
                rcBox.bottom = rcLine.bottom;
                // Cap width at 4000 to avoid large allocations when mistakes made
-               int width = Platform::Minimum(rcBox.Width(), 4000);
-               RGBAImage image(width, rcBox.Height(), 1.0, 0);
+               int width = Platform::Minimum(static_cast<int>(rcBox.Width()), 4000);
+               RGBAImage image(width, static_cast<int>(rcBox.Height()), 1.0, 0);
                // Draw horizontal lines top and bottom
                for (int x=0; x<width; x++) {
-                       for (int y=0; y<rcBox.Height(); y += rcBox.Height()-1) {
-                               image.SetPixel(x, y, fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);
+                       for (int y = 0; y<static_cast<int>(rcBox.Height()); y += 
static_cast<int>(rcBox.Height()) - 1) {
+                               image.SetPixel(x, y, sacDraw.fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);
                        }
                }
                // Draw vertical lines left and right
-               for (int y=1; y<rcBox.Height(); y++) {
+               for (int y = 1; y<static_cast<int>(rcBox.Height()); y++) {
                        for (int x=0; x<width; x += width-1) {
-                               image.SetPixel(x, y, fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);
+                               image.SetPixel(x, y, sacDraw.fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);
                        }
                }
                surface->DrawRGBAImage(rcBox, image.GetWidth(), image.GetHeight(), image.Pixels());
-       } else if (style == INDIC_DASH) {
-               int x = rc.left;
+       } else if (sacDraw.style == INDIC_DASH) {
+               int x = static_cast<int>(rc.left);
                while (x < rc.right) {
                        surface->MoveTo(x, ymid);
-                       surface->LineTo(Platform::Minimum(x + 4, rc.right), ymid);
+                       surface->LineTo(Platform::Minimum(x + 4, static_cast<int>(rc.right)), ymid);
                        x += 7;
                }
-       } else if (style == INDIC_DOTS) {
-               int x = rc.left;
-               while (x < rc.right) {
-                       PRectangle rcDot(x, ymid, x+1, ymid+1);
-                       surface->FillRectangle(rcDot, fore);
+       } else if (sacDraw.style == INDIC_DOTS) {
+               int x = static_cast<int>(rc.left);
+               while (x < static_cast<int>(rc.right)) {
+                       PRectangle rcDot = PRectangle::FromInts(x, ymid, x + 1, ymid + 1);
+                       surface->FillRectangle(rcDot, sacDraw.fore);
                        x += 2;
                }
-       } else if (style == INDIC_COMPOSITIONTHICK) {
+       } else if (sacDraw.style == INDIC_COMPOSITIONTHICK) {
                PRectangle rcComposition(rc.left+1, rcLine.bottom-2, rc.right-1, rcLine.bottom);
-               surface->FillRectangle(rcComposition, fore);
+               surface->FillRectangle(rcComposition, sacDraw.fore);
+       } else if (sacDraw.style == INDIC_COMPOSITIONTHIN) {
+               PRectangle rcComposition(rc.left+1, rcLine.bottom-2, rc.right-1, rcLine.bottom-1);
+               surface->FillRectangle(rcComposition, sacDraw.fore);
+       } else if (sacDraw.style == INDIC_POINT || sacDraw.style == INDIC_POINTCHARACTER) {
+               if (rcCharacter.Width() >= 0.1) {
+                       const int pixelHeight = static_cast<int>(rc.Height() - 1.0f);   // 1 pixel onto next 
line if multiphase
+                       const XYPOSITION x = (sacDraw.style == INDIC_POINT) ? (rcCharacter.left) : 
((rcCharacter.right + rcCharacter.left) / 2);
+                       const int ix = static_cast<int>(x + 0.5f);
+                       const int iy = static_cast<int>(rc.top + 1.0f);
+                       Point pts[] = {
+                               Point::FromInts(ix - pixelHeight, iy + pixelHeight),    // Left
+                               Point::FromInts(ix + pixelHeight, iy + pixelHeight),    // Right
+                               Point::FromInts(ix, iy)                                                       
          // Top
+                       };
+                       surface->Polygon(pts, 3, sacDraw.fore, sacDraw.fore);
+               }
        } else {        // Either INDIC_PLAIN or unknown
-               surface->MoveTo(rc.left, ymid);
-               surface->LineTo(rc.right, ymid);
+               surface->MoveTo(static_cast<int>(rc.left), ymid);
+               surface->LineTo(static_cast<int>(rc.right), ymid);
        }
 }
 
+void Indicator::SetFlags(int attributes_) {
+       attributes = attributes_;
+}
diff --git a/plugins/scintilla/scintilla/src/Indicator.h b/plugins/scintilla/scintilla/src/Indicator.h
index 0284a85..9b887df 100644
--- a/plugins/scintilla/scintilla/src/Indicator.h
+++ b/plugins/scintilla/scintilla/src/Indicator.h
@@ -12,18 +12,45 @@
 namespace Scintilla {
 #endif
 
+struct StyleAndColour {
+       int style;
+       ColourDesired fore;
+       StyleAndColour() : style(INDIC_PLAIN), fore(0, 0, 0) {
+       }
+       StyleAndColour(int style_, ColourDesired fore_ = ColourDesired(0, 0, 0)) : style(style_), fore(fore_) 
{
+       }
+       bool operator==(const StyleAndColour &other) const {
+               return (style == other.style) && (fore == other.fore);
+       }
+};
+
 /**
  */
 class Indicator {
 public:
-       int style;
+       enum DrawState { drawNormal, drawHover };
+       StyleAndColour sacNormal;
+       StyleAndColour sacHover;
        bool under;
-       ColourDesired fore;
        int fillAlpha;
        int outlineAlpha;
-       Indicator() : style(INDIC_PLAIN), under(false), fore(ColourDesired(0,0,0)), fillAlpha(30), 
outlineAlpha(50) {
+       int attributes;
+       Indicator() : under(false), fillAlpha(30), outlineAlpha(50), attributes(0) {
+       }
+       Indicator(int style_, ColourDesired fore_=ColourDesired(0,0,0), bool under_=false, int fillAlpha_=30, 
int outlineAlpha_=50) :
+               sacNormal(style_, fore_), sacHover(style_, fore_), under(under_), fillAlpha(fillAlpha_), 
outlineAlpha(outlineAlpha_), attributes(0) {
+       }
+       void Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine, const PRectangle 
&rcCharacter, DrawState drawState, int value) const;
+       bool IsDynamic() const {
+               return !(sacNormal == sacHover);
+       }
+       bool OverridesTextFore() const {
+               return sacNormal.style == INDIC_TEXTFORE || sacHover.style == INDIC_TEXTFORE;
+       }
+       int Flags() const {
+               return attributes;
        }
-       void Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine);
+       void SetFlags(int attributes_);
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/KeyMap.cxx b/plugins/scintilla/scintilla/src/KeyMap.cxx
index 7407761..2d81ab4 100644
--- a/plugins/scintilla/scintilla/src/KeyMap.cxx
+++ b/plugins/scintilla/scintilla/src/KeyMap.cxx
@@ -5,9 +5,11 @@
 // Copyright 1998-2003 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
+#include <cstdlib>
 
+#include <stdexcept>
 #include <vector>
+#include <map>
 
 #include "Platform.h"
 
@@ -36,26 +38,12 @@ void KeyMap::Clear() {
 }
 
 void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
-       for (size_t keyIndex = 0; keyIndex < kmap.size(); keyIndex++) {
-               if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
-                       kmap[keyIndex].msg = msg;
-                       return;
-               }
-       }
-       KeyToCommand ktc;
-       ktc.key = key;
-       ktc.modifiers = modifiers;
-       ktc.msg = msg;
-       kmap.push_back(ktc);
+       kmap[KeyModifiers(key, modifiers)] = msg;
 }
 
 unsigned int KeyMap::Find(int key, int modifiers) const {
-       for (size_t i = 0; i < kmap.size(); i++) {
-               if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
-                       return kmap[i].msg;
-               }
-       }
-       return 0;
+       std::map<KeyModifiers, unsigned int>::const_iterator it = kmap.find(KeyModifiers(key, modifiers));
+       return (it == kmap.end()) ? 0 : it->second;
 }
 
 #if PLAT_GTK_MACOSX
diff --git a/plugins/scintilla/scintilla/src/KeyMap.h b/plugins/scintilla/scintilla/src/KeyMap.h
index 3fbbeab..7c4f807 100644
--- a/plugins/scintilla/scintilla/src/KeyMap.h
+++ b/plugins/scintilla/scintilla/src/KeyMap.h
@@ -5,8 +5,8 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#ifndef KEYTOCOMMAND_H
-#define KEYTOCOMMAND_H
+#ifndef KEYMAP_H
+#define KEYMAP_H
 
 #ifdef SCI_NAMESPACE
 namespace Scintilla {
@@ -17,11 +17,28 @@ namespace Scintilla {
 #define SCI_CTRL SCMOD_CTRL
 #define SCI_ALT SCMOD_ALT
 #define SCI_META SCMOD_META
+#define SCI_SUPER SCMOD_SUPER
 #define SCI_CSHIFT (SCI_CTRL | SCI_SHIFT)
 #define SCI_ASHIFT (SCI_ALT | SCI_SHIFT)
 
 /**
  */
+class KeyModifiers {
+public:
+       int key;
+       int modifiers;
+       KeyModifiers(int key_, int modifiers_) : key(key_), modifiers(modifiers_) {
+       }
+       bool operator<(const KeyModifiers &other) const {
+               if (key == other.key)
+                       return modifiers < other.modifiers;
+               else
+                       return key < other.key;
+       }
+};
+
+/**
+ */
 class KeyToCommand {
 public:
        int key;
@@ -32,7 +49,7 @@ public:
 /**
  */
 class KeyMap {
-       std::vector<KeyToCommand> kmap;
+       std::map<KeyModifiers, unsigned int> kmap;
        static const KeyToCommand MapDefault[];
 
 public:
diff --git a/plugins/scintilla/scintilla/src/LineMarker.cxx b/plugins/scintilla/scintilla/src/LineMarker.cxx
index 94513f5..d80a3c7 100644
--- a/plugins/scintilla/scintilla/src/LineMarker.cxx
+++ b/plugins/scintilla/scintilla/src/LineMarker.cxx
@@ -1,19 +1,23 @@
 // Scintilla source code edit control
 /** @file LineMarker.cxx
- ** Defines the look of a line marker in the margin .
+ ** Defines the look of a line marker in the margin.
  **/
 // Copyright 1998-2011 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
-#include <math.h>
+#include <cstring>
+#include <cmath>
 
+#include <stdexcept>
 #include <vector>
 #include <map>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
+
+#include "StringCopy.h"
 #include "XPM.h"
 #include "LineMarker.h"
 
@@ -22,71 +26,73 @@ using namespace Scintilla;
 #endif
 
 void LineMarker::SetXPM(const char *textForm) {
-       delete pxpm;
-       pxpm = new XPM(textForm);
+       pxpm.reset(new XPM(textForm));
        markType = SC_MARK_PIXMAP;
 }
 
 void LineMarker::SetXPM(const char *const *linesForm) {
-       delete pxpm;
-       pxpm = new XPM(linesForm);
+       pxpm.reset(new XPM(linesForm));
        markType = SC_MARK_PIXMAP;
 }
 
 void LineMarker::SetRGBAImage(Point sizeRGBAImage, float scale, const unsigned char *pixelsRGBAImage) {
-       delete image;
-       image = new RGBAImage(sizeRGBAImage.x, sizeRGBAImage.y, scale, pixelsRGBAImage);
+       image.reset(new RGBAImage(static_cast<int>(sizeRGBAImage.x), static_cast<int>(sizeRGBAImage.y), 
scale, pixelsRGBAImage));
        markType = SC_MARK_RGBAIMAGE;
 }
 
 static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, ColourDesired fore, 
ColourDesired back) {
-       PRectangle rc;
-       rc.left = centreX - armSize;
-       rc.top = centreY - armSize;
-       rc.right = centreX + armSize + 1;
-       rc.bottom = centreY + armSize + 1;
+       PRectangle rc = PRectangle::FromInts(
+               centreX - armSize,
+               centreY - armSize,
+               centreX + armSize + 1,
+               centreY + armSize + 1);
        surface->RectangleDraw(rc, back, fore);
 }
 
 static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, ColourDesired fore, 
ColourDesired back) {
-       PRectangle rcCircle;
-       rcCircle.left = centreX - armSize;
-       rcCircle.top = centreY - armSize;
-       rcCircle.right = centreX + armSize + 1;
-       rcCircle.bottom = centreY + armSize + 1;
+       PRectangle rcCircle = PRectangle::FromInts(
+               centreX - armSize,
+               centreY - armSize,
+               centreX + armSize + 1,
+               centreY + armSize + 1);
        surface->Ellipse(rcCircle, back, fore);
 }
 
 static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, ColourDesired fore) {
-       PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
+       PRectangle rcV = PRectangle::FromInts(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize 
- 2 + 1);
        surface->FillRectangle(rcV, fore);
-       PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
+       PRectangle rcH = PRectangle::FromInts(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, 
centreY + 1);
        surface->FillRectangle(rcH, fore);
 }
 
 static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, ColourDesired fore) {
-       PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
+       PRectangle rcH = PRectangle::FromInts(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, 
centreY + 1);
        surface->FillRectangle(rcH, fore);
 }
 
-void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter, typeOfFold tFold, int 
marginStyle) {
-       ColourDesired head = back;
-       ColourDesired body = back;
-       ColourDesired tail = back;
+void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter, typeOfFold tFold, int 
marginStyle) const {
+       if (customDraw) {
+               customDraw(surface, rcWhole, fontForCharacter, tFold, marginStyle, this);
+               return;
+       }
+
+       ColourDesired colourHead = back;
+       ColourDesired colourBody = back;
+       ColourDesired colourTail = back;
 
        switch (tFold) {
        case LineMarker::head :
        case LineMarker::headWithTail :
-               head = backSelected;
-               tail = backSelected;
+               colourHead = backSelected;
+               colourTail = backSelected;
                break;
        case LineMarker::body :
-               head = backSelected;
-               body = backSelected;
+               colourHead = backSelected;
+               colourBody = backSelected;
                break;
        case LineMarker::tail :
-               body = backSelected;
-               tail = backSelected;
+               colourBody = backSelected;
+               colourTail = backSelected;
                break;
        default :
                // LineMarker::undefined
@@ -100,9 +106,9 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
        if ((markType == SC_MARK_RGBAIMAGE) && (image)) {
                // Make rectangle just large enough to fit image centred on centre of rcWhole
                PRectangle rcImage;
-               rcImage.top = static_cast<int>(((rcWhole.top + rcWhole.bottom) - image->GetScaledHeight()) / 
2);
+               rcImage.top = ((rcWhole.top + rcWhole.bottom) - image->GetScaledHeight()) / 2;
                rcImage.bottom = rcImage.top + image->GetScaledHeight();
-               rcImage.left = static_cast<int>(((rcWhole.left + rcWhole.right) - image->GetScaledWidth()) / 
2);
+               rcImage.left = ((rcWhole.left + rcWhole.right) - image->GetScaledWidth()) / 2;
                rcImage.right = rcImage.left + image->GetScaledWidth();
                surface->DrawRGBAImage(rcImage, image->GetWidth(), image->GetHeight(), image->Pixels());
                return;
@@ -111,17 +117,17 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
        PRectangle rc = rcWhole;
        rc.top++;
        rc.bottom--;
-       int minDim = Platform::Minimum(rc.Width(), rc.Height());
+       int minDim = Platform::Minimum(static_cast<int>(rc.Width()), static_cast<int>(rc.Height()));
        minDim--;       // Ensure does not go beyond edge
-       int centreX = floor((rc.right + rc.left) / 2.0);
-       int centreY = floor((rc.bottom + rc.top) / 2.0);
-       int dimOn2 = minDim / 2;
-       int dimOn4 = minDim / 4;
+       int centreX = static_cast<int>(floor((rc.right + rc.left) / 2.0));
+       const int centreY = static_cast<int>(floor((rc.bottom + rc.top) / 2.0));
+       const int dimOn2 = minDim / 2;
+       const int dimOn4 = minDim / 4;
        int blobSize = dimOn2-1;
-       int armSize = dimOn2-2;
+       const int armSize = dimOn2-2;
        if (marginStyle == SC_MARGIN_NUMBER || marginStyle == SC_MARGIN_TEXT || marginStyle == 
SC_MARGIN_RTEXT) {
                // On textual margins move marker to the left to try to avoid overlapping the text
-               centreX = rc.left + dimOn2 + 1;
+               centreX = static_cast<int>(rc.left) + dimOn2 + 1;
        }
        if (markType == SC_MARK_ROUNDRECT) {
                PRectangle rcRounded = rc;
@@ -129,57 +135,53 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
                rcRounded.right = rc.right - 1;
                surface->RoundedRectangle(rcRounded, fore, back);
        } else if (markType == SC_MARK_CIRCLE) {
-               PRectangle rcCircle;
-               rcCircle.left = centreX - dimOn2;
-               rcCircle.top = centreY - dimOn2;
-               rcCircle.right = centreX + dimOn2;
-               rcCircle.bottom = centreY + dimOn2;
+               PRectangle rcCircle = PRectangle::FromInts(
+                       centreX - dimOn2,
+                       centreY - dimOn2,
+                       centreX + dimOn2,
+                       centreY + dimOn2);
                surface->Ellipse(rcCircle, fore, back);
        } else if (markType == SC_MARK_ARROW) {
                Point pts[] = {
-               Point(centreX - dimOn4, centreY - dimOn2),
-               Point(centreX - dimOn4, centreY + dimOn2),
-               Point(centreX + dimOn2 - dimOn4, centreY),
+               Point::FromInts(centreX - dimOn4, centreY - dimOn2),
+               Point::FromInts(centreX - dimOn4, centreY + dimOn2),
+               Point::FromInts(centreX + dimOn2 - dimOn4, centreY),
                };
-               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                               fore, back);
+               surface->Polygon(pts, ELEMENTS(pts), fore, back);
 
        } else if (markType == SC_MARK_ARROWDOWN) {
                Point pts[] = {
-               Point(centreX - dimOn2, centreY - dimOn4),
-               Point(centreX + dimOn2, centreY - dimOn4),
-               Point(centreX, centreY + dimOn2 - dimOn4),
+               Point::FromInts(centreX - dimOn2, centreY - dimOn4),
+               Point::FromInts(centreX + dimOn2, centreY - dimOn4),
+               Point::FromInts(centreX, centreY + dimOn2 - dimOn4),
                };
-               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                               fore, back);
+               surface->Polygon(pts, ELEMENTS(pts), fore, back);
 
        } else if (markType == SC_MARK_PLUS) {
                Point pts[] = {
-               Point(centreX - armSize, centreY - 1),
-               Point(centreX - 1, centreY - 1),
-               Point(centreX - 1, centreY - armSize),
-               Point(centreX + 1, centreY - armSize),
-               Point(centreX + 1, centreY - 1),
-               Point(centreX + armSize, centreY -1),
-               Point(centreX + armSize, centreY +1),
-               Point(centreX + 1, centreY + 1),
-               Point(centreX + 1, centreY + armSize),
-               Point(centreX - 1, centreY + armSize),
-               Point(centreX - 1, centreY + 1),
-               Point(centreX - armSize, centreY + 1),
+               Point::FromInts(centreX - armSize, centreY - 1),
+               Point::FromInts(centreX - 1, centreY - 1),
+               Point::FromInts(centreX - 1, centreY - armSize),
+               Point::FromInts(centreX + 1, centreY - armSize),
+               Point::FromInts(centreX + 1, centreY - 1),
+               Point::FromInts(centreX + armSize, centreY -1),
+               Point::FromInts(centreX + armSize, centreY +1),
+               Point::FromInts(centreX + 1, centreY + 1),
+               Point::FromInts(centreX + 1, centreY + armSize),
+               Point::FromInts(centreX - 1, centreY + armSize),
+               Point::FromInts(centreX - 1, centreY + 1),
+               Point::FromInts(centreX - armSize, centreY + 1),
                };
-               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                               fore, back);
+               surface->Polygon(pts, ELEMENTS(pts), fore, back);
 
        } else if (markType == SC_MARK_MINUS) {
                Point pts[] = {
-               Point(centreX - armSize, centreY - 1),
-               Point(centreX + armSize, centreY -1),
-               Point(centreX + armSize, centreY +1),
-               Point(centreX - armSize, centreY + 1),
+               Point::FromInts(centreX - armSize, centreY - 1),
+               Point::FromInts(centreX + armSize, centreY -1),
+               Point::FromInts(centreX + armSize, centreY +1),
+               Point::FromInts(centreX - armSize, centreY + 1),
                };
-               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                               fore, back);
+               surface->Polygon(pts, ELEMENTS(pts), fore, back);
 
        } else if (markType == SC_MARK_SMALLRECT) {
                PRectangle rcSmall;
@@ -194,69 +196,69 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
                // An invisible marker so don't draw anything
 
        } else if (markType == SC_MARK_VLINE) {
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
        } else if (markType == SC_MARK_LCORNER) {
-               surface->PenColour(tail);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourTail);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY);
-               surface->LineTo(rc.right - 1, centreY);
+               surface->LineTo(static_cast<int>(rc.right) - 1, centreY);
 
        } else if (markType == SC_MARK_TCORNER) {
-               surface->PenColour(tail);
+               surface->PenColour(colourTail);
                surface->MoveTo(centreX, centreY);
-               surface->LineTo(rc.right - 1, centreY);
+               surface->LineTo(static_cast<int>(rc.right) - 1, centreY);
 
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY + 1);
 
-               surface->PenColour(head);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->PenColour(colourHead);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
        } else if (markType == SC_MARK_LCORNERCURVE) {
-               surface->PenColour(tail);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourTail);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY-3);
                surface->LineTo(centreX+3, centreY);
-               surface->LineTo(rc.right - 1, centreY);
+               surface->LineTo(static_cast<int>(rc.right) - 1, centreY);
 
        } else if (markType == SC_MARK_TCORNERCURVE) {
-               surface->PenColour(tail);
+               surface->PenColour(colourTail);
                surface->MoveTo(centreX, centreY-3);
                surface->LineTo(centreX+3, centreY);
-               surface->LineTo(rc.right - 1, centreY);
+               surface->LineTo(static_cast<int>(rc.right) - 1, centreY);
 
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY-2);
 
-               surface->PenColour(head);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->PenColour(colourHead);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
        } else if (markType == SC_MARK_BOXPLUS) {
-               DrawBox(surface, centreX, centreY, blobSize, fore, head);
-               DrawPlus(surface, centreX, centreY, blobSize, tail);
+               DrawBox(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawPlus(surface, centreX, centreY, blobSize, colourTail);
 
        } else if (markType == SC_MARK_BOXPLUSCONNECTED) {
                if (tFold == LineMarker::headWithTail)
-                       surface->PenColour(tail);
+                       surface->PenColour(colourTail);
                else
-                       surface->PenColour(body);
+                       surface->PenColour(colourBody);
                surface->MoveTo(centreX, centreY + blobSize);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY - blobSize);
 
-               DrawBox(surface, centreX, centreY, blobSize, fore, head);
-               DrawPlus(surface, centreX, centreY, blobSize, tail);
+               DrawBox(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawPlus(surface, centreX, centreY, blobSize, colourTail);
 
                if (tFold == LineMarker::body) {
-                       surface->PenColour(tail);
+                       surface->PenColour(colourTail);
                        surface->MoveTo(centreX + 1, centreY + blobSize);
                        surface->LineTo(centreX + blobSize + 1, centreY + blobSize);
 
@@ -267,27 +269,27 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
                        surface->LineTo(centreX + blobSize + 1, centreY - blobSize);
                }
        } else if (markType == SC_MARK_BOXMINUS) {
-               DrawBox(surface, centreX, centreY, blobSize, fore, head);
-               DrawMinus(surface, centreX, centreY, blobSize, tail);
+               DrawBox(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawMinus(surface, centreX, centreY, blobSize, colourTail);
 
-               surface->PenColour(head);
+               surface->PenColour(colourHead);
                surface->MoveTo(centreX, centreY + blobSize);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
        } else if (markType == SC_MARK_BOXMINUSCONNECTED) {
-               DrawBox(surface, centreX, centreY, blobSize, fore, head);
-               DrawMinus(surface, centreX, centreY, blobSize, tail);
+               DrawBox(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawMinus(surface, centreX, centreY, blobSize, colourTail);
 
-               surface->PenColour(head);
+               surface->PenColour(colourHead);
                surface->MoveTo(centreX, centreY + blobSize);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY - blobSize);
 
                if (tFold == LineMarker::body) {
-                       surface->PenColour(tail);
+                       surface->PenColour(colourTail);
                        surface->MoveTo(centreX + 1, centreY + blobSize);
                        surface->LineTo(centreX + blobSize + 1, centreY + blobSize);
 
@@ -298,44 +300,44 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
                        surface->LineTo(centreX + blobSize + 1, centreY - blobSize);
                }
        } else if (markType == SC_MARK_CIRCLEPLUS) {
-               DrawCircle(surface, centreX, centreY, blobSize, fore, head);
-               DrawPlus(surface, centreX, centreY, blobSize, tail);
+               DrawCircle(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawPlus(surface, centreX, centreY, blobSize, colourTail);
 
        } else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
                if (tFold == LineMarker::headWithTail)
-                       surface->PenColour(tail);
+                       surface->PenColour(colourTail);
                else
-                       surface->PenColour(body);
+                       surface->PenColour(colourBody);
                surface->MoveTo(centreX, centreY + blobSize);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY - blobSize);
 
-               DrawCircle(surface, centreX, centreY, blobSize, fore, head);
-               DrawPlus(surface, centreX, centreY, blobSize, tail);
+               DrawCircle(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawPlus(surface, centreX, centreY, blobSize, colourTail);
 
        } else if (markType == SC_MARK_CIRCLEMINUS) {
-               DrawCircle(surface, centreX, centreY, blobSize, fore, head);
-               DrawMinus(surface, centreX, centreY, blobSize, tail);
-
-               surface->PenColour(head);
+               surface->PenColour(colourHead);
                surface->MoveTo(centreX, centreY + blobSize);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
-       } else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
-               DrawCircle(surface, centreX, centreY, blobSize, fore, head);
-               DrawMinus(surface, centreX, centreY, blobSize, tail);
+               DrawCircle(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawMinus(surface, centreX, centreY, blobSize, colourTail);
 
-               surface->PenColour(head);
+       } else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
+               surface->PenColour(colourHead);
                surface->MoveTo(centreX, centreY + blobSize);
-               surface->LineTo(centreX, rcWhole.bottom);
+               surface->LineTo(centreX, static_cast<int>(rcWhole.bottom));
 
-               surface->PenColour(body);
-               surface->MoveTo(centreX, rcWhole.top);
+               surface->PenColour(colourBody);
+               surface->MoveTo(centreX, static_cast<int>(rcWhole.top));
                surface->LineTo(centreX, centreY - blobSize);
 
+               DrawCircle(surface, centreX, centreY, blobSize, fore, colourHead);
+               DrawMinus(surface, centreX, centreY, blobSize, colourTail);
+
        } else if (markType >= SC_MARK_CHARACTER) {
                char character[1];
                character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
@@ -346,38 +348,49 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
                        character, 1, fore, back);
 
        } else if (markType == SC_MARK_DOTDOTDOT) {
-               int right = centreX - 6;
+               XYPOSITION right = static_cast<XYPOSITION>(centreX - 6);
                for (int b=0; b<3; b++) {
                        PRectangle rcBlob(right, rc.bottom - 4, right + 2, rc.bottom-2);
                        surface->FillRectangle(rcBlob, fore);
-                       right += 5;
+                       right += 5.0f;
                }
        } else if (markType == SC_MARK_ARROWS) {
                surface->PenColour(fore);
                int right = centreX - 2;
-               for (int b=0; b<3; b++) {
-                       surface->MoveTo(right - 4, centreY - 4);
-                       surface->LineTo(right, centreY);
-                       surface->LineTo(right - 5, centreY + 5);
+               const int armLength = dimOn2 - 1;
+               for (int b = 0; b<3; b++) {
+                       surface->MoveTo(right, centreY);
+                       surface->LineTo(right - armLength, centreY - armLength);
+                       surface->MoveTo(right, centreY);
+                       surface->LineTo(right - armLength, centreY + armLength);
                        right += 4;
                }
        } else if (markType == SC_MARK_SHORTARROW) {
                Point pts[] = {
-                       Point(centreX, centreY + dimOn2),
-                       Point(centreX + dimOn2, centreY),
-                       Point(centreX, centreY - dimOn2),
-                       Point(centreX, centreY - dimOn4),
-                       Point(centreX - dimOn4, centreY - dimOn4),
-                       Point(centreX - dimOn4, centreY + dimOn4),
-                       Point(centreX, centreY + dimOn4),
-                       Point(centreX, centreY + dimOn2),
+                       Point::FromInts(centreX, centreY + dimOn2),
+                       Point::FromInts(centreX + dimOn2, centreY),
+                       Point::FromInts(centreX, centreY - dimOn2),
+                       Point::FromInts(centreX, centreY - dimOn4),
+                       Point::FromInts(centreX - dimOn4, centreY - dimOn4),
+                       Point::FromInts(centreX - dimOn4, centreY + dimOn4),
+                       Point::FromInts(centreX, centreY + dimOn4),
+                       Point::FromInts(centreX, centreY + dimOn2),
                };
-               surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
-                               fore, back);
+               surface->Polygon(pts, ELEMENTS(pts), fore, back);
        } else if (markType == SC_MARK_LEFTRECT) {
                PRectangle rcLeft = rcWhole;
                rcLeft.right = rcLeft.left + 4;
                surface->FillRectangle(rcLeft, back);
+       } else if (markType == SC_MARK_BOOKMARK) {
+               const int halfHeight = minDim / 3;
+               Point pts[] = {
+                       Point::FromInts(static_cast<int>(rc.left), centreY-halfHeight),
+                       Point::FromInts(static_cast<int>(rc.right) - 3, centreY - halfHeight),
+                       Point::FromInts(static_cast<int>(rc.right) - 3 - halfHeight, centreY),
+                       Point::FromInts(static_cast<int>(rc.right) - 3, centreY + halfHeight),
+                       Point::FromInts(static_cast<int>(rc.left), centreY + halfHeight),
+               };
+               surface->Polygon(pts, ELEMENTS(pts), fore, back);
        } else { // SC_MARK_FULLRECT
                surface->FillRectangle(rcWhole, back);
        }
diff --git a/plugins/scintilla/scintilla/src/LineMarker.h b/plugins/scintilla/scintilla/src/LineMarker.h
index e226ef5..2006fe8 100644
--- a/plugins/scintilla/scintilla/src/LineMarker.h
+++ b/plugins/scintilla/scintilla/src/LineMarker.h
@@ -12,6 +12,7 @@
 namespace Scintilla {
 #endif
 
+typedef void (*DrawLineMarkerFn)(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter, int tFold, 
int marginStyle, const void *lineMarker);
 
 /**
  */
@@ -24,50 +25,52 @@ public:
        ColourDesired back;
        ColourDesired backSelected;
        int alpha;
-       XPM *pxpm;
-       RGBAImage *image;
+       std::unique_ptr<XPM> pxpm;
+       std::unique_ptr<RGBAImage> image;
+       /** Some platforms, notably PLAT_CURSES, do not support Scintilla's native
+        * Draw function for drawing line markers. Allow those platforms to override
+        * it instead of creating a new method(s) in the Surface class that existing
+        * platforms must implement as empty. */
+       DrawLineMarkerFn customDraw;
        LineMarker() {
                markType = SC_MARK_CIRCLE;
                fore = ColourDesired(0,0,0);
                back = ColourDesired(0xff,0xff,0xff);
                backSelected = ColourDesired(0xff,0x00,0x00);
                alpha = SC_ALPHA_NOALPHA;
-               pxpm = NULL;
-               image = NULL;
+               customDraw = nullptr;
        }
        LineMarker(const LineMarker &) {
-               // Defined to avoid pxpm being blindly copied, not as a complete copy constructor
+               // Defined to avoid pxpm and image being blindly copied, not as a complete copy constructor.
                markType = SC_MARK_CIRCLE;
                fore = ColourDesired(0,0,0);
                back = ColourDesired(0xff,0xff,0xff);
                backSelected = ColourDesired(0xff,0x00,0x00);
                alpha = SC_ALPHA_NOALPHA;
-               pxpm = NULL;
-               image = NULL;
+               pxpm.reset();
+               image.reset();
+               customDraw = nullptr;
        }
        ~LineMarker() {
-               delete pxpm;
-               delete image;
        }
        LineMarker &operator=(const LineMarker &other) {
-               // Defined to avoid pxpm being blindly copied, not as a complete assignment operator
+               // Defined to avoid pxpm and image being blindly copied, not as a complete assignment 
operator.
                if (this != &other) {
                        markType = SC_MARK_CIRCLE;
                        fore = ColourDesired(0,0,0);
                        back = ColourDesired(0xff,0xff,0xff);
                        backSelected = ColourDesired(0xff,0x00,0x00);
                        alpha = SC_ALPHA_NOALPHA;
-                       delete pxpm;
-                       pxpm = NULL;
-                       delete image;
-                       image = NULL;
+                       pxpm.reset();
+                       image.reset();
+                       customDraw = nullptr;
                }
                return *this;
        }
        void SetXPM(const char *textForm);
        void SetXPM(const char *const *linesForm);
        void SetRGBAImage(Point sizeRGBAImage, float scale, const unsigned char *pixelsRGBAImage);
-       void Draw(Surface *surface, PRectangle &rc, Font &fontForCharacter, typeOfFold tFold, int 
marginStyle);
+       void Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter, typeOfFold tFold, int 
marginStyle) const;
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/MarginView.cxx b/plugins/scintilla/scintilla/src/MarginView.cxx
new file mode 100644
index 0000000..7ecc85c
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/MarginView.cxx
@@ -0,0 +1,470 @@
+// Scintilla source code edit control
+/** @file MarginView.cxx
+ ** Defines the appearance of the editor margin.
+ **/
+// Copyright 1998-2014 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+#include <cctype>
+#include <cstdio>
+#include <cmath>
+
+#include <stdexcept>
+#include <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+#include <memory>
+
+#include "Platform.h"
+
+#include "ILexer.h"
+#include "Scintilla.h"
+
+#include "StringCopy.h"
+#include "Position.h"
+#include "UniqueString.h"
+#include "SplitVector.h"
+#include "Partitioning.h"
+#include "RunStyles.h"
+#include "ContractionState.h"
+#include "CellBuffer.h"
+#include "KeyMap.h"
+#include "Indicator.h"
+#include "XPM.h"
+#include "LineMarker.h"
+#include "Style.h"
+#include "ViewStyle.h"
+#include "CharClassify.h"
+#include "Decoration.h"
+#include "CaseFolder.h"
+#include "Document.h"
+#include "UniConversion.h"
+#include "Selection.h"
+#include "PositionCache.h"
+#include "EditModel.h"
+#include "MarginView.h"
+#include "EditView.h"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+void DrawWrapMarker(Surface *surface, PRectangle rcPlace,
+       bool isEndMarker, ColourDesired wrapColour) {
+       surface->PenColour(wrapColour);
+
+       enum { xa = 1 }; // gap before start
+       int w = static_cast<int>(rcPlace.right - rcPlace.left) - xa - 1;
+
+       const bool xStraight = isEndMarker;  // x-mirrored symbol for start marker
+
+       const int x0 = static_cast<int>(xStraight ? rcPlace.left : rcPlace.right - 1);
+       const int y0 = static_cast<int>(rcPlace.top);
+
+       int dy = static_cast<int>(rcPlace.bottom - rcPlace.top) / 5;
+       int y = static_cast<int>(rcPlace.bottom - rcPlace.top) / 2 + dy;
+
+       struct Relative {
+               Surface *surface;
+               int xBase;
+               int xDir;
+               int yBase;
+               int yDir;
+               void MoveTo(int xRelative, int yRelative) {
+                       surface->MoveTo(xBase + xDir * xRelative, yBase + yDir * yRelative);
+               }
+               void LineTo(int xRelative, int yRelative) {
+                       surface->LineTo(xBase + xDir * xRelative, yBase + yDir * yRelative);
+               }
+       };
+       Relative rel = { surface, x0, xStraight ? 1 : -1, y0, 1 };
+
+       // arrow head
+       rel.MoveTo(xa, y);
+       rel.LineTo(xa + 2 * w / 3, y - dy);
+       rel.MoveTo(xa, y);
+       rel.LineTo(xa + 2 * w / 3, y + dy);
+
+       // arrow body
+       rel.MoveTo(xa, y);
+       rel.LineTo(xa + w, y);
+       rel.LineTo(xa + w, y - 2 * dy);
+       rel.LineTo(xa - 1,   // on windows lineto is exclusive endpoint, perhaps GTK not...
+               y - 2 * dy);
+}
+
+MarginView::MarginView() {
+       wrapMarkerPaddingRight = 3;
+       customDrawWrapMarker = NULL;
+}
+
+void MarginView::DropGraphics(bool freeObjects) {
+       if (freeObjects) {
+               pixmapSelMargin.reset();
+               pixmapSelPattern.reset();
+               pixmapSelPatternOffset1.reset();
+       } else {
+               if (pixmapSelMargin)
+                       pixmapSelMargin->Release();
+               if (pixmapSelPattern)
+                       pixmapSelPattern->Release();
+               if (pixmapSelPatternOffset1)
+                       pixmapSelPatternOffset1->Release();
+       }
+}
+
+void MarginView::AllocateGraphics(const ViewStyle &vsDraw) {
+       if (!pixmapSelMargin)
+               pixmapSelMargin.reset(Surface::Allocate(vsDraw.technology));
+       if (!pixmapSelPattern)
+               pixmapSelPattern.reset(Surface::Allocate(vsDraw.technology));
+       if (!pixmapSelPatternOffset1)
+               pixmapSelPatternOffset1.reset(Surface::Allocate(vsDraw.technology));
+}
+
+void MarginView::RefreshPixMaps(Surface *surfaceWindow, WindowID wid, const ViewStyle &vsDraw) {
+       if (!pixmapSelPattern->Initialised()) {
+               const int patternSize = 8;
+               pixmapSelPattern->InitPixMap(patternSize, patternSize, surfaceWindow, wid);
+               pixmapSelPatternOffset1->InitPixMap(patternSize, patternSize, surfaceWindow, wid);
+               // This complex procedure is to reproduce the checkerboard dithered pattern used by windows
+               // for scroll bars and Visual Studio for its selection margin. The colour of this pattern is 
half
+               // way between the chrome colour and the chrome highlight colour making a nice transition
+               // between the window chrome and the content area. And it works in low colour depths.
+               PRectangle rcPattern = PRectangle::FromInts(0, 0, patternSize, patternSize);
+
+               // Initialize default colours based on the chrome colour scheme.  Typically the highlight is 
white.
+               ColourDesired colourFMFill = vsDraw.selbar;
+               ColourDesired colourFMStripes = vsDraw.selbarlight;
+
+               if (!(vsDraw.selbarlight == ColourDesired(0xff, 0xff, 0xff))) {
+                       // User has chosen an unusual chrome colour scheme so just use the highlight edge 
colour.
+                       // (Typically, the highlight colour is white.)
+                       colourFMFill = vsDraw.selbarlight;
+               }
+
+               if (vsDraw.foldmarginColour.isSet) {
+                       // override default fold margin colour
+                       colourFMFill = vsDraw.foldmarginColour;
+               }
+               if (vsDraw.foldmarginHighlightColour.isSet) {
+                       // override default fold margin highlight colour
+                       colourFMStripes = vsDraw.foldmarginHighlightColour;
+               }
+
+               pixmapSelPattern->FillRectangle(rcPattern, colourFMFill);
+               pixmapSelPatternOffset1->FillRectangle(rcPattern, colourFMStripes);
+               for (int y = 0; y < patternSize; y++) {
+                       for (int x = y % 2; x < patternSize; x += 2) {
+                               PRectangle rcPixel = PRectangle::FromInts(x, y, x + 1, y + 1);
+                               pixmapSelPattern->FillRectangle(rcPixel, colourFMStripes);
+                               pixmapSelPatternOffset1->FillRectangle(rcPixel, colourFMFill);
+                       }
+               }
+       }
+}
+
+static int SubstituteMarkerIfEmpty(int markerCheck, int markerDefault, const ViewStyle &vs) {
+       if (vs.markers[markerCheck].markType == SC_MARK_EMPTY)
+               return markerDefault;
+       return markerCheck;
+}
+
+void MarginView::PaintMargin(Surface *surface, Sci::Line topLine, PRectangle rc, PRectangle rcMargin,
+       const EditModel &model, const ViewStyle &vs) {
+
+       PRectangle rcSelMargin = rcMargin;
+       rcSelMargin.right = rcMargin.left;
+       if (rcSelMargin.bottom < rc.bottom)
+               rcSelMargin.bottom = rc.bottom;
+
+       Point ptOrigin = model.GetVisibleOriginInMain();
+       FontAlias fontLineNumber = vs.styles[STYLE_LINENUMBER].font;
+       for (size_t margin = 0; margin < vs.ms.size(); margin++) {
+               if (vs.ms[margin].width > 0) {
+
+                       rcSelMargin.left = rcSelMargin.right;
+                       rcSelMargin.right = rcSelMargin.left + vs.ms[margin].width;
+
+                       if (vs.ms[margin].style != SC_MARGIN_NUMBER) {
+                               if (vs.ms[margin].mask & SC_MASK_FOLDERS) {
+                                       // Required because of special way brush is created for selection 
margin
+                                       // Ensure patterns line up when scrolling with separate margin view
+                                       // by choosing correctly aligned variant.
+                                       const bool invertPhase = static_cast<int>(ptOrigin.y) & 1;
+                                       surface->FillRectangle(rcSelMargin,
+                                               invertPhase ? *pixmapSelPattern : *pixmapSelPatternOffset1);
+                               } else {
+                                       ColourDesired colour;
+                                       switch (vs.ms[margin].style) {
+                                       case SC_MARGIN_BACK:
+                                               colour = vs.styles[STYLE_DEFAULT].back;
+                                               break;
+                                       case SC_MARGIN_FORE:
+                                               colour = vs.styles[STYLE_DEFAULT].fore;
+                                               break;
+                                       case SC_MARGIN_COLOUR:
+                                               colour = vs.ms[margin].back;
+                                               break;
+                                       default:
+                                               colour = vs.styles[STYLE_LINENUMBER].back;
+                                               break;
+                                       }
+                                       surface->FillRectangle(rcSelMargin, colour);
+                               }
+                       } else {
+                               surface->FillRectangle(rcSelMargin, vs.styles[STYLE_LINENUMBER].back);
+                       }
+
+                       const int lineStartPaint = static_cast<int>(rcMargin.top + ptOrigin.y) / 
vs.lineHeight;
+                       Sci::Line visibleLine = model.TopLineOfMain() + lineStartPaint;
+                       Sci::Position yposScreen = lineStartPaint * vs.lineHeight - 
static_cast<Sci::Position>(ptOrigin.y);
+                       // Work out whether the top line is whitespace located after a
+                       // lessening of fold level which implies a 'fold tail' but which should not
+                       // be displayed until the last of a sequence of whitespace.
+                       bool needWhiteClosure = false;
+                       if (vs.ms[margin].mask & SC_MASK_FOLDERS) {
+                               const int level = model.pdoc->GetLevel(model.cs.DocFromDisplay(visibleLine));
+                               if (level & SC_FOLDLEVELWHITEFLAG) {
+                                       Sci::Line lineBack = model.cs.DocFromDisplay(visibleLine);
+                                       int levelPrev = level;
+                                       while ((lineBack > 0) && (levelPrev & SC_FOLDLEVELWHITEFLAG)) {
+                                               lineBack--;
+                                               levelPrev = model.pdoc->GetLevel(lineBack);
+                                       }
+                                       if (!(levelPrev & SC_FOLDLEVELHEADERFLAG)) {
+                                               if (LevelNumber(level) < LevelNumber(levelPrev))
+                                                       needWhiteClosure = true;
+                                       }
+                               }
+                               if (highlightDelimiter.isEnabled) {
+                                       Sci::Line lastLine = model.cs.DocFromDisplay(topLine + 
model.LinesOnScreen()) + 1;
+                                       model.pdoc->GetHighlightDelimiters(highlightDelimiter, 
model.pdoc->LineFromPosition(model.sel.MainCaret()), lastLine);
+                               }
+                       }
+
+                       // Old code does not know about new markers needed to distinguish all cases
+                       const int folderOpenMid = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEROPENMID,
+                               SC_MARKNUM_FOLDEROPEN, vs);
+                       const int folderEnd = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEREND,
+                               SC_MARKNUM_FOLDER, vs);
+
+                       while ((visibleLine < model.cs.LinesDisplayed()) && yposScreen < rc.bottom) {
+
+                               PLATFORM_ASSERT(visibleLine < model.cs.LinesDisplayed());
+                               const Sci::Line lineDoc = model.cs.DocFromDisplay(visibleLine);
+                               PLATFORM_ASSERT(model.cs.GetVisible(lineDoc));
+                               const Sci::Line firstVisibleLine = model.cs.DisplayFromDoc(lineDoc);
+                               const Sci::Line lastVisibleLine = model.cs.DisplayLastFromDoc(lineDoc);
+                               const bool firstSubLine = visibleLine == firstVisibleLine;
+                               const bool lastSubLine = visibleLine == lastVisibleLine;
+
+                               int marks = model.pdoc->GetMark(lineDoc);
+                               if (!firstSubLine)
+                                       marks = 0;
+
+                               bool headWithTail = false;
+
+                               if (vs.ms[margin].mask & SC_MASK_FOLDERS) {
+                                       // Decide which fold indicator should be displayed
+                                       const int level = model.pdoc->GetLevel(lineDoc);
+                                       const int levelNext = model.pdoc->GetLevel(lineDoc + 1);
+                                       const int levelNum = LevelNumber(level);
+                                       const int levelNextNum = LevelNumber(levelNext);
+                                       if (level & SC_FOLDLEVELHEADERFLAG) {
+                                               if (firstSubLine) {
+                                                       if (levelNum < levelNextNum) {
+                                                               if (model.cs.GetExpanded(lineDoc)) {
+                                                                       if (levelNum == SC_FOLDLEVELBASE)
+                                                                               marks |= 1 << 
SC_MARKNUM_FOLDEROPEN;
+                                                                       else
+                                                                               marks |= 1 << folderOpenMid;
+                                                               } else {
+                                                                       if (levelNum == SC_FOLDLEVELBASE)
+                                                                               marks |= 1 << 
SC_MARKNUM_FOLDER;
+                                                                       else
+                                                                               marks |= 1 << folderEnd;
+                                                               }
+                                                       } else if (levelNum > SC_FOLDLEVELBASE) {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                       }
+                                               } else {
+                                                       if (levelNum < levelNextNum) {
+                                                               if (model.cs.GetExpanded(lineDoc)) {
+                                                                       marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                               } else if (levelNum > SC_FOLDLEVELBASE) {
+                                                                       marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                               }
+                                                       } else if (levelNum > SC_FOLDLEVELBASE) {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                       }
+                                               }
+                                               needWhiteClosure = false;
+                                               const Sci::Line firstFollowupLine = 
model.cs.DocFromDisplay(model.cs.DisplayFromDoc(lineDoc + 1));
+                                               const int firstFollowupLineLevel = 
model.pdoc->GetLevel(firstFollowupLine);
+                                               const int secondFollowupLineLevelNum = 
LevelNumber(model.pdoc->GetLevel(firstFollowupLine + 1));
+                                               if (!model.cs.GetExpanded(lineDoc)) {
+                                                       if ((firstFollowupLineLevel & SC_FOLDLEVELWHITEFLAG) 
&&
+                                                               (levelNum > secondFollowupLineLevelNum))
+                                                               needWhiteClosure = true;
+
+                                                       if 
(highlightDelimiter.IsFoldBlockHighlighted(firstFollowupLine))
+                                                               headWithTail = true;
+                                               }
+                                       } else if (level & SC_FOLDLEVELWHITEFLAG) {
+                                               if (needWhiteClosure) {
+                                                       if (levelNext & SC_FOLDLEVELWHITEFLAG) {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                       } else if (levelNextNum > SC_FOLDLEVELBASE) {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL;
+                                                               needWhiteClosure = false;
+                                                       } else {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERTAIL;
+                                                               needWhiteClosure = false;
+                                                       }
+                                               } else if (levelNum > SC_FOLDLEVELBASE) {
+                                                       if (levelNextNum < levelNum) {
+                                                               if (levelNextNum > SC_FOLDLEVELBASE) {
+                                                                       marks |= 1 << 
SC_MARKNUM_FOLDERMIDTAIL;
+                                                               } else {
+                                                                       marks |= 1 << SC_MARKNUM_FOLDERTAIL;
+                                                               }
+                                                       } else {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                       }
+                                               }
+                                       } else if (levelNum > SC_FOLDLEVELBASE) {
+                                               if (levelNextNum < levelNum) {
+                                                       needWhiteClosure = false;
+                                                       if (levelNext & SC_FOLDLEVELWHITEFLAG) {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                               needWhiteClosure = true;
+                                                       } else if (lastSubLine) {
+                                                               if (levelNextNum > SC_FOLDLEVELBASE) {
+                                                                       marks |= 1 << 
SC_MARKNUM_FOLDERMIDTAIL;
+                                                               } else {
+                                                                       marks |= 1 << SC_MARKNUM_FOLDERTAIL;
+                                                               }
+                                                       } else {
+                                                               marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                                       }
+                                               } else {
+                                                       marks |= 1 << SC_MARKNUM_FOLDERSUB;
+                                               }
+                                       }
+                               }
+
+                               marks &= vs.ms[margin].mask;
+
+                               PRectangle rcMarker = rcSelMargin;
+                               rcMarker.top = static_cast<XYPOSITION>(yposScreen);
+                               rcMarker.bottom = static_cast<XYPOSITION>(yposScreen + vs.lineHeight);
+                               if (vs.ms[margin].style == SC_MARGIN_NUMBER) {
+                                       if (firstSubLine) {
+                                               char number[100] = "";
+                                               if (lineDoc >= 0)
+                                                       sprintf(number, "%d", lineDoc + 1);
+                                               if (model.foldFlags & (SC_FOLDFLAG_LEVELNUMBERS | 
SC_FOLDFLAG_LINESTATE)) {
+                                                       if (model.foldFlags & SC_FOLDFLAG_LEVELNUMBERS) {
+                                                               const int lev = model.pdoc->GetLevel(lineDoc);
+                                                               sprintf(number, "%c%c %03X %03X",
+                                                                       (lev & SC_FOLDLEVELHEADERFLAG) ? 'H' 
: '_',
+                                                                       (lev & SC_FOLDLEVELWHITEFLAG) ? 'W' : 
'_',
+                                                                       LevelNumber(lev),
+                                                                       lev >> 16
+                                                                       );
+                                                       } else {
+                                                               const int state = 
model.pdoc->GetLineState(lineDoc);
+                                                               sprintf(number, "%0X", state);
+                                                       }
+                                               }
+                                               PRectangle rcNumber = rcMarker;
+                                               // Right justify
+                                               XYPOSITION width = surface->WidthText(fontLineNumber, number, 
static_cast<int>(strlen(number)));
+                                               XYPOSITION xpos = rcNumber.right - width - 
vs.marginNumberPadding;
+                                               rcNumber.left = xpos;
+                                               DrawTextNoClipPhase(surface, rcNumber, 
vs.styles[STYLE_LINENUMBER],
+                                                       rcNumber.top + vs.maxAscent, number, 
static_cast<int>(strlen(number)), drawAll);
+                                       } else if (vs.wrapVisualFlags & SC_WRAPVISUALFLAG_MARGIN) {
+                                               PRectangle rcWrapMarker = rcMarker;
+                                               rcWrapMarker.right -= wrapMarkerPaddingRight;
+                                               rcWrapMarker.left = rcWrapMarker.right - 
vs.styles[STYLE_LINENUMBER].aveCharWidth;
+                                               if (customDrawWrapMarker == NULL) {
+                                                       DrawWrapMarker(surface, rcWrapMarker, false, 
vs.styles[STYLE_LINENUMBER].fore);
+                                               } else {
+                                                       customDrawWrapMarker(surface, rcWrapMarker, false, 
vs.styles[STYLE_LINENUMBER].fore);
+                                               }
+                                       }
+                               } else if (vs.ms[margin].style == SC_MARGIN_TEXT || vs.ms[margin].style == 
SC_MARGIN_RTEXT) {
+                                       const StyledText stMargin = model.pdoc->MarginStyledText(lineDoc);
+                                       if (stMargin.text && ValidStyledText(vs, vs.marginStyleOffset, 
stMargin)) {
+                                               if (firstSubLine) {
+                                                       surface->FillRectangle(rcMarker,
+                                                               vs.styles[stMargin.StyleAt(0) + 
vs.marginStyleOffset].back);
+                                                       if (vs.ms[margin].style == SC_MARGIN_RTEXT) {
+                                                               int width = WidestLineWidth(surface, vs, 
vs.marginStyleOffset, stMargin);
+                                                               rcMarker.left = rcMarker.right - width - 3;
+                                                       }
+                                                       DrawStyledText(surface, vs, vs.marginStyleOffset, 
rcMarker,
+                                                               stMargin, 0, stMargin.length, drawAll);
+                                               } else {
+                                                       // if we're displaying annotation lines, color the 
margin to match the associated document line
+                                                       const int annotationLines = 
model.pdoc->AnnotationLines(lineDoc);
+                                                       if (annotationLines && (visibleLine > lastVisibleLine 
- annotationLines)) {
+                                                               surface->FillRectangle(rcMarker, 
vs.styles[stMargin.StyleAt(0) + vs.marginStyleOffset].back);
+                                                       }
+                                               }
+                                       }
+                               }
+
+                               if (marks) {
+                                       for (int markBit = 0; (markBit < 32) && marks; markBit++) {
+                                               if (marks & 1) {
+                                                       LineMarker::typeOfFold tFold = LineMarker::undefined;
+                                                       if ((vs.ms[margin].mask & SC_MASK_FOLDERS) && 
highlightDelimiter.IsFoldBlockHighlighted(lineDoc)) {
+                                                               if 
(highlightDelimiter.IsBodyOfFoldBlock(lineDoc)) {
+                                                                       tFold = LineMarker::body;
+                                                               } else if 
(highlightDelimiter.IsHeadOfFoldBlock(lineDoc)) {
+                                                                       if (firstSubLine) {
+                                                                               tFold = headWithTail ? 
LineMarker::headWithTail : LineMarker::head;
+                                                                       } else {
+                                                                               if 
(model.cs.GetExpanded(lineDoc) || headWithTail) {
+                                                                                       tFold = 
LineMarker::body;
+                                                                               } else {
+                                                                                       tFold = 
LineMarker::undefined;
+                                                                               }
+                                                                       }
+                                                               } else if 
(highlightDelimiter.IsTailOfFoldBlock(lineDoc)) {
+                                                                       tFold = LineMarker::tail;
+                                                               }
+                                                       }
+                                                       vs.markers[markBit].Draw(surface, rcMarker, 
fontLineNumber, tFold, vs.ms[margin].style);
+                                               }
+                                               marks >>= 1;
+                                       }
+                               }
+
+                               visibleLine++;
+                               yposScreen += vs.lineHeight;
+                       }
+               }
+       }
+
+       PRectangle rcBlankMargin = rcMargin;
+       rcBlankMargin.left = rcSelMargin.right;
+       surface->FillRectangle(rcBlankMargin, vs.styles[STYLE_DEFAULT].back);
+}
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
diff --git a/plugins/scintilla/scintilla/src/MarginView.h b/plugins/scintilla/scintilla/src/MarginView.h
new file mode 100644
index 0000000..695126a
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/MarginView.h
@@ -0,0 +1,50 @@
+// Scintilla source code edit control
+/** @file MarginView.h
+ ** Defines the appearance of the editor margin.
+ **/
+// Copyright 1998-2014 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef MARGINVIEW_H
+#define MARGINVIEW_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+void DrawWrapMarker(Surface *surface, PRectangle rcPlace, bool isEndMarker, ColourDesired wrapColour);
+
+typedef void (*DrawWrapMarkerFn)(Surface *surface, PRectangle rcPlace, bool isEndMarker, ColourDesired 
wrapColour);
+
+/**
+* MarginView draws the margins.
+*/
+class MarginView {
+public:
+       std::unique_ptr<Surface> pixmapSelMargin;
+       std::unique_ptr<Surface> pixmapSelPattern;
+       std::unique_ptr<Surface> pixmapSelPatternOffset1;
+       // Highlight current folding block
+       HighlightDelimiter highlightDelimiter;
+
+       int wrapMarkerPaddingRight; // right-most pixel padding of wrap markers
+       /** Some platforms, notably PLAT_CURSES, do not support Scintilla's native
+        * DrawWrapMarker function for drawing wrap markers. Allow those platforms to
+        * override it instead of creating a new method in the Surface class that
+        * existing platforms must implement as empty. */
+       DrawWrapMarkerFn customDrawWrapMarker;
+
+       MarginView();
+
+       void DropGraphics(bool freeObjects);
+       void AllocateGraphics(const ViewStyle &vsDraw);
+       void RefreshPixMaps(Surface *surfaceWindow, WindowID wid, const ViewStyle &vsDraw);
+       void PaintMargin(Surface *surface, Sci::Line topLine, PRectangle rc, PRectangle rcMargin,
+               const EditModel &model, const ViewStyle &vs);
+};
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/Partitioning.h b/plugins/scintilla/scintilla/src/Partitioning.h
index 07f3c5d..968220d 100644
--- a/plugins/scintilla/scintilla/src/Partitioning.h
+++ b/plugins/scintilla/scintilla/src/Partitioning.h
@@ -8,24 +8,31 @@
 #ifndef PARTITIONING_H
 #define PARTITIONING_H
 
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
 /// A split vector of integers with a method for adding a value to all elements
 /// in a range.
 /// Used by the Partitioning class.
 
 class SplitVectorWithRangeAdd : public SplitVector<int> {
 public:
-       SplitVectorWithRangeAdd(int growSize_) {
+       explicit SplitVectorWithRangeAdd(int growSize_) {
                SetGrowSize(growSize_);
                ReAllocate(growSize_);
        }
+       // Deleted so SplitVectorWithRangeAdd objects can not be copied.
+       SplitVectorWithRangeAdd(const SplitVectorWithRangeAdd &) = delete;
+       void operator=(const SplitVectorWithRangeAdd &) = delete;
        ~SplitVectorWithRangeAdd() {
        }
        void RangeAddDelta(int start, int end, int delta) {
                // end is 1 past end, so end-start is number of elements to change
                int i = 0;
-               int rangeLength = end - start;
+               const int rangeLength = end - start;
                int range1Length = rangeLength;
-               int part1Left = part1Length - start;
+               const int part1Left = part1Length - start;
                if (range1Length > part1Left)
                        range1Length = part1Left;
                while (i < range1Length) {
@@ -53,7 +60,7 @@ private:
        // there may be a step somewhere in the list.
        int stepPartition;
        int stepLength;
-       SplitVectorWithRangeAdd *body;
+       std::unique_ptr<SplitVectorWithRangeAdd> body;
 
        // Move step forward
        void ApplyStep(int partitionUpTo) {
@@ -76,7 +83,7 @@ private:
        }
 
        void Allocate(int growSize) {
-               body = new SplitVectorWithRangeAdd(growSize);
+               body.reset(new SplitVectorWithRangeAdd(growSize));
                stepPartition = 0;
                stepLength = 0;
                body->Insert(0, 0);     // This value stays 0 for ever
@@ -84,13 +91,15 @@ private:
        }
 
 public:
-       Partitioning(int growSize) {
+       explicit Partitioning(int growSize) {
                Allocate(growSize);
        }
 
+       // Deleted so Partitioning objects can not be copied.
+       Partitioning(const Partitioning &) = delete;
+       void operator=(const Partitioning &) = delete;
+
        ~Partitioning() {
-               delete body;
-               body = 0;
        }
 
        int Partitions() const {
@@ -166,7 +175,7 @@ public:
                int lower = 0;
                int upper = body->Length()-1;
                do {
-                       int middle = (upper + lower + 1) / 2;   // Round high
+                       const int middle = (upper + lower + 1) / 2;     // Round high
                        int posMiddle = body->ValueAt(middle);
                        if (middle > stepPartition)
                                posMiddle += stepLength;
@@ -180,10 +189,13 @@ public:
        }
 
        void DeleteAll() {
-               int growSize = body->GetGrowSize();
-               delete body;
-               Allocate(growSize);
+               Allocate(body->GetGrowSize());
        }
 };
 
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
 #endif
diff --git a/plugins/scintilla/scintilla/src/PerLine.cxx b/plugins/scintilla/scintilla/src/PerLine.cxx
index a066bd6..d8cf729 100644
--- a/plugins/scintilla/scintilla/src/PerLine.cxx
+++ b/plugins/scintilla/scintilla/src/PerLine.cxx
@@ -5,13 +5,20 @@
 // Copyright 1998-2009 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
+#include <cstddef>
+#include <cassert>
+#include <cstring>
 
+#include <stdexcept>
+#include <vector>
+#include <forward_list>
 #include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
+#include "Position.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "CellBuffer.h"
@@ -22,118 +29,73 @@ using namespace Scintilla;
 #endif
 
 MarkerHandleSet::MarkerHandleSet() {
-       root = 0;
 }
 
 MarkerHandleSet::~MarkerHandleSet() {
-       MarkerHandleNumber *mhn = root;
-       while (mhn) {
-               MarkerHandleNumber *mhnToFree = mhn;
-               mhn = mhn->next;
-               delete mhnToFree;
-       }
-       root = 0;
+       mhList.clear();
 }
 
-int MarkerHandleSet::Length() const {
-       int c = 0;
-       MarkerHandleNumber *mhn = root;
-       while (mhn) {
-               c++;
-               mhn = mhn->next;
-       }
-       return c;
+bool MarkerHandleSet::Empty() const {
+       return mhList.empty();
 }
 
 int MarkerHandleSet::MarkValue() const {
        unsigned int m = 0;
-       MarkerHandleNumber *mhn = root;
-       while (mhn) {
-               m |= (1 << mhn->number);
-               mhn = mhn->next;
+       for (const MarkerHandleNumber &mhn : mhList) {
+               m |= (1 << mhn.number);
        }
        return m;
 }
 
 bool MarkerHandleSet::Contains(int handle) const {
-       MarkerHandleNumber *mhn = root;
-       while (mhn) {
-               if (mhn->handle == handle) {
+       for (const MarkerHandleNumber &mhn : mhList) {
+               if (mhn.handle == handle) {
                        return true;
                }
-               mhn = mhn->next;
        }
        return false;
 }
 
 bool MarkerHandleSet::InsertHandle(int handle, int markerNum) {
-       MarkerHandleNumber *mhn = new MarkerHandleNumber;
-       mhn->handle = handle;
-       mhn->number = markerNum;
-       mhn->next = root;
-       root = mhn;
+       mhList.push_front(MarkerHandleNumber(handle, markerNum));
        return true;
 }
 
 void MarkerHandleSet::RemoveHandle(int handle) {
-       MarkerHandleNumber **pmhn = &root;
-       while (*pmhn) {
-               MarkerHandleNumber *mhn = *pmhn;
-               if (mhn->handle == handle) {
-                       *pmhn = mhn->next;
-                       delete mhn;
-                       return;
-               }
-               pmhn = &((*pmhn)->next);
-       }
+       mhList.remove_if([=](const MarkerHandleNumber &mhn) { return mhn.handle == handle; });
 }
 
 bool MarkerHandleSet::RemoveNumber(int markerNum, bool all) {
        bool performedDeletion = false;
-       MarkerHandleNumber **pmhn = &root;
-       while (*pmhn) {
-               MarkerHandleNumber *mhn = *pmhn;
-               if (mhn->number == markerNum) {
-                       *pmhn = mhn->next;
-                       delete mhn;
+       mhList.remove_if([&](const MarkerHandleNumber &mhn) {
+               if ((all || !performedDeletion) && (mhn.number == markerNum)) {
                        performedDeletion = true;
-                       if (!all)
-                               break; 
-               } else {
-                       pmhn = &((*pmhn)->next);
+                       return true;
                }
-       }
+               return false;
+       });
        return performedDeletion;
 }
 
 void MarkerHandleSet::CombineWith(MarkerHandleSet *other) {
-       MarkerHandleNumber **pmhn = &root;
-       while (*pmhn) {
-               pmhn = &((*pmhn)->next);
-       }
-       *pmhn = other->root;
-       other->root = 0;
+       mhList.splice_after(mhList.before_begin(), other->mhList);
 }
 
 LineMarkers::~LineMarkers() {
-       Init();
+       markers.DeleteAll();
 }
 
 void LineMarkers::Init() {
-       for (int line = 0; line < markers.Length(); line++) {
-               delete markers[line];
-               markers[line] = 0;
-       }
        markers.DeleteAll();
 }
 
-void LineMarkers::InsertLine(int line) {
+void LineMarkers::InsertLine(Sci::Line line) {
        if (markers.Length()) {
                markers.Insert(line, 0);
        }
 }
 
-void LineMarkers::RemoveLine(int line) {
+void LineMarkers::RemoveLine(Sci::Line line) {
        // Retain the markers from the deleted line by oring them into the previous line
        if (markers.Length()) {
                if (line > 0) {
@@ -143,9 +105,9 @@ void LineMarkers::RemoveLine(int line) {
        }
 }
 
-int LineMarkers::LineFromHandle(int markerHandle) {
+Sci::Line LineMarkers::LineFromHandle(int markerHandle) {
        if (markers.Length()) {
-               for (int line = 0; line < markers.Length(); line++) {
+               for (Sci::Line line = 0; line < markers.Length(); line++) {
                        if (markers[line]) {
                                if (markers[line]->Contains(markerHandle)) {
                                        return line;
@@ -156,66 +118,62 @@ int LineMarkers::LineFromHandle(int markerHandle) {
        return -1;
 }
 
-void LineMarkers::MergeMarkers(int pos) {
-       if (markers[pos + 1] != NULL) {
-               if (markers[pos] == NULL)
-                       markers[pos] = new MarkerHandleSet;
-               markers[pos]->CombineWith(markers[pos + 1]);
-               delete markers[pos + 1];
-               markers[pos + 1] = NULL;
+void LineMarkers::MergeMarkers(Sci::Line line) {
+       if (markers[line + 1]) {
+               if (!markers[line])
+                       markers[line].reset(new MarkerHandleSet);
+               markers[line]->CombineWith(markers[line + 1].get());
+               markers[line + 1].reset();
        }
 }
 
-int LineMarkers::MarkValue(int line) {
+int LineMarkers::MarkValue(Sci::Line line) {
        if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line])
                return markers[line]->MarkValue();
        else
                return 0;
 }
 
-int LineMarkers::MarkerNext(int lineStart, int mask) const {
+Sci::Line LineMarkers::MarkerNext(Sci::Line lineStart, int mask) const {
        if (lineStart < 0)
                lineStart = 0;
-       int length = markers.Length();
-       for (int iLine = lineStart; iLine < length; iLine++) {
-               MarkerHandleSet *onLine = markers[iLine];
+       const Sci::Line length = markers.Length();
+       for (Sci::Line iLine = lineStart; iLine < length; iLine++) {
+               const MarkerHandleSet *onLine = markers[iLine].get();
                if (onLine && ((onLine->MarkValue() & mask) != 0))
-               //if ((pdoc->GetMark(iLine) & lParam) != 0)
                        return iLine;
        }
        return -1;
 }
 
-int LineMarkers::AddMark(int line, int markerNum, int lines) {
+int LineMarkers::AddMark(Sci::Line line, int markerNum, Sci::Line lines) {
        handleCurrent++;
        if (!markers.Length()) {
                // No existing markers so allocate one element per line
-               markers.InsertValue(0, lines, 0);
+               markers.InsertEmpty(0, lines);
        }
        if (line >= markers.Length()) {
                return -1;
        }
        if (!markers[line]) {
                // Need new structure to hold marker handle
-               markers[line] = new MarkerHandleSet();
+               markers[line].reset(new MarkerHandleSet());
        }
        markers[line]->InsertHandle(handleCurrent, markerNum);
 
        return handleCurrent;
 }
 
-bool LineMarkers::DeleteMark(int line, int markerNum, bool all) {
+bool LineMarkers::DeleteMark(Sci::Line line, int markerNum, bool all) {
        bool someChanges = false;
        if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) {
                if (markerNum == -1) {
                        someChanges = true;
-                       delete markers[line];
-                       markers[line] = NULL;
+                       markers[line].reset();
                } else {
                        someChanges = markers[line]->RemoveNumber(markerNum, all);
-                       if (markers[line]->Length() == 0) {
-                               delete markers[line];
-                               markers[line] = NULL;
+                       if (markers[line]->Empty()) {
+                               markers[line].reset();
                        }
                }
        }
@@ -223,12 +181,11 @@ bool LineMarkers::DeleteMark(int line, int markerNum, bool all) {
 }
 
 void LineMarkers::DeleteMarkFromHandle(int markerHandle) {
-       int line = LineFromHandle(markerHandle);
+       Sci::Line line = LineFromHandle(markerHandle);
        if (line >= 0) {
                markers[line]->RemoveHandle(markerHandle);
-               if (markers[line]->Length() == 0) {
-                       delete markers[line];
-                       markers[line] = NULL;
+               if (markers[line]->Empty()) {
+                       markers[line].reset();
                }
        }
 }
@@ -240,14 +197,14 @@ void LineLevels::Init() {
        levels.DeleteAll();
 }
 
-void LineLevels::InsertLine(int line) {
+void LineLevels::InsertLine(Sci::Line line) {
        if (levels.Length()) {
                int level = (line < levels.Length()) ? levels[line] : SC_FOLDLEVELBASE;
                levels.InsertValue(line, 1, level);
        }
 }
 
-void LineLevels::RemoveLine(int line) {
+void LineLevels::RemoveLine(Sci::Line line) {
        if (levels.Length()) {
                // Move up following lines but merge header flag from this line
                // to line before to avoid a temporary disappearence causing expansion.
@@ -260,7 +217,7 @@ void LineLevels::RemoveLine(int line) {
        }
 }
 
-void LineLevels::ExpandLevels(int sizeNew) {
+void LineLevels::ExpandLevels(Sci::Line sizeNew) {
        levels.InsertValue(levels.Length(), sizeNew - levels.Length(), SC_FOLDLEVELBASE);
 }
 
@@ -268,7 +225,7 @@ void LineLevels::ClearLevels() {
        levels.DeleteAll();
 }
 
-int LineLevels::SetLevel(int line, int level, int lines) {
+int LineLevels::SetLevel(Sci::Line line, int level, Sci::Line lines) {
        int prev = 0;
        if ((line >= 0) && (line < lines)) {
                if (!levels.Length()) {
@@ -282,7 +239,7 @@ int LineLevels::SetLevel(int line, int level, int lines) {
        return prev;
 }
 
-int LineLevels::GetLevel(int line) const {
+int LineLevels::GetLevel(Sci::Line line) const {
        if (levels.Length() && (line >= 0) && (line < levels.Length())) {
                return levels[line];
        } else {
@@ -297,7 +254,7 @@ void LineState::Init() {
        lineStates.DeleteAll();
 }
 
-void LineState::InsertLine(int line) {
+void LineState::InsertLine(Sci::Line line) {
        if (lineStates.Length()) {
                lineStates.EnsureLength(line);
                int val = (line < lineStates.Length()) ? lineStates[line] : 0;
@@ -305,27 +262,27 @@ void LineState::InsertLine(int line) {
        }
 }
 
-void LineState::RemoveLine(int line) {
+void LineState::RemoveLine(Sci::Line line) {
        if (lineStates.Length() > line) {
                lineStates.Delete(line);
        }
 }
 
-int LineState::SetLineState(int line, int state) {
+int LineState::SetLineState(Sci::Line line, int state) {
        lineStates.EnsureLength(line + 1);
-       int stateOld = lineStates[line];
+       const int stateOld = lineStates[line];
        lineStates[line] = state;
        return stateOld;
 }
 
-int LineState::GetLineState(int line) {
+int LineState::GetLineState(Sci::Line line) {
        if (line < 0)
                return 0;
        lineStates.EnsureLength(line + 1);
        return lineStates[line];
 }
 
-int LineState::GetMaxLineState() const {
+Sci::Line LineState::GetMaxLineState() const {
        return lineStates.Length();
 }
 
@@ -362,125 +319,183 @@ void LineAnnotation::Init() {
        ClearAll();
 }
 
-void LineAnnotation::InsertLine(int line) {
+void LineAnnotation::InsertLine(Sci::Line line) {
        if (annotations.Length()) {
                annotations.EnsureLength(line);
-               annotations.Insert(line, 0);
+               annotations.Insert(line, std::unique_ptr<char []>());
        }
 }
 
-void LineAnnotation::RemoveLine(int line) {
-       if (annotations.Length() && (line < annotations.Length())) {
-               delete []annotations[line];
-               annotations.Delete(line);
+void LineAnnotation::RemoveLine(Sci::Line line) {
+       if (annotations.Length() && (line > 0) && (line <= annotations.Length())) {
+               annotations[line-1].reset();
+               annotations.Delete(line-1);
        }
 }
 
-bool LineAnnotation::MultipleStyles(int line) const {
+bool LineAnnotation::MultipleStyles(Sci::Line line) const {
        if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
-               return reinterpret_cast<AnnotationHeader *>(annotations[line])->style == IndividualStyles;
+               return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->style == 
IndividualStyles;
        else
-               return 0;
+               return false;
 }
 
-int LineAnnotation::Style(int line) const {
+int LineAnnotation::Style(Sci::Line line) const {
        if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
-               return reinterpret_cast<AnnotationHeader *>(annotations[line])->style;
+               return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->style;
        else
                return 0;
 }
 
-const char *LineAnnotation::Text(int line) const {
+const char *LineAnnotation::Text(Sci::Line line) const {
        if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
-               return annotations[line]+sizeof(AnnotationHeader);
+               return annotations[line].get()+sizeof(AnnotationHeader);
        else
                return 0;
 }
 
-const unsigned char *LineAnnotation::Styles(int line) const {
+const unsigned char *LineAnnotation::Styles(Sci::Line line) const {
        if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line] && 
MultipleStyles(line))
-               return reinterpret_cast<unsigned char *>(annotations[line] + sizeof(AnnotationHeader) + 
Length(line));
+               return reinterpret_cast<unsigned char *>(annotations[line].get() + sizeof(AnnotationHeader) + 
Length(line));
        else
                return 0;
 }
 
 static char *AllocateAnnotation(int length, int style) {
-       size_t len = sizeof(AnnotationHeader) + length + ((style == IndividualStyles) ? length : 0);
-       char *ret = new char[len];
-       memset(ret, 0, len);
+       const size_t len = sizeof(AnnotationHeader) + length + ((style == IndividualStyles) ? length : 0);
+       char *ret = new char[len]();
        return ret;
 }
 
-void LineAnnotation::SetText(int line, const char *text) {
+void LineAnnotation::SetText(Sci::Line line, const char *text) {
        if (text && (line >= 0)) {
                annotations.EnsureLength(line+1);
-               int style = Style(line);
-               if (annotations[line]) {
-                       delete []annotations[line];
-               }
-               annotations[line] = AllocateAnnotation(static_cast<int>(strlen(text)), style);
-               AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]);
+               const int style = Style(line);
+               annotations[line].reset(AllocateAnnotation(static_cast<int>(strlen(text)), style));
+               char *pa = annotations[line].get();
+               assert(pa);
+               AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(pa);
                pah->style = static_cast<short>(style);
                pah->length = static_cast<int>(strlen(text));
                pah->lines = static_cast<short>(NumberLines(text));
-               memcpy(annotations[line]+sizeof(AnnotationHeader), text, pah->length);
+               memcpy(pa+sizeof(AnnotationHeader), text, pah->length);
        } else {
                if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && 
annotations[line]) {
-                       delete []annotations[line];
-                       annotations[line] = 0;
+                       annotations[line].reset();
                }
        }
 }
 
 void LineAnnotation::ClearAll() {
-       for (int line = 0; line < annotations.Length(); line++) {
-               delete []annotations[line];
-               annotations[line] = 0;
-       }
        annotations.DeleteAll();
 }
 
-void LineAnnotation::SetStyle(int line, int style) {
+void LineAnnotation::SetStyle(Sci::Line line, int style) {
        annotations.EnsureLength(line+1);
        if (!annotations[line]) {
-               annotations[line] = AllocateAnnotation(0, style);
+               annotations[line].reset(AllocateAnnotation(0, style));
        }
-       reinterpret_cast<AnnotationHeader *>(annotations[line])->style = static_cast<short>(style);
+       reinterpret_cast<AnnotationHeader *>(annotations[line].get())->style = static_cast<short>(style);
 }
 
-void LineAnnotation::SetStyles(int line, const unsigned char *styles) {
+void LineAnnotation::SetStyles(Sci::Line line, const unsigned char *styles) {
        if (line >= 0) {
                annotations.EnsureLength(line+1);
                if (!annotations[line]) {
-                       annotations[line] = AllocateAnnotation(0, IndividualStyles);
+                       annotations[line].reset(AllocateAnnotation(0, IndividualStyles));
                } else {
-                       AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader *>(annotations[line]);
+                       AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader 
*>(annotations[line].get());
                        if (pahSource->style != IndividualStyles) {
                                char *allocation = AllocateAnnotation(pahSource->length, IndividualStyles);
                                AnnotationHeader *pahAlloc = reinterpret_cast<AnnotationHeader *>(allocation);
                                pahAlloc->length = pahSource->length;
                                pahAlloc->lines = pahSource->lines;
-                               memcpy(allocation + sizeof(AnnotationHeader), annotations[line] + 
sizeof(AnnotationHeader), pahSource->length);
-                               delete []annotations[line];
-                               annotations[line] = allocation;
+                               memcpy(allocation + sizeof(AnnotationHeader), annotations[line].get() + 
sizeof(AnnotationHeader), pahSource->length);
+                               annotations[line].reset(allocation);
                        }
                }
-               AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]);
+               AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line].get());
                pah->style = IndividualStyles;
-               memcpy(annotations[line] + sizeof(AnnotationHeader) + pah->length, styles, pah->length);
+               memcpy(annotations[line].get() + sizeof(AnnotationHeader) + pah->length, styles, pah->length);
        }
 }
 
-int LineAnnotation::Length(int line) const {
+int LineAnnotation::Length(Sci::Line line) const {
        if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
-               return reinterpret_cast<AnnotationHeader *>(annotations[line])->length;
+               return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->length;
        else
                return 0;
 }
 
-int LineAnnotation::Lines(int line) const {
+int LineAnnotation::Lines(Sci::Line line) const {
        if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
-               return reinterpret_cast<AnnotationHeader *>(annotations[line])->lines;
+               return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->lines;
        else
                return 0;
 }
+
+LineTabstops::~LineTabstops() {
+       tabstops.DeleteAll();
+}
+
+void LineTabstops::Init() {
+       tabstops.DeleteAll();
+}
+
+void LineTabstops::InsertLine(Sci::Line line) {
+       if (tabstops.Length()) {
+               tabstops.EnsureLength(line);
+               tabstops.Insert(line, nullptr);
+       }
+}
+
+void LineTabstops::RemoveLine(Sci::Line line) {
+       if (tabstops.Length() > line) {
+               tabstops[line].reset();
+               tabstops.Delete(line);
+       }
+}
+
+bool LineTabstops::ClearTabstops(Sci::Line line) {
+       if (line < tabstops.Length()) {
+               TabstopList *tl = tabstops[line].get();
+               if (tl) {
+                       tl->clear();
+                       return true;
+               }
+       }
+       return false;
+}
+
+bool LineTabstops::AddTabstop(Sci::Line line, int x) {
+       tabstops.EnsureLength(line + 1);
+       if (!tabstops[line]) {
+               tabstops[line].reset(new TabstopList());
+       }
+
+       TabstopList *tl = tabstops[line].get();
+       if (tl) {
+               // tabstop positions are kept in order - insert in the right place
+               std::vector<int>::iterator it = std::lower_bound(tl->begin(), tl->end(), x);
+               // don't insert duplicates
+               if (it == tl->end() || *it != x) {
+                       tl->insert(it, x);
+                       return true;
+               }
+       }
+       return false;
+}
+
+int LineTabstops::GetNextTabstop(Sci::Line line, int x) const {
+       if (line < tabstops.Length()) {
+               TabstopList *tl = tabstops[line].get();
+               if (tl) {
+                       for (const int i : *tl) {
+                               if (i > x) {
+                                       return i;
+                               }
+                       }
+               }
+       }
+       return 0;
+}
diff --git a/plugins/scintilla/scintilla/src/PerLine.h b/plugins/scintilla/scintilla/src/PerLine.h
index 70d0023..bd97e53 100644
--- a/plugins/scintilla/scintilla/src/PerLine.h
+++ b/plugins/scintilla/scintilla/src/PerLine.h
@@ -19,19 +19,22 @@ namespace Scintilla {
 struct MarkerHandleNumber {
        int handle;
        int number;
-       MarkerHandleNumber *next;
+       MarkerHandleNumber(int handle_, int number_) : handle(handle_), number(number_) {}
 };
 
 /**
  * A marker handle set contains any number of MarkerHandleNumbers.
  */
 class MarkerHandleSet {
-       MarkerHandleNumber *root;
+       std::forward_list<MarkerHandleNumber> mhList;
 
 public:
        MarkerHandleSet();
+       // Deleted so MarkerHandleSet objects can not be copied.
+       MarkerHandleSet(const MarkerHandleSet &) = delete;
+       void operator=(const MarkerHandleSet &) = delete;
        ~MarkerHandleSet();
-       int Length() const;
+       bool Empty() const;
        int MarkValue() const;  ///< Bit set of marker numbers.
        bool Contains(int handle) const;
        bool InsertHandle(int handle, int markerNum);
@@ -41,38 +44,46 @@ public:
 };
 
 class LineMarkers : public PerLine {
-       SplitVector<MarkerHandleSet *> markers;
+       SplitVector<std::unique_ptr<MarkerHandleSet>> markers;
        /// Handles are allocated sequentially and should never have to be reused as 32 bit ints are very big.
        int handleCurrent;
 public:
        LineMarkers() : handleCurrent(0) {
        }
+       // Deleted so Worker objects can not be copied.
+       LineMarkers(const LineMarkers &) = delete;
+       void operator=(const LineMarkers &) = delete;
        virtual ~LineMarkers();
-       virtual void Init();
-       virtual void InsertLine(int line);
-       virtual void RemoveLine(int line);
-
-       int MarkValue(int line);
-       int MarkerNext(int lineStart, int mask) const;
-       int AddMark(int line, int marker, int lines);
-       void MergeMarkers(int pos);
-       bool DeleteMark(int line, int markerNum, bool all);
+       void Init() override;
+       void InsertLine(Sci::Line line) override;
+       void RemoveLine(Sci::Line line) override;
+
+       int MarkValue(Sci::Line line);
+       Sci::Line MarkerNext(Sci::Line lineStart, int mask) const;
+       int AddMark(Sci::Line line, int markerNum, Sci::Line lines);
+       void MergeMarkers(Sci::Line line);
+       bool DeleteMark(Sci::Line line, int markerNum, bool all);
        void DeleteMarkFromHandle(int markerHandle);
-       int LineFromHandle(int markerHandle);
+       Sci::Line LineFromHandle(int markerHandle);
 };
 
 class LineLevels : public PerLine {
        SplitVector<int> levels;
 public:
+       LineLevels() {
+       }
+       // Deleted so Worker objects can not be copied.
+       LineLevels(const LineLevels &) = delete;
+       void operator=(const LineLevels &) = delete;
        virtual ~LineLevels();
-       virtual void Init();
-       virtual void InsertLine(int line);
-       virtual void RemoveLine(int line);
+       void Init() override;
+       void InsertLine(Sci::Line line) override;
+       void RemoveLine(Sci::Line line) override;
 
-       void ExpandLevels(int sizeNew=-1);
+       void ExpandLevels(Sci::Line sizeNew=-1);
        void ClearLevels();
-       int SetLevel(int line, int level, int lines);
-       int GetLevel(int line) const;
+       int SetLevel(Sci::Line line, int level, Sci::Line lines);
+       int GetLevel(Sci::Line line) const;
 };
 
 class LineState : public PerLine {
@@ -80,36 +91,62 @@ class LineState : public PerLine {
 public:
        LineState() {
        }
+       // Deleted so Worker objects can not be copied.
+       LineState(const LineState &) = delete;
+       void operator=(const LineState &) = delete;
        virtual ~LineState();
-       virtual void Init();
-       virtual void InsertLine(int line);
-       virtual void RemoveLine(int line);
+       void Init() override;
+       void InsertLine(Sci::Line line) override;
+       void RemoveLine(Sci::Line line) override;
 
-       int SetLineState(int line, int state);
-       int GetLineState(int line);
-       int GetMaxLineState() const;
+       int SetLineState(Sci::Line line, int state);
+       int GetLineState(Sci::Line line);
+       Sci::Line GetMaxLineState() const;
 };
 
 class LineAnnotation : public PerLine {
-       SplitVector<char *> annotations;
+       SplitVector<std::unique_ptr<char []>> annotations;
 public:
        LineAnnotation() {
        }
+       // Deleted so Worker objects can not be copied.
+       LineAnnotation(const LineAnnotation &) = delete;
+       void operator=(const LineAnnotation &) = delete;
        virtual ~LineAnnotation();
-       virtual void Init();
-       virtual void InsertLine(int line);
-       virtual void RemoveLine(int line);
-
-       bool MultipleStyles(int line) const;
-       int Style(int line) const;
-       const char *Text(int line) const;
-       const unsigned char *Styles(int line) const;
-       void SetText(int line, const char *text);
+       void Init() override;
+       void InsertLine(Sci::Line line) override;
+       void RemoveLine(Sci::Line line) override;
+
+       bool MultipleStyles(Sci::Line line) const;
+       int Style(Sci::Line line) const;
+       const char *Text(Sci::Line line) const;
+       const unsigned char *Styles(Sci::Line line) const;
+       void SetText(Sci::Line line, const char *text);
        void ClearAll();
-       void SetStyle(int line, int style);
-       void SetStyles(int line, const unsigned char *styles);
-       int Length(int line) const;
-       int Lines(int line) const;
+       void SetStyle(Sci::Line line, int style);
+       void SetStyles(Sci::Line line, const unsigned char *styles);
+       int Length(Sci::Line line) const;
+       int Lines(Sci::Line line) const;
+};
+
+typedef std::vector<int> TabstopList;
+
+class LineTabstops : public PerLine {
+       SplitVector<std::unique_ptr<TabstopList>> tabstops;
+public:
+       LineTabstops() {
+       }
+       // Deleted so Worker objects can not be copied.
+       LineTabstops(const LineTabstops &) = delete;
+       void operator=(const LineTabstops &) = delete;
+       virtual ~LineTabstops();
+       void Init() override;
+       void InsertLine(Sci::Line line) override;
+       void RemoveLine(Sci::Line line) override;
+
+       bool ClearTabstops(Sci::Line line);
+       bool AddTabstop(Sci::Line line, int x);
+       int GetNextTabstop(Sci::Line line, int x) const;
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/Position.h b/plugins/scintilla/scintilla/src/Position.h
new file mode 100644
index 0000000..67365e3
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/Position.h
@@ -0,0 +1,30 @@
+// Scintilla source code edit control
+/** @file Position.h
+ ** Defines global type name Position in the Sci internal namespace.
+ **/
+// Copyright 2015 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef POSITION_H
+#define POSITION_H
+
+/**
+ * A Position is a position within a document between two characters or at the beginning or end.
+ * Sometimes used as a character index where it identifies the character after the position.
+ */
+
+namespace Sci {
+
+typedef int Position;
+typedef int Line;
+
+// A later version (4.x) of this file may:
+//#if defined(SCI_LARGE_FILE_SUPPORT)
+//typedef std::ptrdiff_t Position;
+// or may allow runtime choice between different position sizes.
+
+const Position invalidPosition = -1;
+
+}
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/PositionCache.cxx 
b/plugins/scintilla/scintilla/src/PositionCache.cxx
index 742a226..591cf22 100644
--- a/plugins/scintilla/scintilla/src/PositionCache.cxx
+++ b/plugins/scintilla/scintilla/src/PositionCache.cxx
@@ -5,19 +5,24 @@
 // Copyright 1998-2007 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
 
+#include <stdexcept>
 #include <string>
 #include <vector>
 #include <map>
+#include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
+#include "ILexer.h"
 #include "Scintilla.h"
 
+#include "Position.h"
+#include "UniqueString.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
@@ -31,9 +36,9 @@
 #include "ViewStyle.h"
 #include "CharClassify.h"
 #include "Decoration.h"
-#include "ILexer.h"
 #include "CaseFolder.h"
 #include "Document.h"
+#include "UniConversion.h"
 #include "Selection.h"
 #include "PositionCache.h"
 
@@ -41,13 +46,7 @@
 using namespace Scintilla;
 #endif
 
-static inline bool IsControlCharacter(int ch) {
-       // iscntrl returns true for lots of chars > 127 which are displayable
-       return ch >= 0 && ch < ' ';
-}
-
 LineLayout::LineLayout(int maxLineLength_) :
-       lineStarts(0),
        lenLineStarts(0),
        lineNumber(-1),
        inCache(false),
@@ -56,17 +55,10 @@ LineLayout::LineLayout(int maxLineLength_) :
        numCharsBeforeEOL(0),
        validity(llInvalid),
        xHighlightGuide(0),
-       highlightColumn(0),
-       psel(NULL),
+       highlightColumn(false),
        containsCaret(false),
        edgeColumn(0),
-       chars(0),
-       styles(0),
-       styleBitsSet(0),
-       indicators(0),
-       positions(0),
-       hsStart(0),
-       hsEnd(0),
+       hotspot(0,0),
        widthLine(wrapWidthInfinite),
        lines(1),
        wrapIndent(0) {
@@ -82,27 +74,20 @@ LineLayout::~LineLayout() {
 void LineLayout::Resize(int maxLineLength_) {
        if (maxLineLength_ > maxLineLength) {
                Free();
-               chars = new char[maxLineLength_ + 1];
-               styles = new unsigned char[maxLineLength_ + 1];
-               indicators = new char[maxLineLength_ + 1];
+               chars.reset(new char[maxLineLength_ + 1]);
+               styles.reset(new unsigned char[maxLineLength_ + 1]);
                // Extra position allocated as sometimes the Windows
                // GetTextExtentExPoint API writes an extra element.
-               positions = new XYPOSITION[maxLineLength_ + 1 + 1];
+               positions.reset(new XYPOSITION[maxLineLength_ + 1 + 1]);
                maxLineLength = maxLineLength_;
        }
 }
 
 void LineLayout::Free() {
-       delete []chars;
-       chars = 0;
-       delete []styles;
-       styles = 0;
-       delete []indicators;
-       indicators = 0;
-       delete []positions;
-       positions = 0;
-       delete []lineStarts;
-       lineStarts = 0;
+       chars.reset();
+       styles.reset();
+       positions.reset();
+       lineStarts.reset();
 }
 
 void LineLayout::Invalidate(validLevel validity_) {
@@ -130,6 +115,10 @@ int LineLayout::LineLastVisible(int line) const {
        }
 }
 
+Range LineLayout::SubLineRange(int subLine) const {
+       return Range(LineStart(subLine), LineLastVisible(subLine));
+}
+
 bool LineLayout::InLine(int offset, int line) const {
        return ((offset >= LineStart(line)) && (offset < LineStart(line + 1))) ||
                ((offset == numCharsInLine) && (line == (lines-1)));
@@ -145,14 +134,13 @@ void LineLayout::SetLineStart(int line, int start) {
                        else
                                newLineStarts[i] = 0;
                }
-               delete []lineStarts;
-               lineStarts = newLineStarts;
+               lineStarts.reset(newLineStarts);
                lenLineStarts = newMaxLines;
        }
        lineStarts[line] = start;
 }
 
-void LineLayout::SetBracesHighlight(Range rangeLine, Position braces[],
+void LineLayout::SetBracesHighlight(Range rangeLine, const Sci::Position braces[],
                                     char bracesMatchStyle, int xHighlight, bool ignoreStyle) {
        if (!ignoreStyle && rangeLine.ContainsCharacter(braces[0])) {
                int braceOffset = braces[0] - rangeLine.start;
@@ -174,7 +162,7 @@ void LineLayout::SetBracesHighlight(Range rangeLine, Position braces[],
        }
 }
 
-void LineLayout::RestoreBracesHighlight(Range rangeLine, Position braces[], bool ignoreStyle) {
+void LineLayout::RestoreBracesHighlight(Range rangeLine, const Sci::Position braces[], bool ignoreStyle) {
        if (!ignoreStyle && rangeLine.ContainsCharacter(braces[0])) {
                int braceOffset = braces[0] - rangeLine.start;
                if (braceOffset < numCharsInLine) {
@@ -193,7 +181,7 @@ void LineLayout::RestoreBracesHighlight(Range rangeLine, Position braces[], bool
 int LineLayout::FindBefore(XYPOSITION x, int lower, int upper) const {
        do {
                int middle = (upper + lower + 1) / 2;   // Round high
-               XYPOSITION posMiddle = positions[middle];
+               const XYPOSITION posMiddle = positions[middle];
                if (x < posMiddle) {
                        upper = middle - 1;
                } else {
@@ -203,6 +191,53 @@ int LineLayout::FindBefore(XYPOSITION x, int lower, int upper) const {
        return lower;
 }
 
+
+int LineLayout::FindPositionFromX(XYPOSITION x, Range range, bool charPosition) const {
+       int pos = FindBefore(x, range.start, range.end);
+       while (pos < range.end) {
+               if (charPosition) {
+                       if (x < (positions[pos + 1])) {
+                               return pos;
+                       }
+               } else {
+                       if (x < ((positions[pos] + positions[pos + 1]) / 2)) {
+                               return pos;
+                       }
+               }
+               pos++;
+       }
+       return range.end;
+}
+
+Point LineLayout::PointFromPosition(int posInLine, int lineHeight, PointEnd pe) const {
+       Point pt;
+       // In case of very long line put x at arbitrary large position
+       if (posInLine > maxLineLength) {
+               pt.x = positions[maxLineLength] - positions[LineStart(lines)];
+       }
+
+       for (int subLine = 0; subLine < lines; subLine++) {
+               const Range rangeSubLine = SubLineRange(subLine);
+               if (posInLine >= rangeSubLine.start) {
+                       pt.y = static_cast<XYPOSITION>(subLine*lineHeight);
+                       if (posInLine <= rangeSubLine.end) {
+                               pt.x = positions[posInLine] - positions[rangeSubLine.start];
+                               if (rangeSubLine.start != 0)    // Wrapped lines may be indented
+                                       pt.x += wrapIndent;
+                               if (pe & peSubLineEnd)  // Return end of first subline not start of next
+                                       break;
+                       } else if ((pe & peLineEnd) && (subLine == (lines-1))) {
+                               pt.x = positions[numCharsInLine] - positions[rangeSubLine.start];
+                               if (rangeSubLine.start != 0)    // Wrapped lines may be indented
+                                       pt.x += wrapIndent;
+                       }
+               } else {
+                       break;
+               }
+       }
+       return pt;
+}
+
 int LineLayout::EndLineStyle() const {
        return styles[numCharsBeforeEOL > 0 ? numCharsBeforeEOL-1 : 0];
 }
@@ -223,7 +258,7 @@ void LineLayoutCache::Allocate(size_t length_) {
        cache.resize(length_);
 }
 
-void LineLayoutCache::AllocateForLevel(int linesOnScreen, int linesInDoc) {
+void LineLayoutCache::AllocateForLevel(Sci::Line linesOnScreen, Sci::Line linesInDoc) {
        PLATFORM_ASSERT(useCount == 0);
        size_t lengthForLevel = 0;
        if (level == llcCaret) {
@@ -239,8 +274,7 @@ void LineLayoutCache::AllocateForLevel(int linesOnScreen, int linesInDoc) {
        } else {
                if (lengthForLevel < cache.size()) {
                        for (size_t i = lengthForLevel; i < cache.size(); i++) {
-                               delete cache[i];
-                               cache[i] = 0;
+                               cache[i].reset();
                        }
                }
                cache.resize(lengthForLevel);
@@ -250,16 +284,14 @@ void LineLayoutCache::AllocateForLevel(int linesOnScreen, int linesInDoc) {
 
 void LineLayoutCache::Deallocate() {
        PLATFORM_ASSERT(useCount == 0);
-       for (size_t i = 0; i < cache.size(); i++)
-               delete cache[i];
        cache.clear();
 }
 
 void LineLayoutCache::Invalidate(LineLayout::validLevel validity_) {
        if (!cache.empty() && !allInvalidated) {
-               for (size_t i = 0; i < cache.size(); i++) {
-                       if (cache[i]) {
-                               cache[i]->Invalidate(validity_);
+               for (const std::unique_ptr<LineLayout> &ll : cache) {
+                       if (ll) {
+                               ll->Invalidate(validity_);
                        }
                }
                if (validity_ == LineLayout::llInvalid) {
@@ -276,15 +308,15 @@ void LineLayoutCache::SetLevel(int level_) {
        }
 }
 
-LineLayout *LineLayoutCache::Retrieve(int lineNumber, int lineCaret, int maxChars, int styleClock_,
-                                      int linesOnScreen, int linesInDoc) {
+LineLayout *LineLayoutCache::Retrieve(Sci::Line lineNumber, Sci::Line lineCaret, int maxChars, int 
styleClock_,
+                                      Sci::Line linesOnScreen, Sci::Line linesInDoc) {
        AllocateForLevel(linesOnScreen, linesInDoc);
        if (styleClock != styleClock_) {
                Invalidate(LineLayout::llCheckTextAndStyle);
                styleClock = styleClock_;
        }
        allInvalidated = false;
-       int pos = -1;
+       Sci::Position pos = -1;
        LineLayout *ret = 0;
        if (level == llcCaret) {
                pos = 0;
@@ -303,16 +335,15 @@ LineLayout *LineLayoutCache::Retrieve(int lineNumber, int lineCaret, int maxChar
                        if (cache[pos]) {
                                if ((cache[pos]->lineNumber != lineNumber) ||
                                        (cache[pos]->maxLineLength < maxChars)) {
-                                       delete cache[pos];
-                                       cache[pos] = 0;
+                                       cache[pos].reset();
                                }
                        }
                        if (!cache[pos]) {
-                               cache[pos] = new LineLayout(maxChars);
+                               cache[pos].reset(new LineLayout(maxChars));
                        }
                        cache[pos]->lineNumber = lineNumber;
                        cache[pos]->inCache = true;
-                       ret = cache[pos];
+                       ret = cache[pos].get();
                        useCount++;
                }
        }
@@ -336,133 +367,199 @@ void LineLayoutCache::Dispose(LineLayout *ll) {
        }
 }
 
-void BreakFinder::Insert(int val) {
-       if (val >= nextBreak) {
-               for (std::vector<int>::iterator it = selAndEdge.begin(); it != selAndEdge.end(); ++it) {
-                       if (val == *it) {
-                               return;
-                       }
-                       if (val <*it) {
-                               selAndEdge.insert(it, 1, val);
-                               return;
-                       }
-               }
-               // Not less than any so append
-               selAndEdge.push_back(val);
+// Simply pack the (maximum 4) character bytes into an int
+static inline int KeyFromString(const char *charBytes, size_t len) {
+       PLATFORM_ASSERT(len <= 4);
+       int k=0;
+       for (size_t i=0; i<len && charBytes[i]; i++) {
+               k = k * 0x100;
+               k += static_cast<unsigned char>(charBytes[i]);
+       }
+       return k;
+}
+
+SpecialRepresentations::SpecialRepresentations() {
+       std::fill(startByteHasReprs, startByteHasReprs+0x100, static_cast<short>(0));
+}
+
+void SpecialRepresentations::SetRepresentation(const char *charBytes, const char *value) {
+       MapRepresentation::iterator it = mapReprs.find(KeyFromString(charBytes, UTF8MaxBytes));
+       if (it == mapReprs.end()) {
+               // New entry so increment for first byte
+               startByteHasReprs[static_cast<unsigned char>(charBytes[0])]++;
        }
+       mapReprs[KeyFromString(charBytes, UTF8MaxBytes)] = Representation(value);
 }
 
-extern bool BadUTF(const char *s, int len, int &trailBytes);
+void SpecialRepresentations::ClearRepresentation(const char *charBytes) {
+       MapRepresentation::iterator it = mapReprs.find(KeyFromString(charBytes, UTF8MaxBytes));
+       if (it != mapReprs.end()) {
+               mapReprs.erase(it);
+               startByteHasReprs[static_cast<unsigned char>(charBytes[0])]--;
+       }
+}
 
-static int NextBadU(const char *s, int p, int len, int &trailBytes) {
-       while (p < len) {
-               p++;
-               if (BadUTF(s + p, len - p, trailBytes))
-                       return p;
+const Representation *SpecialRepresentations::RepresentationFromCharacter(const char *charBytes, size_t len) 
const {
+       PLATFORM_ASSERT(len <= 4);
+       if (!startByteHasReprs[static_cast<unsigned char>(charBytes[0])])
+               return 0;
+       MapRepresentation::const_iterator it = mapReprs.find(KeyFromString(charBytes, len));
+       if (it != mapReprs.end()) {
+               return &(it->second);
        }
-       return -1;
+       return 0;
+}
+
+bool SpecialRepresentations::Contains(const char *charBytes, size_t len) const {
+       PLATFORM_ASSERT(len <= 4);
+       if (!startByteHasReprs[static_cast<unsigned char>(charBytes[0])])
+               return false;
+       MapRepresentation::const_iterator it = mapReprs.find(KeyFromString(charBytes, len));
+       return it != mapReprs.end();
 }
 
-BreakFinder::BreakFinder(LineLayout *ll_, int lineStart_, int lineEnd_, int posLineStart_,
-       int xStart, bool breakForSelection, Document *pdoc_) :
+void SpecialRepresentations::Clear() {
+       mapReprs.clear();
+       std::fill(startByteHasReprs, startByteHasReprs+0x100, static_cast<short>(0));
+}
+
+void BreakFinder::Insert(int val) {
+       if (val > nextBreak) {
+               const std::vector<int>::iterator it = std::lower_bound(selAndEdge.begin(), selAndEdge.end(), 
val);
+               if (it == selAndEdge.end()) {
+                       selAndEdge.push_back(val);
+               } else if (*it != val) {
+                       selAndEdge.insert(it, 1, val);
+               }
+       }
+}
+
+BreakFinder::BreakFinder(const LineLayout *ll_, const Selection *psel, Range lineRange_, Sci::Position 
posLineStart_,
+       int xStart, bool breakForSelection, const Document *pdoc_, const SpecialRepresentations *preprs_, 
const ViewStyle *pvsDraw) :
        ll(ll_),
-       lineStart(lineStart_),
-       lineEnd(lineEnd_),
+       lineRange(lineRange_),
        posLineStart(posLineStart_),
-       nextBreak(lineStart_),
+       nextBreak(lineRange_.start),
        saeCurrentPos(0),
        saeNext(0),
        subBreak(-1),
-       pdoc(pdoc_) {
+       pdoc(pdoc_),
+       encodingFamily(pdoc_->CodePageFamily()),
+       preprs(preprs_) {
 
        // Search for first visible break
        // First find the first visible character
-       nextBreak = ll->FindBefore(xStart, lineStart, lineEnd);
+       if (xStart > 0.0f)
+               nextBreak = ll->FindBefore(static_cast<XYPOSITION>(xStart), lineRange.start, lineRange.end);
        // Now back to a style break
-       while ((nextBreak > lineStart) && (ll->styles[nextBreak] == ll->styles[nextBreak - 1])) {
+       while ((nextBreak > lineRange.start) && (ll->styles[nextBreak] == ll->styles[nextBreak - 1])) {
                nextBreak--;
        }
 
        if (breakForSelection) {
-               SelectionPosition posStart(posLineStart);
-               SelectionPosition posEnd(posLineStart + lineEnd);
-               SelectionSegment segmentLine(posStart, posEnd);
-               for (size_t r=0; r<ll->psel->Count(); r++) {
-                       SelectionSegment portion = ll->psel->Range(r).Intersect(segmentLine);
+               const SelectionPosition posStart(posLineStart);
+               const SelectionPosition posEnd(posLineStart + lineRange.end);
+               const SelectionSegment segmentLine(posStart, posEnd);
+               for (size_t r=0; r<psel->Count(); r++) {
+                       const SelectionSegment portion = psel->Range(r).Intersect(segmentLine);
                        if (!(portion.start == portion.end)) {
                                if (portion.start.IsValid())
-                                       Insert(portion.start.Position() - posLineStart - 1);
+                                       Insert(portion.start.Position() - posLineStart);
                                if (portion.end.IsValid())
-                                       Insert(portion.end.Position() - posLineStart - 1);
+                                       Insert(portion.end.Position() - posLineStart);
                        }
                }
        }
-
-       Insert(ll->edgeColumn - 1);
-       Insert(lineEnd - 1);
-
-       if (pdoc && (SC_CP_UTF8 == pdoc->dbcsCodePage)) {
-               int trailBytes=0;
-               for (int pos = -1;;) {
-                       pos = NextBadU(ll->chars, pos, lineEnd, trailBytes);
-                       if (pos < 0)
-                               break;
-                       Insert(pos-1);
-                       Insert(pos);
+       if (pvsDraw && pvsDraw->indicatorsSetFore) {
+               for (const Decoration *deco : pdoc->decorations.View()) {
+                       if (pvsDraw->indicators[deco->Indicator()].OverridesTextFore()) {
+                               Sci::Position startPos = deco->rs.EndRun(posLineStart);
+                               while (startPos < (posLineStart + lineRange.end)) {
+                                       Insert(startPos - posLineStart);
+                                       startPos = deco->rs.EndRun(startPos);
+                               }
+                       }
                }
        }
+       Insert(ll->edgeColumn);
+       Insert(lineRange.end);
        saeNext = (!selAndEdge.empty()) ? selAndEdge[0] : -1;
 }
 
 BreakFinder::~BreakFinder() {
 }
 
-int BreakFinder::First() const {
-       return nextBreak;
-}
-
-int BreakFinder::Next() {
+TextSegment BreakFinder::Next() {
        if (subBreak == -1) {
                int prev = nextBreak;
-               while (nextBreak < lineEnd) {
-                       if ((ll->styles[nextBreak] != ll->styles[nextBreak + 1]) ||
-                                       (nextBreak == saeNext) ||
-                                       IsControlCharacter(ll->chars[nextBreak]) || 
IsControlCharacter(ll->chars[nextBreak + 1])) {
-                               if (nextBreak == saeNext) {
+               while (nextBreak < lineRange.end) {
+                       int charWidth = 1;
+                       if (encodingFamily == efUnicode)
+                               charWidth = UTF8DrawBytes(reinterpret_cast<unsigned char 
*>(&ll->chars[nextBreak]), lineRange.end - nextBreak);
+                       else if (encodingFamily == efDBCS)
+                               charWidth = pdoc->IsDBCSLeadByte(ll->chars[nextBreak]) ? 2 : 1;
+                       const Representation *repr = 
preprs->RepresentationFromCharacter(&ll->chars[nextBreak], charWidth);
+                       if (((nextBreak > 0) && (ll->styles[nextBreak] != ll->styles[nextBreak - 1])) ||
+                                       repr ||
+                                       (nextBreak == saeNext)) {
+                               while ((nextBreak >= saeNext) && (saeNext < lineRange.end)) {
                                        saeCurrentPos++;
-                                       saeNext = (saeCurrentPos < selAndEdge.size()) ? 
selAndEdge[saeCurrentPos] : -1;
+                                       saeNext = (saeCurrentPos < selAndEdge.size()) ? 
selAndEdge[saeCurrentPos] : lineRange.end;
                                }
-                               nextBreak++;
-                               if ((nextBreak - prev) < lengthStartSubdivision) {
-                                       return nextBreak;
+                               if ((nextBreak > prev) || repr) {
+                                       // Have a segment to report
+                                       if (nextBreak == prev) {
+                                               nextBreak += charWidth;
+                                       } else {
+                                               repr = 0;       // Optimize -> should remember repr
+                                       }
+                                       if ((nextBreak - prev) < lengthStartSubdivision) {
+                                               return TextSegment(prev, nextBreak - prev, repr);
+                                       } else {
+                                               break;
+                                       }
                                }
-                               break;
                        }
-                       nextBreak++;
+                       nextBreak += charWidth;
                }
                if ((nextBreak - prev) < lengthStartSubdivision) {
-                       return nextBreak;
+                       return TextSegment(prev, nextBreak - prev);
                }
                subBreak = prev;
        }
        // Splitting up a long run from prev to nextBreak in lots of approximately lengthEachSubdivision.
        // For very long runs add extra breaks after spaces or if no spaces before low punctuation.
+       int startSegment = subBreak;
        if ((nextBreak - subBreak) <= lengthEachSubdivision) {
                subBreak = -1;
-               return nextBreak;
+               return TextSegment(startSegment, nextBreak - startSegment);
        } else {
-               subBreak += pdoc->SafeSegment(ll->chars + subBreak, nextBreak-subBreak, 
lengthEachSubdivision);
+               subBreak += pdoc->SafeSegment(&ll->chars[subBreak], nextBreak-subBreak, 
lengthEachSubdivision);
                if (subBreak >= nextBreak) {
                        subBreak = -1;
-                       return nextBreak;
+                       return TextSegment(startSegment, nextBreak - startSegment);
                } else {
-                       return subBreak;
+                       return TextSegment(startSegment, subBreak - startSegment);
                }
        }
 }
 
+bool BreakFinder::More() const {
+       return (subBreak >= 0) || (nextBreak < lineRange.end);
+}
+
 PositionCacheEntry::PositionCacheEntry() :
-       styleNumber(0), len(0), clock(0), positions(0) {
+       styleNumber(0), len(0), clock(0), positions(nullptr) {
+}
+
+// Copy constructor not currently used, but needed for being element in std::vector.
+PositionCacheEntry::PositionCacheEntry(const PositionCacheEntry &other) :
+       styleNumber(other.styleNumber), len(other.styleNumber), clock(other.styleNumber), positions(nullptr) {
+       if (other.positions) {
+               const size_t lenData = len + (len / sizeof(XYPOSITION)) + 1;
+               positions.reset(new XYPOSITION[lenData]);
+               memcpy(positions.get(), other.positions.get(), lenData * sizeof(XYPOSITION));
+       }
 }
 
 void PositionCacheEntry::Set(unsigned int styleNumber_, const char *s_,
@@ -472,11 +569,11 @@ void PositionCacheEntry::Set(unsigned int styleNumber_, const char *s_,
        len = len_;
        clock = clock_;
        if (s_ && positions_) {
-               positions = new XYPOSITION[len + (len / 4) + 1];
+               positions.reset(new XYPOSITION[len + (len / sizeof(XYPOSITION)) + 1]);
                for (unsigned int i=0; i<len; i++) {
-                       positions[i] = static_cast<XYPOSITION>(positions_[i]);
+                       positions[i] = positions_[i];
                }
-               memcpy(reinterpret_cast<char *>(positions + len), s_, len);
+               memcpy(&positions[len], s_, len);
        }
 }
 
@@ -485,8 +582,7 @@ PositionCacheEntry::~PositionCacheEntry() {
 }
 
 void PositionCacheEntry::Clear() {
-       delete []positions;
-       positions = 0;
+       positions.reset();
        styleNumber = 0;
        len = 0;
        clock = 0;
@@ -495,7 +591,7 @@ void PositionCacheEntry::Clear() {
 bool PositionCacheEntry::Retrieve(unsigned int styleNumber_, const char *s_,
        unsigned int len_, XYPOSITION *positions_) const {
        if ((styleNumber == styleNumber_) && (len == len_) &&
-               (memcmp(reinterpret_cast<char *>(positions + len), s_, len)== 0)) {
+               (memcmp(&positions[len], s_, len)== 0)) {
                for (unsigned int i=0; i<len; i++) {
                        positions_[i] = positions[i];
                }
@@ -505,7 +601,7 @@ bool PositionCacheEntry::Retrieve(unsigned int styleNumber_, const char *s_,
        }
 }
 
-int PositionCacheEntry::Hash(unsigned int styleNumber_, const char *s, unsigned int len_) {
+unsigned int PositionCacheEntry::Hash(unsigned int styleNumber_, const char *s, unsigned int len_) {
        unsigned int ret = s[0] << 7;
        for (unsigned int i=0; i<len_; i++) {
                ret *= 1000003;
@@ -540,8 +636,8 @@ PositionCache::~PositionCache() {
 
 void PositionCache::Clear() {
        if (!allClear) {
-               for (size_t i=0; i<pces.size(); i++) {
-                       pces[i].Clear();
+               for (PositionCacheEntry &pce : pces) {
+                       pce.Clear();
                }
        }
        clock = 1;
@@ -553,22 +649,22 @@ void PositionCache::SetSize(size_t size_) {
        pces.resize(size_);
 }
 
-void PositionCache::MeasureWidths(Surface *surface, ViewStyle &vstyle, unsigned int styleNumber,
-       const char *s, unsigned int len, XYPOSITION *positions, Document *pdoc) {
+void PositionCache::MeasureWidths(Surface *surface, const ViewStyle &vstyle, unsigned int styleNumber,
+       const char *s, unsigned int len, XYPOSITION *positions, const Document *pdoc) {
 
        allClear = false;
-       int probe = -1;
+       size_t probe = pces.size();     // Out of bounds
        if ((!pces.empty()) && (len < 30)) {
                // Only store short strings in the cache so it doesn't churn with
                // long comments with only a single comment.
 
                // Two way associative: try two probe positions.
-               int hashValue = PositionCacheEntry::Hash(styleNumber, s, len);
-               probe = static_cast<int>(hashValue % pces.size());
+               unsigned int hashValue = PositionCacheEntry::Hash(styleNumber, s, len);
+               probe = hashValue % pces.size();
                if (pces[probe].Retrieve(styleNumber, s, len, positions)) {
                        return;
                }
-               int probe2 = static_cast<int>((hashValue * 37) % pces.size());
+               unsigned int probe2 = (hashValue * 37) % pces.size();
                if (pces[probe2].Retrieve(styleNumber, s, len, positions)) {
                        return;
                }
@@ -583,7 +679,8 @@ void PositionCache::MeasureWidths(Surface *surface, ViewStyle &vstyle, unsigned
                XYPOSITION xStartSegment = 0;
                while (startSegment < len) {
                        unsigned int lenSegment = pdoc->SafeSegment(s + startSegment, len - startSegment, 
BreakFinder::lengthEachSubdivision);
-                       surface->MeasureWidths(vstyle.styles[styleNumber].font, s + startSegment, lenSegment, 
positions + startSegment);
+                       FontAlias fontStyle = vstyle.styles[styleNumber].font;
+                       surface->MeasureWidths(fontStyle, s + startSegment, lenSegment, positions + 
startSegment);
                        for (unsigned int inSeg = 0; inSeg < lenSegment; inSeg++) {
                                positions[startSegment + inSeg] += xStartSegment;
                        }
@@ -591,15 +688,17 @@ void PositionCache::MeasureWidths(Surface *surface, ViewStyle &vstyle, unsigned
                        startSegment += lenSegment;
                }
        } else {
-               surface->MeasureWidths(vstyle.styles[styleNumber].font, s, len, positions);
+               FontAlias fontStyle = vstyle.styles[styleNumber].font;
+               surface->MeasureWidths(fontStyle, s, len, positions);
        }
-       if (probe >= 0) {
+       if (probe < pces.size()) {
+               // Store into cache
                clock++;
                if (clock > 60000) {
                        // Since there are only 16 bits for the clock, wrap it round and
                        // reset all cache entries so none get stuck with a high clock.
-                       for (size_t i=0; i<pces.size(); i++) {
-                               pces[i].ResetClock();
+                       for (PositionCacheEntry &pce : pces) {
+                               pce.ResetClock();
                        }
                        clock = 2;
                }
diff --git a/plugins/scintilla/scintilla/src/PositionCache.h b/plugins/scintilla/scintilla/src/PositionCache.h
index 34f2377..402d657 100644
--- a/plugins/scintilla/scintilla/src/PositionCache.h
+++ b/plugins/scintilla/scintilla/src/PositionCache.h
@@ -17,55 +17,84 @@ static inline bool IsEOLChar(char ch) {
 }
 
 /**
+* A point in document space.
+* Uses double for sufficient resolution in large (>20,000,000 line) documents.
+*/
+class PointDocument {
+public:
+       double x;
+       double y;
+
+       explicit PointDocument(double x_ = 0, double y_ = 0) : x(x_), y(y_) {
+       }
+
+       // Conversion from Point.
+       explicit PointDocument(Point pt) : x(pt.x), y(pt.y) {
+       }
+};
+
+// There are two points for some positions and this enumeration
+// can choose between the end of the first line or subline
+// and the start of the next line or subline.
+enum PointEnd {
+       peDefault = 0x0,
+       peLineEnd = 0x1,
+       peSubLineEnd = 0x2
+};
+
+/**
  */
 class LineLayout {
 private:
        friend class LineLayoutCache;
-       int *lineStarts;
+       std::unique_ptr<int []>lineStarts;
        int lenLineStarts;
        /// Drawing is only performed for @a maxLineLength characters on each line.
-       int lineNumber;
+       Sci::Line lineNumber;
        bool inCache;
 public:
        enum { wrapWidthInfinite = 0x7ffffff };
+
        int maxLineLength;
        int numCharsInLine;
        int numCharsBeforeEOL;
        enum validLevel { llInvalid, llCheckTextAndStyle, llPositions, llLines } validity;
        int xHighlightGuide;
        bool highlightColumn;
-       Selection *psel;
        bool containsCaret;
        int edgeColumn;
-       char *chars;
-       unsigned char *styles;
-       int styleBitsSet;
-       char *indicators;
-       XYPOSITION *positions;
+       std::unique_ptr<char[]> chars;
+       std::unique_ptr<unsigned char[]> styles;
+       std::unique_ptr<XYPOSITION[]> positions;
        char bracePreviousStyles[2];
 
        // Hotspot support
-       int hsStart;
-       int hsEnd;
+       Range hotspot;
 
        // Wrapped line support
        int widthLine;
        int lines;
        XYPOSITION wrapIndent; // In pixels
 
-       LineLayout(int maxLineLength_);
+       explicit LineLayout(int maxLineLength_);
+       // Deleted so LineLayout objects can not be copied.
+       LineLayout(const LineLayout &) = delete;
+       void operator=(const LineLayout &) = delete;
        virtual ~LineLayout();
        void Resize(int maxLineLength_);
        void Free();
        void Invalidate(validLevel validity_);
        int LineStart(int line) const;
        int LineLastVisible(int line) const;
+       Range SubLineRange(int subLine) const;
        bool InLine(int offset, int line) const;
        void SetLineStart(int line, int start);
-       void SetBracesHighlight(Range rangeLine, Position braces[],
+       void SetBracesHighlight(Range rangeLine, const Sci::Position braces[],
                char bracesMatchStyle, int xHighlight, bool ignoreStyle);
-       void RestoreBracesHighlight(Range rangeLine, Position braces[], bool ignoreStyle);
+       void RestoreBracesHighlight(Range rangeLine, const Sci::Position braces[], bool ignoreStyle);
        int FindBefore(XYPOSITION x, int lower, int upper) const;
+       int FindPositionFromX(XYPOSITION x, Range range, bool charPosition) const;
+       Point PointFromPosition(int posInLine, int lineHeight, PointEnd pe) const;
        int EndLineStyle() const;
 };
 
@@ -73,14 +102,17 @@ public:
  */
 class LineLayoutCache {
        int level;
-       std::vector<LineLayout *>cache;
+       std::vector<std::unique_ptr<LineLayout>>cache;
        bool allInvalidated;
        int styleClock;
        int useCount;
        void Allocate(size_t length_);
-       void AllocateForLevel(int linesOnScreen, int linesInDoc);
+       void AllocateForLevel(Sci::Line linesOnScreen, Sci::Line linesInDoc);
 public:
        LineLayoutCache();
+       // Deleted so LineLayoutCache objects can not be copied.
+       LineLayoutCache(const LineLayoutCache &) = delete;
+       void operator=(const LineLayoutCache &) = delete;
        virtual ~LineLayoutCache();
        void Deallocate();
        enum {
@@ -92,8 +124,8 @@ public:
        void Invalidate(LineLayout::validLevel validity_);
        void SetLevel(int level_);
        int GetLevel() const { return level; }
-       LineLayout *Retrieve(int lineNumber, int lineCaret, int maxChars, int styleClock_,
-               int linesOnScreen, int linesInDoc);
+       LineLayout *Retrieve(Sci::Line lineNumber, Sci::Line lineCaret, int maxChars, int styleClock_,
+               Sci::Line linesOnScreen, Sci::Line linesInDoc);
        void Dispose(LineLayout *ll);
 };
 
@@ -101,60 +133,100 @@ class PositionCacheEntry {
        unsigned int styleNumber:8;
        unsigned int len:8;
        unsigned int clock:16;
-       XYPOSITION *positions;
+       std::unique_ptr<XYPOSITION []> positions;
 public:
        PositionCacheEntry();
+       // Copy constructor not currently used, but needed for being element in std::vector.
+       PositionCacheEntry(const PositionCacheEntry &);
+       // Deleted so PositionCacheEntry objects can not be assigned.
+       void operator=(const PositionCacheEntry &) = delete;
        ~PositionCacheEntry();
-       void Set(unsigned int styleNumber_, const char *s_, unsigned int len_, XYPOSITION *positions_, 
unsigned int clock);
+       void Set(unsigned int styleNumber_, const char *s_, unsigned int len_, XYPOSITION *positions_, 
unsigned int clock_);
        void Clear();
        bool Retrieve(unsigned int styleNumber_, const char *s_, unsigned int len_, XYPOSITION *positions_) 
const;
-       static int Hash(unsigned int styleNumber_, const char *s, unsigned int len);
+       static unsigned int Hash(unsigned int styleNumber_, const char *s, unsigned int len_);
        bool NewerThan(const PositionCacheEntry &other) const;
        void ResetClock();
 };
 
+class Representation {
+public:
+       std::string stringRep;
+       explicit Representation(const char *value="") : stringRep(value) {
+       }
+};
+
+typedef std::map<int, Representation> MapRepresentation;
+
+class SpecialRepresentations {
+       MapRepresentation mapReprs;
+       short startByteHasReprs[0x100];
+public:
+       SpecialRepresentations();
+       void SetRepresentation(const char *charBytes, const char *value);
+       void ClearRepresentation(const char *charBytes);
+       const Representation *RepresentationFromCharacter(const char *charBytes, size_t len) const;
+       bool Contains(const char *charBytes, size_t len) const;
+       void Clear();
+};
+
+struct TextSegment {
+       int start;
+       int length;
+       const Representation *representation;
+       TextSegment(int start_=0, int length_=0, const Representation *representation_=0) :
+               start(start_), length(length_), representation(representation_) {
+       }
+       int end() const {
+               return start + length;
+       }
+};
+
 // Class to break a line of text into shorter runs at sensible places.
 class BreakFinder {
-       LineLayout *ll;
-       int lineStart;
-       int lineEnd;
-       int posLineStart;
+       const LineLayout *ll;
+       Range lineRange;
+       Sci::Position posLineStart;
        int nextBreak;
        std::vector<int> selAndEdge;
        unsigned int saeCurrentPos;
        int saeNext;
        int subBreak;
-       Document *pdoc;
+       const Document *pdoc;
+       EncodingFamily encodingFamily;
+       const SpecialRepresentations *preprs;
        void Insert(int val);
-       // Private so BreakFinder objects can not be copied
-       BreakFinder(const BreakFinder &);
 public:
        // If a whole run is longer than lengthStartSubdivision then subdivide
        // into smaller runs at spaces or punctuation.
        enum { lengthStartSubdivision = 300 };
        // Try to make each subdivided run lengthEachSubdivision or shorter.
        enum { lengthEachSubdivision = 100 };
-       BreakFinder(LineLayout *ll_, int lineStart_, int lineEnd_, int posLineStart_,
-               int xStart, bool breakForSelection, Document *pdoc_);
+       BreakFinder(const LineLayout *ll_, const Selection *psel, Range lineRange_, Sci::Position 
posLineStart_,
+               int xStart, bool breakForSelection, const Document *pdoc_, const SpecialRepresentations 
*preprs_, const ViewStyle *pvsDraw);
+       // Deleted so BreakFinder objects can not be copied.
+       BreakFinder(const BreakFinder &) = delete;
+       void operator=(const BreakFinder &) = delete;
        ~BreakFinder();
-       int First() const;
-       int Next();
+       TextSegment Next();
+       bool More() const;
 };
 
 class PositionCache {
        std::vector<PositionCacheEntry> pces;
        unsigned int clock;
        bool allClear;
-       // Private so PositionCache objects can not be copied
-       PositionCache(const PositionCache &);
 public:
        PositionCache();
+       // Deleted so PositionCache objects can not be copied.
+       PositionCache(const PositionCache &) = delete;
+       void operator=(const PositionCache &) = delete;
        ~PositionCache();
        void Clear();
        void SetSize(size_t size_);
        size_t GetSize() const { return pces.size(); }
-       void MeasureWidths(Surface *surface, ViewStyle &vstyle, unsigned int styleNumber,
-               const char *s, unsigned int len, XYPOSITION *positions, Document *pdoc);
+       void MeasureWidths(Surface *surface, const ViewStyle &vstyle, unsigned int styleNumber,
+               const char *s, unsigned int len, XYPOSITION *positions, const Document *pdoc);
 };
 
 inline bool IsSpaceOrTab(int ch) {
diff --git a/plugins/scintilla/scintilla/src/RESearch.cxx b/plugins/scintilla/scintilla/src/RESearch.cxx
index efa23eb..9bcea1c 100644
--- a/plugins/scintilla/scintilla/src/RESearch.cxx
+++ b/plugins/scintilla/scintilla/src/RESearch.cxx
@@ -200,18 +200,16 @@
  *  matches:    foo-foo fo-fo fob-fob foobar-foobar ...
  */
 
-#include <stdlib.h>
+#include <cstdlib>
 
+#include <stdexcept>
 #include <string>
+#include <algorithm>
 
+#include "Position.h"
 #include "CharClassify.h"
 #include "RESearch.h"
 
-// Shut up annoying Visual C++ warnings:
-#ifdef _MSC_VER
-#pragma warning(disable: 4514)
-#endif
-
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
@@ -256,22 +254,18 @@ const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' };
 RESearch::RESearch(CharClassify *charClassTable) {
        failure = 0;
        charClass = charClassTable;
-       Init();
+       sta = NOP;                  /* status of lastpat */
+       bol = 0;
+       std::fill(bittab, bittab + BITBLK, static_cast<unsigned char>(0));
+       std::fill(tagstk, tagstk + MAXTAG, 0);
+       std::fill(nfa, nfa + MAXNFA, '\0');
+       Clear();
 }
 
 RESearch::~RESearch() {
        Clear();
 }
 
-void RESearch::Init() {
-       sta = NOP;                  /* status of lastpat */
-       bol = 0;
-       for (int i = 0; i < MAXTAG; i++)
-               pat[i].clear();
-       for (int j = 0; j < BITBLK; j++)
-               bittab[j] = 0;
-}
-
 void RESearch::Clear() {
        for (int i = 0; i < MAXTAG; i++) {
                pat[i].clear();
@@ -283,11 +277,10 @@ void RESearch::Clear() {
 void RESearch::GrabMatches(CharacterIndexer &ci) {
        for (unsigned int i = 0; i < MAXTAG; i++) {
                if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) {
-                       unsigned int len = eopat[i] - bopat[i];
-                       pat[i] = std::string(len+1, '\0');
-                       for (unsigned int j = 0; j < len; j++)
+                       Sci::Position len = eopat[i] - bopat[i];
+                       pat[i].resize(len);
+                       for (Sci::Position j = 0; j < len; j++)
                                pat[i][j] = ci.CharAt(bopat[i] + j);
-                       pat[i][len] = '\0';
                }
        }
 }
@@ -312,7 +305,7 @@ void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) {
        }
 }
 
-unsigned char escapeValue(unsigned char ch) {
+static unsigned char escapeValue(unsigned char ch) {
        switch (ch) {
        case 'a':       return '\a';
        case 'b':       return '\b';
@@ -333,24 +326,26 @@ static int GetHexaChar(unsigned char hd1, unsigned char hd2) {
                hexValue += 16 * (hd1 - 'A' + 10);
        } else if (hd1 >= 'a' && hd1 <= 'f') {
                hexValue += 16 * (hd1 - 'a' + 10);
-       } else
+       } else {
                return -1;
+       }
        if (hd2 >= '0' && hd2 <= '9') {
                hexValue += hd2 - '0';
        } else if (hd2 >= 'A' && hd2 <= 'F') {
                hexValue += hd2 - 'A' + 10;
        } else if (hd2 >= 'a' && hd2 <= 'f') {
                hexValue += hd2 - 'a' + 10;
-       } else
+       } else {
                return -1;
+       }
        return hexValue;
 }
 
 /**
  * Called when the parser finds a backslash not followed
  * by a valid expression (like \( in non-Posix mode).
- * @param pattern: pointer on the char after the backslash.
- * @param incr: (out) number of chars to skip after expression evaluation.
+ * @param pattern : pointer on the char after the backslash.
+ * @param incr : (out) number of chars to skip after expression evaluation.
  * @return the char if it resolves to a simple char,
  * or -1 for a char class. In this case, bittab is changed.
  */
@@ -363,7 +358,7 @@ int RESearch::GetBackslashExpression(
        incr = 0;       // Most of the time, will skip the char "naturally".
        int c;
        int result = -1;
-       unsigned char bsc = *pattern;
+       const unsigned char bsc = *pattern;
        if (!bsc) {
                // Avoid overrun
                result = '\\';  // \ at end of pattern, take it literally
@@ -381,9 +376,9 @@ int RESearch::GetBackslashExpression(
                result = escapeValue(bsc);
                break;
        case 'x': {
-                       unsigned char hd1 = *(pattern + 1);
-                       unsigned char hd2 = *(pattern + 2);
-                       int hexValue = GetHexaChar(hd1, hd2);
+                       const unsigned char hd1 = *(pattern + 1);
+                       const unsigned char hd2 = *(pattern + 2);
+                       const int hexValue = GetHexaChar(hd1, hd2);
                        if (hexValue >= 0) {
                                result = hexValue;
                                incr = 2;       // Must skip the digits
@@ -439,7 +434,7 @@ int RESearch::GetBackslashExpression(
        return result;
 }
 
-const char *RESearch::Compile(const char *pattern, int length, bool caseSensitive, bool posix) {
+const char *RESearch::Compile(const char *pattern, Sci::Position length, bool caseSensitive, bool posix) {
        char *mp=nfa;          /* nfa pointer       */
        char *lp;              /* saved pointer     */
        char *sp=nfa;          /* another one       */
@@ -472,18 +467,18 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
                        break;
 
                case '^':               /* match beginning */
-                       if (p == pattern)
+                       if (p == pattern) {
                                *mp++ = BOL;
-                       else {
+                       } else {
                                *mp++ = CHR;
                                *mp++ = *p;
                        }
                        break;
 
                case '$':               /* match endofline */
-                       if (!*(p+1))
+                       if (!*(p+1)) {
                                *mp++ = EOL;
-                       else {
+                       } else {
                                *mp++ = CHR;
                                *mp++ = *p;
                        }
@@ -498,8 +493,9 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
                                mask = '\377';
                                i++;
                                p++;
-                       } else
+                       } else {
                                mask = 0;
+                       }
 
                        if (*p == '-') {        /* real dash */
                                i++;
@@ -523,9 +519,9 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
                                                        i++;
                                                        c2 = static_cast<unsigned char>(*++p);
                                                        if (c2 == '\\') {
-                                                               if (!*(p+1))    // End of RE
+                                                               if (!*(p+1)) {  // End of RE
                                                                        return badpat("Missing ]");
-                                                               else {
+                                                               } else {
                                                                        i++;
                                                                        p++;
                                                                        int incr;
@@ -654,8 +650,9 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
                                if (tagc > n) {
                                        *mp++ = static_cast<char>(REF);
                                        *mp++ = static_cast<char>(n);
-                               } else
+                               } else {
                                        return badpat("Undetermined reference");
+                               }
                                break;
                        default:
                                if (!posix && *p == '(') {
@@ -663,16 +660,18 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
                                                tagstk[++tagi] = tagc;
                                                *mp++ = BOT;
                                                *mp++ = static_cast<char>(tagc++);
-                                       } else
+                                       } else {
                                                return badpat("Too many \\(\\) pairs");
+                                       }
                                } else if (!posix && *p == ')') {
                                        if (*sp == BOT)
                                                return badpat("Null pattern inside \\(\\)");
                                        if (tagi > 0) {
                                                *mp++ = static_cast<char>(EOT);
                                                *mp++ = static_cast<char>(tagstk[tagi--]);
-                                       } else
+                                       } else {
                                                return badpat("Unmatched \\)");
+                                       }
                                } else {
                                        int incr;
                                        int c = GetBackslashExpression(p, incr);
@@ -697,16 +696,18 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
                                        tagstk[++tagi] = tagc;
                                        *mp++ = BOT;
                                        *mp++ = static_cast<char>(tagc++);
-                               } else
+                               } else {
                                        return badpat("Too many () pairs");
+                               }
                        } else if (posix && *p == ')') {
                                if (*sp == BOT)
                                        return badpat("Null pattern inside ()");
                                if (tagi > 0) {
                                        *mp++ = static_cast<char>(EOT);
                                        *mp++ = static_cast<char>(tagstk[tagi--]);
-                               } else
+                               } else {
                                        return badpat("Unmatched )");
+                               }
                        } else {
                                unsigned char c = *p;
                                if (!c) // End of RE
@@ -754,9 +755,9 @@ const char *RESearch::Compile(const char *pattern, int length, bool caseSensitiv
  *  respectively.
  *
  */
-int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
+int RESearch::Execute(CharacterIndexer &ci, Sci::Position lp, Sci::Position endp) {
        unsigned char c;
-       int ep = NOTFOUND;
+       Sci::Position ep = NOTFOUND;
        char *ap = nfa;
 
        bol = lp;
@@ -781,7 +782,7 @@ int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
                c = *(ap+1);
                while ((lp < endp) && (static_cast<unsigned char>(ci.CharAt(lp)) != c))
                        lp++;
-               if (lp >= endp) /* if EOS, fail, else fall thru. */
+               if (lp >= endp) /* if EOS, fail, else fall through. */
                        return 0;
        default:                        /* regular matching all the way. */
                while (lp < endp) {
@@ -811,7 +812,7 @@ int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
  *
  *  special case optimizations: (nfa[n], nfa[n+1])
  *      CLO ANY
- *          We KNOW .* will match everything upto the
+ *          We KNOW .* will match everything up to the
  *          end of line. Thus, directly go to the end of
  *          line, without recursive PMatch calls. As in
  *          the other closure cases, the remaining pattern
@@ -843,13 +844,13 @@ extern void re_fail(char *,char);
 #define CHRSKIP 3      /* [CLO] CHR chr END      */
 #define CCLSKIP 34     /* [CLO] CCL 32 bytes END */
 
-int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) {
+Sci::Position RESearch::PMatch(CharacterIndexer &ci, Sci::Position lp, Sci::Position endp, char *ap) {
        int op, c, n;
-       int e;          /* extra pointer for CLO  */
-       int bp;         /* beginning of subpat... */
-       int ep;         /* ending of subpat...    */
-       int are;        /* to save the line ptr.  */
-       int llp;        /* lazy lp for LCLO       */
+       Sci::Position e;                /* extra pointer for CLO  */
+       Sci::Position bp;               /* beginning of subpat... */
+       Sci::Position ep;               /* ending of subpat...    */
+       Sci::Position are;      /* to save the line ptr.  */
+       Sci::Position llp;      /* lazy lp for LCLO       */
 
        while ((op = *ap++) != END)
                switch (op) {
@@ -939,7 +940,7 @@ int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) {
                        llp = lp;
                        e = NOTFOUND;
                        while (llp >= are) {
-                               int q;
+                               Sci::Position q;
                                if ((q = PMatch(ci, llp, endp, ap)) != NOTFOUND) {
                                        e = q;
                                        lp = llp;
diff --git a/plugins/scintilla/scintilla/src/RESearch.h b/plugins/scintilla/scintilla/src/RESearch.h
index 702259d..b092a6e 100644
--- a/plugins/scintilla/scintilla/src/RESearch.h
+++ b/plugins/scintilla/scintilla/src/RESearch.h
@@ -23,7 +23,7 @@ namespace Scintilla {
 
 class CharacterIndexer {
 public:
-       virtual char CharAt(int index)=0;
+       virtual char CharAt(Sci::Position index)=0;
        virtual ~CharacterIndexer() {
        }
 };
@@ -31,31 +31,31 @@ public:
 class RESearch {
 
 public:
-       RESearch(CharClassify *charClassTable);
+       explicit RESearch(CharClassify *charClassTable);
+       // No dynamic allocation so default copy constructor and assignment operator are OK.
        ~RESearch();
+       void Clear();
        void GrabMatches(CharacterIndexer &ci);
-       const char *Compile(const char *pattern, int length, bool caseSensitive, bool posix);
-       int Execute(CharacterIndexer &ci, int lp, int endp);
+       const char *Compile(const char *pattern, Sci::Position length, bool caseSensitive, bool posix);
+       int Execute(CharacterIndexer &ci, Sci::Position lp, Sci::Position endp);
 
        enum { MAXTAG=10 };
-       enum { MAXNFA=2048 };
+       enum { MAXNFA=4096 };
        enum { NOTFOUND=-1 };
 
-       int bopat[MAXTAG];
-       int eopat[MAXTAG];
+       Sci::Position bopat[MAXTAG];
+       Sci::Position eopat[MAXTAG];
        std::string pat[MAXTAG];
 
 private:
-       void Init();
-       void Clear();
        void ChSet(unsigned char c);
        void ChSetWithCase(unsigned char c, bool caseSensitive);
        int GetBackslashExpression(const char *pattern, int &incr);
 
-       int PMatch(CharacterIndexer &ci, int lp, int endp, char *ap);
+       Sci::Position PMatch(CharacterIndexer &ci, Sci::Position lp, Sci::Position endp, char *ap);
 
-       int bol;
-       int tagstk[MAXTAG];  /* subpat tag stack */
+       Sci::Position bol;
+       Sci::Position tagstk[MAXTAG];  /* subpat tag stack */
        char nfa[MAXNFA];    /* automaton */
        int sta;
        unsigned char bittab[BITBLK]; /* bit table for CCL pre-set bits */
diff --git a/plugins/scintilla/scintilla/src/RunStyles.cxx b/plugins/scintilla/scintilla/src/RunStyles.cxx
index fdcfc2b..b0a9c1f 100644
--- a/plugins/scintilla/scintilla/src/RunStyles.cxx
+++ b/plugins/scintilla/scintilla/src/RunStyles.cxx
@@ -4,16 +4,21 @@
 // Copyright 1998-2007 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stdarg.h>
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <cstdio>
+#include <cstdarg>
 
 #include <stdexcept>
+#include <vector>
+#include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
+#include "Position.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
@@ -35,7 +40,7 @@ int RunStyles::RunFromPosition(int position) const {
 // If there is no run boundary at position, insert one continuing style.
 int RunStyles::SplitRun(int position) {
        int run = RunFromPosition(position);
-       int posRun = starts->PositionFromPartition(run);
+       const int posRun = starts->PositionFromPartition(run);
        if (posRun < position) {
                int runStyle = ValueAt(position);
                run++;
@@ -67,16 +72,12 @@ void RunStyles::RemoveRunIfSameAsPrevious(int run) {
 }
 
 RunStyles::RunStyles() {
-       starts = new Partitioning(8);
-       styles = new SplitVector<int>();
+       starts.reset(new Partitioning(8));
+       styles.reset(new SplitVector<int>());
        styles->InsertValue(0, 2, 0);
 }
 
 RunStyles::~RunStyles() {
-       delete starts;
-       starts = NULL;
-       delete styles;
-       styles = NULL;
 }
 
 int RunStyles::Length() const {
@@ -88,12 +89,12 @@ int RunStyles::ValueAt(int position) const {
 }
 
 int RunStyles::FindNextChange(int position, int end) const {
-       int run = starts->PartitionFromPosition(position);
+       const int run = starts->PartitionFromPosition(position);
        if (run < starts->Partitions()) {
-               int runChange = starts->PositionFromPartition(run);
+               const int runChange = starts->PositionFromPartition(run);
                if (runChange > position)
                        return runChange;
-               int nextChange = starts->PositionFromPartition(run + 1);
+               const int nextChange = starts->PositionFromPartition(run + 1);
                if (nextChange > position) {
                        return nextChange;
                } else if (position < end) {
@@ -197,12 +198,8 @@ void RunStyles::InsertSpace(int position, int insertLength) {
 }
 
 void RunStyles::DeleteAll() {
-       delete starts;
-       starts = NULL;
-       delete styles;
-       styles = NULL;
-       starts = new Partitioning(8);
-       styles = new SplitVector<int>();
+       starts.reset(new Partitioning(8));
+       styles.reset(new SplitVector<int>());
        styles->InsertValue(0, 2, 0);
 }
 
@@ -270,7 +267,7 @@ void RunStyles::Check() const {
        }
        int start=0;
        while (start < Length()) {
-               int end = EndRun(start);
+               const int end = EndRun(start);
                if (start >= end) {
                        throw std::runtime_error("RunStyles: Partition is 0 length.");
                }
diff --git a/plugins/scintilla/scintilla/src/RunStyles.h b/plugins/scintilla/scintilla/src/RunStyles.h
index b096ad8..1c8ef30 100644
--- a/plugins/scintilla/scintilla/src/RunStyles.h
+++ b/plugins/scintilla/scintilla/src/RunStyles.h
@@ -16,17 +16,18 @@ namespace Scintilla {
 
 class RunStyles {
 private:
-       Partitioning *starts;
-       SplitVector<int> *styles;
+       std::unique_ptr<Partitioning> starts;
+       std::unique_ptr<SplitVector<int>> styles;
        int RunFromPosition(int position) const;
        int SplitRun(int position);
        void RemoveRun(int run);
        void RemoveRunIfEmpty(int run);
        void RemoveRunIfSameAsPrevious(int run);
-       // Private so RunStyles objects can not be copied
-       RunStyles(const RunStyles &);
 public:
        RunStyles();
+       // Deleted so RunStyles objects can not be copied.
+       RunStyles(const RunStyles &) = delete;
+       void operator=(const RunStyles &) = delete;
        ~RunStyles();
        int Length() const;
        int ValueAt(int position) const;
diff --git a/plugins/scintilla/scintilla/src/ScintillaBase.cxx 
b/plugins/scintilla/scintilla/src/ScintillaBase.cxx
index 0576879..3979354 100644
--- a/plugins/scintilla/scintilla/src/ScintillaBase.cxx
+++ b/plugins/scintilla/scintilla/src/ScintillaBase.cxx
@@ -5,28 +5,36 @@
 // Copyright 1998-2003 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <assert.h>
+#include <cstddef>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
 
+#include <stdexcept>
 #include <string>
 #include <vector>
 #include <map>
 #include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "ILexer.h"
 #include "Scintilla.h"
 
-#include "PropSetSimple.h"
 #ifdef SCI_LEXER
 #include "SciLexer.h"
+#endif
+
+#include "PropSetSimple.h"
+
+#ifdef SCI_LEXER
 #include "LexerModule.h"
 #include "Catalogue.h"
 #endif
+
+#include "Position.h"
+#include "UniqueString.h"
 #include "SplitVector.h"
 #include "Partitioning.h"
 #include "RunStyles.h"
@@ -39,14 +47,17 @@
 #include "LineMarker.h"
 #include "Style.h"
 #include "ViewStyle.h"
-#include "AutoComplete.h"
 #include "CharClassify.h"
 #include "Decoration.h"
 #include "CaseFolder.h"
 #include "Document.h"
 #include "Selection.h"
 #include "PositionCache.h"
+#include "EditModel.h"
+#include "MarginView.h"
+#include "EditView.h"
 #include "Editor.h"
+#include "AutoComplete.h"
 #include "ScintillaBase.h"
 
 #ifdef SCI_NAMESPACE
@@ -54,9 +65,10 @@ using namespace Scintilla;
 #endif
 
 ScintillaBase::ScintillaBase() {
-       displayPopupMenu = true;
+       displayPopupMenu = SC_POPUP_ALL;
        listType = 0;
        maxListWidth = 0;
+       multiAutoCMode = SC_MULTIAUTOC_ONCE;
 }
 
 ScintillaBase::~ScintillaBase() {
@@ -67,8 +79,8 @@ void ScintillaBase::Finalise() {
        popup.Destroy();
 }
 
-void ScintillaBase::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
-       bool isFillUp = ac.Active() && ac.IsFillUpChar(*s);
+void ScintillaBase::AddCharUTF(const char *s, unsigned int len, bool treatAsDBCS) {
+       const bool isFillUp = ac.Active() && ac.IsFillUpChar(*s);
        if (!isFillUp) {
                Editor::AddCharUTF(s, len, treatAsDBCS);
        }
@@ -158,10 +170,10 @@ int ScintillaBase::KeyCommand(unsigned int iMessage) {
                        EnsureCaretVisible();
                        return 0;
                case SCI_TAB:
-                       AutoCompleteCompleted();
+                       AutoCompleteCompleted(0, SC_AC_TAB);
                        return 0;
                case SCI_NEWLINE:
-                       AutoCompleteCompleted();
+                       AutoCompleteCompleted(0, SC_AC_NEWLINE);
                        return 0;
 
                default:
@@ -191,15 +203,36 @@ int ScintillaBase::KeyCommand(unsigned int iMessage) {
 }
 
 void ScintillaBase::AutoCompleteDoubleClick(void *p) {
-       ScintillaBase *sci = reinterpret_cast<ScintillaBase *>(p);
-       sci->AutoCompleteCompleted();
+       ScintillaBase *sci = static_cast<ScintillaBase *>(p);
+       sci->AutoCompleteCompleted(0, SC_AC_DOUBLECLICK);
 }
 
-void ScintillaBase::AutoCompleteInsert(Position startPos, int removeLen, const char *text, int textLen) {
+void ScintillaBase::AutoCompleteInsert(Sci::Position startPos, int removeLen, const char *text, int textLen) 
{
        UndoGroup ug(pdoc);
-       pdoc->DeleteChars(startPos, removeLen);
-       pdoc->InsertString(startPos, text, textLen);
-       SetEmptySelection(startPos + textLen);
+       if (multiAutoCMode == SC_MULTIAUTOC_ONCE) {
+               pdoc->DeleteChars(startPos, removeLen);
+               const Sci::Position lengthInserted = pdoc->InsertString(startPos, text, textLen);
+               SetEmptySelection(startPos + lengthInserted);
+       } else {
+               // SC_MULTIAUTOC_EACH
+               for (size_t r=0; r<sel.Count(); r++) {
+                       if (!RangeContainsProtected(sel.Range(r).Start().Position(),
+                               sel.Range(r).End().Position())) {
+                               Sci::Position positionInsert = sel.Range(r).Start().Position();
+                               positionInsert = RealizeVirtualSpace(positionInsert, 
sel.Range(r).caret.VirtualSpace());
+                               if (positionInsert - removeLen >= 0) {
+                                       positionInsert -= removeLen;
+                                       pdoc->DeleteChars(positionInsert, removeLen);
+                               }
+                               const Sci::Position lengthInserted = pdoc->InsertString(positionInsert, text, 
textLen);
+                               if (lengthInserted > 0) {
+                                       sel.Range(r).caret.SetPosition(positionInsert + lengthInserted);
+                                       sel.Range(r).anchor.SetPosition(positionInsert + lengthInserted);
+                               }
+                               sel.Range(r).ClearVirtualSpace();
+                       }
+               }
+       }
 }
 
 void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list) {
@@ -209,7 +242,7 @@ void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list) {
        if (ac.chooseSingle && (listType == 0)) {
                if (list && !strchr(list, ac.GetSeparator())) {
                        const char *typeSep = strchr(list, ac.GetTypesep());
-                       int lenInsert = typeSep ? 
+                       int lenInsert = typeSep ?
                                static_cast<int>(typeSep-list) : static_cast<int>(strlen(list));
                        if (ac.ignoreCase) {
                                // May need to convert the case before invocation, so remove lenEntered 
characters
@@ -233,7 +266,7 @@ void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list) {
        int heightLB = ac.heightLBDefault;
        int widthLB = ac.widthLBDefault;
        if (pt.x >= rcClient.right - widthLB) {
-               HorizontalScrollTo(xOffset + pt.x - rcClient.right + widthLB);
+               HorizontalScrollTo(static_cast<int>(xOffset + pt.x - rcClient.right + widthLB));
                Redraw();
                pt = PointMainCaret();
        }
@@ -244,36 +277,36 @@ void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list) {
        }
        PRectangle rcac;
        rcac.left = pt.x - ac.lb->CaretFromEdge();
-       if (pt.y >= rcPopupBounds.bottom - heightLB &&  // Wont fit below.
+       if (pt.y >= rcPopupBounds.bottom - heightLB &&  // Won't fit below.
                pt.y >= (rcPopupBounds.bottom + rcPopupBounds.top) / 2) { // and there is more room above.
                rcac.top = pt.y - heightLB;
                if (rcac.top < rcPopupBounds.top) {
-                       heightLB -= (rcPopupBounds.top - rcac.top);
+                       heightLB -= static_cast<int>(rcPopupBounds.top - rcac.top);
                        rcac.top = rcPopupBounds.top;
                }
        } else {
                rcac.top = pt.y + vs.lineHeight;
        }
        rcac.right = rcac.left + widthLB;
-       rcac.bottom = Platform::Minimum(rcac.top + heightLB, rcPopupBounds.bottom);
+       rcac.bottom = static_cast<XYPOSITION>(std::min(static_cast<int>(rcac.top) + heightLB, 
static_cast<int>(rcPopupBounds.bottom)));
        ac.lb->SetPositionRelative(rcac, wMain);
        ac.lb->SetFont(vs.styles[STYLE_DEFAULT].font);
-       unsigned int aveCharWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
+       unsigned int aveCharWidth = static_cast<unsigned int>(vs.styles[STYLE_DEFAULT].aveCharWidth);
        ac.lb->SetAverageCharWidth(aveCharWidth);
        ac.lb->SetDoubleClickAction(AutoCompleteDoubleClick, this);
 
-       ac.SetList(list);
+       ac.SetList(list ? list : "");
 
        // Fiddle the position of the list so it is right next to the target and wide enough for all its 
strings
        PRectangle rcList = ac.lb->GetDesiredRect();
-       int heightAlloced = rcList.bottom - rcList.top;
-       widthLB = Platform::Maximum(widthLB, rcList.right - rcList.left);
+       int heightAlloced = static_cast<int>(rcList.bottom - rcList.top);
+       widthLB = std::max(widthLB, static_cast<int>(rcList.right - rcList.left));
        if (maxListWidth != 0)
-               widthLB = Platform::Minimum(widthLB, aveCharWidth*maxListWidth);
+               widthLB = std::min(widthLB, static_cast<int>(aveCharWidth)*maxListWidth);
        // Make an allowance for large strings in list
        rcList.left = pt.x - ac.lb->CaretFromEdge();
        rcList.right = rcList.left + widthLB;
-       if (((pt.y + vs.lineHeight) >= (rcPopupBounds.bottom - heightAlloced)) &&  // Wont fit below.
+       if (((pt.y + vs.lineHeight) >= (rcPopupBounds.bottom - heightAlloced)) &&  // Won't fit below.
                ((pt.y + vs.lineHeight / 2) >= (rcPopupBounds.bottom + rcPopupBounds.top) / 2)) { // and 
there is more room above.
                rcList.top = pt.y - heightAlloced;
        } else {
@@ -289,7 +322,7 @@ void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list) {
 
 void ScintillaBase::AutoCompleteCancel() {
        if (ac.Active()) {
-               SCNotification scn = {0};
+               SCNotification scn = {};
                scn.nmhdr.code = SCN_AUTOCCANCELLED;
                scn.wParam = 0;
                scn.listType = 0;
@@ -309,7 +342,7 @@ void ScintillaBase::AutoCompleteMoveToCurrentWord() {
 
 void ScintillaBase::AutoCompleteCharacterAdded(char ch) {
        if (ac.IsFillUpChar(ch)) {
-               AutoCompleteCompleted();
+               AutoCompleteCompleted(ch, SC_AC_FILLUP);
        } else if (ac.IsStopChar(ch)) {
                AutoCompleteCancel();
        } else {
@@ -325,15 +358,15 @@ void ScintillaBase::AutoCompleteCharacterDeleted() {
        } else {
                AutoCompleteMoveToCurrentWord();
        }
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_AUTOCCHARDELETED;
        scn.wParam = 0;
        scn.listType = 0;
        NotifyParent(scn);
 }
 
-void ScintillaBase::AutoCompleteCompleted() {
-       int item = ac.GetSelection();
+void ScintillaBase::AutoCompleteCompleted(char ch, unsigned int completionMethod) {
+       const int item = ac.GetSelection();
        if (item == -1) {
                AutoCompleteCancel();
                return;
@@ -342,12 +375,14 @@ void ScintillaBase::AutoCompleteCompleted() {
 
        ac.Show(false);
 
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = listType > 0 ? SCN_USERLISTSELECTION : SCN_AUTOCSELECTION;
        scn.message = 0;
+       scn.ch = ch;
+       scn.listCompletionMethod = completionMethod;
        scn.wParam = listType;
        scn.listType = listType;
-       Position firstPos = ac.posStart - ac.startLen;
+       Sci::Position firstPos = ac.posStart - ac.startLen;
        scn.position = firstPos;
        scn.lParam = firstPos;
        scn.text = selected.c_str();
@@ -360,13 +395,17 @@ void ScintillaBase::AutoCompleteCompleted() {
        if (listType > 0)
                return;
 
-       Position endPos = sel.MainCaret();
+       Sci::Position endPos = sel.MainCaret();
        if (ac.dropRestOfWord)
                endPos = pdoc->ExtendWordSelect(endPos, 1, true);
        if (endPos < firstPos)
                return;
        AutoCompleteInsert(firstPos, endPos - firstPos, selected.c_str(), 
static_cast<int>(selected.length()));
        SetLastXChosen();
+
+       scn.nmhdr.code = SCN_AUTOCCOMPLETED;
+       NotifyParent(scn);
+
 }
 
 int ScintillaBase::AutoCompleteGetCurrent() const {
@@ -377,11 +416,11 @@ int ScintillaBase::AutoCompleteGetCurrent() const {
 
 int ScintillaBase::AutoCompleteGetCurrentText(char *buffer) const {
        if (ac.Active()) {
-               int item = ac.GetSelection();
+               const int item = ac.GetSelection();
                if (item != -1) {
                        const std::string selected = ac.GetValue(item);
                        if (buffer != NULL)
-                               strcpy(buffer, selected.c_str());
+                               memcpy(buffer, selected.c_str(), selected.length()+1);
                        return static_cast<int>(selected.length());
                }
        }
@@ -415,18 +454,18 @@ void ScintillaBase::CallTipShow(Point pt, const char *defn) {
                wMain);
        // If the call-tip window would be out of the client
        // space
-       PRectangle rcClient = GetClientRectangle();
-       int offset = vs.lineHeight + rc.Height();
-       // adjust so it displays below the text.
-       if (rc.top < rcClient.top) {
-               rc.top += offset;
-               rc.bottom += offset;
-       }
+       const PRectangle rcClient = GetClientRectangle();
+       int offset = vs.lineHeight + static_cast<int>(rc.Height());
        // adjust so it displays above the text.
-       if (rc.bottom > rcClient.bottom) {
+       if (rc.bottom > rcClient.bottom && rc.Height() < rcClient.Height()) {
                rc.top -= offset;
                rc.bottom -= offset;
        }
+       // adjust so it displays below the text.
+       if (rc.top < rcClient.top && rc.Height() < rcClient.Height()) {
+               rc.top += offset;
+               rc.bottom += offset;
+       }
        // Now display the window.
        CreateCallTipWindow(rc);
        ct.wCallTip.SetPositionRelative(rc, wMain);
@@ -434,15 +473,20 @@ void ScintillaBase::CallTipShow(Point pt, const char *defn) {
 }
 
 void ScintillaBase::CallTipClick() {
-       SCNotification scn = {0};
+       SCNotification scn = {};
        scn.nmhdr.code = SCN_CALLTIPCLICK;
        scn.position = ct.clickPlace;
        NotifyParent(scn);
 }
 
+bool ScintillaBase::ShouldDisplayPopup(Point ptInWindowCoordinates) const {
+       return (displayPopupMenu == SC_POPUP_ALL ||
+               (displayPopupMenu == SC_POPUP_TEXT && !PointInSelMargin(ptInWindowCoordinates)));
+}
+
 void ScintillaBase::ContextMenu(Point pt) {
        if (displayPopupMenu) {
-               bool writable = !WndProc(SCI_GETREADONLY, 0, 0);
+               const bool writable = !WndProc(SCI_GETREADONLY, 0, 0);
                popup.CreatePopUp();
                AddToPopUp("Undo", idcmdUndo, writable && pdoc->CanUndo());
                AddToPopUp("Redo", idcmdRedo, writable && pdoc->CanRedo());
@@ -463,9 +507,18 @@ void ScintillaBase::CancelModes() {
        Editor::CancelModes();
 }
 
+void ScintillaBase::ButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) {
+       CancelModes();
+       Editor::ButtonDownWithModifiers(pt, curTime, modifiers);
+}
+
 void ScintillaBase::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) {
+       ButtonDownWithModifiers(pt, curTime, ModifierFlags(shift, ctrl, alt));
+}
+
+void ScintillaBase::RightButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) {
        CancelModes();
-       Editor::ButtonDown(pt, curTime, shift, ctrl, alt);
+       Editor::RightButtonDownWithModifiers(pt, curTime, modifiers);
 }
 
 #ifdef SCI_LEXER
@@ -482,13 +535,12 @@ class LexState : public LexInterface {
 public:
        int lexLanguage;
 
-       LexState(Document *pdoc_);
-       virtual ~LexState();
+       explicit LexState(Document *pdoc_);
+       ~LexState() override;
        void SetLexer(uptr_t wParam);
        void SetLexerLanguage(const char *languageName);
        const char *DescribeWordListSets();
        void SetWordList(int n, const char *wl);
-       int GetStyleBitsNeeded() const;
        const char *GetName() const;
        void *PrivateCall(int operation, void *pointer);
        const char *PropertyNames();
@@ -503,6 +555,8 @@ public:
        int AllocateSubStyles(int styleBase, int numberStyles);
        int SubStylesStart(int styleBase);
        int SubStylesLength(int styleBase);
+       int StyleFromSubStyle(int subStyle);
+       int PrimaryStyleFromStyle(int style);
        void FreeSubStyles();
        void SetIdentifiers(int style, const char *identifiers);
        int DistanceToSecondaryStyles();
@@ -528,10 +582,10 @@ LexState::~LexState() {
 }
 
 LexState *ScintillaBase::DocumentLexState() {
-       if (!pdoc->pli) {
-               pdoc->pli = new LexState(pdoc);
+       if (!pdoc->GetLexInterface()) {
+               pdoc->SetLexInterface(new LexState(pdoc));
        }
-       return static_cast<LexState *>(pdoc->pli);
+       return static_cast<LexState *>(pdoc->GetLexInterface());
 }
 
 void LexState::SetLexerModule(const LexerModule *lex) {
@@ -551,7 +605,7 @@ void LexState::SetLexerModule(const LexerModule *lex) {
 }
 
 void LexState::SetLexer(uptr_t wParam) {
-       lexLanguage = wParam;
+       lexLanguage = static_cast<int>(wParam);
        if (lexLanguage == SCLEX_CONTAINER) {
                SetLexerModule(0);
        } else {
@@ -588,10 +642,6 @@ void LexState::SetWordList(int n, const char *wl) {
        }
 }
 
-int LexState::GetStyleBitsNeeded() const {
-       return lexCurrent ? lexCurrent->GetStyleBitsNeeded() : 5;
-}
-
 const char *LexState::GetName() const {
        return lexCurrent ? lexCurrent->languageName : "";
 }
@@ -678,6 +728,20 @@ int LexState::SubStylesLength(int styleBase) {
        return 0;
 }
 
+int LexState::StyleFromSubStyle(int subStyle) {
+       if (instance && (interfaceVersion >= lvSubStyles)) {
+               return static_cast<ILexerWithSubStyles *>(instance)->StyleFromSubStyle(subStyle);
+       }
+       return 0;
+}
+
+int LexState::PrimaryStyleFromStyle(int style) {
+       if (instance && (interfaceVersion >= lvSubStyles)) {
+               return static_cast<ILexerWithSubStyles *>(instance)->PrimaryStyleFromStyle(style);
+       }
+       return 0;
+}
+
 void LexState::FreeSubStyles() {
        if (instance && (interfaceVersion >= lvSubStyles)) {
                static_cast<ILexerWithSubStyles *>(instance)->FreeSubStyles();
@@ -687,6 +751,7 @@ void LexState::FreeSubStyles() {
 void LexState::SetIdentifiers(int style, const char *identifiers) {
        if (instance && (interfaceVersion >= lvSubStyles)) {
                static_cast<ILexerWithSubStyles *>(instance)->SetIdentifiers(style, identifiers);
+               pdoc->ModifiedAt(0);
        }
 }
 
@@ -706,11 +771,11 @@ const char *LexState::GetSubStyleBases() {
 
 #endif
 
-void ScintillaBase::NotifyStyleToNeeded(int endStyleNeeded) {
+void ScintillaBase::NotifyStyleToNeeded(Sci::Position endStyleNeeded) {
 #ifdef SCI_LEXER
        if (DocumentLexState()->lexLanguage != SCLEX_CONTAINER) {
-               int lineEndStyled = pdoc->LineFromPosition(pdoc->GetEndStyled());
-               int endStyled = pdoc->LineStart(lineEndStyled);
+               Sci::Line lineEndStyled = pdoc->LineFromPosition(pdoc->GetEndStyled());
+               Sci::Position endStyled = pdoc->LineStart(lineEndStyled);
                DocumentLexState()->Colourise(endStyled, endStyleNeeded);
                return;
        }
@@ -720,8 +785,7 @@ void ScintillaBase::NotifyStyleToNeeded(int endStyleNeeded) {
 
 void ScintillaBase::NotifyLexerChanged(Document *, void *) {
 #ifdef SCI_LEXER
-       int bits = DocumentLexState()->GetStyleBitsNeeded();
-       vs.EnsureStyle((1 << bits) - 1);
+       vs.EnsureStyle(0xff);
 #endif
 }
 
@@ -729,7 +793,7 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
        switch (iMessage) {
        case SCI_AUTOCSHOW:
                listType = 0;
-               AutoCompleteStart(wParam, reinterpret_cast<const char *>(lParam));
+               AutoCompleteStart(static_cast<int>(wParam), reinterpret_cast<const char *>(lParam));
                break;
 
        case SCI_AUTOCCANCEL:
@@ -743,7 +807,7 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                return ac.posStart;
 
        case SCI_AUTOCCOMPLETE:
-               AutoCompleteCompleted();
+               AutoCompleteCompleted(0, SC_AC_COMMAND);
                break;
 
        case SCI_AUTOCSETSEPARATOR:
@@ -793,21 +857,28 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                return ac.ignoreCase;
 
        case SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR:
-               ac.ignoreCaseBehaviour = wParam;
+               ac.ignoreCaseBehaviour = static_cast<unsigned int>(wParam);
                break;
 
        case SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR:
                return ac.ignoreCaseBehaviour;
 
+       case SCI_AUTOCSETMULTI:
+               multiAutoCMode = static_cast<int>(wParam);
+               break;
+
+       case SCI_AUTOCGETMULTI:
+               return multiAutoCMode;
+
        case SCI_AUTOCSETORDER:
-               ac.autoSort = wParam;
+               ac.autoSort = static_cast<int>(wParam);
                break;
 
        case SCI_AUTOCGETORDER:
                return ac.autoSort;
 
        case SCI_USERLISTSHOW:
-               listType = wParam;
+               listType = static_cast<int>(wParam);
                AutoCompleteStart(0, reinterpret_cast<const char *>(lParam));
                break;
 
@@ -826,25 +897,26 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                return ac.dropRestOfWord;
 
        case SCI_AUTOCSETMAXHEIGHT:
-               ac.lb->SetVisibleRows(wParam);
+               ac.lb->SetVisibleRows(static_cast<int>(wParam));
                break;
 
        case SCI_AUTOCGETMAXHEIGHT:
                return ac.lb->GetVisibleRows();
 
        case SCI_AUTOCSETMAXWIDTH:
-               maxListWidth = wParam;
+               maxListWidth = static_cast<int>(wParam);
                break;
 
        case SCI_AUTOCGETMAXWIDTH:
                return maxListWidth;
 
        case SCI_REGISTERIMAGE:
-               ac.lb->RegisterImage(wParam, reinterpret_cast<const char *>(lParam));
+               ac.lb->RegisterImage(static_cast<int>(wParam), reinterpret_cast<const char *>(lParam));
                break;
 
        case SCI_REGISTERRGBAIMAGE:
-               ac.lb->RegisterRGBAImage(wParam, sizeRGBAImage.x, sizeRGBAImage.y, reinterpret_cast<unsigned 
char *>(lParam));
+               ac.lb->RegisterRGBAImage(static_cast<int>(wParam), static_cast<int>(sizeRGBAImage.x), 
static_cast<int>(sizeRGBAImage.y),
+                       reinterpret_cast<unsigned char *>(lParam));
                break;
 
        case SCI_CLEARREGISTEREDIMAGES:
@@ -859,7 +931,7 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                return ac.GetTypesep();
 
        case SCI_CALLTIPSHOW:
-               CallTipShow(LocationFromPosition(wParam),
+               CallTipShow(LocationFromPosition(static_cast<int>(wParam)),
                        reinterpret_cast<const char *>(lParam));
                break;
 
@@ -873,29 +945,33 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
        case SCI_CALLTIPPOSSTART:
                return ct.posStartCallTip;
 
+       case SCI_CALLTIPSETPOSSTART:
+               ct.posStartCallTip = static_cast<int>(wParam);
+               break;
+
        case SCI_CALLTIPSETHLT:
-               ct.SetHighlight(wParam, lParam);
+               ct.SetHighlight(static_cast<int>(wParam), static_cast<int>(lParam));
                break;
 
        case SCI_CALLTIPSETBACK:
-               ct.colourBG = ColourDesired(wParam);
+               ct.colourBG = ColourDesired(static_cast<long>(wParam));
                vs.styles[STYLE_CALLTIP].back = ct.colourBG;
                InvalidateStyleRedraw();
                break;
 
        case SCI_CALLTIPSETFORE:
-               ct.colourUnSel = ColourDesired(wParam);
+               ct.colourUnSel = ColourDesired(static_cast<long>(wParam));
                vs.styles[STYLE_CALLTIP].fore = ct.colourUnSel;
                InvalidateStyleRedraw();
                break;
 
        case SCI_CALLTIPSETFOREHLT:
-               ct.colourSel = ColourDesired(wParam);
+               ct.colourSel = ColourDesired(static_cast<long>(wParam));
                InvalidateStyleRedraw();
                break;
 
        case SCI_CALLTIPUSESTYLE:
-               ct.SetTabSize((int)wParam);
+               ct.SetTabSize(static_cast<int>(wParam));
                InvalidateStyleRedraw();
                break;
 
@@ -905,12 +981,12 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                break;
 
        case SCI_USEPOPUP:
-               displayPopupMenu = wParam != 0;
+               displayPopupMenu = static_cast<int>(wParam);
                break;
 
 #ifdef SCI_LEXER
        case SCI_SETLEXER:
-               DocumentLexState()->SetLexer(wParam);
+               DocumentLexState()->SetLexer(static_cast<int>(wParam));
                break;
 
        case SCI_GETLEXER:
@@ -918,10 +994,10 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
 
        case SCI_COLOURISE:
                if (DocumentLexState()->lexLanguage == SCLEX_CONTAINER) {
-                       pdoc->ModifiedAt(wParam);
-                       NotifyStyleToNeeded((lParam == -1) ? pdoc->Length() : lParam);
+                       pdoc->ModifiedAt(static_cast<Sci::Position>(wParam));
+                       NotifyStyleToNeeded((lParam == -1) ? pdoc->Length() : 
static_cast<Sci::Position>(lParam));
                } else {
-                       DocumentLexState()->Colourise(wParam, lParam);
+                       DocumentLexState()->Colourise(static_cast<Sci::Position>(wParam), 
static_cast<Sci::Position>(lParam));
                }
                Redraw();
                break;
@@ -939,10 +1015,10 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                        reinterpret_cast<char *>(lParam));
 
        case SCI_GETPROPERTYINT:
-               return DocumentLexState()->PropGetInt(reinterpret_cast<const char *>(wParam), lParam);
+               return DocumentLexState()->PropGetInt(reinterpret_cast<const char *>(wParam), 
static_cast<int>(lParam));
 
        case SCI_SETKEYWORDS:
-               DocumentLexState()->SetWordList(wParam, reinterpret_cast<const char *>(lParam));
+               DocumentLexState()->SetWordList(static_cast<int>(wParam), reinterpret_cast<const char 
*>(lParam));
                break;
 
        case SCI_SETLEXERLANGUAGE:
@@ -954,10 +1030,10 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
 
        case SCI_PRIVATELEXERCALL:
                return reinterpret_cast<sptr_t>(
-                       DocumentLexState()->PrivateCall(wParam, reinterpret_cast<void *>(lParam)));
+                       DocumentLexState()->PrivateCall(static_cast<int>(wParam), reinterpret_cast<void 
*>(lParam)));
 
        case SCI_GETSTYLEBITSNEEDED:
-               return DocumentLexState()->GetStyleBitsNeeded();
+               return 8;
 
        case SCI_PROPERTYNAMES:
                return StringResult(lParam, DocumentLexState()->PropertyNames());
@@ -966,7 +1042,8 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                return DocumentLexState()->PropertyType(reinterpret_cast<const char *>(wParam));
 
        case SCI_DESCRIBEPROPERTY:
-               return StringResult(lParam, DocumentLexState()->DescribeProperty(reinterpret_cast<const char 
*>(wParam)));
+               return StringResult(lParam,
+                                   DocumentLexState()->DescribeProperty(reinterpret_cast<const char 
*>(wParam)));
 
        case SCI_DESCRIBEKEYWORDSETS:
                return StringResult(lParam, DocumentLexState()->DescribeWordListSets());
@@ -975,20 +1052,27 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
                return DocumentLexState()->LineEndTypesSupported();
 
        case SCI_ALLOCATESUBSTYLES:
-               return DocumentLexState()->AllocateSubStyles(wParam, lParam);
+               return DocumentLexState()->AllocateSubStyles(static_cast<int>(wParam), 
static_cast<int>(lParam));
 
        case SCI_GETSUBSTYLESSTART:
-               return DocumentLexState()->SubStylesStart(wParam);
+               return DocumentLexState()->SubStylesStart(static_cast<int>(wParam));
 
        case SCI_GETSUBSTYLESLENGTH:
-               return DocumentLexState()->SubStylesLength(wParam);
+               return DocumentLexState()->SubStylesLength(static_cast<int>(wParam));
+
+       case SCI_GETSTYLEFROMSUBSTYLE:
+               return DocumentLexState()->StyleFromSubStyle(static_cast<int>(wParam));
+
+       case SCI_GETPRIMARYSTYLEFROMSTYLE:
+               return DocumentLexState()->PrimaryStyleFromStyle(static_cast<int>(wParam));
 
        case SCI_FREESUBSTYLES:
                DocumentLexState()->FreeSubStyles();
                break;
 
        case SCI_SETIDENTIFIERS:
-               DocumentLexState()->SetIdentifiers(wParam, reinterpret_cast<const char *>(lParam));
+               DocumentLexState()->SetIdentifiers(static_cast<int>(wParam),
+                                                  reinterpret_cast<const char *>(lParam));
                break;
 
        case SCI_DISTANCETOSECONDARYSTYLES:
diff --git a/plugins/scintilla/scintilla/src/ScintillaBase.h b/plugins/scintilla/scintilla/src/ScintillaBase.h
index 9576139..cd8a1f5 100644
--- a/plugins/scintilla/scintilla/src/ScintillaBase.h
+++ b/plugins/scintilla/scintilla/src/ScintillaBase.h
@@ -19,10 +19,6 @@ class LexState;
 /**
  */
 class ScintillaBase : public Editor {
-       // Private so ScintillaBase objects can not be copied
-       ScintillaBase(const ScintillaBase &);
-       ScintillaBase &operator=(const ScintillaBase &);
-
 protected:
        /** Enumeration of commands and child windows. */
        enum {
@@ -38,7 +34,9 @@ protected:
                idcmdSelectAll=16
        };
 
-       bool displayPopupMenu;
+       enum { maxLenInputIME = 200 };
+
+       int displayPopupMenu;
        Menu popup;
        AutoComplete ac;
 
@@ -46,6 +44,7 @@ protected:
 
        int listType;                   ///< 0 is an autocomplete list
        int maxListWidth;               /// Maximum width of list, in average character widths
+       int multiAutoCMode; /// Mode for autocompleting when multiple selections are present
 
 #ifdef SCI_LEXER
        LexState *DocumentLexState();
@@ -55,16 +54,19 @@ protected:
 #endif
 
        ScintillaBase();
+       // Deleted so ScintillaBase objects can not be copied.
+       explicit ScintillaBase(const ScintillaBase &) = delete;
+       ScintillaBase &operator=(const ScintillaBase &) = delete;
        virtual ~ScintillaBase();
-       virtual void Initialise() = 0;
-       virtual void Finalise() = 0;
+       void Initialise() override {}
+       void Finalise() override;
 
-       virtual void AddCharUTF(char *s, unsigned int len, bool treatAsDBCS=false);
+       void AddCharUTF(const char *s, unsigned int len, bool treatAsDBCS=false) override;
        void Command(int cmdId);
-       virtual void CancelModes();
-       virtual int KeyCommand(unsigned int iMessage);
+       void CancelModes() override;
+       int KeyCommand(unsigned int iMessage) override;
 
-       void AutoCompleteInsert(Position startPos, int removeLen, const char *text, int textLen);
+       void AutoCompleteInsert(Sci::Position startPos, int removeLen, const char *text, int textLen);
        void AutoCompleteStart(int lenEntered, const char *list);
        void AutoCompleteCancel();
        void AutoCompleteMove(int delta);
@@ -72,7 +74,7 @@ protected:
        int AutoCompleteGetCurrentText(char *buffer) const;
        void AutoCompleteCharacterAdded(char ch);
        void AutoCompleteCharacterDeleted();
-       void AutoCompleteCompleted();
+       void AutoCompleteCompleted(char ch, unsigned int completionMethod);
        void AutoCompleteMoveToCurrentWord();
        static void AutoCompleteDoubleClick(void *p);
 
@@ -81,16 +83,19 @@ protected:
        virtual void CreateCallTipWindow(PRectangle rc) = 0;
 
        virtual void AddToPopUp(const char *label, int cmd=0, bool enabled=true) = 0;
+       bool ShouldDisplayPopup(Point ptInWindowCoordinates) const;
        void ContextMenu(Point pt);
 
-       virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt);
+       void ButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) override;
+       void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) override;
+       void RightButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) override;
 
-       void NotifyStyleToNeeded(int endStyleNeeded);
-       void NotifyLexerChanged(Document *doc, void *userData);
+       void NotifyStyleToNeeded(Sci::Position endStyleNeeded) override;
+       void NotifyLexerChanged(Document *doc, void *userData) override;
 
 public:
        // Public so scintilla_send_message can use it
-       virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
+       sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) override;
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/Selection.cxx b/plugins/scintilla/scintilla/src/Selection.cxx
index 385e236..fe81cdf 100644
--- a/plugins/scintilla/scintilla/src/Selection.cxx
+++ b/plugins/scintilla/scintilla/src/Selection.cxx
@@ -5,8 +5,9 @@
 // Copyright 2009 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
+#include <cstdlib>
 
+#include <stdexcept>
 #include <vector>
 #include <algorithm>
 
@@ -14,16 +15,17 @@
 
 #include "Scintilla.h"
 
+#include "Position.h"
 #include "Selection.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
 #endif
 
-void SelectionPosition::MoveForInsertDelete(bool insertion, int startChange, int length) {
+void SelectionPosition::MoveForInsertDelete(bool insertion, Sci::Position startChange, Sci::Position length) 
{
        if (insertion) {
                if (position == startChange) {
-                       int virtualLengthRemove = std::min(length, virtualSpace);
+                       Sci::Position virtualLengthRemove = std::min(length, virtualSpace);
                        virtualSpace -= virtualLengthRemove;
                        position += virtualLengthRemove;
                } else if (position > startChange) {
@@ -34,7 +36,7 @@ void SelectionPosition::MoveForInsertDelete(bool insertion, int startChange, int
                        virtualSpace = 0;
                }
                if (position > startChange) {
-                       int endDeletion = startChange + length;
+                       const Sci::Position endDeletion = startChange + length;
                        if (position > endDeletion) {
                                position -= length;
                        } else {
@@ -73,7 +75,7 @@ bool SelectionPosition::operator >=(const SelectionPosition &other) const {
                return *this > other;
 }
 
-int SelectionRange::Length() const {
+Sci::Position SelectionRange::Length() const {
        if (anchor > caret) {
                return anchor.Position() - caret.Position();
        } else {
@@ -81,7 +83,12 @@ int SelectionRange::Length() const {
        }
 }
 
-bool SelectionRange::Contains(int pos) const {
+void SelectionRange::MoveForInsertDelete(bool insertion, Sci::Position startChange, Sci::Position length) {
+       caret.MoveForInsertDelete(insertion, startChange, length);
+       anchor.MoveForInsertDelete(insertion, startChange, length);
+}
+
+bool SelectionRange::Contains(Sci::Position pos) const {
        if (anchor > caret)
                return (pos >= caret.Position()) && (pos <= anchor.Position());
        else
@@ -95,7 +102,7 @@ bool SelectionRange::Contains(SelectionPosition sp) const {
                return (sp >= anchor) && (sp <= caret);
 }
 
-bool SelectionRange::ContainsCharacter(int posCharacter) const {
+bool SelectionRange::ContainsCharacter(Sci::Position posCharacter) const {
        if (anchor > caret)
                return (posCharacter >= caret.Position()) && (posCharacter < anchor.Position());
        else
@@ -119,9 +126,13 @@ SelectionSegment SelectionRange::Intersect(SelectionSegment check) const {
        }
 }
 
+void SelectionRange::Swap() {
+       std::swap(caret, anchor);
+}
+
 bool SelectionRange::Trim(SelectionRange range) {
-       SelectionPosition startRange = range.Start();
-       SelectionPosition endRange = range.End();
+       const SelectionPosition startRange = range.Start();
+       const SelectionPosition endRange = range.End();
        SelectionPosition start = Start();
        SelectionPosition end = End();
        PLATFORM_ASSERT(start <= end);
@@ -157,7 +168,7 @@ bool SelectionRange::Trim(SelectionRange range) {
 // If range is all virtual collapse to start of virtual space
 void SelectionRange::MinimizeVirtualSpace() {
        if (caret.Position() == anchor.Position()) {
-               int virtualSpace = caret.VirtualSpace();
+               Sci::Position virtualSpace = caret.VirtualSpace();
                if (virtualSpace > anchor.VirtualSpace())
                        virtualSpace = anchor.VirtualSpace();
                caret.SetVirtualSpace(virtualSpace);
@@ -166,7 +177,7 @@ void SelectionRange::MinimizeVirtualSpace() {
 }
 
 Selection::Selection() : mainRange(0), moveExtends(false), tentativeMain(false), selType(selStream) {
-       AddSelection(SelectionPosition(0));
+       AddSelection(SelectionRange(SelectionPosition(0)));
 }
 
 Selection::~Selection() {
@@ -176,11 +187,11 @@ bool Selection::IsRectangular() const {
        return (selType == selRectangle) || (selType == selThin);
 }
 
-int Selection::MainCaret() const {
+Sci::Position Selection::MainCaret() const {
        return ranges[mainRange].caret.Position();
 }
 
-int Selection::MainAnchor() const {
+Sci::Position Selection::MainAnchor() const {
        return ranges[mainRange].anchor.Position();
 }
 
@@ -226,10 +237,26 @@ SelectionRange &Selection::Range(size_t r) {
        return ranges[r];
 }
 
+const SelectionRange &Selection::Range(size_t r) const {
+       return ranges[r];
+}
+
 SelectionRange &Selection::RangeMain() {
        return ranges[mainRange];
 }
 
+const SelectionRange &Selection::RangeMain() const {
+       return ranges[mainRange];
+}
+
+SelectionPosition Selection::Start() const {
+       if (IsRectangular()) {
+               return rangeRectangular.Start();
+       } else {
+               return ranges[mainRange].Start();
+       }
+}
+
 bool Selection::MoveExtends() const {
        return moveExtends;
 }
@@ -239,8 +266,8 @@ void Selection::SetMoveExtends(bool moveExtends_) {
 }
 
 bool Selection::Empty() const {
-       for (size_t i=0; i<ranges.size(); i++) {
-               if (!ranges[i].Empty())
+       for (const SelectionRange &range : ranges) {
+               if (!range.Empty())
                        return false;
        }
        return true;
@@ -248,28 +275,30 @@ bool Selection::Empty() const {
 
 SelectionPosition Selection::Last() const {
        SelectionPosition lastPosition;
-       for (size_t i=0; i<ranges.size(); i++) {
-               if (lastPosition < ranges[i].caret)
-                       lastPosition = ranges[i].caret;
-               if (lastPosition < ranges[i].anchor)
-                       lastPosition = ranges[i].anchor;
+       for (const SelectionRange &range : ranges) {
+               if (lastPosition < range.caret)
+                       lastPosition = range.caret;
+               if (lastPosition < range.anchor)
+                       lastPosition = range.anchor;
        }
        return lastPosition;
 }
 
-int Selection::Length() const {
-       int len = 0;
-       for (size_t i=0; i<ranges.size(); i++) {
-               len += ranges[i].Length();
+Sci::Position Selection::Length() const {
+       Sci::Position len = 0;
+       for (const SelectionRange &range : ranges) {
+               len += range.Length();
        }
        return len;
 }
 
-void Selection::MovePositions(bool insertion, int startChange, int length) {
-       for (size_t i=0; i<ranges.size(); i++) {
-               ranges[i].caret.MoveForInsertDelete(insertion, startChange, length);
-               ranges[i].anchor.MoveForInsertDelete(insertion, startChange, length);
+void Selection::MovePositions(bool insertion, Sci::Position startChange, Sci::Position length) {
+       for (SelectionRange &range : ranges) {
+               range.MoveForInsertDelete(insertion, startChange, length);
        }
+       if (selType == selRectangle) {
+               rangeRectangular.MoveForInsertDelete(insertion, startChange, length);
+       } 
 }
 
 void Selection::TrimSelection(SelectionRange range) {
@@ -288,6 +317,14 @@ void Selection::TrimSelection(SelectionRange range) {
        }
 }
 
+void Selection::TrimOtherSelections(size_t r, SelectionRange range) {
+       for (size_t i = 0; i<ranges.size(); ++i) {
+               if (i != r) {
+                       ranges[i].Trim(range);
+               }
+       }
+}
+
 void Selection::SetSelection(SelectionRange range) {
        ranges.clear();
        ranges.push_back(range);
@@ -305,6 +342,25 @@ void Selection::AddSelectionWithoutTrim(SelectionRange range) {
        mainRange = ranges.size() - 1;
 }
 
+void Selection::DropSelection(size_t r) {
+       if ((ranges.size() > 1) && (r < ranges.size())) {
+               size_t mainNew = mainRange;
+               if (mainNew >= r) {
+                       if (mainNew == 0) {
+                               mainNew = ranges.size() - 2;
+                       } else {
+                               mainNew--;
+                       }
+               }
+               ranges.erase(ranges.begin() + r);
+               mainRange = mainNew;
+       }
+}
+
+void Selection::DropAdditionalRanges() {
+       SetSelection(RangeMain());
+}
+
 void Selection::TentativeSelection(SelectionRange range) {
        if (!tentativeMain) {
                rangesSaved = ranges;
@@ -320,7 +376,7 @@ void Selection::CommitTentative() {
        tentativeMain = false;
 }
 
-int Selection::CharacterInSelection(int posCharacter) const {
+int Selection::CharacterInSelection(Sci::Position posCharacter) const {
        for (size_t i=0; i<ranges.size(); i++) {
                if (ranges[i].ContainsCharacter(posCharacter))
                        return i == mainRange ? 1 : 2;
@@ -328,7 +384,7 @@ int Selection::CharacterInSelection(int posCharacter) const {
        return 0;
 }
 
-int Selection::InSelectionForEOL(int pos) const {
+int Selection::InSelectionForEOL(Sci::Position pos) const {
        for (size_t i=0; i<ranges.size(); i++) {
                if (!ranges[i].Empty() && (pos > ranges[i].Start().Position()) && (pos <= 
ranges[i].End().Position()))
                        return i == mainRange ? 1 : 2;
@@ -336,13 +392,13 @@ int Selection::InSelectionForEOL(int pos) const {
        return 0;
 }
 
-int Selection::VirtualSpaceFor(int pos) const {
-       int virtualSpace = 0;
-       for (size_t i=0; i<ranges.size(); i++) {
-               if ((ranges[i].caret.Position() == pos) && (virtualSpace < ranges[i].caret.VirtualSpace()))
-                       virtualSpace = ranges[i].caret.VirtualSpace();
-               if ((ranges[i].anchor.Position() == pos) && (virtualSpace < ranges[i].anchor.VirtualSpace()))
-                       virtualSpace = ranges[i].anchor.VirtualSpace();
+Sci::Position Selection::VirtualSpaceFor(Sci::Position pos) const {
+       Sci::Position virtualSpace = 0;
+       for (const SelectionRange &range : ranges) {
+               if ((range.caret.Position() == pos) && (virtualSpace < range.caret.VirtualSpace()))
+                       virtualSpace = range.caret.VirtualSpace();
+               if ((range.anchor.Position() == pos) && (virtualSpace < range.anchor.VirtualSpace()))
+                       virtualSpace = range.anchor.VirtualSpace();
        }
        return virtualSpace;
 }
diff --git a/plugins/scintilla/scintilla/src/Selection.h b/plugins/scintilla/scintilla/src/Selection.h
index d7c7d79..991864e 100644
--- a/plugins/scintilla/scintilla/src/Selection.h
+++ b/plugins/scintilla/scintilla/src/Selection.h
@@ -13,10 +13,10 @@ namespace Scintilla {
 #endif
 
 class SelectionPosition {
-       int position;
-       int virtualSpace;
+       Sci::Position position;
+       Sci::Position virtualSpace;
 public:
-       explicit SelectionPosition(int position_=INVALID_POSITION, int virtualSpace_=0) : 
position(position_), virtualSpace(virtualSpace_) {
+       explicit SelectionPosition(Sci::Position position_=INVALID_POSITION, Sci::Position virtualSpace_=0) : 
position(position_), virtualSpace(virtualSpace_) {
                PLATFORM_ASSERT(virtualSpace < 800000);
                if (virtualSpace < 0)
                        virtualSpace = 0;
@@ -25,7 +25,7 @@ public:
                position = 0;
                virtualSpace = 0;
        }
-       void MoveForInsertDelete(bool insertion, int startChange, int length);
+       void MoveForInsertDelete(bool insertion, Sci::Position startChange, Sci::Position length);
        bool operator ==(const SelectionPosition &other) const {
                return position == other.position && virtualSpace == other.virtualSpace;
        }
@@ -33,22 +33,22 @@ public:
        bool operator >(const SelectionPosition &other) const;
        bool operator <=(const SelectionPosition &other) const;
        bool operator >=(const SelectionPosition &other) const;
-       int Position() const {
+       Sci::Position Position() const {
                return position;
        }
-       void SetPosition(int position_) {
+       void SetPosition(Sci::Position position_) {
                position = position_;
                virtualSpace = 0;
        }
-       int VirtualSpace() const {
+       Sci::Position VirtualSpace() const {
                return virtualSpace;
        }
-       void SetVirtualSpace(int virtualSpace_) {
+       void SetVirtualSpace(Sci::Position virtualSpace_) {
                PLATFORM_ASSERT(virtualSpace_ < 800000);
                if (virtualSpace_ >= 0)
                        virtualSpace = virtualSpace_;
        }
-       void Add(int increment) {
+       void Add(Sci::Position increment) {
                position = position + increment;
        }
        bool IsValid() const {
@@ -88,19 +88,19 @@ struct SelectionRange {
 
        SelectionRange() : caret(), anchor() {
        }
-       SelectionRange(SelectionPosition single) : caret(single), anchor(single) {
+       explicit SelectionRange(SelectionPosition single) : caret(single), anchor(single) {
        }
-       SelectionRange(int single) : caret(single), anchor(single) {
+       explicit SelectionRange(Sci::Position single) : caret(single), anchor(single) {
        }
        SelectionRange(SelectionPosition caret_, SelectionPosition anchor_) : caret(caret_), anchor(anchor_) {
        }
-       SelectionRange(int caret_, int anchor_) : caret(caret_), anchor(anchor_) {
+       SelectionRange(Sci::Position caret_, Sci::Position anchor_) : caret(caret_), anchor(anchor_) {
        }
        bool Empty() const {
                return anchor == caret;
        }
-       int Length() const;
-       // int Width() const;   // Like Length but takes virtual space into account
+       Sci::Position Length() const;
+       // Sci::Position Width() const; // Like Length but takes virtual space into account
        bool operator ==(const SelectionRange &other) const {
                return caret == other.caret && anchor == other.anchor;
        }
@@ -115,9 +115,10 @@ struct SelectionRange {
                anchor.SetVirtualSpace(0);
                caret.SetVirtualSpace(0);
        }
-       bool Contains(int pos) const;
+       void MoveForInsertDelete(bool insertion, Sci::Position startChange, Sci::Position length);
+       bool Contains(Sci::Position pos) const;
        bool Contains(SelectionPosition sp) const;
-       bool ContainsCharacter(int posCharacter) const;
+       bool ContainsCharacter(Sci::Position posCharacter) const;
        SelectionSegment Intersect(SelectionSegment check) const;
        SelectionPosition Start() const {
                return (anchor < caret) ? anchor : caret;
@@ -125,6 +126,7 @@ struct SelectionRange {
        SelectionPosition End() const {
                return (anchor < caret) ? caret : anchor;
        }
+       void Swap();
        bool Trim(SelectionRange range);
        // If range is all virtual collapse to start of virtual space
        void MinimizeVirtualSpace();
@@ -144,8 +146,8 @@ public:
        Selection();
        ~Selection();
        bool IsRectangular() const;
-       int MainCaret() const;
-       int MainAnchor() const;
+       Sci::Position MainCaret() const;
+       Sci::Position MainAnchor() const;
        SelectionRange &Rectangular();
        SelectionSegment Limits() const;
        // This is for when you want to move the caret in response to a
@@ -156,22 +158,28 @@ public:
        size_t Main() const;
        void SetMain(size_t r);
        SelectionRange &Range(size_t r);
+       const SelectionRange &Range(size_t r) const;
        SelectionRange &RangeMain();
+       const SelectionRange &RangeMain() const;
+       SelectionPosition Start() const;
        bool MoveExtends() const;
        void SetMoveExtends(bool moveExtends_);
        bool Empty() const;
        SelectionPosition Last() const;
-       int Length() const;
-       void MovePositions(bool insertion, int startChange, int length);
+       Sci::Position Length() const;
+       void MovePositions(bool insertion, Sci::Position startChange, Sci::Position length);
        void TrimSelection(SelectionRange range);
+       void TrimOtherSelections(size_t r, SelectionRange range);
        void SetSelection(SelectionRange range);
        void AddSelection(SelectionRange range);
        void AddSelectionWithoutTrim(SelectionRange range);
+       void DropSelection(size_t r);
+       void DropAdditionalRanges();
        void TentativeSelection(SelectionRange range);
        void CommitTentative();
-       int CharacterInSelection(int posCharacter) const;
-       int InSelectionForEOL(int pos) const;
-       int VirtualSpaceFor(int pos) const;
+       int CharacterInSelection(Sci::Position posCharacter) const;
+       int InSelectionForEOL(Sci::Position pos) const;
+       Sci::Position VirtualSpaceFor(Sci::Position pos) const;
        void Clear();
        void RemoveDuplicates();
        void RotateMain();
diff --git a/plugins/scintilla/scintilla/src/SparseVector.h b/plugins/scintilla/scintilla/src/SparseVector.h
new file mode 100644
index 0000000..230871c
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/SparseVector.h
@@ -0,0 +1,158 @@
+// Scintilla source code edit control
+/** @file SparseVector.h
+ ** Hold data sparsely associated with elements in a range.
+ **/
+// Copyright 2016 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef SPARSEVECTOR_H
+#define SPARSEVECTOR_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+// SparseVector is similar to RunStyles but is more efficient for cases where values occur
+// for one position instead of over a range of positions.
+template <typename T>
+class SparseVector {
+private:
+       std::unique_ptr<Partitioning> starts;
+       std::unique_ptr<SplitVector<T>> values;
+       T empty;
+       // Deleted so SparseVector objects can not be copied.
+       SparseVector(const SparseVector &) = delete;
+       void operator=(const SparseVector &) = delete;
+       void ClearValue(int partition) {
+               values->SetValueAt(partition, T());
+       }
+public:
+       SparseVector() : empty() {
+               starts.reset(new Partitioning(8));
+               values.reset(new SplitVector<T>());
+               values->InsertEmpty(0, 2);
+       }
+       ~SparseVector() {
+               starts.reset();
+               // starts dead here but not used by ClearValue.
+               for (int part = 0; part < values->Length(); part++) {
+                       ClearValue(part);
+               }
+               values.reset();
+       }
+       int Length() const {
+               return starts->PositionFromPartition(starts->Partitions());
+       }
+       int Elements() const {
+               return starts->Partitions();
+       }
+       int PositionOfElement(int element) const {
+               return starts->PositionFromPartition(element);
+       }
+       const T& ValueAt(int position) const {
+               assert(position < Length());
+               const int partition = starts->PartitionFromPosition(position);
+               const int startPartition = starts->PositionFromPartition(partition);
+               if (startPartition == position) {
+                       return values->ValueAt(partition);
+               } else {
+                       return empty;
+               }
+       }
+       template <typename ParamType>
+       void SetValueAt(int position, ParamType &&value) {
+               assert(position < Length());
+               const int partition = starts->PartitionFromPosition(position);
+               const int startPartition = starts->PositionFromPartition(partition);
+               if (value == T()) {
+                       // Setting the empty value is equivalent to deleting the position
+                       if (position == 0) {
+                               ClearValue(partition);
+                       } else if (position == startPartition) {
+                               // Currently an element at this position, so remove
+                               ClearValue(partition);
+                               starts->RemovePartition(partition);
+                               values->Delete(partition);
+                       }
+                       // Else element remains empty
+               } else {
+                       if (position == startPartition) {
+                               // Already a value at this position, so replace
+                               ClearValue(partition);
+                               values->SetValueAt(partition, std::move(value));
+                       } else {
+                               // Insert a new element
+                               starts->InsertPartition(partition + 1, position);
+                               values->Insert(partition + 1, std::move(value));
+                       }
+               }
+       }
+       void InsertSpace(int position, int insertLength) {
+               assert(position <= Length());   // Only operation that works at end.
+               const int partition = starts->PartitionFromPosition(position);
+               const int startPartition = starts->PositionFromPartition(partition);
+               if (startPartition == position) {
+                       const bool positionOccupied = values->ValueAt(partition) != T();
+                       // Inserting at start of run so make previous longer
+                       if (partition == 0) {
+                               // Inserting at start of document so ensure start empty
+                               if (positionOccupied) {
+                                       starts->InsertPartition(1, 0);
+                                       values->InsertEmpty(0, 1);
+                               }
+                               starts->InsertText(partition, insertLength);
+                       } else {
+                               if (positionOccupied) {
+                                       starts->InsertText(partition - 1, insertLength);
+                               } else {
+                                       // Insert at end of run so do not extend style
+                                       starts->InsertText(partition, insertLength);
+                               }
+                       }
+               } else {
+                       starts->InsertText(partition, insertLength);
+               }
+       }
+       void DeletePosition(int position) {
+               assert(position < Length());
+               int partition = starts->PartitionFromPosition(position);
+               const int startPartition = starts->PositionFromPartition(partition);
+               if (startPartition == position) {
+                       if (partition == 0) {
+                               ClearValue(0);
+                       } else if (partition == starts->Partitions()) {
+                               // This should not be possible
+                               ClearValue(partition);
+                               throw std::runtime_error("SparseVector: deleting end partition.");
+                       } else {
+                               ClearValue(partition);
+                               starts->RemovePartition(partition);
+                               values->Delete(partition);
+                               // Its the previous partition now that gets smaller 
+                               partition--;
+                       }
+               }
+               starts->InsertText(partition, -1);
+       }
+       void Check() const {
+               if (Length() < 0) {
+                       throw std::runtime_error("SparseVector: Length can not be negative.");
+               }
+               if (starts->Partitions() < 1) {
+                       throw std::runtime_error("SparseVector: Must always have 1 or more partitions.");
+               }
+               if (starts->Partitions() != values->Length() - 1) {
+                       throw std::runtime_error("SparseVector: Partitions and values different lengths.");
+               }
+               // The final element can not be set
+               if (values->ValueAt(values->Length() - 1) != T()) {
+                       throw std::runtime_error("SparseVector: Unused style at end changed.");
+               }
+       }
+};
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/SplitVector.h b/plugins/scintilla/scintilla/src/SplitVector.h
index 502101b..6b839b2 100644
--- a/plugins/scintilla/scintilla/src/SplitVector.h
+++ b/plugins/scintilla/scintilla/src/SplitVector.h
@@ -9,14 +9,18 @@
 #ifndef SPLITVECTOR_H
 #define SPLITVECTOR_H
 
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
 template <typename T>
 class SplitVector {
 protected:
-       T *body;
-       int size;
+       std::vector<T> body;
+       T empty;        /// Returned as the result of out-of-bounds access.
        int lengthBody;
        int part1Length;
-       int gapLength;  /// invariant: gapLength == size - lengthBody
+       int gapLength;  /// invariant: gapLength == body.size() - lengthBody
        int growSize;
 
        /// Move the gap to a particular position so that insertion and
@@ -25,15 +29,17 @@ protected:
        void GapTo(int position) {
                if (position != part1Length) {
                        if (position < part1Length) {
-                               memmove(
-                                       body + position + gapLength,
-                                       body + position,
-                                       sizeof(T) * (part1Length - position));
+                               // Moving the gap towards start so moving elements towards end
+                               std::move_backward(
+                                       body.data() + position,
+                                       body.data() + part1Length,
+                                       body.data() + gapLength + part1Length);
                        } else {        // position > part1Length
-                               memmove(
-                                       body + part1Length,
-                                       body + part1Length + gapLength,
-                                       sizeof(T) * (position - part1Length));
+                               // Moving the gap towards end so moving elements towards start
+                               std::move(
+                                       body.data() + part1Length + gapLength,
+                                       body.data() + gapLength + position,
+                                       body.data() + part1Length);
                        }
                        part1Length = position;
                }
@@ -43,16 +49,16 @@ protected:
        /// reallocating if more space needed.
        void RoomFor(int insertionLength) {
                if (gapLength <= insertionLength) {
-                       while (growSize < size / 6)
+                       while (growSize < static_cast<int>(body.size() / 6))
                                growSize *= 2;
-                       ReAllocate(size + insertionLength + growSize);
+                       ReAllocate(static_cast<int>(body.size()) + insertionLength + growSize);
                }
        }
 
        void Init() {
-               body = NULL;
+               body.clear();
+               body.shrink_to_fit();
                growSize = 8;
-               size = 0;
                lengthBody = 0;
                part1Length = 0;
                gapLength = 0;
@@ -60,13 +66,15 @@ protected:
 
 public:
        /// Construct a split buffer.
-       SplitVector() {
+       SplitVector() : empty() {
                Init();
        }
 
+       // Deleted so SplitVector objects can not be copied.
+       SplitVector(const SplitVector &) = delete;
+       void operator=(const SplitVector &) = delete;
+
        ~SplitVector() {
-               delete []body;
-               body = 0;
        }
 
        int GetGrowSize() const {
@@ -81,61 +89,76 @@ public:
        /// copy exisiting contents to the new buffer.
        /// Must not be used to decrease the size of the buffer.
        void ReAllocate(int newSize) {
-               if (newSize > size) {
+               if (newSize < 0)
+                       throw std::runtime_error("SplitVector::ReAllocate: negative size.");
+
+               if (newSize > static_cast<int>(body.size())) {
                        // Move the gap to the end
                        GapTo(lengthBody);
-                       T *newBody = new T[newSize];
-                       if ((size != 0) && (body != 0)) {
-                               memmove(newBody, body, sizeof(T) * lengthBody);
-                               delete []body;
-                       }
-                       body = newBody;
-                       gapLength += newSize - size;
-                       size = newSize;
+                       gapLength += newSize - static_cast<int>(body.size());
+                       // RoomFor implements a growth strategy but so does vector::resize so
+                       // ensure vector::resize allocates exactly the amount wanted by
+                       // calling reserve first.
+                       body.reserve(newSize);
+                       body.resize(newSize);
                }
        }
 
-       /// Retrieve the character at a particular position.
-       /// Retrieving positions outside the range of the buffer returns 0.
-       /// The assertions here are disabled since calling code can be
-       /// simpler if out of range access works and returns 0.
-       T ValueAt(int position) const {
+       /// Retrieve the element at a particular position.
+       /// Retrieving positions outside the range of the buffer returns empty or 0.
+       const T& ValueAt(int position) const {
                if (position < part1Length) {
-                       //PLATFORM_ASSERT(position >= 0);
                        if (position < 0) {
-                               return 0;
+                               return empty;
                        } else {
                                return body[position];
                        }
                } else {
-                       //PLATFORM_ASSERT(position < lengthBody);
                        if (position >= lengthBody) {
-                               return 0;
+                               return empty;
                        } else {
                                return body[gapLength + position];
                        }
                }
        }
 
-       void SetValueAt(int position, T v) {
+       /// Set the element at a particular position.
+       /// Setting positions outside the range of the buffer performs no assignment
+       /// but asserts in debug builds.
+       template <typename ParamType>
+       void SetValueAt(int position, ParamType&& v) {
                if (position < part1Length) {
                        PLATFORM_ASSERT(position >= 0);
                        if (position < 0) {
                                ;
                        } else {
-                               body[position] = v;
+                               body[position] = std::move(v);
                        }
                } else {
                        PLATFORM_ASSERT(position < lengthBody);
                        if (position >= lengthBody) {
                                ;
                        } else {
-                               body[gapLength + position] = v;
+                               body[gapLength + position] = std::move(v);
                        }
                }
        }
 
-       T &operator[](int position) const {
+       /// Retrieve the element at a particular position.
+       /// The position must be within bounds or an assertion is triggered.
+       const T &operator[](int position) const {
+               PLATFORM_ASSERT(position >= 0 && position < lengthBody);
+               if (position < part1Length) {
+                       return body[position];
+               } else {
+                       return body[gapLength + position];
+               }
+       }
+
+       /// Retrieve reference to the element at a particular position.
+       /// This, instead of the const variant, can be used to mutate in-place.
+       /// The position must be within bounds or an assertion is triggered.
+       T &operator[](int position) {
                PLATFORM_ASSERT(position >= 0 && position < lengthBody);
                if (position < part1Length) {
                        return body[position];
@@ -158,7 +181,7 @@ public:
                }
                RoomFor(1);
                GapTo(position);
-               body[part1Length] = v;
+               body[part1Length] = std::move(v);
                lengthBody++;
                part1Length++;
                gapLength--;
@@ -174,7 +197,28 @@ public:
                        }
                        RoomFor(insertLength);
                        GapTo(position);
-                       std::fill(&body[part1Length], &body[part1Length + insertLength], v);
+                       std::fill(body.data() + part1Length, body.data() + part1Length + insertLength, v);
+                       lengthBody += insertLength;
+                       part1Length += insertLength;
+                       gapLength -= insertLength;
+               }
+       }
+
+       /// Add some new empty elements.
+       /// InsertValue is good for value objects but not for unique_ptr objects
+       /// since they can only be moved from once.
+       void InsertEmpty(int position, int insertLength) {
+               PLATFORM_ASSERT((position >= 0) && (position <= lengthBody));
+               if (insertLength > 0) {
+                       if ((position < 0) || (position > lengthBody)) {
+                               return;
+                       }
+                       RoomFor(insertLength);
+                       GapTo(position);
+                       for (int elem = part1Length; elem < part1Length + insertLength; elem++) {
+                               T emptyOne = {};
+                               body[elem] = std::move(emptyOne);
+                       }
                        lengthBody += insertLength;
                        part1Length += insertLength;
                        gapLength -= insertLength;
@@ -185,7 +229,7 @@ public:
        /// appending zero valued elements if needed.
        void EnsureLength(int wantedLength) {
                if (Length() < wantedLength) {
-                       InsertValue(Length(), wantedLength - Length(), 0);
+                       InsertEmpty(Length(), wantedLength - Length());
                }
        }
 
@@ -198,7 +242,7 @@ public:
                        }
                        RoomFor(insertLength);
                        GapTo(positionToInsert);
-                       memmove(body + part1Length, s + positionFrom, sizeof(T) * insertLength);
+                       std::copy(s + positionFrom, s + positionFrom + insertLength, body.data() + 
part1Length);
                        lengthBody += insertLength;
                        part1Length += insertLength;
                        gapLength -= insertLength;
@@ -223,7 +267,8 @@ public:
                }
                if ((position == 0) && (deleteLength == lengthBody)) {
                        // Full deallocation returns storage and is faster
-                       delete []body;
+                       body.clear();
+                       body.shrink_to_fit();
                        Init();
                } else if (deleteLength > 0) {
                        GapTo(position);
@@ -234,50 +279,59 @@ public:
 
        /// Delete all the buffer contents.
        void DeleteAll() {
-               DeleteRange(0, lengthBody);
+               DeleteRange(0, static_cast<int>(lengthBody));
        }
 
-       // Retrieve a range of elements into an array
+       /// Retrieve a range of elements into an array
        void GetRange(T *buffer, int position, int retrieveLength) const {
                // Split into up to 2 ranges, before and after the split then use memcpy on each.
                int range1Length = 0;
                if (position < part1Length) {
-                       int part1AfterPosition = part1Length - position;
+                       const int part1AfterPosition = part1Length - position;
                        range1Length = retrieveLength;
                        if (range1Length > part1AfterPosition)
                                range1Length = part1AfterPosition;
                }
-               memcpy(buffer, body + position, range1Length * sizeof(T));
+               std::copy(body.data() + position, body.data() + position + range1Length, buffer);
                buffer += range1Length;
-               position = position + range1Length + gapLength;
+               position = static_cast<int>(position + range1Length + gapLength);
                int range2Length = retrieveLength - range1Length;
-               memcpy(buffer, body + position, range2Length * sizeof(T));
+               std::copy(body.data() + position, body.data() + position + range2Length, buffer);
        }
 
+       /// Compact the buffer and return a pointer to the first element.
        T *BufferPointer() {
                RoomFor(1);
                GapTo(lengthBody);
-               body[lengthBody] = 0;
-               return body;
+               T emptyOne = {};
+               body[lengthBody] = std::move(emptyOne);
+               return body.data();
        }
 
+       /// Return a pointer to a range of elements, first rearranging the buffer if
+       /// needed to make that range contiguous.
        T *RangePointer(int position, int rangeLength) {
                if (position < part1Length) {
                        if ((position + rangeLength) > part1Length) {
                                // Range overlaps gap, so move gap to start of range.
                                GapTo(position);
-                               return body + position + gapLength;
+                               return body.data() + position + gapLength;
                        } else {
-                               return body + position ;
+                               return body.data() + position;
                        }
                } else {
-                       return body + position + gapLength;
+                       return body.data() + position + gapLength;
                }
        }
 
+       /// Return the position of the gap within the buffer.
        int GapPosition() const {
-               return part1Length; 
+               return part1Length;
        }
 };
 
+#ifdef SCI_NAMESPACE
+}
+#endif
+
 #endif
diff --git a/plugins/scintilla/scintilla/src/Style.cxx b/plugins/scintilla/scintilla/src/Style.cxx
index 8b5b42d..99be5f3 100644
--- a/plugins/scintilla/scintilla/src/Style.cxx
+++ b/plugins/scintilla/scintilla/src/Style.cxx
@@ -5,7 +5,7 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
+#include <stdexcept>
 
 #include "Platform.h"
 
@@ -19,6 +19,10 @@ using namespace Scintilla;
 FontAlias::FontAlias() {
 }
 
+FontAlias::FontAlias(const FontAlias &other) : Font() {
+       SetID(other.fid);
+}
+
 FontAlias::~FontAlias() {
        SetID(0);
        // ~Font will not release the actual font resource since it is now 0
@@ -64,6 +68,7 @@ FontMeasurements::FontMeasurements() {
 void FontMeasurements::Clear() {
        ascent = 1;
        descent = 1;
+       capitalHeight = 1;
        aveCharWidth = 1;
        spaceWidth = 1;
        sizeZoomed = 2;
@@ -159,8 +164,5 @@ void Style::ClearTo(const Style &source) {
 
 void Style::Copy(Font &font_, const FontMeasurements &fm_) {
        font.MakeAlias(font_);
-#if PLAT_WX
-       font.SetAscent(fm_.ascent);
-#endif
        (FontMeasurements &)(*this) = fm_;
 }
diff --git a/plugins/scintilla/scintilla/src/Style.h b/plugins/scintilla/scintilla/src/Style.h
index 4bd79de..c0696a7 100644
--- a/plugins/scintilla/scintilla/src/Style.h
+++ b/plugins/scintilla/scintilla/src/Style.h
@@ -33,11 +33,11 @@ struct FontSpecification {
 
 // Just like Font but only has a copy of the FontID so should not delete it
 class FontAlias : public Font {
-       // Private so FontAlias objects can not be copied
-       FontAlias(const FontAlias &);
-       FontAlias &operator=(const FontAlias &);
 public:
        FontAlias();
+       // FontAlias objects can not be assigned except for initialization
+       FontAlias &operator=(const FontAlias &) = delete;
+       FontAlias(const FontAlias &);
        virtual ~FontAlias();
        void MakeAlias(Font &fontOrigin);
        void ClearFont();
@@ -46,6 +46,7 @@ public:
 struct FontMeasurements {
        unsigned int ascent;
        unsigned int descent;
+       XYPOSITION capitalHeight;       // Top of capital letter to baseline: ascent - internal leading
        XYPOSITION aveCharWidth;
        XYPOSITION spaceWidth;
        int sizeZoomed;
@@ -61,7 +62,7 @@ public:
        ColourDesired back;
        bool eolFilled;
        bool underline;
-       enum ecaseForced {caseMixed, caseUpper, caseLower};
+       enum ecaseForced {caseMixed, caseUpper, caseLower, caseCamel};
        ecaseForced caseForce;
        bool visible;
        bool changeable;
diff --git a/plugins/scintilla/scintilla/src/UniConversion.cxx 
b/plugins/scintilla/scintilla/src/UniConversion.cxx
index ffe67f7..b02850a 100644
--- a/plugins/scintilla/scintilla/src/UniConversion.cxx
+++ b/plugins/scintilla/scintilla/src/UniConversion.cxx
@@ -5,18 +5,25 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <stdlib.h>
+#include <cstdlib>
+
+#include <stdexcept>
+#include <string>
 
 #include "UniConversion.h"
 
-enum { SURROGATE_LEAD_FIRST = 0xD800 };
-enum { SURROGATE_TRAIL_FIRST = 0xDC00 };
-enum { SURROGATE_TRAIL_LAST = 0xDFFF };
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
 
-unsigned int UTF8Length(const wchar_t *uptr, unsigned int tlen) {
-       unsigned int len = 0;
-       for (unsigned int i = 0; i < tlen && uptr[i];) {
-               unsigned int uch = uptr[i];
+size_t UTF8Length(const wchar_t *uptr, size_t tlen) {
+       size_t len = 0;
+       for (size_t i = 0; i < tlen && uptr[i];) {
+               const unsigned int uch = uptr[i];
                if (uch < 0x80) {
                        len++;
                } else if (uch < 0x800) {
@@ -33,10 +40,10 @@ unsigned int UTF8Length(const wchar_t *uptr, unsigned int tlen) {
        return len;
 }
 
-void UTF8FromUTF16(const wchar_t *uptr, unsigned int tlen, char *putf, unsigned int len) {
-       int k = 0;
-       for (unsigned int i = 0; i < tlen && uptr[i];) {
-               unsigned int uch = uptr[i];
+void UTF8FromUTF16(const wchar_t *uptr, size_t tlen, char *putf, size_t len) {
+       size_t k = 0;
+       for (size_t i = 0; i < tlen && uptr[i];) {
+               const unsigned int uch = uptr[i];
                if (uch < 0x80) {
                        putf[k++] = static_cast<char>(uch);
                } else if (uch < 0x800) {
@@ -46,7 +53,7 @@ void UTF8FromUTF16(const wchar_t *uptr, unsigned int tlen, char *putf, unsigned
                        (uch <= SURROGATE_TRAIL_LAST)) {
                        // Half a surrogate pair
                        i++;
-                       unsigned int xch = 0x10000 + ((uch & 0x3ff) << 10) + (uptr[i] & 0x3ff);
+                       const unsigned int xch = 0x10000 + ((uch & 0x3ff) << 10) + (uptr[i] & 0x3ff);
                        putf[k++] = static_cast<char>(0xF0 | (xch >> 18));
                        putf[k++] = static_cast<char>(0x80 | ((xch >> 12) & 0x3f));
                        putf[k++] = static_cast<char>(0x80 | ((xch >> 6) & 0x3f));
@@ -58,7 +65,8 @@ void UTF8FromUTF16(const wchar_t *uptr, unsigned int tlen, char *putf, unsigned
                }
                i++;
        }
-       putf[len] = '\0';
+       if (k < len)
+               putf[k] = '\0';
 }
 
 unsigned int UTF8CharLength(unsigned char ch) {
@@ -73,11 +81,11 @@ unsigned int UTF8CharLength(unsigned char ch) {
        }
 }
 
-unsigned int UTF16Length(const char *s, unsigned int len) {
-       unsigned int ulen = 0;
-       unsigned int charLen;
-       for (unsigned int i=0; i<len;) {
-               unsigned char ch = static_cast<unsigned char>(s[i]);
+size_t UTF16Length(const char *s, size_t len) {
+       size_t ulen = 0;
+       size_t charLen;
+       for (size_t i = 0; i<len;) {
+               const unsigned char ch = static_cast<unsigned char>(s[i]);
                if (ch < 0x80) {
                        charLen = 1;
                } else if (ch < 0x80 + 0x40 + 0x20) {
@@ -94,10 +102,10 @@ unsigned int UTF16Length(const char *s, unsigned int len) {
        return ulen;
 }
 
-unsigned int UTF16FromUTF8(const char *s, unsigned int len, wchar_t *tbuf, unsigned int tlen) {
-       unsigned int ui=0;
+size_t UTF16FromUTF8(const char *s, size_t len, wchar_t *tbuf, size_t tlen) {
+       size_t ui = 0;
        const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
-       unsigned int i=0;
+       size_t i = 0;
        while ((i<len) && (ui<tlen)) {
                unsigned char ch = us[i++];
                if (ch < 0x80) {
@@ -130,6 +138,51 @@ unsigned int UTF16FromUTF8(const char *s, unsigned int len, wchar_t *tbuf, unsig
        return ui;
 }
 
+size_t UTF32FromUTF8(const char *s, size_t len, unsigned int *tbuf, size_t tlen) {
+       size_t ui=0;
+       const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
+       size_t i=0;
+       while ((i<len) && (ui<tlen)) {
+               unsigned char ch = us[i++];
+               unsigned int value = 0;
+               if (ch < 0x80) {
+                       value = ch;
+               } else if (((len-i) >= 1) && (ch < 0x80 + 0x40 + 0x20)) {
+                       value = (ch & 0x1F) << 6;
+                       ch = us[i++];
+                       value += ch & 0x7F;
+               } else if (((len-i) >= 2) && (ch < 0x80 + 0x40 + 0x20 + 0x10)) {
+                       value = (ch & 0xF) << 12;
+                       ch = us[i++];
+                       value += (ch & 0x7F) << 6;
+                       ch = us[i++];
+                       value += ch & 0x7F;
+               } else if ((len-i) >= 3) {
+                       value = (ch & 0x7) << 18;
+                       ch = us[i++];
+                       value += (ch & 0x3F) << 12;
+                       ch = us[i++];
+                       value += (ch & 0x3F) << 6;
+                       ch = us[i++];
+                       value += ch & 0x3F;
+               }
+               tbuf[ui] = value;
+               ui++;
+       }
+       return ui;
+}
+
+unsigned int UTF16FromUTF32Character(unsigned int val, wchar_t *tbuf) {
+       if (val < SUPPLEMENTAL_PLANE_FIRST) {
+               tbuf[0] = static_cast<wchar_t>(val);
+               return 1;
+       } else {
+               tbuf[0] = static_cast<wchar_t>(((val - SUPPLEMENTAL_PLANE_FIRST) >> 10) + 
SURROGATE_LEAD_FIRST);
+               tbuf[1] = static_cast<wchar_t>((val & 0x3ff) + SURROGATE_TRAIL_FIRST);
+               return 2;
+       }
+}
+
 int UTF8BytesOfLead[256];
 static bool initialisedBytesOfLead = false;
 
@@ -151,7 +204,7 @@ static int BytesFromLead(int leadByte) {
 
 void UTF8BytesOfLeadInitialise() {
        if (!initialisedBytesOfLead) {
-               for (int i=0;i<256;i++) {
+               for (int i=0; i<256; i++) {
                        UTF8BytesOfLead[i] = BytesFromLead(i);
                }
                initialisedBytesOfLead = true;
@@ -246,3 +299,34 @@ int UTF8Classify(const unsigned char *us, int len) {
                return UTF8MaskInvalid | 1;
        }
 }
+
+int UTF8DrawBytes(const unsigned char *us, int len) {
+       const int utf8StatusNext = UTF8Classify(us, len);
+       return (utf8StatusNext & UTF8MaskInvalid) ? 1 : (utf8StatusNext & UTF8MaskWidth);
+}
+
+// Replace invalid bytes in UTF-8 with the replacement character
+std::string FixInvalidUTF8(const std::string &text) {
+       std::string result;
+       const unsigned char *us = reinterpret_cast<const unsigned char *>(text.c_str());
+       size_t remaining = text.size();
+       while (remaining > 0) {
+               const int utf8Status = UTF8Classify(us, static_cast<int>(remaining));
+               if (utf8Status & UTF8MaskInvalid) {
+                       // Replacement character 0xFFFD = UTF8:"efbfbd".
+                       result.append("\xef\xbf\xbd");
+                       us++;
+                       remaining--;
+               } else {
+                       const int len = utf8Status&UTF8MaskWidth;
+                       result.append(reinterpret_cast<const char *>(us), len);
+                       us += len;
+                       remaining -= len;
+               }
+       }
+       return result;
+}
+
+#ifdef SCI_NAMESPACE
+}
+#endif
diff --git a/plugins/scintilla/scintilla/src/UniConversion.h b/plugins/scintilla/scintilla/src/UniConversion.h
index 70e8a95..8011e05 100644
--- a/plugins/scintilla/scintilla/src/UniConversion.h
+++ b/plugins/scintilla/scintilla/src/UniConversion.h
@@ -5,13 +5,25 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+#ifndef UNICONVERSION_H
+#define UNICONVERSION_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
 const int UTF8MaxBytes = 4;
 
-unsigned int UTF8Length(const wchar_t *uptr, unsigned int tlen);
-void UTF8FromUTF16(const wchar_t *uptr, unsigned int tlen, char *putf, unsigned int len);
+const int unicodeReplacementChar = 0xFFFD;
+
+size_t UTF8Length(const wchar_t *uptr, size_t tlen);
+void UTF8FromUTF16(const wchar_t *uptr, size_t tlen, char *putf, size_t len);
 unsigned int UTF8CharLength(unsigned char ch);
-unsigned int UTF16Length(const char *s, unsigned int len);
-unsigned int UTF16FromUTF8(const char *s, unsigned int len, wchar_t *tbuf, unsigned int tlen);
+size_t UTF16Length(const char *s, size_t len);
+size_t UTF16FromUTF8(const char *s, size_t len, wchar_t *tbuf, size_t tlen);
+size_t UTF32FromUTF8(const char *s, size_t len, unsigned int *tbuf, size_t tlen);
+unsigned int UTF16FromUTF32Character(unsigned int val, wchar_t *tbuf);
+std::string FixInvalidUTF8(const std::string &text);
 
 extern int UTF8BytesOfLead[256];
 void UTF8BytesOfLeadInitialise();
@@ -27,6 +39,10 @@ inline bool UTF8IsAscii(int ch) {
 enum { UTF8MaskWidth=0x7, UTF8MaskInvalid=0x8 };
 int UTF8Classify(const unsigned char *us, int len);
 
+// Similar to UTF8Classify but returns a length of 1 for invalid bytes
+// instead of setting the invalid flag
+int UTF8DrawBytes(const unsigned char *us, int len);
+
 // Line separator is U+2028 \xe2\x80\xa8
 // Paragraph separator is U+2029 \xe2\x80\xa9
 const int UTF8SeparatorLength = 3;
@@ -39,3 +55,19 @@ const int UTF8NELLength = 2;
 inline bool UTF8IsNEL(const unsigned char *us) {
        return (us[0] == 0xc2) && (us[1] == 0x85);
 }
+
+enum { SURROGATE_LEAD_FIRST = 0xD800 };
+enum { SURROGATE_LEAD_LAST = 0xDBFF };
+enum { SURROGATE_TRAIL_FIRST = 0xDC00 };
+enum { SURROGATE_TRAIL_LAST = 0xDFFF };
+enum { SUPPLEMENTAL_PLANE_FIRST = 0x10000 };
+
+inline unsigned int UTF16CharLength(wchar_t uch) {
+       return ((uch >= SURROGATE_LEAD_FIRST) && (uch <= SURROGATE_LEAD_LAST)) ? 2 : 1;
+}
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/UnicodeFromUTF8.h 
b/plugins/scintilla/scintilla/src/UnicodeFromUTF8.h
index 24517e8..ae66cb0 100644
--- a/plugins/scintilla/scintilla/src/UnicodeFromUTF8.h
+++ b/plugins/scintilla/scintilla/src/UnicodeFromUTF8.h
@@ -5,6 +5,13 @@
 // Copyright 2013 by Neil Hodgson <neilh scintilla org>
 // This file is in the public domain.
 
+#ifndef UNICODEFROMUTF8_H
+#define UNICODEFROMUTF8_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
 inline int UnicodeFromUTF8(const unsigned char *us) {
        if (us[0] < 0xC2) {
                return us[0];
@@ -17,3 +24,9 @@ inline int UnicodeFromUTF8(const unsigned char *us) {
        }
        return us[0];
 }
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/UniqueString.h b/plugins/scintilla/scintilla/src/UniqueString.h
new file mode 100644
index 0000000..07da0f1
--- /dev/null
+++ b/plugins/scintilla/scintilla/src/UniqueString.h
@@ -0,0 +1,34 @@
+// Scintilla source code edit control
+/** @file UniqueString.h
+ ** Define UniqueString, a unique_ptr based string type for storage in containers
+ ** and an allocator for UniqueString.
+ **/
+// Copyright 2017 by Neil Hodgson <neilh scintilla org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#ifndef UNIQUESTRING_H
+#define UNIQUESTRING_H
+
+#ifdef SCI_NAMESPACE
+namespace Scintilla {
+#endif
+
+using UniqueString = std::unique_ptr<const char[]>;
+
+/// Equivalent to strdup but produces a std::unique_ptr<const char[]> allocation to go
+/// into collections.
+inline UniqueString UniqueStringCopy(const char *text) {
+       if (!text) {
+               return UniqueString();
+       }
+       const size_t len = strlen(text);
+       char *sNew = new char[len + 1];
+       std::copy(text, text + len + 1, sNew);
+       return UniqueString(sNew);
+}
+
+#ifdef SCI_NAMESPACE
+}
+#endif
+
+#endif
diff --git a/plugins/scintilla/scintilla/src/ViewStyle.cxx b/plugins/scintilla/scintilla/src/ViewStyle.cxx
index 8d2a60e..7a0b146 100644
--- a/plugins/scintilla/scintilla/src/ViewStyle.cxx
+++ b/plugins/scintilla/scintilla/src/ViewStyle.cxx
@@ -5,18 +5,21 @@
 // Copyright 1998-2003 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
-#include <assert.h>
+#include <cstddef>
+#include <cassert>
+#include <cstring>
 
+#include <stdexcept>
 #include <vector>
 #include <map>
+#include <algorithm>
+#include <memory>
 
 #include "Platform.h"
 
 #include "Scintilla.h"
-#include "SplitVector.h"
-#include "Partitioning.h"
-#include "RunStyles.h"
+#include "Position.h"
+#include "UniqueString.h"
 #include "Indicator.h"
 #include "XPM.h"
 #include "LineMarker.h"
@@ -27,8 +30,8 @@
 using namespace Scintilla;
 #endif
 
-MarginStyle::MarginStyle() :
-       style(SC_MARGIN_SYMBOL), width(0), mask(0), sensitive(false), cursor(SC_CURSORREVERSEARROW) {
+MarginStyle::MarginStyle(int style_, int width_, int mask_) :
+       style(style_), width(width_), mask(mask_), sensitive(false), cursor(SC_CURSORREVERSEARROW) {
 }
 
 // A list of the fontnames - avoids wasting space in each style
@@ -40,25 +43,21 @@ FontNames::~FontNames() {
 }
 
 void FontNames::Clear() {
-       for (std::vector<char *>::const_iterator it=names.begin(); it != names.end(); ++it) {
-               delete []*it;
-       }
        names.clear();
 }
 
 const char *FontNames::Save(const char *name) {
        if (!name)
-               return 0;
+               return nullptr;
 
-       for (std::vector<char *>::const_iterator it=names.begin(); it != names.end(); ++it) {
-               if (strcmp(*it, name) == 0) {
-                       return *it;
+       for (const UniqueString &nm : names) {
+               if (strcmp(nm.get(), name) == 0) {
+                       return nm.get();
                }
        }
-       char *nameSave = new char[strlen(name) + 1];
-       strcpy(nameSave, name);
-       names.push_back(nameSave);
-       return nameSave;
+
+       names.push_back(UniqueStringCopy(name));
+       return names.back().get();
 }
 
 FontRealised::FontRealised() {
@@ -74,88 +73,81 @@ void FontRealised::Realise(Surface &surface, int zoomLevel, int technology, cons
        if (sizeZoomed <= 2 * SC_FONT_SIZE_MULTIPLIER)  // Hangs if sizeZoomed <= 1
                sizeZoomed = 2 * SC_FONT_SIZE_MULTIPLIER;
 
-       float deviceHeight = surface.DeviceHeightFont(sizeZoomed);
+       float deviceHeight = static_cast<float>(surface.DeviceHeightFont(sizeZoomed));
        FontParameters fp(fs.fontName, deviceHeight / SC_FONT_SIZE_MULTIPLIER, fs.weight, fs.italic, 
fs.extraFontFlag, technology, fs.characterSet);
        font.Create(fp);
 
-       ascent = surface.Ascent(font);
-       descent = surface.Descent(font);
+       ascent = static_cast<unsigned int>(surface.Ascent(font));
+       descent = static_cast<unsigned int>(surface.Descent(font));
+       capitalHeight = surface.Ascent(font) - surface.InternalLeading(font);
        aveCharWidth = surface.AverageCharWidth(font);
        spaceWidth = surface.WidthChar(font, ' ');
 }
 
-ViewStyle::ViewStyle() {
+ViewStyle::ViewStyle() : markers(MARKER_MAX + 1), indicators(INDIC_MAX + 1) {
        Init();
 }
 
-ViewStyle::ViewStyle(const ViewStyle &source) {
+// Copy constructor only called when printing copies the screen ViewStyle so it can be
+// modified for printing styles.
+ViewStyle::ViewStyle(const ViewStyle &source) : markers(MARKER_MAX + 1), indicators(INDIC_MAX + 1) {
        Init(source.styles.size());
-       for (unsigned int sty=0; sty<source.styles.size(); sty++) {
-               styles[sty] = source.styles[sty];
-               // Can't just copy fontname as its lifetime is relative to its owning ViewStyle
+       styles = source.styles;
+       for (size_t sty=0; sty<source.styles.size(); sty++) {
+               // Can't just copy fontName as its lifetime is relative to its owning ViewStyle
                styles[sty].fontName = fontNames.Save(source.styles[sty].fontName);
        }
        nextExtendedStyle = source.nextExtendedStyle;
-       for (int mrk=0; mrk<=MARKER_MAX; mrk++) {
-               markers[mrk] = source.markers[mrk];
-       }
+       markers = source.markers;
        CalcLargestMarkerHeight();
-       for (int ind=0; ind<=INDIC_MAX; ind++) {
-               indicators[ind] = source.indicators[ind];
-       }
 
-       selforeset = source.selforeset;
-       selforeground = source.selforeground;
+       indicators = source.indicators;
+
+       indicatorsDynamic = source.indicatorsDynamic;
+       indicatorsSetFore = source.indicatorsSetFore;
+
+       selColours = source.selColours;
        selAdditionalForeground = source.selAdditionalForeground;
-       selbackset = source.selbackset;
-       selbackground = source.selbackground;
        selAdditionalBackground = source.selAdditionalBackground;
-       selbackground2 = source.selbackground2;
+       selBackground2 = source.selBackground2;
        selAlpha = source.selAlpha;
        selAdditionalAlpha = source.selAdditionalAlpha;
        selEOLFilled = source.selEOLFilled;
 
-       foldmarginColourSet = source.foldmarginColourSet;
        foldmarginColour = source.foldmarginColour;
-       foldmarginHighlightColourSet = source.foldmarginHighlightColourSet;
        foldmarginHighlightColour = source.foldmarginHighlightColour;
 
-       hotspotForegroundSet = source.hotspotForegroundSet;
-       hotspotForeground = source.hotspotForeground;
-       hotspotBackgroundSet = source.hotspotBackgroundSet;
-       hotspotBackground = source.hotspotBackground;
+       hotspotColours = source.hotspotColours;
        hotspotUnderline = source.hotspotUnderline;
        hotspotSingleLine = source.hotspotSingleLine;
 
-       whitespaceForegroundSet = source.whitespaceForegroundSet;
-       whitespaceForeground = source.whitespaceForeground;
-       whitespaceBackgroundSet = source.whitespaceBackgroundSet;
-       whitespaceBackground = source.whitespaceBackground;
+       whitespaceColours = source.whitespaceColours;
+       controlCharSymbol = source.controlCharSymbol;
+       controlCharWidth = source.controlCharWidth;
        selbar = source.selbar;
        selbarlight = source.selbarlight;
        caretcolour = source.caretcolour;
        additionalCaretColour = source.additionalCaretColour;
+       caretLineFrame = source.caretLineFrame;
        showCaretLineBackground = source.showCaretLineBackground;
        alwaysShowCaretLineBackground = source.alwaysShowCaretLineBackground;
        caretLineBackground = source.caretLineBackground;
        caretLineAlpha = source.caretLineAlpha;
-       edgecolour = source.edgecolour;
-       edgeState = source.edgeState;
        caretStyle = source.caretStyle;
        caretWidth = source.caretWidth;
        someStylesProtected = false;
        someStylesForceCase = false;
        leftMarginWidth = source.leftMarginWidth;
        rightMarginWidth = source.rightMarginWidth;
-       for (int margin=0; margin <= SC_MAX_MARGIN; margin++) {
-               ms[margin] = source.ms[margin];
-       }
+       ms = source.ms;
        maskInLine = source.maskInLine;
+       maskDrawInText = source.maskDrawInText;
        fixedColumnWidth = source.fixedColumnWidth;
        marginInside = source.marginInside;
        textStart = source.textStart;
        zoomLevel = source.zoomLevel;
        viewWhitespace = source.viewWhitespace;
+       tabDrawMode = source.tabDrawMode;
        whitespaceSize = source.whitespaceSize;
        viewIndentationGuides = source.viewIndentationGuides;
        viewEOL = source.viewEOL;
@@ -169,16 +161,53 @@ ViewStyle::ViewStyle(const ViewStyle &source) {
        braceHighlightIndicator = source.braceHighlightIndicator;
        braceBadLightIndicatorSet = source.braceBadLightIndicatorSet;
        braceBadLightIndicator = source.braceBadLightIndicator;
+
+       edgeState = source.edgeState;
+       theEdge = source.theEdge;
+       theMultiEdge = source.theMultiEdge;
+
+       marginNumberPadding = source.marginNumberPadding;
+       ctrlCharPadding = source.ctrlCharPadding;
+       lastSegItalicsOffset = source.lastSegItalicsOffset;
+
+       wrapState = source.wrapState;
+       wrapVisualFlags = source.wrapVisualFlags;
+       wrapVisualFlagsLocation = source.wrapVisualFlagsLocation;
+       wrapVisualStartIndent = source.wrapVisualStartIndent;
+       wrapIndentMode = source.wrapIndentMode;
 }
 
 ViewStyle::~ViewStyle() {
        styles.clear();
-       for (FontMap::iterator it = fonts.begin(); it != fonts.end(); ++it) {
-               delete it->second;
-       }
        fonts.clear();
 }
 
+void ViewStyle::CalculateMarginWidthAndMask() {
+       fixedColumnWidth = marginInside ? leftMarginWidth : 0;
+       maskInLine = 0xffffffff;
+       int maskDefinedMarkers = 0;
+       for (const MarginStyle &m : ms) {
+               fixedColumnWidth += m.width;
+               if (m.width > 0)
+                       maskInLine &= ~m.mask;
+               maskDefinedMarkers |= m.mask;
+       }
+       maskDrawInText = 0;
+       for (int markBit = 0; markBit < 32; markBit++) {
+               const int maskBit = 1 << markBit;
+               switch (markers[markBit].markType) {
+               case SC_MARK_EMPTY:
+                       maskInLine &= ~maskBit;
+                       break;
+               case SC_MARK_BACKGROUND:
+               case SC_MARK_UNDERLINE:
+                       maskInLine &= ~maskBit;
+                       maskDrawInText |= maskDefinedMarkers & maskBit;
+                       break;
+               }
+       }
+}
+
 void ViewStyle::Init(size_t stylesSize_) {
        AllocStyles(stylesSize_);
        nextExtendedStyle = 256;
@@ -188,89 +217,70 @@ void ViewStyle::Init(size_t stylesSize_) {
        // There are no image markers by default, so no need for calling CalcLargestMarkerHeight()
        largestMarkerHeight = 0;
 
-       indicators[0].style = INDIC_SQUIGGLE;
-       indicators[0].under = false;
-       indicators[0].fore = ColourDesired(0, 0x7f, 0);
-       indicators[1].style = INDIC_TT;
-       indicators[1].under = false;
-       indicators[1].fore = ColourDesired(0, 0, 0xff);
-       indicators[2].style = INDIC_PLAIN;
-       indicators[2].under = false;
-       indicators[2].fore = ColourDesired(0xff, 0, 0);
+       indicators[0] = Indicator(INDIC_SQUIGGLE, ColourDesired(0, 0x7f, 0));
+       indicators[1] = Indicator(INDIC_TT, ColourDesired(0, 0, 0xff));
+       indicators[2] = Indicator(INDIC_PLAIN, ColourDesired(0xff, 0, 0));
 
        technology = SC_TECHNOLOGY_DEFAULT;
+       indicatorsDynamic = false;
+       indicatorsSetFore = false;
        lineHeight = 1;
+       lineOverlap = 0;
        maxAscent = 1;
        maxDescent = 1;
        aveCharWidth = 8;
        spaceWidth = 8;
+       tabWidth = spaceWidth * 8;
 
-       selforeset = false;
-       selforeground = ColourDesired(0xff, 0, 0);
+       selColours.fore = ColourOptional(ColourDesired(0xff, 0, 0));
+       selColours.back = ColourOptional(ColourDesired(0xc0, 0xc0, 0xc0), true);
        selAdditionalForeground = ColourDesired(0xff, 0, 0);
-       selbackset = true;
-       selbackground = ColourDesired(0xc0, 0xc0, 0xc0);
        selAdditionalBackground = ColourDesired(0xd7, 0xd7, 0xd7);
-       selbackground2 = ColourDesired(0xb0, 0xb0, 0xb0);
+       selBackground2 = ColourDesired(0xb0, 0xb0, 0xb0);
        selAlpha = SC_ALPHA_NOALPHA;
        selAdditionalAlpha = SC_ALPHA_NOALPHA;
        selEOLFilled = false;
 
-       foldmarginColourSet = false;
-       foldmarginColour = ColourDesired(0xff, 0, 0);
-       foldmarginHighlightColourSet = false;
-       foldmarginHighlightColour = ColourDesired(0xc0, 0xc0, 0xc0);
+       foldmarginColour = ColourOptional(ColourDesired(0xff, 0, 0));
+       foldmarginHighlightColour = ColourOptional(ColourDesired(0xc0, 0xc0, 0xc0));
 
-       whitespaceForegroundSet = false;
-       whitespaceForeground = ColourDesired(0, 0, 0);
-       whitespaceBackgroundSet = false;
-       whitespaceBackground = ColourDesired(0xff, 0xff, 0xff);
+       whitespaceColours.fore = ColourOptional();
+       whitespaceColours.back = ColourOptional(ColourDesired(0xff, 0xff, 0xff));
+       controlCharSymbol = 0;  /* Draw the control characters */
+       controlCharWidth = 0;
        selbar = Platform::Chrome();
        selbarlight = Platform::ChromeHighlight();
        styles[STYLE_LINENUMBER].fore = ColourDesired(0, 0, 0);
        styles[STYLE_LINENUMBER].back = Platform::Chrome();
        caretcolour = ColourDesired(0, 0, 0);
        additionalCaretColour = ColourDesired(0x7f, 0x7f, 0x7f);
+       caretLineFrame = 0;
        showCaretLineBackground = false;
        alwaysShowCaretLineBackground = false;
        caretLineBackground = ColourDesired(0xff, 0xff, 0);
        caretLineAlpha = SC_ALPHA_NOALPHA;
-       edgecolour = ColourDesired(0xc0, 0xc0, 0xc0);
-       edgeState = EDGE_NONE;
        caretStyle = CARETSTYLE_LINE;
        caretWidth = 1;
        someStylesProtected = false;
        someStylesForceCase = false;
 
-       hotspotForegroundSet = false;
-       hotspotForeground = ColourDesired(0, 0, 0xff);
-       hotspotBackgroundSet = false;
-       hotspotBackground = ColourDesired(0xff, 0xff, 0xff);
+       hotspotColours.fore = ColourOptional(ColourDesired(0, 0, 0xff));
+       hotspotColours.back = ColourOptional(ColourDesired(0xff, 0xff, 0xff));
        hotspotUnderline = true;
        hotspotSingleLine = true;
 
        leftMarginWidth = 1;
        rightMarginWidth = 1;
-       ms[0].style = SC_MARGIN_NUMBER;
-       ms[0].width = 0;
-       ms[0].mask = 0;
-       ms[1].style = SC_MARGIN_SYMBOL;
-       ms[1].width = 16;
-       ms[1].mask = ~SC_MASK_FOLDERS;
-       ms[2].style = SC_MARGIN_SYMBOL;
-       ms[2].width = 0;
-       ms[2].mask = 0;
+       ms.resize(SC_MAX_MARGIN + 1);
+       ms[0] = MarginStyle(SC_MARGIN_NUMBER);
+       ms[1] = MarginStyle(SC_MARGIN_SYMBOL, 16, ~SC_MASK_FOLDERS);
+       ms[2] = MarginStyle(SC_MARGIN_SYMBOL);
        marginInside = true;
-       fixedColumnWidth = marginInside ? leftMarginWidth : 0;
-       maskInLine = 0xffffffff;
-       for (int margin=0; margin <= SC_MAX_MARGIN; margin++) {
-               fixedColumnWidth += ms[margin].width;
-               if (ms[margin].width > 0)
-                       maskInLine &= ~ms[margin].mask;
-       }
+       CalculateMarginWidthAndMask();
        textStart = marginInside ? fixedColumnWidth : leftMarginWidth;
        zoomLevel = 0;
        viewWhitespace = wsInvisible;
+       tabDrawMode = tdLongArrow;
        whitespaceSize = 1;
        viewIndentationGuides = ivNone;
        viewEOL = false;
@@ -284,62 +294,83 @@ void ViewStyle::Init(size_t stylesSize_) {
        braceHighlightIndicator = 0;
        braceBadLightIndicatorSet = false;
        braceBadLightIndicator = 0;
+
+       edgeState = EDGE_NONE;
+       theEdge = EdgeProperties(0, ColourDesired(0xc0, 0xc0, 0xc0));
+
+       marginNumberPadding = 3;
+       ctrlCharPadding = 3; // +3 For a blank on front and rounded edge each side
+       lastSegItalicsOffset = 2;
+
+       wrapState = eWrapNone;
+       wrapVisualFlags = 0;
+       wrapVisualFlagsLocation = 0;
+       wrapVisualStartIndent = 0;
+       wrapIndentMode = SC_WRAPINDENT_FIXED;
 }
 
-void ViewStyle::Refresh(Surface &surface) {
-       for (FontMap::iterator it = fonts.begin(); it != fonts.end(); ++it) {
-               delete it->second;
-       }
+void ViewStyle::Refresh(Surface &surface, int tabInChars) {
        fonts.clear();
 
        selbar = Platform::Chrome();
        selbarlight = Platform::ChromeHighlight();
 
-       for (unsigned int i=0; i<styles.size(); i++) {
-               styles[i].extraFontFlag = extraFontFlag;
+       // Apply the extra font flag which controls text drawing quality to each style.
+       for (Style &style : styles) {
+               style.extraFontFlag = extraFontFlag;
        }
-
-       CreateFont(styles[STYLE_DEFAULT]);
-       for (unsigned int j=0; j<styles.size(); j++) {
-               CreateFont(styles[j]);
+       
+       // Create a FontRealised object for each unique font in the styles.
+       CreateAndAddFont(styles[STYLE_DEFAULT]);
+       for (const Style &style : styles) {
+               CreateAndAddFont(style);
        }
 
-       for (FontMap::iterator it = fonts.begin(); it != fonts.end(); ++it) {
-               it->second->Realise(surface, zoomLevel, technology, it->first);
+       // Ask platform to allocate each unique font.
+       for (std::pair<const FontSpecification, std::unique_ptr<FontRealised>> &font : fonts) {
+               font.second->Realise(surface, zoomLevel, technology, font.first);
        }
 
-       for (unsigned int k=0; k<styles.size(); k++) {
-               FontRealised *fr = Find(styles[k]);
-               styles[k].Copy(fr->font, *fr);
+       // Set the platform font handle and measurements for each style.
+       for (Style &style : styles) {
+               FontRealised *fr = Find(style);
+               style.Copy(fr->font, *fr);
        }
+
+       indicatorsDynamic = std::any_of(indicators.cbegin(), indicators.cend(),
+               [](const Indicator &indicator) { return indicator.IsDynamic(); });
+
+       indicatorsSetFore = std::any_of(indicators.cbegin(), indicators.cend(),
+               [](const Indicator &indicator) { return indicator.OverridesTextFore(); });
+
        maxAscent = 1;
        maxDescent = 1;
-       FindMaxAscentDescent(maxAscent, maxDescent);
+       FindMaxAscentDescent();
        maxAscent += extraAscent;
        maxDescent += extraDescent;
        lineHeight = maxAscent + maxDescent;
+       lineOverlap = lineHeight / 10;
+       if (lineOverlap < 2)
+               lineOverlap = 2;
+       if (lineOverlap > lineHeight)
+               lineOverlap = lineHeight;
 
-       someStylesProtected = false;
-       someStylesForceCase = false;
-       for (unsigned int l=0; l<styles.size(); l++) {
-               if (styles[l].IsProtected()) {
-                       someStylesProtected = true;
-               }
-               if (styles[l].caseForce != Style::caseMixed) {
-                       someStylesForceCase = true;
-               }
-       }
+       someStylesProtected = std::any_of(styles.cbegin(), styles.cend(),
+               [](const Style &style) { return style.IsProtected(); });
+
+       someStylesForceCase = std::any_of(styles.cbegin(), styles.cend(),
+               [](const Style &style) { return style.caseForce != Style::caseMixed; });
 
        aveCharWidth = styles[STYLE_DEFAULT].aveCharWidth;
        spaceWidth = styles[STYLE_DEFAULT].spaceWidth;
+       tabWidth = spaceWidth * tabInChars;
 
-       fixedColumnWidth = marginInside ? leftMarginWidth : 0;
-       maskInLine = 0xffffffff;
-       for (int margin=0; margin <= SC_MAX_MARGIN; margin++) {
-               fixedColumnWidth += ms[margin].width;
-               if (ms[margin].width > 0)
-                       maskInLine &= ~ms[margin].mask;
+       controlCharWidth = 0.0;
+       if (controlCharSymbol >= 32) {
+               controlCharWidth = surface.WidthChar(styles[STYLE_CONTROLCHAR].font, 
static_cast<char>(controlCharSymbol));
        }
+
+       CalculateMarginWidthAndMask();
        textStart = marginInside ? fixedColumnWidth : leftMarginWidth;
 }
 
@@ -350,6 +381,10 @@ void ViewStyle::ReleaseAllExtendedStyles() {
 int ViewStyle::AllocateExtendedStyles(int numberStyles) {
        int startRange = static_cast<int>(nextExtendedStyle);
        nextExtendedStyle += numberStyles;
+       EnsureStyle(nextExtendedStyle);
+       for (size_t i=startRange; i<nextExtendedStyle; i++) {
+               styles[i].ClearTo(styles[STYLE_DEFAULT]);
+       }
        return startRange;
 }
 
@@ -389,26 +424,154 @@ bool ViewStyle::ProtectionActive() const {
        return someStylesProtected;
 }
 
+int ViewStyle::ExternalMarginWidth() const {
+       return marginInside ? 0 : fixedColumnWidth;
+}
+
+int ViewStyle::MarginFromLocation(Point pt) const {
+       int margin = -1;
+       int x = textStart - fixedColumnWidth;
+       for (size_t i = 0; i < ms.size(); i++) {
+               if ((pt.x >= x) && (pt.x < x + ms[i].width))
+                       margin = static_cast<int>(i);
+               x += ms[i].width;
+       }
+       return margin;
+}
+
 bool ViewStyle::ValidStyle(size_t styleIndex) const {
        return styleIndex < styles.size();
 }
 
 void ViewStyle::CalcLargestMarkerHeight() {
        largestMarkerHeight = 0;
-       for (int m = 0; m <= MARKER_MAX; ++m) {
-               switch (markers[m].markType) {
+       for (const LineMarker &marker : markers) {
+               switch (marker.markType) {
                case SC_MARK_PIXMAP:
-                       if (markers[m].pxpm && markers[m].pxpm->GetHeight() > largestMarkerHeight)
-                               largestMarkerHeight = markers[m].pxpm->GetHeight();
+                       if (marker.pxpm && marker.pxpm->GetHeight() > largestMarkerHeight)
+                               largestMarkerHeight = marker.pxpm->GetHeight();
                        break;
                case SC_MARK_RGBAIMAGE:
-                       if (markers[m].image && markers[m].image->GetHeight() > largestMarkerHeight)
-                               largestMarkerHeight = markers[m].image->GetHeight();
+                       if (marker.image && marker.image->GetHeight() > largestMarkerHeight)
+                               largestMarkerHeight = marker.image->GetHeight();
                        break;
                }
        }
 }
 
+int ViewStyle::GetFrameWidth() const {
+       return Platform::Clamp(caretLineFrame, 1, lineHeight / 3);
+}
+
+bool ViewStyle::IsLineFrameOpaque(bool caretActive, bool lineContainsCaret) const {
+       return caretLineFrame && (caretActive || alwaysShowCaretLineBackground) && showCaretLineBackground &&
+               (caretLineAlpha == SC_ALPHA_NOALPHA) && lineContainsCaret;
+}
+
+// See if something overrides the line background color:  Either if caret is on the line
+// and background color is set for that, or if a marker is defined that forces its background
+// color onto the line, or if a marker is defined but has no selection margin in which to
+// display itself (as long as it's not an SC_MARK_EMPTY marker).  These are checked in order
+// with the earlier taking precedence.  When multiple markers cause background override,
+// the color for the highest numbered one is used.
+ColourOptional ViewStyle::Background(int marksOfLine, bool caretActive, bool lineContainsCaret) const {
+       ColourOptional background;
+       if (!caretLineFrame && (caretActive || alwaysShowCaretLineBackground) && showCaretLineBackground &&
+               (caretLineAlpha == SC_ALPHA_NOALPHA) && lineContainsCaret) {
+               background = ColourOptional(caretLineBackground, true);
+       }
+       if (!background.isSet && marksOfLine) {
+               int marks = marksOfLine;
+               for (int markBit = 0; (markBit < 32) && marks; markBit++) {
+                       if ((marks & 1) && (markers[markBit].markType == SC_MARK_BACKGROUND) &&
+                               (markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
+                               background = ColourOptional(markers[markBit].back, true);
+                       }
+                       marks >>= 1;
+               }
+       }
+       if (!background.isSet && maskInLine) {
+               int marksMasked = marksOfLine & maskInLine;
+               if (marksMasked) {
+                       for (int markBit = 0; (markBit < 32) && marksMasked; markBit++) {
+                               if ((marksMasked & 1) &&
+                                       (markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
+                                       background = ColourOptional(markers[markBit].back, true);
+                               }
+                               marksMasked >>= 1;
+                       }
+               }
+       }
+       return background;
+}
+
+bool ViewStyle::SelectionBackgroundDrawn() const {
+       return selColours.back.isSet &&
+               ((selAlpha == SC_ALPHA_NOALPHA) || (selAdditionalAlpha == SC_ALPHA_NOALPHA));
+}
+
+bool ViewStyle::WhitespaceBackgroundDrawn() const {
+       return (viewWhitespace != wsInvisible) && (whitespaceColours.back.isSet);
+}
+
+bool ViewStyle::WhiteSpaceVisible(bool inIndent) const {
+       return (!inIndent && viewWhitespace == wsVisibleAfterIndent) ||
+               (inIndent && viewWhitespace == wsVisibleOnlyInIndent) ||
+               viewWhitespace == wsVisibleAlways;
+}
+
+ColourDesired ViewStyle::WrapColour() const {
+       if (whitespaceColours.fore.isSet)
+               return whitespaceColours.fore;
+       else
+               return styles[STYLE_DEFAULT].fore;
+}
+
+bool ViewStyle::SetWrapState(int wrapState_) {
+       WrapMode wrapStateWanted;
+       switch (wrapState_) {
+       case SC_WRAP_WORD:
+               wrapStateWanted = eWrapWord;
+               break;
+       case SC_WRAP_CHAR:
+               wrapStateWanted = eWrapChar;
+               break;
+       case SC_WRAP_WHITESPACE:
+               wrapStateWanted = eWrapWhitespace;
+               break;
+       default:
+               wrapStateWanted = eWrapNone;
+               break;
+       }
+       const bool changed = wrapState != wrapStateWanted;
+       wrapState = wrapStateWanted;
+       return changed;
+}
+
+bool ViewStyle::SetWrapVisualFlags(int wrapVisualFlags_) {
+       const bool changed = wrapVisualFlags != wrapVisualFlags_;
+       wrapVisualFlags = wrapVisualFlags_;
+       return changed;
+}
+
+bool ViewStyle::SetWrapVisualFlagsLocation(int wrapVisualFlagsLocation_) {
+       const bool changed = wrapVisualFlagsLocation != wrapVisualFlagsLocation_;
+       wrapVisualFlagsLocation = wrapVisualFlagsLocation_;
+       return changed;
+}
+
+bool ViewStyle::SetWrapVisualStartIndent(int wrapVisualStartIndent_) {
+       const bool changed = wrapVisualStartIndent != wrapVisualStartIndent_;
+       wrapVisualStartIndent = wrapVisualStartIndent_;
+       return changed;
+}
+
+bool ViewStyle::SetWrapIndentMode(int wrapIndentMode_) {
+       const bool changed = wrapIndentMode != wrapIndentMode_;
+       wrapIndentMode = wrapIndentMode_;
+       return changed;
+}
+
 void ViewStyle::AllocStyles(size_t sizeNew) {
        size_t i=styles.size();
        styles.resize(sizeNew);
@@ -421,28 +584,28 @@ void ViewStyle::AllocStyles(size_t sizeNew) {
        }
 }
 
-void ViewStyle::CreateFont(const FontSpecification &fs) {
+void ViewStyle::CreateAndAddFont(const FontSpecification &fs) {
        if (fs.fontName) {
                FontMap::iterator it = fonts.find(fs);
                if (it == fonts.end()) {
-                       fonts[fs] = new FontRealised();
+                       fonts[fs] = std::unique_ptr<FontRealised>(new FontRealised());
                }
        }
 }
 
 FontRealised *ViewStyle::Find(const FontSpecification &fs) {
        if (!fs.fontName)       // Invalid specification so return arbitrary object
-               return fonts.begin()->second;
+               return fonts.begin()->second.get();
        FontMap::iterator it = fonts.find(fs);
        if (it != fonts.end()) {
                // Should always reach here since map was just set for all styles
-               return it->second;
+               return it->second.get();
        }
        return 0;
 }
 
-void ViewStyle::FindMaxAscentDescent(unsigned int &maxAscent, unsigned int &maxDescent) {
-       for (FontMap::const_iterator it = fonts.begin(); it != fonts.end(); ++it) {
+void ViewStyle::FindMaxAscentDescent() {
+       for (FontMap::const_iterator it = fonts.cbegin(); it != fonts.cend(); ++it) {
                if (maxAscent < it->second->ascent)
                        maxAscent = it->second->ascent;
                if (maxDescent < it->second->descent)
diff --git a/plugins/scintilla/scintilla/src/ViewStyle.h b/plugins/scintilla/scintilla/src/ViewStyle.h
index 5593c0b..7210fa6 100644
--- a/plugins/scintilla/scintilla/src/ViewStyle.h
+++ b/plugins/scintilla/scintilla/src/ViewStyle.h
@@ -17,44 +17,74 @@ namespace Scintilla {
 class MarginStyle {
 public:
        int style;
+       ColourDesired back;
        int width;
        int mask;
        bool sensitive;
        int cursor;
-       MarginStyle();
+       MarginStyle(int style_= SC_MARGIN_SYMBOL, int width_=0, int mask_=0);
 };
 
 /**
  */
 class FontNames {
 private:
-       std::vector<char *> names;
-
-       // Private so FontNames objects can not be copied
-       FontNames(const FontNames &);
+       std::vector<UniqueString> names;
 public:
        FontNames();
+       // FontNames objects can not be copied.
+       FontNames(const FontNames &) = delete;
+       FontNames &operator=(const FontNames &) = delete;
        ~FontNames();
        void Clear();
        const char *Save(const char *name);
 };
 
 class FontRealised : public FontMeasurements {
-       // Private so FontRealised objects can not be copied
-       FontRealised(const FontRealised &);
-       FontRealised &operator=(const FontRealised &);
 public:
        Font font;
        FontRealised();
+       // FontRealised objects can not be copied.
+       FontRealised(const FontRealised &) = delete;
+       FontRealised &operator=(const FontRealised &) = delete;
        virtual ~FontRealised();
        void Realise(Surface &surface, int zoomLevel, int technology, const FontSpecification &fs);
 };
 
 enum IndentView {ivNone, ivReal, ivLookForward, ivLookBoth};
 
-enum WhiteSpaceVisibility {wsInvisible=0, wsVisibleAlways=1, wsVisibleAfterIndent=2};
+enum WhiteSpaceVisibility {wsInvisible=0, wsVisibleAlways=1, wsVisibleAfterIndent=2, 
wsVisibleOnlyInIndent=3};
+
+enum TabDrawMode {tdLongArrow=0, tdStrikeOut=1};
+
+typedef std::map<FontSpecification, std::unique_ptr<FontRealised>> FontMap;
+
+enum WrapMode { eWrapNone, eWrapWord, eWrapChar, eWrapWhitespace };
+
+class ColourOptional : public ColourDesired {
+public:
+       bool isSet;
+       ColourOptional(ColourDesired colour_=ColourDesired(0,0,0), bool isSet_=false) : 
ColourDesired(colour_), isSet(isSet_) {
+       }
+       ColourOptional(uptr_t wParam, sptr_t lParam) : ColourDesired(static_cast<long>(lParam)), isSet(wParam 
!= 0) {
+       }
+};
+
+struct ForeBackColours {
+       ColourOptional fore;
+       ColourOptional back;
+};
 
-typedef std::map<FontSpecification, FontRealised *> FontMap;
+struct EdgeProperties {
+       int column;
+       ColourDesired colour;
+       EdgeProperties(int column_ = 0, ColourDesired colour_ = ColourDesired(0)) :
+               column(column_), colour(colour_) {
+       }
+       EdgeProperties(uptr_t wParam, sptr_t lParam) :
+               column(static_cast<int>(wParam)), colour(static_cast<long>(lParam)) {
+       }
+};
 
 /**
  */
@@ -64,62 +94,58 @@ class ViewStyle {
 public:
        std::vector<Style> styles;
        size_t nextExtendedStyle;
-       LineMarker markers[MARKER_MAX + 1];
+       std::vector<LineMarker> markers;
        int largestMarkerHeight;
-       Indicator indicators[INDIC_MAX + 1];
+       std::vector<Indicator> indicators;
+       bool indicatorsDynamic;
+       bool indicatorsSetFore;
        int technology;
        int lineHeight;
+       int lineOverlap;
        unsigned int maxAscent;
        unsigned int maxDescent;
        XYPOSITION aveCharWidth;
        XYPOSITION spaceWidth;
-       bool selforeset;
-       ColourDesired selforeground;
+       XYPOSITION tabWidth;
+       ForeBackColours selColours;
        ColourDesired selAdditionalForeground;
-       bool selbackset;
-       ColourDesired selbackground;
        ColourDesired selAdditionalBackground;
-       ColourDesired selbackground2;
+       ColourDesired selBackground2;
        int selAlpha;
        int selAdditionalAlpha;
        bool selEOLFilled;
-       bool whitespaceForegroundSet;
-       ColourDesired whitespaceForeground;
-       bool whitespaceBackgroundSet;
-       ColourDesired whitespaceBackground;
+       ForeBackColours whitespaceColours;
+       int controlCharSymbol;
+       XYPOSITION controlCharWidth;
        ColourDesired selbar;
        ColourDesired selbarlight;
-       bool foldmarginColourSet;
-       ColourDesired foldmarginColour;
-       bool foldmarginHighlightColourSet;
-       ColourDesired foldmarginHighlightColour;
-       bool hotspotForegroundSet;
-       ColourDesired hotspotForeground;
-       bool hotspotBackgroundSet;
-       ColourDesired hotspotBackground;
+       ColourOptional foldmarginColour;
+       ColourOptional foldmarginHighlightColour;
+       ForeBackColours hotspotColours;
        bool hotspotUnderline;
        bool hotspotSingleLine;
        /// Margins are ordered: Line Numbers, Selection Margin, Spacing Margin
        int leftMarginWidth;    ///< Spacing margin on left of text
        int rightMarginWidth;   ///< Spacing margin on right of text
        int maskInLine; ///< Mask for markers to be put into text because there is nowhere for them to go in 
margin
-       MarginStyle ms[SC_MAX_MARGIN+1];
+       int maskDrawInText;     ///< Mask for markers that always draw in text
+       std::vector<MarginStyle> ms;
        int fixedColumnWidth;   ///< Total width of margins
        bool marginInside;      ///< true: margin included in text view, false: separate views
        int textStart;  ///< Starting x position of text within the view
        int zoomLevel;
        WhiteSpaceVisibility viewWhitespace;
+       TabDrawMode tabDrawMode;
        int whitespaceSize;
        IndentView viewIndentationGuides;
        bool viewEOL;
        ColourDesired caretcolour;
        ColourDesired additionalCaretColour;
+       int caretLineFrame;
        bool showCaretLineBackground;
        bool alwaysShowCaretLineBackground;
        ColourDesired caretLineBackground;
        int caretLineAlpha;
-       ColourDesired edgecolour;
-       int edgeState;
        int caretStyle;
        int caretWidth;
        bool someStylesProtected;
@@ -134,12 +160,28 @@ public:
        int braceHighlightIndicator;
        bool braceBadLightIndicatorSet;
        int braceBadLightIndicator;
+       int edgeState;
+       EdgeProperties theEdge;
+       std::vector<EdgeProperties> theMultiEdge;
+       int marginNumberPadding; // the right-side padding of the number margin
+       int ctrlCharPadding; // the padding around control character text blobs
+       int lastSegItalicsOffset; // the offset so as not to clip italic characters at EOLs
+
+       // Wrapping support
+       WrapMode wrapState;
+       int wrapVisualFlags;
+       int wrapVisualFlagsLocation;
+       int wrapVisualStartIndent;
+       int wrapIndentMode; // SC_WRAPINDENT_FIXED, _SAME, _INDENT
 
        ViewStyle();
        ViewStyle(const ViewStyle &source);
+       // Can only be copied through copy constructor which ensures font names initialised correctly
+       ViewStyle &operator=(const ViewStyle &) = delete;
        ~ViewStyle();
-       void Init(size_t stylesSize_=64);
-       void Refresh(Surface &surface);
+       void CalculateMarginWidthAndMask();
+       void Init(size_t stylesSize_=256);
+       void Refresh(Surface &surface, int tabInChars);
        void ReleaseAllExtendedStyles();
        int AllocateExtendedStyles(int numberStyles);
        void EnsureStyle(size_t index);
@@ -147,15 +189,30 @@ public:
        void ClearStyles();
        void SetStyleFontName(int styleIndex, const char *name);
        bool ProtectionActive() const;
+       int ExternalMarginWidth() const;
+       int MarginFromLocation(Point pt) const;
        bool ValidStyle(size_t styleIndex) const;
        void CalcLargestMarkerHeight();
+       int GetFrameWidth() const;
+       bool IsLineFrameOpaque(bool caretActive, bool lineContainsCaret) const;
+       ColourOptional Background(int marksOfLine, bool caretActive, bool lineContainsCaret) const;
+       bool SelectionBackgroundDrawn() const;
+       bool WhitespaceBackgroundDrawn() const;
+       ColourDesired WrapColour() const;
+
+       bool SetWrapState(int wrapState_);
+       bool SetWrapVisualFlags(int wrapVisualFlags_);
+       bool SetWrapVisualFlagsLocation(int wrapVisualFlagsLocation_);
+       bool SetWrapVisualStartIndent(int wrapVisualStartIndent_);
+       bool SetWrapIndentMode(int wrapIndentMode_);
+
+       bool WhiteSpaceVisible(bool inIndent) const;
+
 private:
        void AllocStyles(size_t sizeNew);
-       void CreateFont(const FontSpecification &fs);
+       void CreateAndAddFont(const FontSpecification &fs);
        FontRealised *Find(const FontSpecification &fs);
-       void FindMaxAscentDescent(unsigned int &maxAscent, unsigned int &maxDescent);
-       // Private so can only be copied through copy constructor which ensures font names initialised 
correctly
-       ViewStyle &operator=(const ViewStyle &);
+       void FindMaxAscentDescent();
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/XPM.cxx b/plugins/scintilla/scintilla/src/XPM.cxx
index d6397af..818a1ac 100644
--- a/plugins/scintilla/scintilla/src/XPM.cxx
+++ b/plugins/scintilla/scintilla/src/XPM.cxx
@@ -5,11 +5,13 @@
 // Copyright 1998-2003 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
-#include <string.h>
-#include <stdlib.h>
+#include <cstdlib>
+#include <cstring>
 
+#include <stdexcept>
 #include <vector>
 #include <map>
+#include <memory>
 
 #include "Platform.h"
 
@@ -21,13 +23,13 @@ using namespace Scintilla;
 
 static const char *NextField(const char *s) {
        // In case there are leading spaces in the string
-       while (*s && *s == ' ') {
+       while (*s == ' ') {
                s++;
        }
        while (*s && *s != ' ') {
                s++;
        }
-       while (*s && *s == ' ') {
+       while (*s == ' ') {
                s++;
        }
        return s;
@@ -45,9 +47,9 @@ ColourDesired XPM::ColourFromCode(int ch) const {
        return colourCodeTable[ch];
 }
 
-void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) {
+void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) const {
        if ((code != codeTransparent) && (startX != x)) {
-               PRectangle rc(startX, y, x, y+1);
+               PRectangle rc = PRectangle::FromInts(startX, y, x, y + 1);
                surface->FillRectangle(rc, ColourFromCode(code));
        }
 }
@@ -61,11 +63,9 @@ XPM::XPM(const char *const *linesForm) {
 }
 
 XPM::~XPM() {
-       Clear();
 }
 
 void XPM::Init(const char *textForm) {
-       Clear();
        // Test done is two parts to avoid possibility of overstepping the memory
        // if memcmp implemented strangely. Must be 4 bytes at least at destination.
        if ((0 == memcmp(textForm, "/* X", 4)) && (0 == memcmp(textForm, "/* XPM */", 9))) {
@@ -81,7 +81,6 @@ void XPM::Init(const char *textForm) {
 }
 
 void XPM::Init(const char *const *linesForm) {
-       Clear();
        height = 1;
        width = 1;
        nColours = 1;
@@ -112,34 +111,31 @@ void XPM::Init(const char *const *linesForm) {
                if (*colourDef == '#') {
                        colour.Set(colourDef);
                } else {
-                       codeTransparent = code;
+                       codeTransparent = static_cast<char>(code);
                }
                colourCodeTable[code] = colour;
        }
 
        for (int y=0; y<height; y++) {
                const char *lform = linesForm[y+nColours+1];
-               size_t len = MeasureLength(lform);
-               for (size_t x = 0; x<len; x++) 
+               const size_t len = MeasureLength(lform);
+               for (size_t x = 0; x<len; x++)
                        pixels[y * width + x] = static_cast<unsigned char>(lform[x]);
        }
 }
 
-void XPM::Clear() {
-}
-
-void XPM::Draw(Surface *surface, PRectangle &rc) {
+void XPM::Draw(Surface *surface, const PRectangle &rc) {
        if (pixels.empty()) {
                return;
        }
        // Centre the pixmap
-       int startY = rc.top + (rc.Height() - height) / 2;
-       int startX = rc.left + (rc.Width() - width) / 2;
+       const int startY = static_cast<int>(rc.top + (rc.Height() - height) / 2);
+       const int startX = static_cast<int>(rc.left + (rc.Width() - width) / 2);
        for (int y=0; y<height; y++) {
                int prevCode = 0;
                int xStartRun = 0;
                for (int x=0; x<width; x++) {
-                       int code = pixels[y * width + x];
+                       const int code = pixels[y * width + x];
                        if (code != prevCode) {
                                FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + x);
                                xStartRun = x;
@@ -244,7 +240,7 @@ void RGBAImage::SetPixel(int x, int y, ColourDesired colour, int alpha) {
        pixel[3] = static_cast<unsigned char>(alpha);
 }
 
-RGBAImageSet::RGBAImageSet() : height(-1), width(-1){
+RGBAImageSet::RGBAImageSet() : height(-1), width(-1) {
 }
 
 RGBAImageSet::~RGBAImageSet() {
@@ -253,10 +249,6 @@ RGBAImageSet::~RGBAImageSet() {
 
 /// Remove all images.
 void RGBAImageSet::Clear() {
-       for (ImageMap::iterator it=images.begin(); it != images.end(); ++it) {
-               delete it->second;
-               it->second = 0;
-       }
        images.clear();
        height = -1;
        width = -1;
@@ -266,10 +258,9 @@ void RGBAImageSet::Clear() {
 void RGBAImageSet::Add(int ident, RGBAImage *image) {
        ImageMap::iterator it=images.find(ident);
        if (it == images.end()) {
-               images[ident] = image;
+               images[ident] = std::unique_ptr<RGBAImage>(image);
        } else {
-               delete it->second;
-               it->second = image;
+               it->second.reset(image);
        }
        height = -1;
        width = -1;
@@ -279,17 +270,17 @@ void RGBAImageSet::Add(int ident, RGBAImage *image) {
 RGBAImage *RGBAImageSet::Get(int ident) {
        ImageMap::iterator it = images.find(ident);
        if (it != images.end()) {
-               return it->second;
+               return it->second.get();
        }
-       return NULL;
+       return nullptr;
 }
 
 /// Give the largest height of the set.
 int RGBAImageSet::GetHeight() const {
        if (height < 0) {
-               for (ImageMap::const_iterator it=images.begin(); it != images.end(); ++it) {
-                       if (height < it->second->GetHeight()) {
-                               height = it->second->GetHeight();
+               for (const std::pair<const int, std::unique_ptr<RGBAImage>> &image : images) {
+                       if (height < image.second->GetHeight()) {
+                               height = image.second->GetHeight();
                        }
                }
        }
@@ -299,9 +290,9 @@ int RGBAImageSet::GetHeight() const {
 /// Give the largest width of the set.
 int RGBAImageSet::GetWidth() const {
        if (width < 0) {
-               for (ImageMap::const_iterator it=images.begin(); it != images.end(); ++it) {
-                       if (width < it->second->GetWidth()) {
-                               width = it->second->GetWidth();
+               for (const std::pair<const int, std::unique_ptr<RGBAImage>> &image : images) {
+                       if (width < image.second->GetWidth()) {
+                               width = image.second->GetWidth();
                        }
                }
        }
diff --git a/plugins/scintilla/scintilla/src/XPM.h b/plugins/scintilla/scintilla/src/XPM.h
index c19025d..cd78b14 100644
--- a/plugins/scintilla/scintilla/src/XPM.h
+++ b/plugins/scintilla/scintilla/src/XPM.h
@@ -23,16 +23,15 @@ class XPM {
        ColourDesired colourCodeTable[256];
        char codeTransparent;
        ColourDesired ColourFromCode(int ch) const;
-       void FillRun(Surface *surface, int code, int startX, int y, int x);
+       void FillRun(Surface *surface, int code, int startX, int y, int x) const;
 public:
-       XPM(const char *textForm);
-       XPM(const char *const *linesForm);
+       explicit XPM(const char *textForm);
+       explicit XPM(const char *const *linesForm);
        ~XPM();
        void Init(const char *textForm);
        void Init(const char *const *linesForm);
-       void Clear();
        /// Decompose image into runs and use FillRectangle for each run
-       void Draw(Surface *surface, PRectangle &rc);
+       void Draw(Surface *surface, const PRectangle &rc);
        int GetHeight() const { return height; }
        int GetWidth() const { return width; }
        void PixelAt(int x, int y, ColourDesired &colour, bool &transparent) const;
@@ -44,16 +43,16 @@ private:
  * A translucent image stored as a sequence of RGBA bytes.
  */
 class RGBAImage {
-       // Private so RGBAImage objects can not be copied
-       RGBAImage(const RGBAImage &);
-       RGBAImage &operator=(const RGBAImage &);
        int height;
        int width;
        float scale;
        std::vector<unsigned char> pixelBytes;
 public:
        RGBAImage(int width_, int height_, float scale_, const unsigned char *pixels_);
-       RGBAImage(const XPM &xpm);
+       explicit RGBAImage(const XPM &xpm);
+       // Deleted so RGBAImage objects can not be copied.
+       RGBAImage(const RGBAImage &) = delete;
+       RGBAImage &operator=(const RGBAImage &) = delete;
        virtual ~RGBAImage();
        int GetHeight() const { return height; }
        int GetWidth() const { return width; }
@@ -62,14 +61,14 @@ public:
        float GetScaledWidth() const { return width / scale; }
        int CountBytes() const;
        const unsigned char *Pixels() const;
-       void SetPixel(int x, int y, ColourDesired colour, int alpha=0xff); 
+       void SetPixel(int x, int y, ColourDesired colour, int alpha=0xff);
 };
 
 /**
  * A collection of RGBAImage pixmaps indexed by integer id.
  */
 class RGBAImageSet {
-       typedef std::map<int, RGBAImage*> ImageMap;
+       typedef std::map<int, std::unique_ptr<RGBAImage>> ImageMap;
        ImageMap images;
        mutable int height;     ///< Memorize largest height of the set.
        mutable int width;      ///< Memorize largest width of the set.
diff --git a/plugins/scintilla/text-editor-iterable.c b/plugins/scintilla/text-editor-iterable.c
index fe7ad6f..79822b4 100644
--- a/plugins/scintilla/text-editor-iterable.c
+++ b/plugins/scintilla/text-editor-iterable.c
@@ -35,6 +35,7 @@
 #undef PLAT_GTK
 #define PLAT_GTK 1
 
+#define INCLUDE_DEPRECATED_FEATURES
 #include <gtk/gtk.h>
 #include "Scintilla.h"
 #include "ScintillaWidget.h"
diff --git a/plugins/scintilla/text_editor.c b/plugins/scintilla/text_editor.c
index 12c8601..40718d7 100644
--- a/plugins/scintilla/text_editor.c
+++ b/plugins/scintilla/text_editor.c
@@ -72,6 +72,7 @@
 #define GTK
 #undef PLAT_GTK
 #define PLAT_GTK 1
+#define INCLUDE_DEPRECATED_FEATURES
 #include "Scintilla.h"
 #include "SciLexer.h"
 #include "ScintillaWidget.h"
diff --git a/plugins/scintilla/text_editor_cbs.c b/plugins/scintilla/text_editor_cbs.c
index c69399f..77dda30 100644
--- a/plugins/scintilla/text_editor_cbs.c
+++ b/plugins/scintilla/text_editor_cbs.c
@@ -37,6 +37,7 @@
 #define GTK
 #undef PLAT_GTK
 #define PLAT_GTK 1
+#define INCLUDE_DEPRECATED_FEATURES
 #include "Scintilla.h"
 #include "SciLexer.h"
 #include "ScintillaWidget.h"
diff --git a/plugins/scintilla/text_editor_prefs.c b/plugins/scintilla/text_editor_prefs.c
index b5d4a89..887cf5f 100644
--- a/plugins/scintilla/text_editor_prefs.c
+++ b/plugins/scintilla/text_editor_prefs.c
@@ -28,6 +28,7 @@
 #define GTK
 #undef PLAT_GTK
 #define PLAT_GTK 1
+#define INCLUDE_DEPRECATED_FEATURES
 #include "Scintilla.h"
 #include "SciLexer.h"
 #include "ScintillaWidget.h"


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]