[anjuta-extras] scintilla: Update to scintilla 3.2.0



commit 0febcae503d14b59bbce8fb3df39f27a0902fab4
Author: SÃbastien Granjoux <seb sfo free fr>
Date:   Sat Jun 2 21:41:06 2012 +0200

    scintilla: Update to scintilla 3.2.0

 plugins/scintilla/properties/styles.properties     |  313 +++++++++++-
 plugins/scintilla/scintilla/Makefile.am            |    2 +-
 plugins/scintilla/scintilla/gtk/PlatGTK.cxx        |   22 +-
 plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx   |   48 +-
 plugins/scintilla/scintilla/include/Platform.h     |   11 +
 plugins/scintilla/scintilla/include/SciLexer.h     |   73 +++
 plugins/scintilla/scintilla/include/Scintilla.h    |   11 +
 .../scintilla/scintilla/include/Scintilla.iface    |  113 ++++-
 plugins/scintilla/scintilla/lexers.make            |    6 +
 plugins/scintilla/scintilla/lexers/LexAsm.cxx      |    2 +-
 plugins/scintilla/scintilla/lexers/LexBash.cxx     |   11 +-
 plugins/scintilla/scintilla/lexers/LexBasic.cxx    |    2 +-
 plugins/scintilla/scintilla/lexers/LexCPP.cxx      |   23 +-
 plugins/scintilla/scintilla/lexers/LexD.cxx        |    2 +-
 plugins/scintilla/scintilla/lexers/LexECL.cxx      |  512 ++++++++++++++++++
 plugins/scintilla/scintilla/lexers/LexHTML.cxx     |   16 +-
 plugins/scintilla/scintilla/lexers/LexNsis.cxx     |    1 +
 plugins/scintilla/scintilla/lexers/LexOScript.cxx  |  548 ++++++++++++++++++++
 plugins/scintilla/scintilla/lexers/LexOthers.cxx   |   21 +-
 plugins/scintilla/scintilla/lexers/LexPascal.cxx   |   20 +
 plugins/scintilla/scintilla/lexers/LexPerl.cxx     |    5 +-
 plugins/scintilla/scintilla/lexers/LexRuby.cxx     |    2 -
 plugins/scintilla/scintilla/lexers/LexSQL.cxx      |  130 ++++--
 plugins/scintilla/scintilla/lexers/LexTADS3.cxx    |    2 +-
 plugins/scintilla/scintilla/lexers/LexVHDL.cxx     |    3 -
 .../scintilla/scintilla/lexers/LexVisualProlog.cxx |  470 +++++++++++++++++
 plugins/scintilla/scintilla/lexlib/LexAccessor.h   |    2 +-
 .../scintilla/patches/scintilla-scroll-mask.diff   |   10 -
 plugins/scintilla/scintilla/src/AutoComplete.cxx   |    7 +-
 plugins/scintilla/scintilla/src/AutoComplete.h     |    1 +
 plugins/scintilla/scintilla/src/Catalogue.cxx      |    3 +
 plugins/scintilla/scintilla/src/CellBuffer.cxx     |    8 +
 plugins/scintilla/scintilla/src/CellBuffer.h       |    2 +
 plugins/scintilla/scintilla/src/Decoration.cxx     |    4 +-
 plugins/scintilla/scintilla/src/Document.cxx       |  243 +++++-----
 plugins/scintilla/scintilla/src/Document.h         |    3 +-
 plugins/scintilla/scintilla/src/Editor.cxx         |  532 ++++++++++---------
 plugins/scintilla/scintilla/src/Editor.h           |   13 +-
 plugins/scintilla/scintilla/src/LineMarker.cxx     |   41 +-
 plugins/scintilla/scintilla/src/LineMarker.h       |   28 +-
 plugins/scintilla/scintilla/src/PerLine.cxx        |   50 +-
 plugins/scintilla/scintilla/src/ScintillaBase.cxx  |    7 +
 plugins/scintilla/scintilla/src/SplitVector.h      |   18 +
 plugins/scintilla/scintilla/src/Style.cxx          |    2 -
 plugins/scintilla/scintilla/src/Style.h            |    4 +-
 plugins/scintilla/scintilla/src/UniConversion.cxx  |  117 +++++
 plugins/scintilla/scintilla/src/UniConversion.h    |   15 +
 plugins/scintilla/scintilla/src/ViewStyle.cxx      |   29 +-
 plugins/scintilla/scintilla/src/ViewStyle.h        |    4 +-
 plugins/scintilla/scintilla/src/XPM.cxx            |    8 -
 50 files changed, 2950 insertions(+), 570 deletions(-)
---
diff --git a/plugins/scintilla/properties/styles.properties b/plugins/scintilla/properties/styles.properties
index f85201e..b069b2c 100644
--- a/plugins/scintilla/properties/styles.properties
+++ b/plugins/scintilla/properties/styles.properties
@@ -1990,7 +1990,7 @@ if PLAT_GTK
 if PLAT_WIN
 	command.build.*.cs=csc /t:winexe $(FileNameExt) /r:system.dll,system.drawing.dll
 	command.go.*.cs=$(FileName)
-	command.go.subsystem.*.cs=1
+	command.go.subsystem.*.cs=0
 if PLAT_GTK
 	command.build.*.cs=mcs /t:winexe $(FileNameExt) /r:System,System.Drawing
 	command.go.*.cs=mono $(FileName).exe
@@ -2400,6 +2400,43 @@ command.go.*.d=$(FileName)
 
 
 ###############################################################################
+# From ecl.properties
+file.patterns.ecl=*.ecl;*.eclattr;*.hql
+filter.ecl=ECL (ecl, eclattr, hql)|$(file.patterns.ecl)|
+lexer.$(file.patterns.ecl)=ecl
+
+word.chars.ecl=$(chars.alpha)$(chars.numeric)_#
+word.characters.$(file.patterns.ecl)=$(word.chars.ecl)
+calltip.ecl.word.characters=$(chars.alpha)$(chars.numeric)_
+
+#comment.block.at.line.start.ecl=1
+comment.block.ecl=//
+comment.stream.start.ecl=/+
+comment.stream.end.ecl=+/
+comment.box.start.ecl=/*
+comment.box.middle.ecl= *
+comment.box.end.ecl= */
+#lexer.ecl.fold.at.else=1
+
+statement.indent.$(file.patterns.ecl)=record module
+statement.end.$(file.patterns.ecl)=13 ;
+statement.lookback.$(file.patterns.ecl)=20
+block.start.$(file.patterns.ecl)=13 {
+block.end.$(file.patterns.ecl)=13 }
+
+
+keywords.$(file.patterns.ecl)=abs acos ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize cos cosh count cron dataset dedup denormalize distribute distributed distribution ebcdic enth error evaluate event exists exp fetch fromunicode getisvalid global group hash hash32 hash64 hashcrc hashmd5 if index intformat isvalid iterate join keyunicode length limit ln log map matched matchlength matchposition matchtext matchunicode max merge min normalize parse pipe power preload project pull random rank ranked realformat recordof regexfind regexreplace rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt sum table tan tanh topn tounicode transfer trim truncate typeof ungroup unicodeorder which workunit xmldecode xmlencode xmltext xmlunicode
+keywords2.$(file.patterns.ecl)=apply build buildindex evaluate fail keydiff keypatch loadxml notify output parallel sequential soapcall
+keywords3.$(file.patterns.ecl)=__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat full function group header heading hole ifblock import in joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase( noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath
+keywords4.$(file.patterns.ecl)=ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode
+keywords5.$(file.patterns.ecl)=checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when
+keywords6.$(file.patterns.ecl)=#append #break #declare #demangle #end #for #getdatatype #if #inmodule #loop #mangle #onwarning #option #set #stored #uniquename #workunit integer symbol value text symbol value
+
+#command.build.$(file.patterns.ecl)=eclcc.exe -I"$(HPCCBIN)\ecllibrary" -I"$(HPCCBIN)\ecllibrary" -I"$(HPCCBIN)\plugins" "$(FileNameExt)"
+
+
+
+###############################################################################
 # From eiffel.properties
 # Define SciTE settings for Eiffel files.
 
@@ -4882,6 +4919,170 @@ keywords2.$(file.patterns.opal)=$(keywordclass.opal_sorts)
 
 
 ###############################################################################
+# From oscript.properties
+# Defines SciTE settings for OScript sources; osx files and/or OSpace dumps.
+# OScript is a programming language used to develop applications for the
+# Livelink server platform.
+
+##############################################################################
+# Specify file extension and lexer class.
+
+file.patterns.oscript=*.osx
+filter.oscript=OScript (osx)|$(file.patterns.oscript)|
+lexer.$(file.patterns.oscript)=oscript
+
+##############################################################################
+# Specify various editor parameters.
+
+word.chars.oscript=$(chars.alpha)$(chars.numeric)_$
+word.characters.$(file.patterns.oscript)=$(word.chars.oscript)
+
+#comment.block.at.line.start.oscript=1
+comment.block.oscript=//~
+#~ comment.stream.start.oscript=#ifdef DOC
+#~ comment.stream.end.oscript=#endif
+comment.stream.start.oscript=/*
+comment.stream.end.oscript=*/
+comment.box.start.oscript=/*
+comment.box.middle.oscript= *
+comment.box.end.oscript= */
+
+statement.indent.$(file.patterns.oscript)=6 case default else for if \
+repeat switch while
+statement.lookback.$(file.patterns.oscript)=20
+statement.end.$(file.patterns.oscript)=10 ;
+block.start.$(file.patterns.oscript)=10 if
+block.end.$(file.patterns.oscript)=10 end
+indent.maintain.$(file.patterns.oscript)=1
+indent.size.$(file.patterns.oscript)=4
+use.tabs.$(file.patterns.oscript)=1
+tab.size.$(file.patterns.oscript)=4
+
+preprocessor.symbol.$(file.patterns.oscript)=#
+preprocessor.start.$(file.patterns.oscript)=ifdef ifndef
+preprocessor.middle.$(file.patterns.oscript)=else
+preprocessor.end.$(file.patterns.oscript)=endif
+
+##############################################################################
+# Specify API autocompletion and calltip help.
+
+api.$(file.patterns.oscript)=$(SciteDefaultHome)\api\oscript.api
+autocomplete.oscript.ignorecase=1
+calltip.oscript.ignorecase=1
+calltip.oscript.use.escapes=1
+calltip.oscript.word.characters=_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$.
+
+##############################################################################
+# Define keyword classes separately according to the language semantics
+# before grouping them to keywords for styling. OScript is not case-sensitive;
+# all keywords configured here must be entered in lower-case.
+
+# Language native value and reference types.
+keywordclass.type=\
+assoc boolean bytes date dynamic error extern file integer list long object \
+point real recarray record script string
+
+# Word-like (literal) operators (boolean).
+keywordclass.operator=\
+and eq ge gt le lt ne not or xor
+
+# Code-flow control statements.
+keywordclass.oscript.control=\
+break breakif by case continue continueif default downto else elseif end for \
+goto if in repeat switch to until while
+
+# Keywords to declare functions.
+keywordclass.function=\
+function return void
+
+# Various language native keywords and reserved words.
+keywordclass.miscellaneous=\
+dll inbyref inout linked nodebug super this xcmd xfcn
+
+# Constants with values and defaults for primitive types.
+keywordclass.constant=\
+false true undefined
+
+# Language native constants (type classification integers).
+keywordclass.coreconstant=\
+booleantype bytestype datatype dynamictype errortype externtype integertype \
+listtype longtype objecttype objreftype pointtype realtype scripttype \
+stringtype undefinedtype voidtype
+
+# Language native functions not bound to any object (global).
+keywordclass.corefunction=\
+datatypename echo echodebug echoerror echoinfo echostamp echowarn \
+getfeatures isdefined iserror isfeature isinvokable isnoterror isnotset \
+isobject isset isundefined length nparameters parameters pointh pointv type
+
+# Object types available in Livelink kernel and core modules.
+keywordclass.builtintype=\
+cachetree capiconnect capierr capilog capilogin compiler dapisession \
+dapinode dapiversion dapistream filecopy fileprefs frame javaobject \
+mailmessage pop3session smtpsession ssloptions patfind patchange regex \
+socket sqlconnection sqlcursor uapisession uapiuser wapisession wapimap \
+wapimaptask wapiwork wapisubwork domattr domcdatasection domcharacterdata \
+domcomment domdocument domdocumentfragment domdocumenttype domelement \
+domentity domentityreference domimplementation domnamednodemap domnode \
+domnodelist domnotation domparser domprocessinginstruction domtext saxparser \
+xslprocessor
+
+# Singletons available in Livelink kernel and core modules; they offer only
+# static methods to call.
+keywordclass.builtinobject=\
+capi dapi env global language logging math memcached otds pattern security \
+sql str system uapi vis wapi web zip
+
+# Keywords usable in WebLingo sources (HTML templates including OScript).
+keywordclass.weblingo=\
+call html oscript
+
+##############################################################################
+# Define keyword groups that are recognized by the lexer and can be assigned
+# different styles.
+
+# Language native keywords: SCE_OSCRIPT_KEYWORD state.
+keywords.$(file.patterns.oscript)=$(keywordclass.oscript.control) \
+$(keywordclass.function) $(keywordclass.miscellaneous)
+
+# Constants: SCE_OSCRIPT_CONSTANT state.
+keywords2.$(file.patterns.oscript)=$(keywordclass.constant) \
+$(keywordclass.coreconstant)
+
+# Word-like (literal) operators: SCE_OSCRIPT_OPERATOR state.
+keywords3.$(file.patterns.oscript)=$(keywordclass.operator)
+
+# Value and reference (object) types: SCE_OSCRIPT_TYPE state.
+keywords4.$(file.patterns.oscript)=$(keywordclass.type) \
+$(keywordclass.builtintype)
+
+# Language native (global) functions: SCE_OSCRIPT_FUNCTION state.
+keywords5.$(file.patterns.oscript)=$(keywordclass.corefunction)
+
+# Core static objects: SCE_OSCRIPT_OBJECT state.
+keywords6.$(file.patterns.oscript)=$(keywordclass.builtinobject)
+
+##############################################################################
+# Define Style definitions supported by the lexical states. There are multiple
+# states for language keyword groups although they all are reserved words; to
+# be able ot assign them different styles.
+
+# Documentation comment; a text delimited by preprocessor directives
+# Type available in the language, in kernel or code modules.
+# Global function in the language, in kernel or code modules.
+
+braces.oscript.style=12
+
+##############################################################################
+# Specify help.
+
+if PLAT_WIN
+	command.help.$(file.patterns.oscript)=$(CurrentWord)!C:\LL971\builder\documentation.chm
+	command.help.subsystem.$(file.patterns.oscript)=4
+
+
+
+###############################################################################
 # From others.properties
 # Define SciTE settings for other simple files.
 
@@ -5207,6 +5408,8 @@ command.2.$(file.patterns.perl)=perl -d:DProf $(FileNameExt)
 command.name.3.$(file.patterns.perl)=Profiler Parser
 command.3.$(file.patterns.perl)=C:\Perl\bin\dprofpp.bat $(FileDir)\tmon.out
 
+command.go.$(file.patterns.bash)=bash $(FileNameExt)
+
 
 
 ###############################################################################
@@ -6322,7 +6525,7 @@ join \
 key \
 language large last lateral leading left less level like \
 limit local localtime localtimestamp locator \
-map match minute modifies modify module month \
+map match merge minute modifies modify module month \
 names national natural nchar nclob new next no none \
 not null numeric \
 object of off old on only open operation option \
@@ -6634,6 +6837,14 @@ command.7.$(file.patterns.context)=
 command.8.$(file.patterns.context)=
 command.9.$(file.patterns.context)=
 
+# BibTeX command
+command.name.2.$(file.patterns.tex)=BibTeX
+command.name.2.$(file.patterns.latex)=BibTeX
+command.name.2.$(file.patterns.context)=BibTeX
+command.2.$(file.patterns.tex)=bibtex $(FileName)
+command.2.$(file.patterns.latex)=bibtex $(FileName)
+command.2.$(file.patterns.context)=bibtex $(FileName)
+
 # TeX: highlighting
 
 
@@ -8212,6 +8423,68 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 
 ###############################################################################
+# Style for ecl from file ecl.properties
+
+#
+	style.ecl.0=$(style.anjuta.normal)
+#
+	style.ecl.1=$(style.anjuta.comment)
+#
+	style.ecl.2=$(style.anjuta.comment)
+#
+	style.ecl.3=$(style.anjuta.number)
+#
+	style.ecl.4=$(style.anjuta.string)
+#
+	style.ecl.5=$(style.anjuta.definition)
+#
+	style.ecl.6=$(style.anjuta.operator)
+#
+	style.ecl.7=$(style.anjuta.char)
+#
+	style.ecl.8=$(style.anjuta.attribute)
+#
+	style.ecl.9=$(style.anjuta.preprocessor)
+#
+	style.ecl.10=$(style.anjuta.error)
+#
+	style.ecl.11=$(style.anjuta.identifier)
+#
+	style.ecl.12=$(style.anjuta.unclosed)
+#
+	style.ecl.13=$(style.anjuta.string)
+#
+	style.ecl.14=$(style.anjuta.regex)
+#
+	style.ecl.15=$(style.anjuta.comment)
+#
+	style.ecl.16=$(style.anjuta.keyword)
+#
+	style.ecl.17=$(style.anjuta.comment)
+#
+	style.ecl.18=$(style.anjuta.comment)
+#
+	style.ecl.19=$(style.anjuta.localkeyword)
+#
+	style.ecl.20=$(style.anjuta.syskeyword)
+#
+	style.ecl.21=$(style.anjuta.extrakeyword)
+#
+	style.ecl.22=$(style.anjuta.function)
+#
+	style.ecl.23=$(style.anjuta.comment)
+#
+	style.ecl.24=$(style.anjuta.attribute)
+#
+	style.ecl.25=$(style.anjuta.attribute)
+#
+	style.ecl.26=$(style.anjuta.attribute)
+#
+	style.ecl.27=$(style.anjuta.attribute)
+
+
+
+###############################################################################
 # Style for eiffel from file eiffel.properties
 
 # Default
@@ -9342,6 +9615,42 @@ keywords.$(file.patterns.yaml)=true false yes no
 
 
 ###############################################################################
+# Style for oscript from file oscript.properties
+
+# Single-line comment.
+	style.oscript.1=$(style.anjuta.comment)
+# Multi-line comment.
+	style.oscript.2=$(style.anjuta.comment)
+# #ifdef DOC and #endif; the value of DOC is supposed to be never defined.
+	style.oscript.3=$(style.anjuta.comment)
+# Preprocessor directive.
+	style.oscript.4=$(style.anjuta.preprocessor)
+# Number.
+	style.oscript.5=$(style.anjuta.number)
+# String enclosed in single quotes (apostrophes).
+	style.oscript.6=$(style.anjuta.char)
+# String enclosed in double quotes (quotation marks).
+	style.oscript.7=$(style.anjuta.string)
+# Constant literal. See the property keywords2 above.
+	style.oscript.8=$(style.anjuta.localkeyword)
+# Server-global variable (prefixed by $).
+	style.oscript.10=$(style.anjuta.definition)
+# Language native keyword or reserved word. See the property keywords above.
+	style.oscript.11=$(style.anjuta.keyword)
+# Operator; either symbolic or literal. See the property keywords3 above.
+	style.oscript.12=$(style.anjuta.operator)
+# Label to jump to with the GoTo statement.
+	style.oscript.13=$(style.anjuta.identifier)
+# See the property keywords4 above.
+	style.oscript.14=$(style.anjuta.syskeyword)
+# See the property keywords5 above.
+	style.oscript.15=$(style.anjuta.extrakeyword)
+# Static built-in object. See the property keywords6 above.
+	style.oscript.16=$(style.anjuta.function)
+
+
+
+###############################################################################
 # Style for pascal from file pascal.properties
 
 # White space
diff --git a/plugins/scintilla/scintilla/Makefile.am b/plugins/scintilla/scintilla/Makefile.am
index dd6e80d..b517ebc 100644
--- a/plugins/scintilla/scintilla/Makefile.am
+++ b/plugins/scintilla/scintilla/Makefile.am
@@ -139,7 +139,7 @@ update-scintilla:
 	echo "Patching files ..."
 	cd $(srcdir); \
 	for patchfile in patches/*.diff; do \
-		patch -p0 < $$patchfile; \
+		patch -p0 < $$patchfile || true; \
 	done
 	echo "Updating properties file..."
 	cd $(srcdir); \
diff --git a/plugins/scintilla/scintilla/gtk/PlatGTK.cxx b/plugins/scintilla/scintilla/gtk/PlatGTK.cxx
index b7ce385..d98c235 100644
--- a/plugins/scintilla/scintilla/gtk/PlatGTK.cxx
+++ b/plugins/scintilla/scintilla/gtk/PlatGTK.cxx
@@ -25,6 +25,11 @@
 #include "UniConversion.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
@@ -1355,7 +1360,7 @@ struct ListImage {
 };
 
 static void list_image_free(gpointer, gpointer value, gpointer) {
-	ListImage *list_image = (ListImage *) value;
+	ListImage *list_image = static_cast<ListImage *>(value);
 	if (list_image->pixbuf)
 		g_object_unref(list_image->pixbuf);
 	g_free(list_image);
@@ -1577,6 +1582,11 @@ 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);
+#endif
 		int height;
 
 		// First calculate height of the clist for our desired visible
@@ -1610,7 +1620,7 @@ PRectangle ListBoxX::GetDesiredRect() {
 		gtk_widget_size_request(GTK_WIDGET(scroller), &req);
 #endif
 		rc.right = req.width;
-		rc.bottom = req.height;
+		rc.bottom = Platform::Maximum(height, req.height);
 
 		gtk_widget_set_size_request(GTK_WIDGET(list), -1, -1);
 		int width = maxItemCharacters;
@@ -1659,8 +1669,8 @@ static void init_pixmap(ListImage *list_image) {
 void ListBoxX::Append(char *s, int type) {
 	ListImage *list_image = NULL;
 	if ((type >= 0) && pixhash) {
-		list_image = (ListImage *) g_hash_table_lookup((GHashTable *) pixhash
-		             , (gconstpointer) GINT_TO_POINTER(type));
+		list_image = static_cast<ListImage *>(g_hash_table_lookup((GHashTable *) pixhash
+		             , (gconstpointer) GINT_TO_POINTER(type)));
 	}
 	GtkTreeIter iter;
 	GtkListStore *store =
@@ -1825,8 +1835,8 @@ void ListBoxX::RegisterRGBA(int type, RGBAImage *image) {
 	if (!pixhash) {
 		pixhash = g_hash_table_new(g_direct_hash, g_direct_equal);
 	}
-	ListImage *list_image = (ListImage *) g_hash_table_lookup((GHashTable *) pixhash,
-		(gconstpointer) GINT_TO_POINTER(type));
+	ListImage *list_image = static_cast<ListImage *>(g_hash_table_lookup((GHashTable *) pixhash,
+		(gconstpointer) GINT_TO_POINTER(type)));
 	if (list_image) {
 		// Drop icon already registered
 		if (list_image->pixbuf)
diff --git a/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx b/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx
index 4bb46cc..be007e7 100644
--- a/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx
+++ b/plugins/scintilla/scintilla/gtk/ScintillaGTK.cxx
@@ -64,6 +64,11 @@
 
 #include "Converter.h"
 
+#if defined(__clang__)
+// Clang 3.0 incorrectly displays  sentinel warnings. Fixed by clang 3.1.
+#pragma GCC diagnostic ignored "-Wsentinel"
+#endif
+
 #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)))
@@ -1074,8 +1079,8 @@ bool ScintillaGTK::PaintContains(PRectangle rc) {
 				rc.right - rc.left, rc.bottom - rc.top};
 			contains = CRectListContains(rgnUpdate, grc);
 #else
-			GdkRectangle grc = {rc.left, rc.top,
-				rc.right - rc.left, rc.bottom - rc.top};
+			GdkRectangle grc = {static_cast<gint>(rc.left), static_cast<gint>(rc.top),
+				static_cast<gint>(rc.right - rc.left), static_cast<gint>(rc.bottom - rc.top)};
 			if (gdk_region_rect_in(rgnUpdate, &grc) != GDK_OVERLAP_RECTANGLE_IN) {
 				contains = false;
 			}
@@ -1134,8 +1139,10 @@ void ScintillaGTK::ScrollText(int linesToMove) {
 	//	rc.left, rc.top, rc.right, rc.bottom);
 	GtkWidget *wi = PWidget(wText);
 
-	gdk_window_scroll(WindowFromWidget(wi), 0, -diff);
-	gdk_window_process_updates(WindowFromWidget(wi), FALSE);
+	if (IS_WIDGET_REALIZED(wi)) {
+		gdk_window_scroll(WindowFromWidget(wi), 0, -diff);
+		gdk_window_process_updates(WindowFromWidget(wi), FALSE);
+	}
 }
 
 void ScintillaGTK::SetVerticalScrollPos() {
@@ -1399,21 +1406,9 @@ std::string ScintillaGTK::CaseMapString(const std::string &s, int caseMapping) {
 }
 
 int ScintillaGTK::KeyDefault(int key, int modifiers) {
-	if (!(modifiers & SCI_CTRL) && !(modifiers & SCI_ALT)) {
-		if (key < 256) {
-			NotifyKey(key, modifiers);
-			return 0;
-		} else {
-			// Pass up to container in case it is an accelerator
-			NotifyKey(key, modifiers);
-			return 0;
-		}
-	} else {
-		// Pass up to container in case it is an accelerator
-		NotifyKey(key, modifiers);
-		return 0;
-	}
-	//Platform::DebugPrintf("SK-key: %d %x %x\n",key, modifiers);
+	// Pass up to container in case it is an accelerator
+	NotifyKey(key, modifiers);
+	return 0;
 }
 
 void ScintillaGTK::CopyToClipboard(const SelectionText &selectedText) {
@@ -1977,6 +1972,13 @@ gint ScintillaGTK::ScrollEvent(GtkWidget *widget,
 			return FALSE;
 		}
 
+#if GTK_CHECK_VERSION(3,4,0)
+		// Smooth scrolling not supported
+		if (event->direction == GDK_SCROLL_SMOOTH) {
+			return FALSE;
+		}
+#endif
+
 		// Horizontal scrolling
 		if (event->direction == GDK_SCROLL_LEFT || event->direction == GDK_SCROLL_RIGHT) {
 			sciThis->HorizontalScrollTo(sciThis->xOffset + cLineScroll);
@@ -2010,7 +2012,12 @@ gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) {
 		int y = 0;
 		GdkModifierType state;
 		if (event->is_hint) {
+#if GTK_CHECK_VERSION(3,0,0)
+			gdk_window_get_device_position(event->window, 
+				event->device, &x, &y, &state);
+#else
 			gdk_window_get_pointer(event->window, &x, &y, &state);
+#endif
 		} else {
 			x = static_cast<int>(event->x);
 			y = static_cast<int>(event->y);
@@ -2202,8 +2209,7 @@ gboolean ScintillaGTK::KeyThis(GdkEventKey *event) {
 		bool added = KeyDown(key, shift, ctrl, alt, &consumed) != 0;
 #else
 		bool meta = ctrl;
-		ctrl = alt;
-		alt = (event->state & GDK_MOD5_MASK) != 0;
+		ctrl = (event->state & GDK_META_MASK) != 0;
 		bool added = KeyDownWithModifiers(key, (shift ? SCI_SHIFT : 0) |
 		                                       (ctrl ? SCI_CTRL : 0) |
 		                                       (alt ? SCI_ALT : 0) |
diff --git a/plugins/scintilla/scintilla/include/Platform.h b/plugins/scintilla/scintilla/include/Platform.h
index 654c487..4cd2c5c 100644
--- a/plugins/scintilla/scintilla/include/Platform.h
+++ b/plugins/scintilla/scintilla/include/Platform.h
@@ -20,6 +20,7 @@
 #define PLAT_MACOSX 0
 #define PLAT_WIN 0
 #define PLAT_WX  0
+#define PLAT_QT 0
 #define PLAT_FOX 0
 
 #if defined(FOX)
@@ -34,6 +35,10 @@
 #undef PLAT_GTK
 #define PLAT_GTK 1
 
+#elif defined(SCINTILLA_QT)
+#undef PLAT_QT
+#define PLAT_QT 1
+
 #if defined(__WIN32__) || defined(_MSC_VER)
 #undef PLAT_GTK_WIN32
 #define PLAT_GTK_WIN32 1
@@ -511,4 +516,10 @@ public:
 #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 2758b92..7fc0719 100644
--- a/plugins/scintilla/scintilla/include/SciLexer.h
+++ b/plugins/scintilla/scintilla/include/SciLexer.h
@@ -117,6 +117,9 @@
 #define SCLEX_COFFEESCRIPT 102
 #define SCLEX_TCMD 103
 #define SCLEX_AVS 104
+#define SCLEX_ECL 105
+#define SCLEX_OSCRIPT 106
+#define SCLEX_VISUALPROLOG 107
 #define SCLEX_AUTOMATIC 1000
 #define SCE_P_DEFAULT 0
 #define SCE_P_COMMENTLINE 1
@@ -1533,6 +1536,76 @@
 #define SCE_AVS_FUNCTION 12
 #define SCE_AVS_CLIPPROP 13
 #define SCE_AVS_USERDFN 14
+#define SCE_ECL_DEFAULT 0
+#define SCE_ECL_COMMENT 1
+#define SCE_ECL_COMMENTLINE 2
+#define SCE_ECL_NUMBER 3
+#define SCE_ECL_STRING 4
+#define SCE_ECL_WORD0 5
+#define SCE_ECL_OPERATOR 6
+#define SCE_ECL_CHARACTER 7
+#define SCE_ECL_UUID 8
+#define SCE_ECL_PREPROCESSOR 9
+#define SCE_ECL_UNKNOWN 10
+#define SCE_ECL_IDENTIFIER 11
+#define SCE_ECL_STRINGEOL 12
+#define SCE_ECL_VERBATIM 13
+#define SCE_ECL_REGEX 14
+#define SCE_ECL_COMMENTLINEDOC 15
+#define SCE_ECL_WORD1 16
+#define SCE_ECL_COMMENTDOCKEYWORD 17
+#define SCE_ECL_COMMENTDOCKEYWORDERROR 18
+#define SCE_ECL_WORD2 19
+#define SCE_ECL_WORD3 20
+#define SCE_ECL_WORD4 21
+#define SCE_ECL_WORD5 22
+#define SCE_ECL_COMMENTDOC 23
+#define SCE_ECL_ADDED 24
+#define SCE_ECL_DELETED 25
+#define SCE_ECL_CHANGED 26
+#define SCE_ECL_MOVED 27
+#define SCE_OSCRIPT_DEFAULT 0
+#define SCE_OSCRIPT_LINE_COMMENT 1
+#define SCE_OSCRIPT_BLOCK_COMMENT 2
+#define SCE_OSCRIPT_DOC_COMMENT 3
+#define SCE_OSCRIPT_PREPROCESSOR 4
+#define SCE_OSCRIPT_NUMBER 5
+#define SCE_OSCRIPT_SINGLEQUOTE_STRING 6
+#define SCE_OSCRIPT_DOUBLEQUOTE_STRING 7
+#define SCE_OSCRIPT_CONSTANT 8
+#define SCE_OSCRIPT_IDENTIFIER 9
+#define SCE_OSCRIPT_GLOBAL 10
+#define SCE_OSCRIPT_KEYWORD 11
+#define SCE_OSCRIPT_OPERATOR 12
+#define SCE_OSCRIPT_LABEL 13
+#define SCE_OSCRIPT_TYPE 14
+#define SCE_OSCRIPT_FUNCTION 15
+#define SCE_OSCRIPT_OBJECT 16
+#define SCE_OSCRIPT_PROPERTY 17
+#define SCE_OSCRIPT_METHOD 18
+#define SCE_VISUALPROLOG_DEFAULT 0
+#define SCE_VISUALPROLOG_KEY_MAJOR 1
+#define SCE_VISUALPROLOG_KEY_MINOR 2
+#define SCE_VISUALPROLOG_KEY_DIRECTIVE 3
+#define SCE_VISUALPROLOG_COMMENT_BLOCK 4
+#define SCE_VISUALPROLOG_COMMENT_LINE 5
+#define SCE_VISUALPROLOG_COMMENT_KEY 6
+#define SCE_VISUALPROLOG_COMMENT_KEY_ERROR 7
+#define SCE_VISUALPROLOG_IDENTIFIER 8
+#define SCE_VISUALPROLOG_VARIABLE 9
+#define SCE_VISUALPROLOG_ANONYMOUS 10
+#define SCE_VISUALPROLOG_NUMBER 11
+#define SCE_VISUALPROLOG_OPERATOR 12
+#define SCE_VISUALPROLOG_CHARACTER 13
+#define SCE_VISUALPROLOG_CHARACTER_TOO_MANY 14
+#define SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR 15
+#define SCE_VISUALPROLOG_STRING 16
+#define SCE_VISUALPROLOG_STRING_ESCAPE 17
+#define SCE_VISUALPROLOG_STRING_ESCAPE_ERROR 18
+#define SCE_VISUALPROLOG_STRING_EOL_OPEN 19
+#define SCE_VISUALPROLOG_STRING_VERBATIM 20
+#define SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL 21
+#define SCE_VISUALPROLOG_STRING_VERBATIM_EOL 22
 /* --Autogenerated -- end of section automatically generated from Scintilla.iface */
 
 #endif
diff --git a/plugins/scintilla/scintilla/include/Scintilla.h b/plugins/scintilla/scintilla/include/Scintilla.h
index 474416c..5a7bc75 100644
--- a/plugins/scintilla/scintilla/include/Scintilla.h
+++ b/plugins/scintilla/scintilla/include/Scintilla.h
@@ -57,6 +57,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_ADDSTYLEDTEXT 2002
 #define SCI_INSERTTEXT 2003
 #define SCI_CLEARALL 2004
+#define SCI_DELETERANGE 2645
 #define SCI_CLEARDOCUMENTSTYLE 2005
 #define SCI_GETLENGTH 2006
 #define SCI_GETCHARAT 2007
@@ -466,6 +467,7 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SC_WRAPVISUALFLAG_NONE 0x0000
 #define SC_WRAPVISUALFLAG_END 0x0001
 #define SC_WRAPVISUALFLAG_START 0x0002
+#define SC_WRAPVISUALFLAG_MARGIN 0x0004
 #define SCI_SETWRAPVISUALFLAGS 2460
 #define SCI_GETWRAPVISUALFLAGS 2461
 #define SC_WRAPVISUALFLAGLOC_DEFAULT 0x0000
@@ -691,6 +693,10 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SETCHARSDEFAULT 2444
 #define SCI_AUTOCGETCURRENT 2445
 #define SCI_AUTOCGETCURRENTTEXT 2610
+#define SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE 0
+#define SC_CASEINSENSITIVEBEHAVIOUR_IGNORECASE 1
+#define SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR 2634
+#define SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR 2635
 #define SCI_ALLOCATE 2446
 #define SCI_TARGETASUTF8 2447
 #define SCI_SETLENGTHFORENCODE 2448
@@ -729,6 +735,8 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_GETPOSITIONCACHE 2515
 #define SCI_COPYALLOWLINE 2519
 #define SCI_GETCHARACTERPOINTER 2520
+#define SCI_GETRANGEPOINTER 2643
+#define SCI_GETGAPPOSITION 2644
 #define SCI_SETKEYSUNICODE 2521
 #define SCI_GETKEYSUNICODE 2522
 #define SCI_INDICSETALPHA 2523
@@ -839,6 +847,9 @@ typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam,
 #define SCI_SETTECHNOLOGY 2630
 #define SCI_GETTECHNOLOGY 2631
 #define SCI_CREATELOADER 2632
+#define SCI_FINDINDICATORSHOW 2640
+#define SCI_FINDINDICATORFLASH 2641
+#define SCI_FINDINDICATORHIDE 2642
 #define SCI_STARTRECORD 3001
 #define SCI_STOPRECORD 3002
 #define SCI_SETLEXER 4001
diff --git a/plugins/scintilla/scintilla/include/Scintilla.iface b/plugins/scintilla/scintilla/include/Scintilla.iface
index f70266e..7abbb68 100644
--- a/plugins/scintilla/scintilla/include/Scintilla.iface
+++ b/plugins/scintilla/scintilla/include/Scintilla.iface
@@ -101,6 +101,9 @@ fun void InsertText=2003(position pos, 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)
+
 # Set all style bytes to 0, remove all folding information.
 fun void ClearDocumentStyle=2005(,)
 
@@ -791,7 +794,7 @@ set void SetHighlightGuide=2134(int column,)
 get int GetHighlightGuide=2135(,)
 
 # Get the position after the last visible characters on a line.
-get int GetLineEndPosition=2136(int line,)
+get position GetLineEndPosition=2136(int line,)
 
 # Get the code page used to interpret the bytes of the document as characters.
 get int GetCodePage=2137(,)
@@ -1152,6 +1155,7 @@ enu WrapVisualFlag=SC_WRAPVISUALFLAG_
 val SC_WRAPVISUALFLAG_NONE=0x0000
 val SC_WRAPVISUALFLAG_END=0x0001
 val SC_WRAPVISUALFLAG_START=0x0002
+val SC_WRAPVISUALFLAG_MARGIN=0x0004
 
 # Set the display mode of visual flags for wrapped lines.
 set void SetWrapVisualFlags=2460(int wrapVisualFlags,)
@@ -1806,6 +1810,16 @@ fun int AutoCGetCurrent=2445(,)
 # Returns the length of the item text
 fun int AutoCGetCurrentText=2610(, stringresult s)
 
+enu CaseInsensitiveBehaviour=SC_CASEINSENSITIVEBEHAVIOUR_
+val SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE=0
+val SC_CASEINSENSITIVEBEHAVIOUR_IGNORECASE=1
+
+# Set auto-completion case insensitive behaviour to either prefer case-sensitive matches or have no preference.
+set void AutoCSetCaseInsensitiveBehaviour=2634(int behaviour,)
+
+# Get auto-completion case insensitive behaviour.
+get int AutoCGetCaseInsensitiveBehaviour=2635(,)
+
 # Enlarge the document to a particular size of text bytes.
 fun void Allocate=2446(int bytes,)
 
@@ -1913,6 +1927,15 @@ fun void CopyAllowLine=2519(,)
 # characters in the document.
 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)
+
+# 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,)
 
@@ -2207,6 +2230,15 @@ get int GetTechnology=2631(,)
 # Create an ILoader*.
 fun int CreateLoader=2632(int bytes,)
 
+# On OS X, show a find indicator.
+fun void FindIndicatorShow=2640(position start, position end)
+
+# On OS X, flash a find indicator, then fade out.
+fun void FindIndicatorFlash=2641(position start, position end)
+
+# On OS X, hide the find indicator.
+fun void FindIndicatorHide=2642(,)
+
 # Start notifying the container of all key presses and commands.
 fun void StartRecord=3001(,)
 
@@ -2456,6 +2488,9 @@ val SCLEX_MODULA=101
 val SCLEX_COFFEESCRIPT=102
 val SCLEX_TCMD=103
 val SCLEX_AVS=104
+val SCLEX_ECL=105
+val SCLEX_OSCRIPT=106
+val SCLEX_VISUALPROLOG=107
 
 # When a lexer specifies its language as SCLEX_AUTOMATIC it receives a
 # value assigned in sequence from SCLEX_AUTOMATIC+1.
@@ -4063,6 +4098,82 @@ val SCE_AVS_PLUGIN=11
 val SCE_AVS_FUNCTION=12
 val SCE_AVS_CLIPPROP=13
 val SCE_AVS_USERDFN=14
+# Lexical states for SCLEX_ECL
+lex ECL=SCLEX_ECL SCE_ECL_
+val SCE_ECL_DEFAULT=0
+val SCE_ECL_COMMENT=1
+val SCE_ECL_COMMENTLINE=2
+val SCE_ECL_NUMBER=3
+val SCE_ECL_STRING=4
+val SCE_ECL_WORD0=5
+val SCE_ECL_OPERATOR=6
+val SCE_ECL_CHARACTER=7
+val SCE_ECL_UUID=8
+val SCE_ECL_PREPROCESSOR=9
+val SCE_ECL_UNKNOWN=10
+val SCE_ECL_IDENTIFIER=11
+val SCE_ECL_STRINGEOL=12
+val SCE_ECL_VERBATIM=13
+val SCE_ECL_REGEX=14
+val SCE_ECL_COMMENTLINEDOC=15
+val SCE_ECL_WORD1=16
+val SCE_ECL_COMMENTDOCKEYWORD=17
+val SCE_ECL_COMMENTDOCKEYWORDERROR=18
+val SCE_ECL_WORD2=19
+val SCE_ECL_WORD3=20
+val SCE_ECL_WORD4=21
+val SCE_ECL_WORD5=22
+val SCE_ECL_COMMENTDOC=23
+val SCE_ECL_ADDED=24
+val SCE_ECL_DELETED=25
+val SCE_ECL_CHANGED=26
+val SCE_ECL_MOVED=27
+# Lexical states for SCLEX_OSCRIPT
+lex OScript=SCLEX_OSCRIPT SCE_OSCRIPT_
+val SCE_OSCRIPT_DEFAULT=0
+val SCE_OSCRIPT_LINE_COMMENT=1
+val SCE_OSCRIPT_BLOCK_COMMENT=2
+val SCE_OSCRIPT_DOC_COMMENT=3
+val SCE_OSCRIPT_PREPROCESSOR=4
+val SCE_OSCRIPT_NUMBER=5
+val SCE_OSCRIPT_SINGLEQUOTE_STRING=6
+val SCE_OSCRIPT_DOUBLEQUOTE_STRING=7
+val SCE_OSCRIPT_CONSTANT=8
+val SCE_OSCRIPT_IDENTIFIER=9
+val SCE_OSCRIPT_GLOBAL=10
+val SCE_OSCRIPT_KEYWORD=11
+val SCE_OSCRIPT_OPERATOR=12
+val SCE_OSCRIPT_LABEL=13
+val SCE_OSCRIPT_TYPE=14
+val SCE_OSCRIPT_FUNCTION=15
+val SCE_OSCRIPT_OBJECT=16
+val SCE_OSCRIPT_PROPERTY=17
+val SCE_OSCRIPT_METHOD=18
+# Lexical states for SCLEX_VISUALPROLOG
+lex VisualProlog=SCLEX_VISUALPROLOG SCE_VISUALPROLOG_
+val SCE_VISUALPROLOG_DEFAULT=0
+val SCE_VISUALPROLOG_KEY_MAJOR=1
+val SCE_VISUALPROLOG_KEY_MINOR=2
+val SCE_VISUALPROLOG_KEY_DIRECTIVE=3
+val SCE_VISUALPROLOG_COMMENT_BLOCK=4
+val SCE_VISUALPROLOG_COMMENT_LINE=5
+val SCE_VISUALPROLOG_COMMENT_KEY=6
+val SCE_VISUALPROLOG_COMMENT_KEY_ERROR=7
+val SCE_VISUALPROLOG_IDENTIFIER=8
+val SCE_VISUALPROLOG_VARIABLE=9
+val SCE_VISUALPROLOG_ANONYMOUS=10
+val SCE_VISUALPROLOG_NUMBER=11
+val SCE_VISUALPROLOG_OPERATOR=12
+val SCE_VISUALPROLOG_CHARACTER=13
+val SCE_VISUALPROLOG_CHARACTER_TOO_MANY=14
+val SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR=15
+val SCE_VISUALPROLOG_STRING=16
+val SCE_VISUALPROLOG_STRING_ESCAPE=17
+val SCE_VISUALPROLOG_STRING_ESCAPE_ERROR=18
+val SCE_VISUALPROLOG_STRING_EOL_OPEN=19
+val SCE_VISUALPROLOG_STRING_VERBATIM=20
+val SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL=21
+val SCE_VISUALPROLOG_STRING_VERBATIM_EOL=22
 
 # Events
 
diff --git a/plugins/scintilla/scintilla/lexers.make b/plugins/scintilla/scintilla/lexers.make
index 298ba5f..a703339 100644
--- a/plugins/scintilla/scintilla/lexers.make
+++ b/plugins/scintilla/scintilla/lexers.make
@@ -25,6 +25,7 @@ LEXER_OBJS = \
 	lexers/LexCsound.o\
 	lexers/LexCSS.o\
 	lexers/LexD.o\
+	lexers/LexECL.o\
 	lexers/LexEiffel.o\
 	lexers/LexErlang.o\
 	lexers/LexEScript.o\
@@ -52,6 +53,7 @@ LEXER_OBJS = \
 	lexers/LexNimrod.o\
 	lexers/LexNsis.o\
 	lexers/LexOpal.o\
+	lexers/LexOScript.o\
 	lexers/LexOthers.o\
 	lexers/LexPascal.o\
 	lexers/LexPB.o\
@@ -83,6 +85,7 @@ LEXER_OBJS = \
 	lexers/LexVB.o\
 	lexers/LexVerilog.o\
 	lexers/LexVHDL.o\
+	lexers/LexVisualProlog.o\
 	lexers/LexYAML.o
 
 LEXER_SRCS = \
@@ -111,6 +114,7 @@ LEXER_SRCS = \
 	lexers/LexCsound.cxx\
 	lexers/LexCSS.cxx\
 	lexers/LexD.cxx\
+	lexers/LexECL.cxx\
 	lexers/LexEiffel.cxx\
 	lexers/LexErlang.cxx\
 	lexers/LexEScript.cxx\
@@ -138,6 +142,7 @@ LEXER_SRCS = \
 	lexers/LexNimrod.cxx\
 	lexers/LexNsis.cxx\
 	lexers/LexOpal.cxx\
+	lexers/LexOScript.cxx\
 	lexers/LexOthers.cxx\
 	lexers/LexPascal.cxx\
 	lexers/LexPB.cxx\
@@ -169,4 +174,5 @@ LEXER_SRCS = \
 	lexers/LexVB.cxx\
 	lexers/LexVerilog.cxx\
 	lexers/LexVHDL.cxx\
+	lexers/LexVisualProlog.cxx\
 	lexers/LexYAML.cxx
diff --git a/plugins/scintilla/scintilla/lexers/LexAsm.cxx b/plugins/scintilla/scintilla/lexers/LexAsm.cxx
index 71e24bc..78874de 100644
--- a/plugins/scintilla/scintilla/lexers/LexAsm.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexAsm.cxx
@@ -153,7 +153,7 @@ class LexerAsm : public ILexer {
 public:
 	LexerAsm() {
 	}
-	~LexerAsm() {
+	virtual ~LexerAsm() {
 	}
 	void SCI_METHOD Release() {
 		delete this;
diff --git a/plugins/scintilla/scintilla/lexers/LexBash.cxx b/plugins/scintilla/scintilla/lexers/LexBash.cxx
index 165e104..8cd6cc5 100644
--- a/plugins/scintilla/scintilla/lexers/LexBash.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexBash.cxx
@@ -425,7 +425,6 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
 				}
 				break;
 			case SCE_SH_STRING:	// delimited styles
-			case SCE_SH_CHARACTER:
 			case SCE_SH_BACKTICKS:
 			case SCE_SH_PARAM:
 				if (sc.ch == '\\' && Quote.Up != '\\') {
@@ -439,6 +438,14 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
 					Quote.Count++;
 				}
 				break;
+			case SCE_SH_CHARACTER: // singly-quoted strings
+				if (sc.ch == Quote.Down) {
+					Quote.Count--;
+					if (Quote.Count == 0) {
+						sc.ForwardSetState(SCE_SH_DEFAULT);
+					}
+				}
+				break;
 		}
 
 		// Must check end of HereDoc state 1 before default state is handled
@@ -507,7 +514,7 @@ static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle,
 				if (sc.ch == '{') {
 					sc.ChangeState(SCE_SH_PARAM);
 				} else if (sc.ch == '\'') {
-					sc.ChangeState(SCE_SH_CHARACTER);
+					sc.ChangeState(SCE_SH_STRING);
 				} else if (sc.ch == '"') {
 					sc.ChangeState(SCE_SH_STRING);
 				} else if (sc.ch == '(' || sc.ch == '`') {
diff --git a/plugins/scintilla/scintilla/lexers/LexBasic.cxx b/plugins/scintilla/scintilla/lexers/LexBasic.cxx
index b15ce09..bc8fcee 100644
--- a/plugins/scintilla/scintilla/lexers/LexBasic.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexBasic.cxx
@@ -223,7 +223,7 @@ public:
 	           CheckFoldPoint(CheckFoldPoint_),
 	           osBasic(wordListDescriptions) {
 	}
-	~LexerBasic() {
+	virtual ~LexerBasic() {
 	}
 	void SCI_METHOD Release() {
 		delete this;
diff --git a/plugins/scintilla/scintilla/lexers/LexCPP.cxx b/plugins/scintilla/scintilla/lexers/LexCPP.cxx
index b92f279..7d0990f 100644
--- a/plugins/scintilla/scintilla/lexers/LexCPP.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexCPP.cxx
@@ -335,7 +335,7 @@ public:
 		setRelOp(CharacterSet::setNone, "=!<>"),
 		setLogicalOp(CharacterSet::setNone, "|&") {
 	}
-	~LexerCPP() {
+	virtual ~LexerCPP() {
 	}
 	void SCI_METHOD Release() {
 		delete this;
@@ -464,9 +464,9 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 	bool isIncludePreprocessor = false;
 
 	int lineCurrent = styler.GetLine(startPos);
-	if ((initStyle == SCE_C_PREPROCESSOR) ||
-      (initStyle == SCE_C_COMMENTLINE) ||
-      (initStyle == SCE_C_COMMENTLINEDOC)) {
+	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 chBack = styler.SafeGetCharAt(startPos-1, 0);
@@ -484,9 +484,9 @@ 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;
-		while (--back && IsSpaceEquiv(styler.StyleAt(back)))
+		while (--back && IsSpaceEquiv(MaskActive(styler.StyleAt(back))))
 			;
-		if (styler.StyleAt(back) == SCE_C_OPERATOR) {
+		if (MaskActive(styler.StyleAt(back)) == SCE_C_OPERATOR) {
 			chPrevNonWhite = styler.SafeGetCharAt(back);
 		}
 	}
@@ -520,6 +520,8 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 	for (; sc.More(); sc.Forward()) {
 
 		if (sc.atLineStart) {
+			// Using MaskActive() is not needed in the following statement.
+			// 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.
@@ -534,13 +536,6 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 				activitySet = activeFlag;
 				sc.SetState(sc.state | activitySet);
 			}
-			if (activitySet) {
-				if (sc.ch == '#') {
-					if (sc.Match("#else") || sc.Match("#end") || sc.Match("#if")) {
-						//activitySet = 0;
-					}
-				}
-			}
 		}
 
 		if (sc.atLineEnd) {
@@ -676,7 +671,7 @@ void SCI_METHOD LexerCPP::Lex(unsigned int startPos, int length, int initStyle,
 					if (!IsASpace(sc.ch) || !keywords3.InList(s + 1)) {
 						sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR|activitySet);
 					}
-					sc.SetState(styleBeforeDCKeyword);
+					sc.SetState(styleBeforeDCKeyword|activitySet);
 				}
 				break;
 			case SCE_C_STRING:
diff --git a/plugins/scintilla/scintilla/lexers/LexD.cxx b/plugins/scintilla/scintilla/lexers/LexD.cxx
index eb76be3..32e3c86 100644
--- a/plugins/scintilla/scintilla/lexers/LexD.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexD.cxx
@@ -160,7 +160,7 @@ public:
 	LexerD(bool caseSensitive_) :
 		caseSensitive(caseSensitive_) {
 	}
-	~LexerD() {
+	virtual ~LexerD() {
 	}
 	void SCI_METHOD Release() {
 		delete this;
diff --git a/plugins/scintilla/scintilla/lexers/LexECL.cxx b/plugins/scintilla/scintilla/lexers/LexECL.cxx
new file mode 100644
index 0000000..cf15a62
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexECL.cxx
@@ -0,0 +1,512 @@
+// Scintilla source code edit control
+/** @file LexECL.cxx
+ ** Lexer for ECL.
+ **/
+// 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 <ctype.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+
+#ifdef _MSC_VER
+#pragma warning(disable: 4786)
+#endif
+#ifdef __BORLANDC__
+// Borland C++ displays warnings in vector header without this
+#pragma option -w-ccc -w-rch
+#endif
+
+#include <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+
+#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"
+
+#define SET_LOWER "abcdefghijklmnopqrstuvwxyz"
+#define SET_UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+#define SET_DIGITS "0123456789"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+static bool IsSpaceEquiv(int state) {
+	return (state <= SCE_ECL_COMMENTDOC) ||
+		// including SCE_ECL_DEFAULT, SCE_ECL_COMMENT, SCE_ECL_COMMENTLINE
+		(state == SCE_ECL_COMMENTLINEDOC) || (state == SCE_ECL_COMMENTDOCKEYWORD) ||
+		(state == SCE_ECL_COMMENTDOCKEYWORDERROR);
+}
+
+static void ColouriseEclDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
+                            Accessor &styler) {
+	WordList &keywords0 = *keywordlists[0];
+	WordList &keywords1 = *keywordlists[1];
+	WordList &keywords2 = *keywordlists[2];
+	WordList &keywords3 = *keywordlists[3]; //Value Types
+	WordList &keywords4 = *keywordlists[4];
+	WordList &keywords5 = *keywordlists[5];
+	WordList &keywords6 = *keywordlists[6];	//Javadoc Tags
+	WordList cplusplus;
+	cplusplus.Set("beginc endc");
+
+	bool stylingWithinPreprocessor = false;
+
+	CharacterSet setOKBeforeRE(CharacterSet::setNone, "(=,");
+	CharacterSet setDoxygen(CharacterSet::setLower, "$ \\&<>#{}[]");
+	CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
+	CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);
+	CharacterSet setQualified(CharacterSet::setNone, "uUxX");
+
+	int chPrevNonWhite = ' ';
+	int visibleChars = 0;
+	bool lastWordWasUUID = false;
+	int styleBeforeDCKeyword = SCE_ECL_DEFAULT;
+	bool continuationLine = false;
+
+	if (initStyle == SCE_ECL_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 == '\\';
+		}
+	}
+
+	// look back to set chPrevNonWhite properly for better regex colouring
+	if (startPos > 0) {
+		int back = startPos;
+		while (--back && IsSpaceEquiv(styler.StyleAt(back)))
+			;
+		if (styler.StyleAt(back) == SCE_ECL_OPERATOR) {
+			chPrevNonWhite = styler.SafeGetCharAt(back);
+		}
+	}
+
+	StyleContext sc(startPos, length, initStyle, styler);
+
+	for (; sc.More(); sc.Forward()) {
+		if (sc.atLineStart) {
+			if (sc.state == SCE_ECL_STRING) {
+				// Prevent SCE_ECL_STRINGEOL from leaking back to previous line which
+				// ends with a line continuation by locking in the state upto this position.
+				sc.SetState(SCE_ECL_STRING);
+			}
+			// Reset states to begining of colourise so no surprises
+			// if different sets of lines lexed.
+			visibleChars = 0;
+			lastWordWasUUID = 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_ECL_ADDED:
+			case SCE_ECL_DELETED:
+			case SCE_ECL_CHANGED:
+			case SCE_ECL_MOVED:
+			if (sc.atLineStart)
+					sc.SetState(SCE_ECL_DEFAULT);
+				break;
+			case SCE_ECL_OPERATOR:
+				sc.SetState(SCE_ECL_DEFAULT);
+				break;
+			case SCE_ECL_NUMBER:
+				// We accept almost anything because of hex. and number suffixes
+				if (!setWord.Contains(sc.ch)) {
+					sc.SetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_IDENTIFIER:
+				if (!setWord.Contains(sc.ch) || (sc.ch == '.')) {
+					char s[1000];
+					sc.GetCurrentLowered(s, sizeof(s));
+					if (keywords0.InList(s)) {
+						lastWordWasUUID = strcmp(s, "uuid") == 0;
+						sc.ChangeState(SCE_ECL_WORD0);
+					} else if (keywords1.InList(s)) {
+						sc.ChangeState(SCE_ECL_WORD1);
+					} else if (keywords2.InList(s)) {
+						sc.ChangeState(SCE_ECL_WORD2);
+					} else if (keywords4.InList(s)) {
+						sc.ChangeState(SCE_ECL_WORD4);
+					} else if (keywords5.InList(s)) {
+						sc.ChangeState(SCE_ECL_WORD5);
+					}
+					else	//Data types are of from KEYWORD## 
+					{
+						int i = static_cast<int>(strlen(s)) - 1;
+						while(i >= 0 && (isdigit(s[i]) || s[i] == '_'))
+							--i;
+
+						char s2[1000];
+						strncpy(s2, s, i + 1);
+						s2[i + 1] = 0;
+						if (keywords3.InList(s2)) {
+							sc.ChangeState(SCE_ECL_WORD3);
+						} 
+					}
+					sc.SetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_PREPROCESSOR:
+				if (sc.atLineStart && !continuationLine) {
+					sc.SetState(SCE_ECL_DEFAULT);
+				} else if (stylingWithinPreprocessor) {
+					if (IsASpace(sc.ch)) {
+						sc.SetState(SCE_ECL_DEFAULT);
+					}
+				} else {
+					if (sc.Match('/', '*') || sc.Match('/', '/')) {
+						sc.SetState(SCE_ECL_DEFAULT);
+					}
+				}
+				break;
+			case SCE_ECL_COMMENT:
+				if (sc.Match('*', '/')) {
+					sc.Forward();
+					sc.ForwardSetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_COMMENTDOC:
+				if (sc.Match('*', '/')) {
+					sc.Forward();
+					sc.ForwardSetState(SCE_ECL_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_ECL_COMMENTDOC;
+						sc.SetState(SCE_ECL_COMMENTDOCKEYWORD);
+					}
+				}
+				break;
+			case SCE_ECL_COMMENTLINE:
+				if (sc.atLineStart) {
+					sc.SetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_COMMENTLINEDOC:
+				if (sc.atLineStart) {
+					sc.SetState(SCE_ECL_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_ECL_COMMENTLINEDOC;
+						sc.SetState(SCE_ECL_COMMENTDOCKEYWORD);
+					}
+				}
+				break;
+			case SCE_ECL_COMMENTDOCKEYWORD:
+				if ((styleBeforeDCKeyword == SCE_ECL_COMMENTDOC) && sc.Match('*', '/')) {
+					sc.ChangeState(SCE_ECL_COMMENTDOCKEYWORDERROR);
+					sc.Forward();
+					sc.ForwardSetState(SCE_ECL_DEFAULT);
+				} else if (!setDoxygen.Contains(sc.ch)) {
+					char s[1000];
+					sc.GetCurrentLowered(s, sizeof(s));
+					if (!IsASpace(sc.ch) || !keywords6.InList(s+1)) {
+						sc.ChangeState(SCE_ECL_COMMENTDOCKEYWORDERROR);
+					}
+					sc.SetState(styleBeforeDCKeyword);
+				}
+				break;
+			case SCE_ECL_STRING:
+				if (sc.atLineEnd) {
+					sc.ChangeState(SCE_ECL_STRINGEOL);
+				} else if (sc.ch == '\\') {
+					if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
+						sc.Forward();
+					}
+				} else if (sc.ch == '\"') {
+					sc.ForwardSetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_CHARACTER:
+				if (sc.atLineEnd) {
+					sc.ChangeState(SCE_ECL_STRINGEOL);
+				} else if (sc.ch == '\\') {
+					if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
+						sc.Forward();
+					}
+				} else if (sc.ch == '\'') {
+					sc.ForwardSetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_REGEX:
+				if (sc.atLineStart) {
+					sc.SetState(SCE_ECL_DEFAULT);
+				} else if (sc.ch == '/') {
+					sc.Forward();
+					while ((sc.ch < 0x80) && islower(sc.ch))
+						sc.Forward();    // gobble regex flags
+					sc.SetState(SCE_ECL_DEFAULT);
+				} else if (sc.ch == '\\') {
+					// Gobble up the quoted character
+					if (sc.chNext == '\\' || sc.chNext == '/') {
+						sc.Forward();
+					}
+				}
+				break;
+			case SCE_ECL_STRINGEOL:
+				if (sc.atLineStart) {
+					sc.SetState(SCE_ECL_DEFAULT);
+				}
+				break;
+			case SCE_ECL_VERBATIM:
+				if (sc.ch == '\"') {
+					if (sc.chNext == '\"') {
+						sc.Forward();
+					} else {
+						sc.ForwardSetState(SCE_ECL_DEFAULT);
+					}
+				}
+				break;
+			case SCE_ECL_UUID:
+				if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
+					sc.SetState(SCE_ECL_DEFAULT);
+				}
+				break;
+		}
+
+		// Determine if a new state should be entered.
+		int lineCurrent = styler.GetLine(sc.currentPos);
+		int lineState = styler.GetLineState(lineCurrent);
+		if (sc.state == SCE_ECL_DEFAULT) {
+			if (lineState) {
+				sc.SetState(lineState);
+			}
+			else if (sc.Match('@', '\"')) {
+				sc.SetState(SCE_ECL_VERBATIM);
+				sc.Forward();
+			} else if (setQualified.Contains(sc.ch) && sc.chNext == '\'') {
+				sc.SetState(SCE_ECL_CHARACTER);
+				sc.Forward();
+			} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+				if (lastWordWasUUID) {
+					sc.SetState(SCE_ECL_UUID);
+					lastWordWasUUID = false;
+				} else {
+					sc.SetState(SCE_ECL_NUMBER);
+				}
+			} else if (setWordStart.Contains(sc.ch) || (sc.ch == '@')) {
+				if (lastWordWasUUID) {
+					sc.SetState(SCE_ECL_UUID);
+					lastWordWasUUID = false;
+				} else {
+					sc.SetState(SCE_ECL_IDENTIFIER);
+				}
+			} else if (sc.Match('/', '*')) {
+				if (sc.Match("/**") || sc.Match("/*!")) {	// Support of Qt/Doxygen doc. style
+					sc.SetState(SCE_ECL_COMMENTDOC);
+				} else {
+					sc.SetState(SCE_ECL_COMMENT);
+				}
+				sc.Forward();	// Eat the * so it isn't used for the end of the comment
+			} else if (sc.Match('/', '/')) {
+				if ((sc.Match("///") && !sc.Match("////")) || sc.Match("//!"))
+					// Support of Qt/Doxygen doc. style
+					sc.SetState(SCE_ECL_COMMENTLINEDOC);
+				else
+					sc.SetState(SCE_ECL_COMMENTLINE);
+			} else if (sc.ch == '/' && setOKBeforeRE.Contains(chPrevNonWhite)) {
+				sc.SetState(SCE_ECL_REGEX);	// JavaScript's RegEx
+//			} else if (sc.ch == '\"') {
+//				sc.SetState(SCE_ECL_STRING);
+			} else if (sc.ch == '\'') {
+				sc.SetState(SCE_ECL_CHARACTER);
+			} else if (sc.ch == '#' && visibleChars == 0) {
+				// Preprocessor commands are alone on their line
+				sc.SetState(SCE_ECL_PREPROCESSOR);
+				// Skip whitespace between # and preprocessor word
+				do {
+					sc.Forward();
+				} while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
+				if (sc.atLineEnd) {
+					sc.SetState(SCE_ECL_DEFAULT);
+				}
+			} else if (isoperator(static_cast<char>(sc.ch))) {
+				sc.SetState(SCE_ECL_OPERATOR);
+			}
+		}
+
+		if (!IsASpace(sc.ch) && !IsSpaceEquiv(sc.state)) {
+			chPrevNonWhite = sc.ch;
+			visibleChars++;
+		}
+		continuationLine = false;
+	}
+	sc.Complete();
+
+}
+
+static bool IsStreamCommentStyle(int style) {
+	return style == SCE_ECL_COMMENT ||
+		style == SCE_ECL_COMMENTDOC ||
+		style == SCE_ECL_COMMENTDOCKEYWORD ||
+		style == SCE_ECL_COMMENTDOCKEYWORDERROR;
+}
+
+bool MatchNoCase(Accessor & styler, unsigned int & pos, const char *s) {
+	int i=0;
+	for (; *s; i++) {
+		char compare_char = tolower(*s);
+		char styler_char = tolower(styler.SafeGetCharAt(pos+i));
+		if (compare_char != styler_char) 
+			return false;
+		s++;
+	}
+	pos+=i-1;
+	return true;
+}
+
+
+// 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, 
+					   WordList *[], Accessor &styler) {
+	bool foldComment = true;
+	bool foldPreprocessor = true;
+	bool foldCompact = true;
+	bool foldAtElse = true;
+	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 = styler[startPos];
+	int styleNext = styler.StyleAt(startPos);
+	int style = initStyle;
+	for (unsigned int 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 (foldComment && IsStreamCommentStyle(style)) {
+			if (!IsStreamCommentStyle(stylePrev) && (stylePrev != SCE_ECL_COMMENTLINEDOC)) {
+				levelNext++;
+			} else if (!IsStreamCommentStyle(styleNext) && (styleNext != SCE_ECL_COMMENTLINEDOC) && !atEOL) {
+				// Comments don't end at end of line and the next character may be unstyled.
+				levelNext--;
+			}
+		}
+		if (foldComment && (style == SCE_ECL_COMMENTLINE)) {
+			if ((ch == '/') && (chNext == '/')) {
+				char chNext2 = styler.SafeGetCharAt(i + 2);
+				if (chNext2 == '{') {
+					levelNext++;
+				} else if (chNext2 == '}') {
+					levelNext--;
+				}
+			}
+		}
+		if (foldPreprocessor && (style == SCE_ECL_PREPROCESSOR)) {
+			if (ch == '#') {
+				unsigned int j = i + 1;
+				while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
+					j++;
+				}
+				if (MatchNoCase(styler, j, "region") || MatchNoCase(styler, j, "if")) {
+					levelNext++;
+				} else if (MatchNoCase(styler, j, "endregion") || MatchNoCase(styler, j, "end")) {
+					levelNext--;
+				}
+			}
+		}
+		if (style == SCE_ECL_OPERATOR) {
+			if (ch == '{') {
+				// Measure the minimum before a '{' to allow
+				// folding on "} else {"
+				if (levelMinCurrent > levelNext) {
+					levelMinCurrent = levelNext;
+				}
+				levelNext++;
+			} else if (ch == '}') {
+				levelNext--;
+			}
+		}
+		if (style == SCE_ECL_WORD2) {
+			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++;
+			} else if (MatchNoCase(styler, i, "endmacro") || MatchNoCase(styler, i, "endc++") || MatchNoCase(styler, i, "end")) {
+				levelNext--;
+			}
+		}
+		if (atEOL || (i == endPos-1)) {
+			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;
+			if (atEOL && (i == static_cast<unsigned int>(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;
+		}
+		if (!IsASpace(ch))
+			visibleChars++;
+	}
+}
+
+static const char * const EclWordListDesc[] = {
+	"Keywords",
+	0
+};
+
+LexerModule lmECL(
+   SCLEX_ECL,
+   ColouriseEclDoc,
+   "ecl",
+   FoldEclDoc,
+   EclWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexHTML.cxx b/plugins/scintilla/scintilla/lexers/LexHTML.cxx
index d8d4d2e..372a5b7 100644
--- a/plugins/scintilla/scintilla/lexers/LexHTML.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexHTML.cxx
@@ -598,11 +598,12 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
 	char djangoBlockType[2];
 	djangoBlockType[0] = '\0';
 
-	// If inside a tag, it may be a script tag, so reread from the start to ensure any language tags are seen
+	// 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)))) {
-			startPos--;
-			length++;
+			int backLineStart = styler.LineStart(styler.GetLine(startPos-1));
+			length += startPos - backLineStart;
+			startPos = backLineStart;
 		}
 		state = SCE_H_DEFAULT;
 	}
@@ -903,7 +904,7 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
 		         (chNext == '?') &&
 				 !IsScriptCommentState(state)) {
  			beforeLanguage = scriptLanguage;
-			scriptLanguage = segIsScriptingIndicator(styler, i + 2, i + 6, eScriptPHP);
+			scriptLanguage = segIsScriptingIndicator(styler, i + 2, i + 6, isXml ? eScriptXML : eScriptPHP);
 			if (scriptLanguage != eScriptPHP && isStringState(state)) continue;
 			styler.ColourTo(i - 1, StateToPrint);
 			beforePreProc = state;
@@ -1584,6 +1585,10 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
 					state = SCE_HJ_COMMENTDOC;
 				else
 					state = SCE_HJ_COMMENT;
+				if (chNext2 == '/') {
+					// Eat the * so it isn't used for the end of the comment
+					i++;
+				}
 			} else if (ch == '/' && chNext == '/') {
 				styler.ColourTo(i - 1, StateToPrint);
 				state = SCE_HJ_COMMENTLINE;
@@ -2129,7 +2134,8 @@ static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initSty
 		break;
 	default:
 		StateToPrint = statePrintForState(state, inScriptType);
-		styler.ColourTo(lengthDoc - 1, StateToPrint);
+		if (static_cast<int>(styler.GetStartSegment()) < lengthDoc)
+			styler.ColourTo(lengthDoc - 1, StateToPrint);
 		break;
 	}
 
diff --git a/plugins/scintilla/scintilla/lexers/LexNsis.cxx b/plugins/scintilla/scintilla/lexers/LexNsis.cxx
index cd74d54..599ccfb 100644
--- a/plugins/scintilla/scintilla/lexers/LexNsis.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexNsis.cxx
@@ -142,6 +142,7 @@ static int calculateFoldNsis(unsigned int start, unsigned int end, int foldlevel
     bIgnoreCase = true;
 
   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++)
 	{
 		s[i] = static_cast<char>( styler[ start + i ] );
diff --git a/plugins/scintilla/scintilla/lexers/LexOScript.cxx b/plugins/scintilla/scintilla/lexers/LexOScript.cxx
new file mode 100644
index 0000000..9daff34
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexOScript.cxx
@@ -0,0 +1,548 @@
+// Scintilla source code edit control
+/** @file LexOScript.cxx
+ ** Lexer for OScript sources; ocx files and/or OSpace dumps.
+ ** OScript is a programming language used to develop applications for the
+ ** Livelink server platform.
+ **/
+// Written by Ferdinand Prantl <prantlf gmail com>, inspired by the code from
+// LexVB.cxx and LexPascal.cxx. 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
+
+// -----------------------------------------
+// Functions classifying a single character.
+
+// This function is generic and should be probably moved to CharSet.h where
+// IsAlphaNumeric the others reside.
+inline bool IsAlpha(int ch) {
+	return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
+}
+
+static inline bool IsIdentifierChar(int ch) {
+	// Identifiers cannot contain non-ASCII letters; a word with non-English
+	// language-specific characters cannot be an identifier.
+	return IsAlphaNumeric(ch) || ch == '_';
+}
+
+static inline bool IsIdentifierStart(int ch) {
+	// Identifiers cannot contain non-ASCII letters; a word with non-English
+	// language-specific characters cannot be an identifier.
+	return IsAlpha(ch) || ch == '_';
+}
+
+static inline bool IsNumberChar(int ch, int chNext) {
+	// Numeric constructs are not checked for lexical correctness. They are
+	// expected to look like +1.23-E9 but actually any bunch of the following
+	// characters will be styled as number.
+	// KNOWN PROBLEM: if you put + or - operators immediately after a number
+	// and the next operand starts with the letter E, the operator will not be
+	// recognized and it will be styled together with the preceding number.
+	// This should not occur; at least not often. The coding style recommends
+	// putting spaces around operators.
+	return IsADigit(ch) || toupper(ch) == 'E' || ch == '.' ||
+		   ((ch == '-' || ch == '+') && toupper(chNext) == 'E');
+}
+
+// This function checks for the start or a natural number without any symbols
+// or operators as a prefix; the IsPrefixedNumberStart should be called
+// immediately after this one to cover all possible numeric constructs.
+static inline bool IsNaturalNumberStart(int ch) {
+	return IsADigit(ch) != 0;
+}
+
+static inline bool IsPrefixedNumberStart(int ch, int chNext) {
+	// KNOWN PROBLEM: if you put + or - operators immediately before a number
+	// the operator will not be recognized and it will be styled together with
+	// the succeeding number. This should not occur; at least not often. The
+	// coding style recommends putting spaces around operators.
+	return (ch == '.' || ch == '-' || ch == '+') && IsADigit(chNext);
+}
+
+static inline bool IsOperator(int ch) {
+	return strchr("%^&*()-+={}[]:;<>,/?!.~|\\", ch) != NULL;
+}
+
+// ---------------------------------------------------------------
+// Functions classifying a token currently processed in the lexer.
+
+// Checks if the current line starts with the preprocessor directive used
+// usually to introduce documentation comments: #ifdef DOC. This method is
+// supposed to be called if the line has been recognized as a preprocessor
+// directive already.
+static bool IsDocCommentStart(StyleContext &sc) {
+	// Check the line back to its start only if the end looks promising.
+	if (sc.LengthCurrent() == 10 && !IsAlphaNumeric(sc.ch)) {
+		char s[11];
+		sc.GetCurrentLowered(s, sizeof(s));
+		return strcmp(s, "#ifdef doc") == 0;
+	}
+	return false;
+}
+
+// Checks if the current line starts with the preprocessor directive that
+// is complementary to the #ifdef DOC start: #endif. This method is supposed
+// to be called if the current state point to the documentation comment.
+// QUESTIONAL ASSUMPTION: The complete #endif directive is not checked; just
+// the starting #e. However, there is no other preprocessor directive with
+// the same starting letter and thus this optimization should always work.
+static bool IsDocCommentEnd(StyleContext &sc) {
+	return sc.ch == '#' && sc.chNext == 'e';
+}
+
+class IdentifierClassifier {
+	WordList &keywords;  // Passed from keywords property.
+	WordList &constants; // Passed from keywords2 property.
+	WordList &operators; // Passed from keywords3 property.
+	WordList &types;     // Passed from keywords4 property.
+	WordList &functions; // Passed from keywords5 property.
+	WordList &objects;   // Passed from keywords6 property.
+
+	IdentifierClassifier(IdentifierClassifier const&);
+	IdentifierClassifier& operator=(IdentifierClassifier const&);
+
+public:
+	IdentifierClassifier(WordList *keywordlists[]) :
+		keywords(*keywordlists[0]), constants(*keywordlists[1]),
+		operators(*keywordlists[2]), types(*keywordlists[3]),
+		functions(*keywordlists[4]), objects(*keywordlists[5])
+	{}
+
+	void ClassifyIdentifier(StyleContext &sc) {
+		// Opening parenthesis following an identifier makes it a possible
+		// function call.
+		// KNOWN PROBLEM: If some whitespace is inserted between the
+		// identifier and the parenthesis they will not be able to be
+		// recognized as a function call. This should not occur; at
+		// least not often. Such coding style would be weird.
+		if (sc.Match('(')) {
+			char s[100];
+			sc.GetCurrentLowered(s, sizeof(s));
+			// Before an opening brace can be control statements and
+			// operators too; function call is the last option.
+			if (keywords.InList(s)) {
+				sc.ChangeState(SCE_OSCRIPT_KEYWORD);
+			} else if (operators.InList(s)) {
+				sc.ChangeState(SCE_OSCRIPT_OPERATOR);
+			} else if (functions.InList(s)) {
+				sc.ChangeState(SCE_OSCRIPT_FUNCTION);
+			} else {
+				sc.ChangeState(SCE_OSCRIPT_METHOD);
+			}
+			sc.SetState(SCE_OSCRIPT_OPERATOR);
+		} else {
+			char s[100];
+			sc.GetCurrentLowered(s, sizeof(s));
+			// A dot following an identifier means an access to an object
+			// member. The related object identifier can be special.
+			// KNOWN PROBLEM: If there is whitespace between the identifier
+			// and the following dot, the identifier will not be recognized
+			// as an object in an object member access. If it is one of the
+			// listed static objects it will not be styled.
+			if (sc.Match('.') && objects.InList(s)) {
+				sc.ChangeState(SCE_OSCRIPT_OBJECT);
+				sc.SetState(SCE_OSCRIPT_OPERATOR);
+			} else {
+				if (keywords.InList(s)) {
+					sc.ChangeState(SCE_OSCRIPT_KEYWORD);
+				} else if (constants.InList(s)) {
+					sc.ChangeState(SCE_OSCRIPT_CONSTANT);
+				} else if (operators.InList(s)) {
+					sc.ChangeState(SCE_OSCRIPT_OPERATOR);
+				} else if (types.InList(s)) {
+					sc.ChangeState(SCE_OSCRIPT_TYPE);
+				} else if (functions.InList(s)) {
+					sc.ChangeState(SCE_OSCRIPT_FUNCTION);
+				}
+				sc.SetState(SCE_OSCRIPT_DEFAULT);
+			}
+		}
+	}
+};
+
+// ------------------------------------------------
+// Function colourising an excerpt of OScript code.
+
+static void ColouriseOScriptDoc(unsigned int startPos, int length,
+								int initStyle, WordList *keywordlists[],
+								Accessor &styler) {
+	// I wonder how whole-line styles ended by EOLN can escape the resetting
+	// code in the loop below and overflow to the next line. Let us make sure
+	// that a new line does not start with them carried from the previous one.
+	// NOTE: An overflowing string is intentionally not checked; it reminds
+	// the developer that the string must be ended on the same line.
+	if (initStyle == SCE_OSCRIPT_LINE_COMMENT ||
+			initStyle == SCE_OSCRIPT_PREPROCESSOR) {
+		initStyle = SCE_OSCRIPT_DEFAULT;
+	}
+
+	styler.StartAt(startPos);
+	StyleContext sc(startPos, length, initStyle, styler);
+	IdentifierClassifier identifierClassifier(keywordlists);
+
+	// It starts with true at the beginning of a line and changes to false as
+	// soon as the first non-whitespace character has been processed.
+	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; 
+	// 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; 
+
+	for (; sc.More(); sc.Forward()) {
+
+		if (sc.atLineStart) {
+			isFirstToken = true;
+			isFirstIdentifier = true;
+		// Detect the current state is neither whitespace nor identifier. It
+		// means that no next identifier can be the first token on the line.
+		} else if (isFirstIdentifier && sc.state != SCE_OSCRIPT_DEFAULT &&
+				   sc.state != SCE_OSCRIPT_IDENTIFIER) {
+			isFirstIdentifier = false;
+		}
+
+		// Check if the current state should be changed.
+		if (sc.state == SCE_OSCRIPT_OPERATOR) {
+			// Multiple-symbol operators are marked by single characters.
+			sc.SetState(SCE_OSCRIPT_DEFAULT);
+		} else if (sc.state == SCE_OSCRIPT_IDENTIFIER) {
+			if (!IsIdentifierChar(sc.ch)) {
+				// Colon after an identifier makes it a label if it is the
+				// first token on the line.
+				// KNOWN PROBLEM: If some whitespace is inserted between the
+				// identifier and the colon they will not be recognized as a
+				// label. This should not occur; at least not often. It would
+				// make the code structure less legible and examples in the
+				// Livelink documentation do not show it.
+				if (sc.Match(':') && isFirstIdentifier) {
+					sc.ChangeState(SCE_OSCRIPT_LABEL);
+					sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+				} else {
+					identifierClassifier.ClassifyIdentifier(sc);
+				}
+				// Avoid a sequence of two words be mistaken for a label. A
+				// switch case would be an example.
+				isFirstIdentifier = false;
+			}
+		} else if (sc.state == SCE_OSCRIPT_GLOBAL) {
+			if (!IsIdentifierChar(sc.ch)) {
+				sc.SetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_PROPERTY) {
+			if (!IsIdentifierChar(sc.ch)) {
+				// Any member access introduced by the dot operator is
+				// initially marked as a property access. If an opening
+				// parenthesis is detected later it is changed to method call.
+				// KNOWN PROBLEM: The same as at the function call recognition
+				// for SCE_OSCRIPT_IDENTIFIER above.
+				if (sc.Match('(')) {
+					sc.ChangeState(SCE_OSCRIPT_METHOD);
+				}
+				sc.SetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_NUMBER) {
+			if (!IsNumberChar(sc.ch, sc.chNext)) {
+				sc.SetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_SINGLEQUOTE_STRING) {
+			if (sc.ch == '\'') {
+				// Two consequential apostrophes convert to a single one.
+				if (sc.chNext == '\'') {
+					sc.Forward();
+				} else {
+					sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+				}
+			} else if (sc.atLineEnd) {
+				sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_DOUBLEQUOTE_STRING) {
+			if (sc.ch == '\"') {
+				// Two consequential quotation marks convert to a single one.
+				if (sc.chNext == '\"') {
+					sc.Forward();
+				} else {
+					sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+				}
+			} else if (sc.atLineEnd) {
+				sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_BLOCK_COMMENT) {
+			if (sc.Match('*', '/')) {
+				sc.Forward();
+				sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_LINE_COMMENT) {
+			if (sc.atLineEnd) {
+				sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_PREPROCESSOR) {
+			if (IsDocCommentStart(sc)) {
+				sc.ChangeState(SCE_OSCRIPT_DOC_COMMENT);
+				endDocComment = false;
+			} else if (sc.atLineEnd) {
+				sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+			}
+		} else if (sc.state == SCE_OSCRIPT_DOC_COMMENT) {
+			// KNOWN PROBLEM: The first line detected that would close a
+			// conditional preprocessor block (#endif) the documentation
+			// comment block will end. (Nested #if-#endif blocks are not
+			// supported. Hopefully it will not occur often that a line
+			// within the text block would stat with #endif.
+			if (isFirstToken && IsDocCommentEnd(sc)) {
+				endDocComment = true;
+			} else if (sc.atLineEnd && endDocComment) {
+				sc.ForwardSetState(SCE_OSCRIPT_DEFAULT);
+			}
+		}
+
+		// Check what state starts with the current character.
+		if (sc.state == SCE_OSCRIPT_DEFAULT) {
+			if (sc.Match('\'')) {
+				sc.SetState(SCE_OSCRIPT_SINGLEQUOTE_STRING);
+			} else if (sc.Match('\"')) {
+				sc.SetState(SCE_OSCRIPT_DOUBLEQUOTE_STRING);
+			} else if (sc.Match('/', '/')) {
+				sc.SetState(SCE_OSCRIPT_LINE_COMMENT);
+				sc.Forward();
+			} else if (sc.Match('/', '*')) {
+				sc.SetState(SCE_OSCRIPT_BLOCK_COMMENT);
+				sc.Forward();
+			} else if (isFirstToken && sc.Match('#')) {
+				sc.SetState(SCE_OSCRIPT_PREPROCESSOR);
+			} else if (sc.Match('$')) {
+				// Both process-global ($xxx) and thread-global ($$xxx)
+				// variables are handled as one global.
+				sc.SetState(SCE_OSCRIPT_GLOBAL);
+			} else if (IsNaturalNumberStart(sc.ch)) {
+				sc.SetState(SCE_OSCRIPT_NUMBER);
+			} else if (IsPrefixedNumberStart(sc.ch, sc.chNext)) {
+				sc.SetState(SCE_OSCRIPT_NUMBER);
+				sc.Forward();
+			} else if (sc.Match('.') && IsIdentifierStart(sc.chNext)) {
+				// Every object member access is marked as a property access
+				// initially. The decision between property and method is made
+				// after parsing the identifier and looking what comes then.
+				// KNOWN PROBLEM: If there is whitespace between the following
+				// identifier and the dot, the dot will not be recognized
+				// as a member accessing operator. In turn, the identifier
+				// will not be recognizable as a property or a method too.
+				sc.SetState(SCE_OSCRIPT_OPERATOR);
+				sc.Forward();
+				sc.SetState(SCE_OSCRIPT_PROPERTY);
+			} else if (IsIdentifierStart(sc.ch)) {
+				sc.SetState(SCE_OSCRIPT_IDENTIFIER);
+			} else if (IsOperator(sc.ch)) {
+				sc.SetState(SCE_OSCRIPT_OPERATOR);
+			}
+		}
+
+		if (isFirstToken && !IsASpaceOrTab(sc.ch)) {
+			isFirstToken = false;
+		}
+	}
+
+	sc.Complete();
+}
+
+// ------------------------------------------
+// Functions supporting OScript code folding.
+
+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++) {
+		char ch = styler[i];
+		char chNext = styler.SafeGetCharAt(i + 1);
+		int style = styler.StyleAt(i);
+		if (ch == '/' && chNext == '/' && style == SCE_OSCRIPT_LINE_COMMENT) {
+			return true;
+		} else if (!IsASpaceOrTab(ch)) {
+			return false;
+		}
+	}
+	return false;
+}
+
+static inline bool IsPreprocessor(int style) {
+	return style == SCE_OSCRIPT_PREPROCESSOR ||
+		   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;
+	while (i < end - start + 1 && i < len - 1) {
+		s[i] = static_cast<char>(tolower(styler[start + i]));
+		i++;
+	}
+	s[i] = '\0';
+}
+
+static void GetForwardWordLowered(unsigned int start, Accessor &styler,
+								  char *s, unsigned int len) {
+	unsigned int i = 0;
+	while (i < len - 1 && IsAlpha(styler.SafeGetCharAt(start + i))) {
+		s[i] = static_cast<char>(tolower(styler.SafeGetCharAt(start + i)));
+		i++;
+	}
+	s[i] = '\0';
+}
+
+static void UpdatePreprocessorFoldLevel(int &levelCurrent,
+		unsigned int startPos, Accessor &styler) {
+	char s[7]; // Size of the longest possible keyword + null.
+	GetForwardWordLowered(startPos, styler, s, sizeof(s));
+
+	if (strcmp(s, "ifdef") == 0 ||
+		strcmp(s, "ifndef") == 0) {
+		levelCurrent++;
+	} else if (strcmp(s, "endif") == 0) {
+		levelCurrent--;
+		if (levelCurrent < SC_FOLDLEVELBASE) {
+			levelCurrent = SC_FOLDLEVELBASE;
+		}
+	}
+}
+
+static void UpdateKeywordFoldLevel(int &levelCurrent, unsigned int lastStart,
+		unsigned int currentPos, Accessor &styler) {
+	char s[9];
+	GetRangeLowered(lastStart, currentPos, styler, s, sizeof(s));
+
+	if (strcmp(s, "if") == 0 || strcmp(s, "for") == 0 ||
+		strcmp(s, "switch") == 0 || strcmp(s, "function") == 0 ||
+		strcmp(s, "while") == 0 || strcmp(s, "repeat") == 0) {
+		levelCurrent++;
+	} else if (strcmp(s, "end") == 0 || strcmp(s, "until") == 0) {
+		levelCurrent--;
+		if (levelCurrent < SC_FOLDLEVELBASE) {
+			levelCurrent = SC_FOLDLEVELBASE;
+		}
+	}
+}
+
+// ------------------------------
+// Function folding OScript code.
+
+static void FoldOScriptDoc(unsigned int startPos, int 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;
+	int visibleChars = 0;
+	int 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;
+
+	for (int i = startPos; i < endPos; i++) {
+		char ch = chNext;
+		chNext = styler.SafeGetCharAt(i + 1);
+		int stylePrev = style;
+		style = styleNext;
+		styleNext = styler.StyleAt(i + 1);
+		bool atLineEnd = (ch == '\r' && chNext != '\n') || (ch == '\n');
+
+		if (foldComment && IsBlockComment(style)) {
+			if (!IsBlockComment(stylePrev)) {
+				levelCurrent++;
+			} else if (!IsBlockComment(styleNext) && !atLineEnd) {
+				// Comments do not end at end of line and the next character
+				// may not be styled.
+				levelCurrent--;
+			}
+		}
+		if (foldComment && atLineEnd && IsLineComment(lineCurrent, styler)) {
+			if (!IsLineComment(lineCurrent - 1, styler) &&
+				IsLineComment(lineCurrent + 1, styler))
+				levelCurrent++;
+			else if (IsLineComment(lineCurrent - 1, styler) &&
+					 !IsLineComment(lineCurrent+1, styler))
+				levelCurrent--;
+		}
+		if (foldPreprocessor) {
+			if (ch == '#' && IsPreprocessor(style)) {
+				UpdatePreprocessorFoldLevel(levelCurrent, i + 1, styler);
+			}
+		}
+
+		if (stylePrev != SCE_OSCRIPT_KEYWORD && style == SCE_OSCRIPT_KEYWORD) {
+			lastStart = i;
+		}
+		if (stylePrev == SCE_OSCRIPT_KEYWORD) {
+			if(IsIdentifierChar(ch) && !IsIdentifierChar(chNext)) {
+				UpdateKeywordFoldLevel(levelCurrent, lastStart, i, styler);
+			}
+		}
+
+		if (!IsASpace(ch))
+			visibleChars++;
+
+		if (atLineEnd) {
+			int level = levelPrev;
+			if (visibleChars == 0 && foldCompact)
+				level |= SC_FOLDLEVELWHITEFLAG;
+			if ((levelCurrent > levelPrev) && (visibleChars > 0))
+				level |= SC_FOLDLEVELHEADERFLAG;
+			if (level != styler.LevelAt(lineCurrent)) {
+				styler.SetLevel(lineCurrent, level);
+			}
+			lineCurrent++;
+			levelPrev = levelCurrent;
+			visibleChars = 0;
+		}
+	}
+
+	// If we did not reach EOLN in the previous loop, store the line level and
+	// whitespace information. The rest will be filled in later.
+	int lev = levelPrev;
+	if (visibleChars == 0 && foldCompact)
+		lev |= SC_FOLDLEVELWHITEFLAG;
+	styler.SetLevel(lineCurrent, lev);
+}
+
+// --------------------------------------------
+// Declaration of the OScript lexer descriptor.
+
+static const char * const oscriptWordListDesc[] = {
+	"Keywords and reserved words",
+	"Literal constants",
+	"Literal operators",
+	"Built-in value and reference types",
+	"Built-in global functions",
+	"Built-in static objects",
+	0
+};
+
+LexerModule lmOScript(SCLEX_OSCRIPT, ColouriseOScriptDoc, "oscript", FoldOScriptDoc, oscriptWordListDesc);
diff --git a/plugins/scintilla/scintilla/lexers/LexOthers.cxx b/plugins/scintilla/scintilla/lexers/LexOthers.cxx
index 5f4eaed..259059f 100644
--- a/plugins/scintilla/scintilla/lexers/LexOthers.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexOthers.cxx
@@ -500,6 +500,10 @@ static void ColouriseBatchDoc(
 	}
 }
 
+#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, int endLine, Accessor &styler) {
 	// It is needed to remember the current state to recognize starting
 	// comment lines before the first "diff " or "--- ". If a real
@@ -556,20 +560,27 @@ static void ColouriseDiffLine(char *lineBuffer, int endLine, Accessor &styler) {
 }
 
 static void ColouriseDiffDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
-	char lineBuffer[1024];
+	char lineBuffer[DIFF_BUFFER_START_SIZE];
 	styler.StartAt(startPos);
 	styler.StartSegment(startPos);
 	unsigned int linePos = 0;
 	for (unsigned int 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';
+		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);
 	}
 }
diff --git a/plugins/scintilla/scintilla/lexers/LexPascal.cxx b/plugins/scintilla/scintilla/lexers/LexPascal.cxx
index 867b00e..1e2be23 100644
--- a/plugins/scintilla/scintilla/lexers/LexPascal.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPascal.cxx
@@ -54,6 +54,8 @@ are ignored as fold points
 4. Every other situation when class keyword doesn't actually start class
 declaration ("class procedure", "class function", "class of", "class var",
 "class property" and "class operator")
+5. Forward (disp)interface declarations ("type IMyInterface = interface;") are
+ignored as fold points
 
 - Folding of code blocks inside preprocessor blocks is disabled (any comments
 inside them will be folded fine) because there is no guarantee that complete
@@ -484,6 +486,24 @@ static void ClassifyPascalWordFoldPoint(int &levelCurrent, int &lineFoldStateCur
 			ignoreKeyword = false;
 		}
 		if (!ignoreKeyword) {
+			unsigned int k = SkipWhiteSpace(currentPos, endPos, styler);
+			if (k < endPos && styler.SafeGetCharAt(k) == ';') {
+				// Handle forward interface declarations ("type IMyInterface = interface;")
+				ignoreKeyword = true;
+			}
+		}
+		if (!ignoreKeyword) {
+			levelCurrent++;
+		}
+	} else if (strcmp(s, "dispinterface") == 0) {
+		// "dispinterface" keyword requires special handling...
+		bool ignoreKeyword = false;
+		unsigned int j = SkipWhiteSpace(currentPos, endPos, styler);
+		if (j < endPos && styler.SafeGetCharAt(j) == ';') {
+			// Handle forward dispinterface declarations ("type IMyInterface = dispinterface;")
+			ignoreKeyword = true;
+		}
+		if (!ignoreKeyword) {
 			levelCurrent++;
 		}
 	} else if (strcmp(s, "end") == 0) {
diff --git a/plugins/scintilla/scintilla/lexers/LexPerl.cxx b/plugins/scintilla/scintilla/lexers/LexPerl.cxx
index 87a06d4..da90387 100644
--- a/plugins/scintilla/scintilla/lexers/LexPerl.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexPerl.cxx
@@ -366,7 +366,7 @@ public:
 		setSpecialVar(CharacterSet::setNone, "\"$;<>&`'+,./\\%:=~!? []"),
 		setControlVar(CharacterSet::setNone, "ACDEFHILMNOPRSTVWX") {
 	}
-	~LexerPerl() {
+	virtual ~LexerPerl() {
 	}
 	void SCI_METHOD Release() {
 		delete this;
@@ -945,8 +945,7 @@ void SCI_METHOD LexerPerl::Lex(unsigned int startPos, int length, int initStyle,
 							sc.SetState(SCE_PL_POD);
 						} else
 							fw = fw2;
-					} else
-						pod = SCE_PL_POD;
+					}
 				} else {
 					if (pod == SCE_PL_POD_VERB	// still part of current paragraph
 					        && (styler.GetLineState(ln - 1) == SCE_PL_POD)) {
diff --git a/plugins/scintilla/scintilla/lexers/LexRuby.cxx b/plugins/scintilla/scintilla/lexers/LexRuby.cxx
index d21a3df..23115e6 100644
--- a/plugins/scintilla/scintilla/lexers/LexRuby.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexRuby.cxx
@@ -1192,7 +1192,6 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                     state = SCE_RB_DEFAULT;
                     i--;
                     chNext = ch;
-                    chNext2 = chNext;
                     preferRE = false;
                 } else if (HereDoc.Quoted) {
 					if (ch == HereDoc.Quote) { // closing quote => end of delimiter
@@ -1349,7 +1348,6 @@ static void ColouriseRbDoc(unsigned int startPos, int length, int initStyle,
                         }
                     }
                     chNext = styler.SafeGetCharAt(i + 1);
-                    chNext2 = styler.SafeGetCharAt(i + 2);
                 }
             }
         // Quotes of all kinds...
diff --git a/plugins/scintilla/scintilla/lexers/LexSQL.cxx b/plugins/scintilla/scintilla/lexers/LexSQL.cxx
index 3a8ddec..d9013db 100644
--- a/plugins/scintilla/scintilla/lexers/LexSQL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexSQL.cxx
@@ -1,8 +1,10 @@
+//-*- coding: utf-8 -*-
 // Scintilla source code edit control
 /** @file LexSQL.cxx
  ** Lexer for SQL, including PL/SQL and SQL*Plus.
+ ** Improved by JÃrÃme LAFORGE <jerome.laforge_AT_gmail_DOT_com> from 2010 to 2012.
  **/
-// Copyright 1998-2011 by Neil Hodgson <neilh scintilla org>
+// Copyright 1998-2012 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
 #include <stdlib.h>
@@ -28,6 +30,7 @@
 #include "CharacterSet.h"
 #include "LexerModule.h"
 #include "OptionSet.h"
+#include "SparseState.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
@@ -63,10 +66,7 @@ static inline bool IsANumberChar(int ch) {
 class SQLStates {
 public :
 	void Set(int lineNumber, unsigned short int sqlStatesLine) {
-		if (!sqlStatement.size() == 0 || !sqlStatesLine == 0) {
-			sqlStatement.resize(lineNumber + 1, 0);
-			sqlStatement[lineNumber] = sqlStatesLine;
-		}
+		sqlStatement.Set(lineNumber, sqlStatesLine);
 	}
 
 	unsigned short int IgnoreWhen (unsigned short int sqlStatesLine, bool enable) {
@@ -105,6 +105,33 @@ public :
 		return sqlStatesLine;
 	}
 
+	unsigned short int IntoMergeStatement (unsigned short int sqlStatesLine, bool enable) {
+		if (enable)
+			sqlStatesLine |= MASK_MERGE_STATEMENT;
+		else
+			sqlStatesLine &= ~MASK_MERGE_STATEMENT;
+
+		return sqlStatesLine;
+	}
+
+	unsigned short int CaseMergeWithoutWhenFound (unsigned short int sqlStatesLine, bool found) {
+		if (found)
+			sqlStatesLine |= MASK_CASE_MERGE_WITHOUT_WHEN_FOUND;
+		else
+			sqlStatesLine &= ~MASK_CASE_MERGE_WITHOUT_WHEN_FOUND;
+
+		return sqlStatesLine;
+	}
+
+	unsigned short int IntoSelectStatement (unsigned short int sqlStatesLine, bool found) {
+		if (found)
+			sqlStatesLine |= MASK_INTO_SELECT_STATEMENT;
+		else
+			sqlStatesLine &= ~MASK_INTO_SELECT_STATEMENT;
+
+		return sqlStatesLine;
+	}
+
 	unsigned short int BeginCaseBlock (unsigned short int sqlStatesLine) {
 		if ((sqlStatesLine & MASK_NESTED_CASES) < MASK_NESTED_CASES) {
 			sqlStatesLine++;
@@ -135,28 +162,39 @@ public :
 		return (sqlStatesLine & MASK_INTO_EXCEPTION) != 0;
 	}
 
+	bool IsIntoSelectStatement (unsigned short int sqlStatesLine) {
+		return (sqlStatesLine & MASK_INTO_SELECT_STATEMENT) != 0;
+	}
+
+	bool IsCaseMergeWithoutWhenFound (unsigned short int sqlStatesLine) {
+		return (sqlStatesLine & MASK_CASE_MERGE_WITHOUT_WHEN_FOUND) != 0;
+	}
+
 	bool IsIntoDeclareBlock (unsigned short int sqlStatesLine) {
 		return (sqlStatesLine & MASK_INTO_DECLARE) != 0;
 	}
 
+	bool IsIntoMergeStatement (unsigned short int sqlStatesLine) {
+		return (sqlStatesLine & MASK_MERGE_STATEMENT) != 0;
+	}
+
 	unsigned short int ForLine(int lineNumber) {
-		if ((lineNumber > 0) && (sqlStatement.size() > static_cast<size_t>(lineNumber))) {
-			return sqlStatement[lineNumber];
-		} else {
-			return 0;
-		}
+		return sqlStatement.ValueAt(lineNumber);
 	}
 
 	SQLStates() {}
 
 private :
-	std::vector <unsigned short int> sqlStatement;
+	SparseState <unsigned short int> sqlStatement;
 	enum {
+		MASK_NESTED_CASES = 0x01FF,
+		MASK_INTO_SELECT_STATEMENT = 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 = 0x0FFF
+		MASK_IGNORE_WHEN = 0x8000
 	};
 };
 
@@ -229,6 +267,8 @@ class LexerSQL : public ILexer {
 public :
 	LexerSQL() {}
 
+	virtual ~LexerSQL() {}
+
 	int SCI_METHOD Version () const {
 		return lvOriginal;
 	}
@@ -560,6 +600,17 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 			endFound = false;
 			isUnfoldingIgnored = false;
 		}
+		if ((!IsCommentStyle(style) && ch == ';')) {
+			if (sqlStates.IsIntoMergeStatement(sqlStatesCurrentLine)) {
+				// This is the end of "MERGE" statement.
+				if (!sqlStates.IsCaseMergeWithoutWhenFound(sqlStatesCurrentLine))
+					levelNext--;
+				sqlStatesCurrentLine = sqlStates.IntoMergeStatement(sqlStatesCurrentLine, false);
+				levelNext--;
+			}
+			if (sqlStates.IsIntoSelectStatement(sqlStatesCurrentLine))
+				sqlStatesCurrentLine = sqlStates.IntoSelectStatement(sqlStatesCurrentLine, false);
+		}
 		if (options.foldComment && IsStreamCommentStyle(style)) {
 			if (!IsStreamCommentStyle(stylePrev)) {
 				levelNext++;
@@ -616,7 +667,10 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 				s[j] = '\0';
 			}
 
-			if (strcmp(s, "if") == 0) {
+			if (!options.foldOnlyBegin &&
+			        strcmp(s, "select") == 0) {
+				sqlStatesCurrentLine = sqlStates.IntoSelectStatement(sqlStatesCurrentLine, true);
+			} else if (strcmp(s, "if") == 0) {
 				if (endFound) {
 					endFound = false;
 					if (options.foldOnlyBegin && !isUnfoldingIgnored) {
@@ -661,23 +715,20 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 					}
 					if ((!options.foldOnlyBegin) && strcmp(s, "case") == 0) {
 						sqlStatesCurrentLine = sqlStates.EndCaseBlock(sqlStatesCurrentLine);
-						levelNext--; //again for the "end case;" and block when
+						if (!sqlStates.IsCaseMergeWithoutWhenFound(sqlStatesCurrentLine))
+							levelNext--; //again for the "end case;" and block when
 					}
 				} else if (!options.foldOnlyBegin) {
-					if (strcmp(s, "case") == 0) {
+					if (strcmp(s, "case") == 0)
 						sqlStatesCurrentLine = sqlStates.BeginCaseBlock(sqlStatesCurrentLine);
 
-						//for case block increment 2 times
-						if (!statementFound)
-							levelNext++;
-					}
-
-					if (levelCurrent > levelNext) {
+					if (levelCurrent > levelNext)
 						levelCurrent = levelNext;
-					}
+
 					if (!statementFound)
 						levelNext++;
 
+					sqlStatesCurrentLine = sqlStates.CaseMergeWithoutWhenFound(sqlStatesCurrentLine, true);
 					statementFound = true;
 				} else if (levelCurrent > levelNext) {
 					// doesn't include this line into the folding block
@@ -697,9 +748,13 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 			               options.foldAtElse && !statementFound) && strcmp(s, "else") == 0) {
 				// prevent also ELSE is on the same line (eg. "ELSE ... END IF;")
 				statementFound = true;
-				// we are in same case "} ELSE {" in C language
-				levelCurrent--;
-
+				if (sqlStates.IsIntoCaseBlock(sqlStatesCurrentLine) && sqlStates.IsCaseMergeWithoutWhenFound(sqlStatesCurrentLine)) {
+					sqlStatesCurrentLine = sqlStates.CaseMergeWithoutWhenFound(sqlStatesCurrentLine, false);
+					levelNext++;
+				} else {
+					// we are in same case "} ELSE {" in C language
+					levelCurrent--;
+				}
 			} else if (strcmp(s, "begin") == 0) {
 				levelNext++;
 				sqlStatesCurrentLine = sqlStates.IntoDeclareBlock(sqlStatesCurrentLine, false);
@@ -710,6 +765,8 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 			           (strcmp(s, "endif") == 0)) {
 				endFound = true;
 				levelNext--;
+				if (sqlStates.IsIntoSelectStatement(sqlStatesCurrentLine) && !sqlStates.IsCaseMergeWithoutWhenFound(sqlStatesCurrentLine))
+					levelNext--;
 				if (levelNext < SC_FOLDLEVELBASE) {
 					levelNext = SC_FOLDLEVELBASE;
 					isUnfoldingIgnored = true;
@@ -717,14 +774,21 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 			} else if ((!options.foldOnlyBegin) &&
 			           strcmp(s, "when") == 0 &&
 			           !sqlStates.IsIgnoreWhen(sqlStatesCurrentLine) &&
-			           !sqlStates.IsIntoExceptionBlock(sqlStatesCurrentLine) &&
-			           sqlStates.IsIntoCaseBlock(sqlStatesCurrentLine)) {
+			           !sqlStates.IsIntoExceptionBlock(sqlStatesCurrentLine) && (
+			               sqlStates.IsIntoCaseBlock(sqlStatesCurrentLine) ||
+			               sqlStates.IsIntoMergeStatement(sqlStatesCurrentLine)
+			               )
+			           ) {
 				sqlStatesCurrentLine = sqlStates.IntoCondition(sqlStatesCurrentLine, true);
 
 				// Don't foldind when CASE and WHEN are on the same line (with flag statementFound) (eg. "CASE selector WHEN expression1 THEN sequence_of_statements1;\n")
+				// and same way for MERGE statement.
 				if (!statementFound) {
-					levelCurrent--;
-					levelNext--;
+					if (!sqlStates.IsCaseMergeWithoutWhenFound(sqlStatesCurrentLine)) {
+						levelCurrent--;
+						levelNext--;
+					}
+					sqlStatesCurrentLine = sqlStates.CaseMergeWithoutWhenFound(sqlStatesCurrentLine, false);
 				}
 			} else if ((!options.foldOnlyBegin) && strcmp(s, "exit") == 0) {
 				sqlStatesCurrentLine = sqlStates.IgnoreWhen(sqlStatesCurrentLine, true);
@@ -736,6 +800,12 @@ void SCI_METHOD LexerSQL::Fold(unsigned int startPos, int length, int initStyle,
 			            strcmp(s, "procedure") == 0 ||
 			            strcmp(s, "package") == 0)) {
 				sqlStatesCurrentLine = sqlStates.IntoDeclareBlock(sqlStatesCurrentLine, true);
+			} else if ((!options.foldOnlyBegin) &&
+			           strcmp(s, "merge") == 0) {
+				sqlStatesCurrentLine = sqlStates.IntoMergeStatement(sqlStatesCurrentLine, true);
+				sqlStatesCurrentLine = sqlStates.CaseMergeWithoutWhenFound(sqlStatesCurrentLine, true);
+				levelNext++;
+				statementFound = true;
 			}
 		}
 		if (atEOL) {
diff --git a/plugins/scintilla/scintilla/lexers/LexTADS3.cxx b/plugins/scintilla/scintilla/lexers/LexTADS3.cxx
index a180544..54cb88a 100644
--- a/plugins/scintilla/scintilla/lexers/LexTADS3.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexTADS3.cxx
@@ -697,7 +697,7 @@ static inline bool IsAnIdentifier(const int style) {
 }
 
 static inline bool IsAnOperator(const int style) {
-    return style == SCE_T3_OPERATOR || SCE_T3_BRACE;
+    return style == SCE_T3_OPERATOR || style == SCE_T3_BRACE;
 }
 
 static inline bool IsSpaceEquivalent(const int ch, const int style) {
diff --git a/plugins/scintilla/scintilla/lexers/LexVHDL.cxx b/plugins/scintilla/scintilla/lexers/LexVHDL.cxx
index 5580b3c..ee9d662 100644
--- a/plugins/scintilla/scintilla/lexers/LexVHDL.cxx
+++ b/plugins/scintilla/scintilla/lexers/LexVHDL.cxx
@@ -128,9 +128,6 @@ static void ColouriseVHDLDoc(
       } else if (IsAWordStart(sc.ch)) {
         sc.SetState(SCE_VHDL_IDENTIFIER);
       } else if (sc.Match('-', '-')) {
-        sc.SetState(SCE_VHDL_COMMENT);
-        sc.Forward();
-      } else if (sc.Match('-', '-')) {
         if (sc.Match("--!"))  // Nice to have a different comment style
           sc.SetState(SCE_VHDL_COMMENTLINEBANG);
         else
diff --git a/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx b/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx
new file mode 100644
index 0000000..8a7495b
--- /dev/null
+++ b/plugins/scintilla/scintilla/lexers/LexVisualProlog.cxx
@@ -0,0 +1,470 @@
+// Scintilla source code edit control
+/** @file LexVisualProlog.cxx
+** Lexer for Visual Prolog.
+**/
+// Author Thomas Linder Puls, Prolog Development Denter A/S, http://www.visual-prolog.com
+// Based on Lexer for C++, C, Java, and JavaScript.
+// 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 <ctype.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+
+#ifdef _MSC_VER
+#pragma warning(disable: 4786)
+#endif
+
+#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"
+
+#ifdef SCI_NAMESPACE
+using namespace Scintilla;
+#endif
+
+// Options used for LexerVisualProlog
+struct OptionsVisualProlog {
+    OptionsVisualProlog() {
+    }
+};
+
+static const char *const visualPrologWordLists[] = {
+    "Major keywords (class, predicates, ...)",
+    "Minor keywords (if, then, try, ...)",
+    "Directive keywords without the '#' (include, requires, ...)",
+    "Documentation keywords without the '@' (short, detail, ...)",
+    0,
+};
+
+struct OptionSetVisualProlog : public OptionSet<OptionsVisualProlog> {
+    OptionSetVisualProlog() {
+        DefineWordListSets(visualPrologWordLists);
+    }
+};
+
+class LexerVisualProlog : public ILexer {
+    WordList majorKeywords;
+    WordList minorKeywords;
+    WordList directiveKeywords;
+    WordList docKeywords;
+    OptionsVisualProlog options;
+    OptionSetVisualProlog osVisualProlog;
+public:
+    LexerVisualProlog() {
+    }
+    virtual ~LexerVisualProlog() {
+    }
+    void SCI_METHOD Release() {
+        delete this;
+    }
+    int SCI_METHOD Version() const {
+        return lvOriginal;
+    }
+    const char * SCI_METHOD PropertyNames() {
+        return osVisualProlog.PropertyNames();
+    }
+    int SCI_METHOD PropertyType(const char *name) {
+        return osVisualProlog.PropertyType(name);
+    }
+    const char * SCI_METHOD DescribeProperty(const char *name) {
+        return osVisualProlog.DescribeProperty(name);
+    }
+    int SCI_METHOD PropertySet(const char *key, const char *val);
+    const char * SCI_METHOD DescribeWordListSets() {
+        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);
+
+    void * SCI_METHOD PrivateCall(int, void *) {
+        return 0;
+    }
+
+    static ILexer *LexerFactoryVisualProlog() {
+        return new LexerVisualProlog();
+    }
+};
+
+int 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) {
+    WordList *wordListN = 0;
+    switch (n) {
+    case 0:
+        wordListN = &majorKeywords;
+        break;
+    case 1:
+        wordListN = &minorKeywords;
+        break;
+    case 2:
+        wordListN = &directiveKeywords;
+        break;
+    case 3:
+        wordListN = &docKeywords;
+        break;
+    }
+    int firstModification = -1;
+    if (wordListN) {
+        WordList wlNew;
+        wlNew.Set(wl);
+        if (*wordListN != wlNew) {
+            wordListN->Set(wl);
+            firstModification = 0;
+        }
+    }
+    return firstModification;
+}
+
+// Functor used to truncate history
+struct After {
+    int line;
+    After(int line_) : line(line_) {}
+};
+
+// 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) {
+    char ch = styler.SafeGetCharAt(start, '\n');
+    while (' ' == ch) {
+        start++;
+        ch = styler.SafeGetCharAt(start, '\n');
+    }
+    int i = 0;
+    while (i < 100 && setIdentifier.Contains(ch)){
+        s[i] = ch;
+        i++;
+        ch = styler.SafeGetCharAt(start + i, '\n');
+    }
+    s[i] = '\0';
+}
+
+static void forwardEscapeLiteral(StyleContext &sc, int OwnChar, int EscapeState) {
+    sc.Forward();
+    if (sc.ch == OwnChar || sc.ch == '\\' || sc.ch == 'n' || sc.ch == 'l' || sc.ch == 'r' || sc.ch == 't') {
+        sc.ChangeState(EscapeState);
+    } else if (sc.ch == 'u') {
+        if (IsADigit(sc.chNext, 16)) {
+            sc.Forward();
+            if (IsADigit(sc.chNext, 16)) {
+                sc.Forward();
+                if (IsADigit(sc.chNext, 16)) {
+                    sc.Forward();
+                    if (IsADigit(sc.chNext, 16)) {
+                        sc.Forward();
+                        sc.ChangeState(EscapeState);
+                    }
+                }
+            }
+        }
+    }
+}
+
+void SCI_METHOD LexerVisualProlog::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+    LexAccessor styler(pAccess);
+
+    CharacterSet setDoxygen(CharacterSet::setAlpha, "$ \\&<>#{}[]");
+
+    CharacterSet setLowerStart(CharacterSet::setLower);
+    CharacterSet setVariableStart(CharacterSet::setUpper);
+    CharacterSet setIdentifier(CharacterSet::setAlphaNum, "_", 0x80, true);
+
+    int styleBeforeDocKeyword = SCE_VISUALPROLOG_DEFAULT;
+
+    int currentLine = styler.GetLine(startPos);
+
+    int nestLevel = 0;
+    if (currentLine >= 1)
+    {
+        nestLevel = styler.GetLineState(currentLine - 1);
+    }
+
+    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:
+            sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+            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')))) {
+                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+            }
+            break;
+        case SCE_VISUALPROLOG_IDENTIFIER:
+            if (!setIdentifier.Contains(sc.ch)) {
+                char s[1000];
+                sc.GetCurrent(s, sizeof(s));
+                if (0 == strcmp(s, "end")) {
+                    endLookAhead(s, styler, sc.currentPos, setIdentifier);
+                }
+                if (majorKeywords.InList(s)) {
+                    sc.ChangeState(SCE_VISUALPROLOG_KEY_MAJOR);
+                } else if (minorKeywords.InList(s)) {
+                    sc.ChangeState(SCE_VISUALPROLOG_KEY_MINOR);
+                }
+                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+            }
+            break;
+        case SCE_VISUALPROLOG_VARIABLE:
+        case SCE_VISUALPROLOG_ANONYMOUS:
+            if (!setIdentifier.Contains(sc.ch)) {
+                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+            }
+            break;
+        case SCE_VISUALPROLOG_KEY_DIRECTIVE:
+            if (!setLowerStart.Contains(sc.ch)) {
+                char s[1000];
+                sc.GetCurrent(s, sizeof(s));
+                if (!directiveKeywords.InList(s+1)) {
+                    sc.ChangeState(SCE_VISUALPROLOG_IDENTIFIER);
+                }
+                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+            }
+            break;
+        case SCE_VISUALPROLOG_COMMENT_BLOCK:
+            if (sc.Match('*', '/')) {
+                sc.Forward();
+                nestLevel--;
+                int nextState = (nestLevel == 0) ? SCE_VISUALPROLOG_DEFAULT : SCE_VISUALPROLOG_COMMENT_BLOCK;
+                sc.ForwardSetState(nextState);
+            } else if (sc.Match('/', '*')) {
+                sc.Forward();
+                nestLevel++;
+            } else if (sc.ch == '%') {
+                sc.SetState(SCE_VISUALPROLOG_COMMENT_LINE);
+            } else if (sc.ch == '@') {
+                styleBeforeDocKeyword = sc.state;
+                sc.SetState(SCE_VISUALPROLOG_COMMENT_KEY_ERROR);
+            }
+            break;
+        case SCE_VISUALPROLOG_COMMENT_LINE:
+            if (sc.atLineEnd) {
+                int nextState = (nestLevel == 0) ? SCE_VISUALPROLOG_DEFAULT : SCE_VISUALPROLOG_COMMENT_BLOCK;
+                sc.SetState(nextState);
+            } else if (sc.ch == '@') {
+                styleBeforeDocKeyword = sc.state;
+                sc.SetState(SCE_VISUALPROLOG_COMMENT_KEY_ERROR);
+            }
+            break;
+        case SCE_VISUALPROLOG_COMMENT_KEY_ERROR:
+            if (!setDoxygen.Contains(sc.ch)) {
+                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);
+            }
+            break;
+        case SCE_VISUALPROLOG_STRING_ESCAPE:
+        case SCE_VISUALPROLOG_STRING_ESCAPE_ERROR:
+            // return to SCE_VISUALPROLOG_STRING and treat as such (fall-through)
+            sc.SetState(SCE_VISUALPROLOG_STRING);
+        case SCE_VISUALPROLOG_STRING:
+            if (sc.atLineEnd) {
+                sc.SetState(SCE_VISUALPROLOG_STRING_EOL_OPEN);
+            } else if (sc.ch == '"') {
+                sc.ForwardSetState(SCE_VISUALPROLOG_DEFAULT);
+            } else if (sc.ch == '\\') {
+                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);
+                }
+            }
+            break;
+        case SCE_VISUALPROLOG_STRING_EOL_OPEN:
+            if (sc.atLineStart) {
+                sc.SetState(SCE_VISUALPROLOG_DEFAULT);
+            }
+            break;
+        case SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL:
+        case SCE_VISUALPROLOG_STRING_VERBATIM_EOL:
+            // return to SCE_VISUALPROLOG_STRING_VERBATIM and treat as such (fall-through)
+            sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM);
+        case SCE_VISUALPROLOG_STRING_VERBATIM:
+            if (sc.atLineEnd) {
+                sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM_EOL);
+            } else if (sc.ch == '\"') {
+                if (sc.chNext == '\"') {
+                    sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL);
+                    sc.Forward();
+                } else {
+                    sc.ForwardSetState(SCE_VISUALPROLOG_DEFAULT);
+                }
+            }
+            break;
+        }
+
+        if (sc.atLineEnd && !atLineEndBeforeSwitch) {
+            // State exit processing consumed characters up to end of line.
+            currentLine++;
+        }
+
+        // Determine if a new state should be entered.
+        if (sc.state == SCE_VISUALPROLOG_DEFAULT) {
+            if (sc.Match('@', '\"')) {
+                sc.SetState(SCE_VISUALPROLOG_STRING_VERBATIM);
+                sc.Forward();
+            } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
+                sc.SetState(SCE_VISUALPROLOG_NUMBER);
+            } else if (setLowerStart.Contains(sc.ch)) {
+                sc.SetState(SCE_VISUALPROLOG_IDENTIFIER);
+            } else if (setVariableStart.Contains(sc.ch)) {
+                sc.SetState(SCE_VISUALPROLOG_VARIABLE);
+            } else if (sc.ch == '_') {
+                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 == '%') {
+                sc.SetState(SCE_VISUALPROLOG_COMMENT_LINE);
+            } else if (sc.ch == '\"') {
+                sc.SetState(SCE_VISUALPROLOG_STRING);
+            } else if (sc.ch == '\'') {
+                sc.SetState(SCE_VISUALPROLOG_CHARACTER);
+            } else if (sc.ch == '#') {
+                sc.SetState(SCE_VISUALPROLOG_KEY_DIRECTIVE);
+            } else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '\\') {
+                sc.SetState(SCE_VISUALPROLOG_OPERATOR);
+            }
+        }
+
+    }
+    sc.Complete();
+    styler.Flush();
+}
+
+// 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 {".
+
+void SCI_METHOD LexerVisualProlog::Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
+
+    LexAccessor styler(pAccess);
+
+    unsigned int endPos = startPos + length;
+    int visibleChars = 0;
+    int currentLine = styler.GetLine(startPos);
+    int levelCurrent = SC_FOLDLEVELBASE;
+    if (currentLine > 0)
+        levelCurrent = styler.LevelAt(currentLine-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++) {
+        char ch = chNext;
+        chNext = styler.SafeGetCharAt(i + 1);
+        style = styleNext;
+        styleNext = styler.StyleAt(i + 1);
+        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
+        if (style == SCE_VISUALPROLOG_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;
+            int lev = levelUse | levelNext << 16;
+            if (levelUse < levelNext)
+                lev |= SC_FOLDLEVELHEADERFLAG;
+            if (lev != styler.LevelAt(currentLine)) {
+                styler.SetLevel(currentLine, lev);
+            }
+            currentLine++;
+            levelCurrent = levelNext;
+            levelMinCurrent = levelCurrent;
+            if (atEOL && (i == static_cast<unsigned int>(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);
+            }
+            visibleChars = 0;
+        }
+    }
+}
+
+LexerModule lmVisualProlog(SCLEX_VISUALPROLOG, LexerVisualProlog::LexerFactoryVisualProlog, "visualprolog", visualPrologWordLists);
diff --git a/plugins/scintilla/scintilla/lexlib/LexAccessor.h b/plugins/scintilla/scintilla/lexlib/LexAccessor.h
index dccf31e..c38392e 100644
--- a/plugins/scintilla/scintilla/lexlib/LexAccessor.h
+++ b/plugins/scintilla/scintilla/lexlib/LexAccessor.h
@@ -146,7 +146,7 @@ public:
 			} else {
 				if (chAttr != chWhile)
 					chFlags = 0;
-				chAttr |= chFlags;
+				chAttr = static_cast<char>(chAttr | chFlags);
 				for (unsigned int i = startSeg; i <= pos; i++) {
 					assert((startPosStyling + validLen) < Length());
 					styleBuf[validLen++] = static_cast<char>(chAttr);
diff --git a/plugins/scintilla/scintilla/src/AutoComplete.cxx b/plugins/scintilla/scintilla/src/AutoComplete.cxx
index 2752ef0..aa65810 100644
--- a/plugins/scintilla/scintilla/src/AutoComplete.cxx
+++ b/plugins/scintilla/scintilla/src/AutoComplete.cxx
@@ -14,6 +14,7 @@
 
 #include "CharacterSet.h"
 #include "AutoComplete.h"
+#include "Scintilla.h"
 
 #ifdef SCI_NAMESPACE
 using namespace Scintilla;
@@ -30,7 +31,8 @@ AutoComplete::AutoComplete() :
 	startLen(0),
 	cancelAtStartPos(true),
 	autoHide(true),
-	dropRestOfWord(false)	{
+	dropRestOfWord(false),
+	ignoreCaseBehaviour(SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE) {
 	lb = ListBox::Allocate();
 	stopChars[0] = '\0';
 	fillUpChars[0] = '\0';
@@ -153,7 +155,8 @@ void AutoComplete::Select(const char *word) {
 				--pivot;
 			}
 			location = pivot;
-			if (ignoreCase) {
+			if (ignoreCase
+				&& ignoreCaseBehaviour == SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE) {
 				// Check for exact-case match
 				for (; pivot <= end; pivot++) {
 					lb->GetValue(pivot, item, maxItemLen);
diff --git a/plugins/scintilla/scintilla/src/AutoComplete.h b/plugins/scintilla/scintilla/src/AutoComplete.h
index aefab12..19a1271 100644
--- a/plugins/scintilla/scintilla/src/AutoComplete.h
+++ b/plugins/scintilla/scintilla/src/AutoComplete.h
@@ -31,6 +31,7 @@ public:
 	bool cancelAtStartPos;
 	bool autoHide;
 	bool dropRestOfWord;
+	unsigned int ignoreCaseBehaviour;
 
 	AutoComplete();
 	~AutoComplete();
diff --git a/plugins/scintilla/scintilla/src/Catalogue.cxx b/plugins/scintilla/scintilla/src/Catalogue.cxx
index 4773fff..2f75247 100644
--- a/plugins/scintilla/scintilla/src/Catalogue.cxx
+++ b/plugins/scintilla/scintilla/src/Catalogue.cxx
@@ -109,6 +109,7 @@ int Scintilla_LinkLexers() {
 	LINK_LEXER(lmCss);
 	LINK_LEXER(lmD);
 	LINK_LEXER(lmDiff);
+	LINK_LEXER(lmECL);
 	LINK_LEXER(lmEiffel);
 	LINK_LEXER(lmEiffelkw);
 	LINK_LEXER(lmErlang);
@@ -145,6 +146,7 @@ int Scintilla_LinkLexers() {
 	LINK_LEXER(lmNull);
 	LINK_LEXER(lmOctave);
 	LINK_LEXER(lmOpal);
+	LINK_LEXER(lmOScript);
 	LINK_LEXER(lmPascal);
 	LINK_LEXER(lmPB);
 	LINK_LEXER(lmPerl);
@@ -180,6 +182,7 @@ int Scintilla_LinkLexers() {
 	LINK_LEXER(lmVBScript);
 	LINK_LEXER(lmVerilog);
 	LINK_LEXER(lmVHDL);
+	LINK_LEXER(lmVisualProlog);
 	LINK_LEXER(lmXML);
 	LINK_LEXER(lmYAML);
 
diff --git a/plugins/scintilla/scintilla/src/CellBuffer.cxx b/plugins/scintilla/scintilla/src/CellBuffer.cxx
index 19f6670..11b8b4a 100644
--- a/plugins/scintilla/scintilla/src/CellBuffer.cxx
+++ b/plugins/scintilla/scintilla/src/CellBuffer.cxx
@@ -375,6 +375,14 @@ const char *CellBuffer::BufferPointer() {
 	return substance.BufferPointer();
 }
 
+const char *CellBuffer::RangePointer(int position, int rangeLength) {
+	return substance.RangePointer(position, rangeLength);
+}
+
+int 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) {
 	char *data = 0;
diff --git a/plugins/scintilla/scintilla/src/CellBuffer.h b/plugins/scintilla/scintilla/src/CellBuffer.h
index a82a397..388b902 100644
--- a/plugins/scintilla/scintilla/src/CellBuffer.h
+++ b/plugins/scintilla/scintilla/src/CellBuffer.h
@@ -157,6 +157,8 @@ public:
 	char StyleAt(int position) const;
 	void GetStyleRange(unsigned char *buffer, int position, int lengthRetrieve) const;
 	const char *BufferPointer();
+	const char *RangePointer(int position, int rangeLength);
+	int GapPosition() const;
 
 	int Length() const;
 	void Allocate(int newSize);
diff --git a/plugins/scintilla/scintilla/src/Decoration.cxx b/plugins/scintilla/scintilla/src/Decoration.cxx
index 24632d7..b489c3c 100644
--- a/plugins/scintilla/scintilla/src/Decoration.cxx
+++ b/plugins/scintilla/scintilla/src/Decoration.cxx
@@ -28,7 +28,7 @@ Decoration::~Decoration() {
 }
 
 bool Decoration::Empty() {
-	return rs.Runs() == 1;
+	return (rs.Runs() == 1) && (rs.AllSameAs(0));
 }
 
 DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(0),
@@ -148,7 +148,7 @@ void DecorationList::DeleteRange(int position, int deleteLength) {
 void DecorationList::DeleteAnyEmpty() {
 	Decoration *deco = root;
 	while (deco) {
-		if (deco->Empty()) {
+		if ((lengthDocument == 0) || deco->Empty()) {
 			Delete(deco->indicator);
 			deco = root;
 		} else {
diff --git a/plugins/scintilla/scintilla/src/Document.cxx b/plugins/scintilla/scintilla/src/Document.cxx
index a0dc7f5..244e96e 100644
--- a/plugins/scintilla/scintilla/src/Document.cxx
+++ b/plugins/scintilla/scintilla/src/Document.cxx
@@ -57,7 +57,6 @@ static inline bool IsUpperCase(char ch) {
 }
 
 void LexInterface::Colourise(int start, int end) {
-	ElapsedTime et;
 	if (pdoc && instance && !performingStyle) {
 		// Protect against reentrance, which may occur, for example, when
 		// fold points are discovered while performing styling and the folding
@@ -113,6 +112,8 @@ Document::Document() {
 	matchesValid = false;
 	regex = 0;
 
+	UTF8BytesOfLeadInitialise();
+
 	perLineData[ldMarkers] = new LineMarkers();
 	perLineData[ldLevels] = new LineLevels();
 	perLineData[ldState] = new LineState();
@@ -450,19 +451,13 @@ int Document::LenChar(int pos) {
 	} else if (IsCrLf(pos)) {
 		return 2;
 	} else if (SC_CP_UTF8 == dbcsCodePage) {
-		unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
-		if (ch < 0x80)
-			return 1;
-		int len = 2;
-		if (ch >= (0x80 + 0x40 + 0x20 + 0x10))
-			len = 4;
-		else if (ch >= (0x80 + 0x40 + 0x20))
-			len = 3;
+		const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(pos));
+		const int widthCharBytes = UTF8BytesOfLead[leadByte];
 		int lengthDoc = Length();
-		if ((pos + len) > lengthDoc)
-			return lengthDoc -pos;
+		if ((pos + widthCharBytes) > lengthDoc)
+			return lengthDoc - pos;
 		else
-			return len;
+			return widthCharBytes;
 	} else if (dbcsCodePage) {
 		return IsDBCSLeadByte(cb.CharAt(pos)) ? 2 : 1;
 	} else {
@@ -470,51 +465,29 @@ int Document::LenChar(int pos) {
 	}
 }
 
-static bool IsTrailByte(int ch) {
-	return (ch >= 0x80) && (ch < (0x80 + 0x40));
-}
-
-static int BytesFromLead(int leadByte) {
-	if (leadByte > 0xF4) {
-		// Characters longer than 4 bytes not possible in current UTF-8
-		return 0;
-	} else if (leadByte >= 0xF0) {
-		return 4;
-	} else if (leadByte >= 0xE0) {
-		return 3;
-	} else if (leadByte >= 0xC2) {
-		return 2;
-	}
-	return 0;
-}
-
 bool Document::InGoodUTF8(int pos, int &start, int &end) const {
-	int lead = pos;
-	while ((lead>0) && (pos-lead < 4) && IsTrailByte(static_cast<unsigned char>(cb.CharAt(lead-1))))
-		lead--;
-	start = 0;
-	if (lead > 0) {
-		start = lead-1;
-	}
-	int leadByte = static_cast<unsigned char>(cb.CharAt(start));
-	int bytes = BytesFromLead(leadByte);
-	if (bytes == 0) {
+	int trail = pos;
+	while ((trail>0) && (pos-trail < UTF8MaxBytes) && UTF8IsTrailByte(static_cast<unsigned char>(cb.CharAt(trail-1))))
+		trail--;
+	start = (trail > 0) ? trail-1 : trail;
+
+	const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(start));
+	const int widthCharBytes = UTF8BytesOfLead[leadByte];
+	if (widthCharBytes == 1) {
 		return false;
 	} else {
-		int trailBytes = bytes - 1;
-		int len = pos - lead + 1;
+		int trailBytes = widthCharBytes - 1;
+		int len = pos - start;
 		if (len > trailBytes)
 			// pos too far from lead
 			return false;
-		// Check that there are enough trails for this lead
-		int trail = pos + 1;
-		while ((trail-lead<trailBytes) && (trail < Length())) {
-			if (!IsTrailByte(static_cast<unsigned char>(cb.CharAt(trail)))) {
-				return false;
-			}
-			trail++;
-		}
-		end = start + bytes;
+		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);
+		if (utf8status & UTF8MaskInvalid)
+			return false;
+		end = start + widthCharBytes;
 		return true;
 	}
 }
@@ -543,14 +516,18 @@ 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));
-			int startUTF = pos;
-			int endUTF = pos;
-			if (IsTrailByte(ch) && InGoodUTF8(pos, startUTF, endUTF)) {
-				// ch is a trail byte within a UTF-8 character
-				if (moveDir > 0)
-					pos = endUTF;
-				else
-					pos = startUTF;
+			// If ch is not a trail byte then pos is valid intercharacter position
+			if (UTF8IsTrailByte(ch)) {
+				int startUTF = pos;
+				int endUTF = pos;
+				if (InGoodUTF8(pos, startUTF, endUTF)) {
+					// ch is a trail byte within a UTF-8 character
+					if (moveDir > 0)
+						pos = endUTF;
+					else
+						pos = startUTF;
+				}
+				// Else invalid UTF-8 so return position of isolated trail byte
 			}
 		} else {
 			// Anchor DBCS calculations at start of line because start of line can
@@ -597,16 +574,37 @@ int Document::NextPosition(int pos, int moveDir) const {
 
 	if (dbcsCodePage) {
 		if (SC_CP_UTF8 == dbcsCodePage) {
-			pos += increment;
-			unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
-			int startUTF = pos;
-			int endUTF = pos;
-			if (IsTrailByte(ch) && InGoodUTF8(pos, startUTF, endUTF)) {
-				// ch is a trail byte within a UTF-8 character
-				if (moveDir > 0)
-					pos = endUTF;
-				else
-					pos = startUTF;
+			if (increment == 1) {
+				// Simple forward movement case so can avoid some checks
+				const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(pos));
+				if (UTF8IsAscii(leadByte)) {
+					// Single byte character or invalid
+					pos++;
+				} else {
+					const int widthCharBytes = UTF8BytesOfLead[leadByte];
+					char charBytes[UTF8MaxBytes] = {static_cast<char>(leadByte),0,0,0};
+					for (int b=1; b<widthCharBytes; b++)
+						charBytes[b] = cb.CharAt(static_cast<int>(pos+b));
+					int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(charBytes), widthCharBytes);
+					if (utf8status & UTF8MaskInvalid)
+						pos++;
+					else
+						pos += utf8status & UTF8MaskWidth;
+				}
+			} else {
+				// Examine byte before position
+				pos--;
+				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;
+					if (InGoodUTF8(pos, startUTF, endUTF)) {
+						pos = startUTF;
+					}
+					// Else invalid UTF-8 so return position of isolated trail byte
+				}
 			}
 		} else {
 			if (moveDir > 0) {
@@ -687,7 +685,7 @@ bool SCI_METHOD Document::IsDBCSLeadByte(char ch) const {
 	return false;
 }
 
-inline bool IsSpaceOrTab(int ch) {
+static inline bool IsSpaceOrTab(int ch) {
 	return ch == ' ' || ch == '\t';
 }
 
@@ -721,7 +719,7 @@ int Document::SafeSegment(const char *text, int length, int lengthSegment) {
 		lastEncodingAllowedBreak = j;
 
 		if (dbcsCodePage == SC_CP_UTF8) {
-			j += (ch < 0x80) ? 1 : BytesFromLead(ch);
+			j += UTF8BytesOfLead[ch];
 		} else if (dbcsCodePage) {
 			j += IsDBCSLeadByte(ch) ? 2 : 1;
 		} else {
@@ -976,7 +974,7 @@ bool Document::InsertChar(int pos, char ch) {
  * Insert a null terminated string.
  */
 bool Document::InsertCString(int position, const char *s) {
-	return InsertString(position, s, static_cast<int>(strlen(s)));
+	return InsertString(position, s, static_cast<int>(s ? strlen(s) : 0));
 }
 
 void Document::ChangeChar(int pos, char ch) {
@@ -1001,10 +999,6 @@ void Document::DelCharBack(int pos) {
 	}
 }
 
-static bool isindentchar(char ch) {
-	return (ch == ' ') || (ch == '\t');
-}
-
 static int NextTab(int pos, int tabSize) {
 	return ((pos / tabSize) + 1) * tabSize;
 }
@@ -1064,7 +1058,7 @@ int Document::GetLineIndentPosition(int line) const {
 		return 0;
 	int pos = LineStart(line);
 	int length = Length();
-	while ((pos < length) && isindentchar(cb.CharAt(pos))) {
+	while ((pos < length) && IsSpaceOrTab(cb.CharAt(pos))) {
 		pos++;
 	}
 	return pos;
@@ -1116,6 +1110,8 @@ int Document::FindColumn(int line, int column) {
 			char ch = cb.CharAt(position);
 			if (ch == '\t') {
 				columnCurrent = NextTab(columnCurrent, tabInChars);
+				if (columnCurrent > column)
+					return position;
 				position++;
 			} else if (ch == '\r') {
 				return position;
@@ -1253,7 +1249,7 @@ int Document::ParaDown(int pos) {
 }
 
 CharClassify::cc Document::WordCharClass(unsigned char ch) {
-	if ((SC_CP_UTF8 == dbcsCodePage) && (ch >= 0x80))
+	if ((SC_CP_UTF8 == dbcsCodePage) && (!UTF8IsAscii(ch)))
 		return CharClassify::ccWord;
 	return charClass.GetClass(ch);
 }
@@ -1380,23 +1376,6 @@ static inline char MakeLowerCase(char ch) {
 		return static_cast<char>(ch - 'A' + 'a');
 }
 
-static bool GoodTrailByte(int v) {
-	return (v >= 0x80) && (v < 0xc0);
-}
-
-size_t Document::ExtractChar(int pos, char *bytes) {
-	unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
-	size_t widthChar = UTF8CharLength(ch);
-	bytes[0] = ch;
-	for (size_t i=1; i<widthChar; i++) {
-		bytes[i] = cb.CharAt(static_cast<int>(pos+i));
-		if (!GoodTrailByte(static_cast<unsigned char>(bytes[i]))) { // Bad byte
-			widthChar = 1;
-		}
-	}
-	return widthChar;
-}
-
 CaseFolderTable::CaseFolderTable() {
 	for (size_t iChar=0; iChar<sizeof(mapping); iChar++) {
 		mapping[iChar] = static_cast<char>(iChar);
@@ -1472,49 +1451,61 @@ long Document::FindText(int minPos, int maxPos, const char *search,
 		}
 		if (caseSensitive) {
 			const int endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
+			const char charStartSearch =  search[0];
 			while (forward ? (pos < endSearch) : (pos >= endSearch)) {
-				bool found = (pos + lengthFind) <= limitPos;
-				for (int indexSearch = 0; (indexSearch < lengthFind) && found; indexSearch++) {
-					found = CharAt(pos + indexSearch) == search[indexSearch];
-				}
-				if (found && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
-					return pos;
+				if (CharAt(pos) == charStartSearch) {
+					bool found = (pos + lengthFind) <= limitPos;
+					for (int indexSearch = 1; (indexSearch < lengthFind) && found; indexSearch++) {
+						found = CharAt(pos + indexSearch) == search[indexSearch];
+					}
+					if (found && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
+						return pos;
+					}
 				}
 				if (!NextCharacter(pos, increment))
 					break;
 			}
 		} else if (SC_CP_UTF8 == dbcsCodePage) {
-			const size_t maxBytesCharacter = 4;
 			const size_t maxFoldingExpansion = 4;
-			std::vector<char> searchThing(lengthFind * maxBytesCharacter * maxFoldingExpansion + 1);
+			std::vector<char> searchThing(lengthFind * 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 indexDocument = 0;
+				int posIndexDocument = pos;
 				int indexSearch = 0;
 				bool characterMatches = true;
-				while (characterMatches &&
-					((pos + indexDocument) < limitPos) &&
-					(indexSearch < lenSearch)) {
-					char bytes[maxBytesCharacter + 1];
-					bytes[maxBytesCharacter] = 0;
-					const int widthChar = static_cast<int>(ExtractChar(pos + indexDocument, bytes));
+				for (;;) {
+					const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(posIndexDocument));
+					bytes[0] = leadByte;
+					int widthChar = 1;
+					if (!UTF8IsAscii(leadByte)) {
+						const int widthCharBytes = UTF8BytesOfLead[leadByte];
+						for (int b=1; b<widthCharBytes; b++) {
+							bytes[b] = cb.CharAt(posIndexDocument+b);
+						}
+						widthChar = UTF8Classify(reinterpret_cast<const unsigned char *>(bytes), widthCharBytes) & UTF8MaskWidth;
+					}
 					if (!widthFirstCharacter)
 						widthFirstCharacter = widthChar;
-					if ((pos + indexDocument + widthChar) > limitPos)
+					if ((posIndexDocument + widthChar) > limitPos)
 						break;
-					char folded[maxBytesCharacter * maxFoldingExpansion + 1];
 					const int lenFlat = static_cast<int>(pcf->Fold(folded, sizeof(folded), bytes, widthChar));
 					folded[lenFlat] = 0;
 					// Does folded match the buffer
 					characterMatches = 0 == memcmp(folded, &searchThing[0] + indexSearch, lenFlat);
-					indexDocument += widthChar;
+					if (!characterMatches)
+						break;
+					posIndexDocument += widthChar;
 					indexSearch += lenFlat;
+					if (indexSearch >= lenSearch)
+						break;
 				}
 				if (characterMatches && (indexSearch == static_cast<int>(lenSearch))) {
-					if (MatchesWordOptions(word, wordStart, pos, indexDocument)) {
-						*length = indexDocument;
+					if (MatchesWordOptions(word, wordStart, pos, posIndexDocument - pos)) {
+						*length = posIndexDocument - pos;
 						return pos;
 					}
 				}
@@ -1768,12 +1759,14 @@ StyledText Document::AnnotationStyledText(int line) {
 }
 
 void Document::AnnotationSetText(int line, const char *text) {
-	const int linesBefore = AnnotationLines(line);
-	static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetText(line, text);
-	const int linesAfter = AnnotationLines(line);
-	DocModification mh(SC_MOD_CHANGEANNOTATION, LineStart(line), 0, 0, 0, line);
-	mh.annotationLinesAdded = linesAfter - linesBefore;
-	NotifyModified(mh);
+	if (line >= 0 && line < LinesTotal()) {
+		const int linesBefore = AnnotationLines(line);
+		static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetText(line, text);
+		const int linesAfter = AnnotationLines(line);
+		DocModification mh(SC_MOD_CHANGEANNOTATION, LineStart(line), 0, 0, 0, line);
+		mh.annotationLinesAdded = linesAfter - linesBefore;
+		NotifyModified(mh);
+	}
 }
 
 void Document::AnnotationSetStyle(int line, int style) {
@@ -1783,7 +1776,9 @@ void Document::AnnotationSetStyle(int line, int style) {
 }
 
 void Document::AnnotationSetStyles(int line, const unsigned char *styles) {
-	static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetStyles(line, styles);
+	if (line >= 0 && line < LinesTotal()) {
+		static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetStyles(line, styles);
+	}
 }
 
 int Document::AnnotationLength(int line) const {
@@ -2189,7 +2184,7 @@ const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text,
 	unsigned int lenResult = 0;
 	for (int i = 0; i < *length; i++) {
 		if (text[i] == '\\') {
-			if (text[i + 1] >= '1' && text[i + 1] <= '9') {
+			if (text[i + 1] >= '0' && text[i + 1] <= '9') {
 				unsigned int patNum = text[i + 1] - '0';
 				lenResult += search.eopat[patNum] - search.bopat[patNum];
 				i++;
@@ -2215,7 +2210,7 @@ const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text,
 	char *o = substituted;
 	for (int j = 0; j < *length; j++) {
 		if (text[j] == '\\') {
-			if (text[j + 1] >= '1' && text[j + 1] <= '9') {
+			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];
 				if (search.pat[patNum])	// Will be null if try for a match that did not occur
diff --git a/plugins/scintilla/scintilla/src/Document.h b/plugins/scintilla/scintilla/src/Document.h
index ec41603..7e03f3d 100644
--- a/plugins/scintilla/scintilla/src/Document.h
+++ b/plugins/scintilla/scintilla/src/Document.h
@@ -298,6 +298,8 @@ public:
 	void SetSavePoint();
 	bool IsSavePoint() { return cb.IsSavePoint(); }
 	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);
@@ -352,7 +354,6 @@ public:
 	int NextWordEnd(int pos, int delta);
 	int SCI_METHOD Length() const { return cb.Length(); }
 	void Allocate(int newSize) { cb.Allocate(newSize); }
-	size_t ExtractChar(int pos, char *bytes);
 	bool MatchesWordOptions(bool word, bool wordStart, int pos, int length);
 	long FindText(int minPos, int maxPos, const char *search, bool caseSensitive, bool word,
 		bool wordStart, bool regExp, int flags, int *length, CaseFolder *pcf);
diff --git a/plugins/scintilla/scintilla/src/Editor.cxx b/plugins/scintilla/scintilla/src/Editor.cxx
index 26032b8..d72ff30 100644
--- a/plugins/scintilla/scintilla/src/Editor.cxx
+++ b/plugins/scintilla/scintilla/src/Editor.cxx
@@ -36,6 +36,7 @@
 #include "CharClassify.h"
 #include "Decoration.h"
 #include "Document.h"
+#include "UniConversion.h"
 #include "Selection.h"
 #include "PositionCache.h"
 #include "Editor.h"
@@ -213,7 +214,6 @@ Editor::Editor() {
 	wrapVisualFlagsLocation = 0;
 	wrapVisualStartIndent = 0;
 	wrapIndentMode = SC_WRAPINDENT_FIXED;
-	wrapAddIndent = 0;
 
 	convertPastes = true;
 
@@ -297,15 +297,6 @@ void Editor::RefreshStyleData() {
 		if (surface) {
 			vs.Refresh(*surface);
 		}
-		if (wrapIndentMode == SC_WRAPINDENT_INDENT) {
-			wrapAddIndent = pdoc->IndentSize() * vs.spaceWidth;
-		} else if (wrapIndentMode == SC_WRAPINDENT_SAME) {
-			wrapAddIndent = 0;
-		} else { //SC_WRAPINDENT_FIXED
-			wrapAddIndent = wrapVisualStartIndent * vs.aveCharWidth;
-			if ((wrapVisualFlags & SC_WRAPVISUALFLAG_START) && (wrapAddIndent <= 0))
-				wrapAddIndent = vs.aveCharWidth; // must indent to show start visual
-		}
 		SetScrollBars();
 		SetRectangularRange();
 	}
@@ -486,7 +477,7 @@ SelectionPosition Editor::SPositionFromLocation(Point pt, bool canReturnInvalid,
 	pt.x = pt.x - vs.fixedColumnWidth + xOffset;
 	int visibleLine = pt.y / vs.lineHeight + topLine;
 	if (pt.y < 0) {	// Division rounds towards 0
-		visibleLine = (pt.y - (vs.lineHeight - 1)) / vs.lineHeight + topLine;
+		visibleLine = (static_cast<int>(pt.y) - (vs.lineHeight - 1)) / vs.lineHeight + topLine;
 	}
 	if (!canReturnInvalid && (visibleLine < 0))
 		visibleLine = 0;
@@ -639,6 +630,18 @@ void Editor::RedrawSelMargin(int line, bool allAfter) {
 			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;
@@ -909,7 +912,12 @@ int Editor::MovePositionTo(SelectionPosition newPos, Selection::selTypes selt, b
 		SetEmptySelection(newPos);
 	}
 	ShowCaretAtCurrentPosition();
+
+	int currentLine = pdoc->LineFromPosition(newPos.Position());
 	if (ensureVisible) {
+		// In case in need of wrapping to ensure DisplayFromDoc works.
+		if (currentLine >= wrapStart)
+			WrapLines(true, -1);
 		XYScrollPosition newXY = XYScrollToMakeVisible(true, true, true);
 		if (simpleCaret && (newXY.xOffset == xOffset)) {
 			// simple vertical scroll then invalidate
@@ -920,8 +928,6 @@ int Editor::MovePositionTo(SelectionPosition newPos, Selection::selTypes selt, b
 		}
 	}
 
-	int currentLine = pdoc->LineFromPosition(newPos.Position());
-
 	if (highlightDelimiter.NeedsDrawing(currentLine)) {
 		RedrawSelMargin();
 	}
@@ -1025,6 +1031,12 @@ 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));
+}
+
 void Editor::MoveSelectedLines(int lineDelta) {
 
 	// if selection doesn't start at the beginning of the line, set the new start
@@ -1038,9 +1050,11 @@ void Editor::MoveSelectedLines(int lineDelta) {
 	int selectionEnd = SelectionEnd().Position();
 	int endLine = pdoc->LineFromPosition(selectionEnd);
 	int beginningOfEndLine = pdoc->LineStart(endLine);
+	bool appendEol = false;
 	if (selectionEnd > beginningOfEndLine
 		|| selectionStart == selectionEnd) {
 		selectionEnd = pdoc->LineStart(endLine + 1);
+		appendEol = (selectionEnd == pdoc->Length() && pdoc->LineFromPosition(selectionEnd) == endLine);
 	}
 
 	// if there's nowhere for the selection to move
@@ -1054,19 +1068,34 @@ void Editor::MoveSelectedLines(int lineDelta) {
 
 	UndoGroup ug(pdoc);
 
+	if (lineDelta > 0 && selectionEnd == pdoc->LineStart(pdoc->LinesTotal() - 1)) {
+		SetSelection(pdoc->MovePositionOutsideChar(selectionEnd - 1, -1), selectionEnd);
+		ClearSelection();
+		selectionEnd = CurrentPosition();
+	}
 	SetSelection(selectionStart, selectionEnd);
 
 	SelectionText selectedText;
 	CopySelectionRange(&selectedText);
 
 	int selectionLength = SelectionRange(selectionStart, selectionEnd).Length();
-	ClearSelection();
-
 	Point currentLocation = LocationFromPosition(CurrentPosition());
 	int currentLine = LineFromLocation(currentLocation);
+
+	if (appendEol)
+		SetSelection(pdoc->MovePositionOutsideChar(selectionStart - 1, -1), selectionEnd);
+	ClearSelection();
+
+	const char *eol = StringFromEOLMode(pdoc->eolMode);
+	if (currentLine + lineDelta >= pdoc->LinesTotal())
+		pdoc->InsertCString(pdoc->Length(), eol);
 	GoToLine(currentLine + lineDelta);
 
 	pdoc->InsertCString(CurrentPosition(), selectedText.s);
+	if (appendEol) {
+		pdoc->InsertCString(CurrentPosition() + selectionLength, eol);
+		selectionLength += istrlen(eol);
+	}
 	SetSelection(CurrentPosition(), CurrentPosition() + selectionLength);
 }
 
@@ -1465,6 +1494,12 @@ bool Editor::WrapOneLine(Surface *surface, int lineToWrap) {
 bool Editor::WrapLines(bool fullWrap, int priorityWrapLineStart) {
 	// If there are any pending wraps, do them during idle if possible.
 	int linesInOneCall = LinesOnScreen() + 100;
+	if (priorityWrapLineStart >= 0) {
+		// Using DocFromDisplay() here may result in chicken and egg problem in certain corner cases,
+		// which will hopefully be handled by added 100 lines. If some lines are still missed, idle wrapping will catch on.
+		int docLinesInOneCall = cs.DocFromDisplay(topLine + LinesOnScreen() + 100) - cs.DocFromDisplay(topLine);
+		linesInOneCall = Platform::Maximum(linesInOneCall, docLinesInOneCall);
+	}
 	if (wrapState != eWrapNone) {
 		if (wrapStart < wrapEnd) {
 			if (!SetIdle(true)) {
@@ -1625,12 +1660,6 @@ int Editor::SubstituteMarkerIfEmpty(int markerCheck, int markerDefault) {
 	return markerCheck;
 }
 
-// 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));
-}
-
 bool ValidStyledText(ViewStyle &vs, size_t styleOffset, const StyledText &st) {
 	if (st.multipleStyles) {
 		for (size_t iStyle=0; iStyle<st.length; iStyle++) {
@@ -1911,28 +1940,33 @@ void Editor::PaintSelMargin(Surface *surfWindow, PRectangle &rc) {
 				rcMarker.top = yposScreen;
 				rcMarker.bottom = yposScreen + vs.lineHeight;
 				if (vs.ms[margin].style == SC_MARGIN_NUMBER) {
-					char number[100];
-					number[0] = '\0';
-					if (firstSubLine)
+					if (firstSubLine) {
+						char number[100];
 						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
-						       );
+						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 - 3;
+						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);
 					}
-					PRectangle rcNumber = rcMarker;
-					// Right justify
-					int width = surface->WidthText(vs.styles[STYLE_LINENUMBER].font, number, istrlen(number));
-					int xpos = rcNumber.right - width - 3;
-					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 (vs.ms[margin].style == SC_MARGIN_TEXT || vs.ms[margin].style == SC_MARGIN_RTEXT) {
 					if (firstSubLine) {
 						const StyledText stMargin  = pdoc->MarginStyledText(lineDoc);
@@ -1970,7 +2004,7 @@ void Editor::PaintSelMargin(Surface *surfWindow, PRectangle &rc) {
 									tFold = LineMarker::tail;
 								}
 							}
-							vs.markers[markBit].Draw(surface, rcMarker, vs.styles[STYLE_LINENUMBER].font, tFold);
+							vs.markers[markBit].Draw(surface, rcMarker, vs.styles[STYLE_LINENUMBER].font, tFold, vs.ms[margin].style);
 						}
 						marks >>= 1;
 					}
@@ -2018,92 +2052,18 @@ LineLayout *Editor::RetrieveLineLayout(int lineNumber) {
 	        LinesOnScreen() + 1, pdoc->LinesTotal());
 }
 
-static bool GoodTrailByte(int v) {
-	return (v >= 0x80) && (v < 0xc0);
-}
-
 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;
 	}
-	const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
-	if (*us < 0x80) {
-		// Single bytes easy
-		return false;
-	} else if (*us > 0xF4) {
-		// Characters longer than 4 bytes not possible in current UTF-8
-		return true;
-	} else if (*us >= 0xF0) {
-		// 4 bytes
-		if (len < 4)
-			return true;
-		if (GoodTrailByte(us[1]) && GoodTrailByte(us[2]) && GoodTrailByte(us[3])) {
-			if (*us == 0xf4) {
-				// Check if encoding a value beyond the last Unicode character 10FFFF
-				if (us[1] > 0x8f) {
-					return true;
-				} else if (us[1] == 0x8f) {
-					if (us[2] > 0xbf) {
-						return true;
-					} else if (us[2] == 0xbf) {
-						if (us[3] > 0xbf) {
-							return true;
-						}
-					}
-				}
-			} else if ((*us == 0xf0) && ((us[1] & 0xf0) == 0x80)) {
-				// Overlong
-				return true;
-			}
-			trailBytes = 3;
-			return false;
-		} else {
-			return true;
-		}
-	} else if (*us >= 0xE0) {
-		// 3 bytes
-		if (len < 3)
-			return true;
-		if (GoodTrailByte(us[1]) && GoodTrailByte(us[2])) {
-			if ((*us == 0xe0) && ((us[1] & 0xe0) == 0x80)) {
-				// Overlong
-				return true;
-			}
-			if ((*us == 0xed) && ((us[1] & 0xe0) == 0xa0)) {
-				// Surrogate
-				return true;
-			}
-			if ((*us == 0xef) && (us[1] == 0xbf) && (us[2] == 0xbe)) {
-				// U+FFFE
-				return true;
-			}
-			if ((*us == 0xef) && (us[1] == 0xbf) && (us[2] == 0xbf)) {
-				// U+FFFF
-				return true;
-			}
-			trailBytes = 2;
-			return false;
-		} else {
-			return true;
-		}
-	} else if (*us >= 0xC2) {
-		// 2 bytes
-		if (len < 2)
-			return true;
-		if (GoodTrailByte(us[1])) {
-			trailBytes = 1;
-			return false;
-		} else {
-			return true;
-		}
-	} else if (*us >= 0xC0) {
-		// Overlong encoding
+	int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(s), len);
+	if (utf8status & UTF8MaskInvalid) {
 		return true;
 	} else {
-		// Trail byte
-		return true;
+		trailBytes = (utf8status & UTF8MaskWidth) - 1;
+		return false;
 	}
 }
 
@@ -2127,11 +2087,7 @@ void Editor::LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayou
 	if (ll->validity == LineLayout::llCheckTextAndStyle) {
 		int lineLength = posLineEnd - posLineStart;
 		if (!vstyle.viewEOL) {
-			int cid = posLineEnd - 1;
-			while ((cid > posLineStart) && IsEOLChar(pdoc->CharAt(cid))) {
-				cid--;
-				lineLength--;
-			}
+			lineLength = pdoc->LineEnd(line) - posLineStart;
 		}
 		if (lineLength == ll->numCharsInLine) {
 			// See if chars, styles, indicators, are all the same
@@ -2188,10 +2144,7 @@ void Editor::LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayou
 		const int lineLength = posLineEnd - posLineStart;
 		pdoc->GetCharRange(ll->chars, posLineStart, lineLength);
 		pdoc->GetStyleRange(ll->styles, posLineStart, lineLength);
-		int numCharsBeforeEOL = lineLength;
-		while ((numCharsBeforeEOL > 0) && IsEOLChar(ll->chars[numCharsBeforeEOL-1])) {
-			numCharsBeforeEOL--;
-		}
+		int numCharsBeforeEOL = pdoc->LineEnd(line) - posLineStart;
 		const int numCharsInLine = (vstyle.viewEOL) ? lineLength : numCharsBeforeEOL;
 		for (int styleInLine = 0; styleInLine < numCharsInLine; styleInLine++) {
 			styleByte = ll->styles[styleInLine];
@@ -2307,6 +2260,12 @@ void Editor::LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayou
 			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++) {
@@ -2389,7 +2348,7 @@ ColourDesired Editor::TextBackground(ViewStyle &vsDraw, bool overrideBackground,
 	} else {
 		if ((vsDraw.edgeState == EDGE_BACKGROUND) &&
 		        (i >= ll->edgeColumn) &&
-		        !IsEOLChar(ll->chars[i]))
+		        (i < ll->numCharsBeforeEOL))
 			return vsDraw.edgecolour;
 		if (inHotspot && vsDraw.hotspotBackgroundSet)
 			return vsDraw.hotspotBackground;
@@ -2499,9 +2458,6 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 		const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
 		virtualSpace = sel.VirtualSpaceFor(pdoc->LineEnd(line)) * spaceWidth;
 	}
-
-	// Fill in a PRectangle representing the end of line characters
-
 	XYPOSITION xEol = ll->positions[lineEnd] - subLineStart;
 
 	// Fill the virtual space and show selections within it
@@ -2528,34 +2484,41 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 		}
 	}
 
-	int posAfterLineEnd = pdoc->LineStart(line + 1);
-	int eolInSelection = (subLine == (ll->lines - 1)) ? sel.InSelectionForEOL(posAfterLineEnd) : 0;
-	int alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
+	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
-	int blobsWidth = 0;
+	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();
 			const char *ctrlChar = ControlCharacterString(ll->chars[eolPos]);
-			int inSelection = 0;
-			bool inHotspot = false;
 			int styleMain = ll->styles[eolPos];
-			ColourDesired textBack = TextBackground(vsDraw, overrideBackground, background, inSelection, inHotspot, styleMain, eolPos, ll);
+			ColourDesired textBack = TextBackground(vsDraw, overrideBackground, background, eolInSelection, false, styleMain, eolPos, ll);
 			ColourDesired textFore = vsDraw.styles[styleMain].fore;
-			if (!hideSelection && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1)) {
+			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);
-					SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection == 1), alpha);
 				}
 			} 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);
+			}
 		}
 	}
 
@@ -2563,7 +2526,7 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 	rcSegment.left = xEol + xStart + virtualSpace + blobsWidth;
 	rcSegment.right = rcSegment.left + vsDraw.aveCharWidth;
 
-	if (!hideSelection && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
+	if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
 		surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1));
 	} else {
 		if (overrideBackground) {
@@ -2575,7 +2538,7 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 		} else {
 			surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back);
 		}
-		if (!hideSelection && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
+		if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
 			SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection == 1), alpha);
 		}
 	}
@@ -2586,7 +2549,7 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 		rcSegment.left = rcLine.left;
 	rcSegment.right = rcLine.right;
 
-	if (!hideSelection && vsDraw.selEOLFilled && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
+	if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
 		surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1));
 	} else {
 		if (overrideBackground) {
@@ -2596,7 +2559,7 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 		} else {
 			surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back);
 		}
-		if (!hideSelection && vsDraw.selEOLFilled && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
+		if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
 			SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection == 1), alpha);
 		}
 	}
@@ -2608,8 +2571,8 @@ void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, Lin
 			rcPlace.left = xEol + xStart + virtualSpace;
 			rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
 		} else {
-			// draw left of the right text margin, to avoid clipping by the current clip rect
-			rcPlace.right = rcLine.right - vs.rightMarginWidth;
+			// rcLine is clipped to text area
+			rcPlace.right = rcLine.right;
 			rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
 		}
 		DrawWrapMarker(surface, rcPlace, true, wrapColour);
@@ -2719,7 +2682,6 @@ void Editor::DrawAnnotation(Surface *surface, ViewStyle &vsDraw, int line, int x
 			widthAnnotation += vsDraw.spaceWidth * 2; // Margins
 			rcSegment.left = xStart + indent;
 			rcSegment.right = rcSegment.left + widthAnnotation;
-			surface->PenColour(vsDraw.styles[vsDraw.annotationStyleOffset].fore);
 		} else {
 			rcSegment.left = xStart;
 		}
@@ -2741,6 +2703,7 @@ void Editor::DrawAnnotation(Surface *surface, ViewStyle &vsDraw, int line, int x
 		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);
@@ -2810,7 +2773,8 @@ void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVis
 	        (!overrideBackground) && (vsDraw.whitespaceBackgroundSet);
 
 	bool inIndentation = subLine == 0;	// Do not handle indentation except on first subline.
-	int indentWidth = pdoc->IndentSize() * vsDraw.spaceWidth;
+	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);
 
@@ -3027,10 +2991,13 @@ void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVis
 					surface->PenColour(textFore);
 				}
 				if (inIndentation && vsDraw.viewIndentationGuides == ivReal) {
-					for (int xIG = ll->positions[i] / indentWidth * indentWidth; xIG < ll->positions[i + 1]; xIG += indentWidth) {
-						if (xIG >= ll->positions[i] && xIG > 0) {
-							DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIG + xStart, rcSegment,
-							        (ll->xHighlightGuide == xIG));
+					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));
 						}
 					}
 				}
@@ -3097,10 +3064,14 @@ void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVis
 								}
 							}
 							if (inIndentation && vsDraw.viewIndentationGuides == ivReal) {
-								int startSpace = ll->positions[cpos + startseg];
-								if (startSpace > 0 && (startSpace % indentWidth == 0)) {
-									DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, startSpace + xStart, rcSegment,
-									        (ll->xHighlightGuide == ll->positions[cpos + startseg]));
+								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 {
@@ -3191,7 +3162,7 @@ void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVis
 		if (subLine == (ll->lines - 1)) {
 			virtualSpaces = sel.VirtualSpaceFor(pdoc->LineEnd(line));
 		}
-		SelectionPosition posStart(posLineStart);
+		SelectionPosition posStart(posLineStart + lineStart);
 		SelectionPosition posEnd(posLineStart + lineEnd, virtualSpaces);
 		SelectionSegment virtualSpaceRange(posStart, posEnd);
 		for (size_t r=0; r<sel.Count(); r++) {
@@ -3202,17 +3173,21 @@ void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVis
 					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;
-					SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, r == sel.Main()), alpha);
+					if (rcSegment.right > rcLine.left)
+						SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, r == sel.Main()), alpha);
 				}
 			}
 		}
 	}
 
 	// Draw any translucent whole line states
-	rcSegment.left = 0;
-	rcSegment.right = rcLine.right - 1;
+	rcSegment = rcLine;
 	if (caret.active && vsDraw.showCaretLineBackground && ll->containsCaret) {
 		SimpleAlphaRectangle(surface, rcSegment, vsDraw.caretLineBackground, vsDraw.caretLineAlpha);
 	}
@@ -3456,12 +3431,11 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 	//	paintingAllText, rcArea.left, rcArea.top, rcArea.right, rcArea.bottom);
 	AllocateGraphics();
 
-	StyleToPositionInView(PositionAfterArea(rcArea));
-
-	pixmapLine->Release();
 	RefreshStyleData();
 	RefreshPixMaps(surfaceWindow);
 
+	StyleToPositionInView(PositionAfterArea(rcArea));
+
 	PRectangle rcClient = GetClientRectangle();
 	//Platform::DebugPrintf("Client: (%3d,%3d) ... (%3d,%3d)   %d\n",
 	//	rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
@@ -3499,6 +3473,9 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 	}
 	PLATFORM_ASSERT(pixmapSelPattern->Initialised());
 
+	if (!bufferedDraw)
+		surfaceWindow->SetClip(rcArea);
+
 	if (paintState != paintAbandoned) {
 		PaintSelMargin(surfaceWindow, rcArea);
 
@@ -3542,12 +3519,15 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 			posCaret = posDrag;
 		int lineCaret = pdoc->LineFromPosition(posCaret.Position());
 
-		// Remove selection margin from drawing area so text will not be drawn
-		// on it in unbuffered mode.
 		PRectangle rcTextArea = rcClient;
 		rcTextArea.left = vs.fixedColumnWidth;
 		rcTextArea.right -= vs.rightMarginWidth;
-		surfaceWindow->SetClip(rcTextArea);
+
+		// Remove selection margin from drawing area so text will not be drawn
+		// on it in unbuffered mode.
+		if (!bufferedDraw) {
+			surfaceWindow->SetClip(rcTextArea);
+		}
 
 		// Loop on visible lines
 		//double durLayout = 0.0;
@@ -3583,7 +3563,7 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 
 				GetHotSpotRange(ll->hsStart, ll->hsEnd);
 
-				PRectangle rcLine = rcClient;
+				PRectangle rcLine = rcTextArea;
 				rcLine.top = ypos;
 				rcLine.bottom = ypos + vs.lineHeight;
 
@@ -3632,7 +3612,7 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 				if (bufferedDraw) {
 					Point from(vs.fixedColumnWidth, 0);
 					PRectangle rcCopyArea(vs.fixedColumnWidth, yposScreen,
-					        rcClient.right, yposScreen + vs.lineHeight);
+					        rcClient.right - vs.rightMarginWidth, yposScreen + vs.lineHeight);
 					surfaceWindow->Copy(rcCopyArea, from, *pixmapLine);
 				}
 
@@ -3657,7 +3637,7 @@ void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) {
 		// Right column limit indicator
 		PRectangle rcBeyondEOF = rcClient;
 		rcBeyondEOF.left = vs.fixedColumnWidth;
-		rcBeyondEOF.right = rcBeyondEOF.right;
+		rcBeyondEOF.right = rcBeyondEOF.right - vs.rightMarginWidth;
 		rcBeyondEOF.top = (cs.LinesDisplayed() - topLine) * vs.lineHeight;
 		if (rcBeyondEOF.top < rcBeyondEOF.bottom) {
 			surfaceWindow->FillRectangle(rcBeyondEOF, vs.styles[STYLE_DEFAULT].back);
@@ -3699,10 +3679,10 @@ long Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
 	if (!pfr)
 		return 0;
 
-	AutoSurface surface(pfr->hdc, this);
+	AutoSurface surface(pfr->hdc, this, SC_TECHNOLOGY_DEFAULT);
 	if (!surface)
 		return 0;
-	AutoSurface surfaceMeasure(pfr->hdcTarget, this);
+	AutoSurface surfaceMeasure(pfr->hdcTarget, this, SC_TECHNOLOGY_DEFAULT);
 	if (!surfaceMeasure) {
 		return 0;
 	}
@@ -3711,6 +3691,7 @@ long Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
 	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.
@@ -3722,9 +3703,10 @@ long Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
 			vsPrint.ms[margin].width = 0;
 		}
 	}
-	vsPrint.showMarkedLines = false;
 	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;
@@ -3757,6 +3739,10 @@ long Editor::FormatRange(bool draw, Sci_RangeToFormat *pfr) {
 	// 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;
@@ -4496,6 +4482,7 @@ void Editor::CheckModificationForWrap(DocModification mh) {
 		if (wrapState != eWrapNone) {
 			NeedWrapping(lineDoc, lineDoc + lines + 1);
 		}
+		RefreshStyleData();
 		// Fix up annotation heights
 		SetAnnotationHeights(lineDoc, lineDoc + lines + 2);
 	}
@@ -4925,7 +4912,7 @@ void Editor::Duplicate(bool forLine) {
 	if (sel.Empty()) {
 		forLine = true;
 	}
-	UndoGroup ug(pdoc, sel.Count() > 1);
+	UndoGroup ug(pdoc);
 	const char *eol = "";
 	int eolLen = 0;
 	if (forLine) {
@@ -4965,14 +4952,28 @@ void Editor::CancelModes() {
 }
 
 void Editor::NewLine() {
-	ClearSelection();
+	// Remove non-main ranges
+	InvalidateSelection(sel.RangeMain(), true);
+	sel.SetSelection(sel.RangeMain());
+
+	// Clear main range and insert line end
+	bool needGroupUndo = !sel.Empty();
+	if (needGroupUndo)
+		pdoc->BeginUndoAction();
+
+	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
-	if (pdoc->InsertCString(sel.MainCaret(), eol)) {
+	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));
 		while (*eol) {
 			NotifyChar(*eol);
@@ -5001,30 +5002,50 @@ void Editor::CursorUpOrDown(int direction, Selection::selTypes selt) {
 			caretToUse = sel.Rectangular().caret;
 		}
 	}
+
 	Point pt = LocationFromPosition(caretToUse);
-	int lineDoc = pdoc->LineFromPosition(caretToUse.Position());
-	Point ptStartLine = LocationFromPosition(pdoc->LineStart(lineDoc));
-	int subLine = (pt.y - ptStartLine.y) / vs.lineHeight;
-	int commentLines = vs.annotationVisible ? pdoc->AnnotationLines(lineDoc) : 0;
-	SelectionPosition posNew = SPositionFromLocation(
-	            Point(lastXChosen - xOffset, pt.y + direction * vs.lineHeight), false, false, UserVirtualSpace());
-	if ((direction > 0) && (subLine >= (cs.GetHeight(lineDoc) - 1 - commentLines))) {
-		posNew = SPositionFromLocation(
-	            Point(lastXChosen - xOffset, pt.y + (commentLines + 1) * vs.lineHeight), false, false, UserVirtualSpace());
+	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;
+
+		if (direction < 0 && subLine == 0) {
+			int lineDisplay = cs.DisplayFromDoc(lineDoc);
+			if (lineDisplay > 0) {
+				skipLines = pdoc->AnnotationLines(cs.DocFromDisplay(lineDisplay - 1));
+			}
+		} else if (direction > 0 && subLine >= (cs.GetHeight(lineDoc) - 1 - pdoc->AnnotationLines(lineDoc))) {
+			skipLines = pdoc->AnnotationLines(lineDoc);
+		}
 	}
+
+	int newY = pt.y + (1 + skipLines) * direction * vs.lineHeight;
+	SelectionPosition posNew = SPositionFromLocation(
+	            Point(lastXChosen - xOffset, newY), false, false, UserVirtualSpace());
+
 	if (direction < 0) {
 		// Line wrapping may lead to a location on the same line, so
 		// seek back if that is the case.
-		// There is an equivalent case when moving down which skips
-		// over a line but as that does not trap the user it is fine.
 		Point ptNew = LocationFromPosition(posNew.Position());
 		while ((posNew.Position() > 0) && (pt.y == ptNew.y)) {
-			posNew.Add(- 1);
+			posNew.Add(-1);
+			posNew.SetVirtualSpace(0);
+			ptNew = LocationFromPosition(posNew.Position());
+		}
+	} else if (direction > 0 && posNew.Position() != pdoc->Length()) {
+		// 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)) {
+			posNew.Add(-1);
 			posNew.SetVirtualSpace(0);
 			ptNew = LocationFromPosition(posNew.Position());
 		}
 	}
-	MovePositionTo(posNew, selt);
+
+	MovePositionTo(MovePositionSoVisible(posNew, direction), selt);
 }
 
 void Editor::ParaUpOrDown(int direction, Selection::selTypes selt) {
@@ -5565,14 +5586,6 @@ int Editor::KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed) {
 	return KeyDownWithModifiers(key, modifiers, consumed);
 }
 
-void Editor::SetWhitespaceVisible(int view) {
-	vs.viewWhitespace = static_cast<WhiteSpaceVisibility>(view);
-}
-
-int Editor::GetWhitespaceVisible() {
-	return vs.viewWhitespace;
-}
-
 void Editor::Indent(bool forwards) {
 	for (size_t r=0; r<sel.Count(); r++) {
 		int lineOfAnchor = pdoc->LineFromPosition(sel.Range(r).anchor.Position());
@@ -5657,16 +5670,6 @@ public:
 	}
 	~CaseFolderASCII() {
 	}
-	virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
-		if (lenMixed > sizeFolded) {
-			return 0;
-		} else {
-			for (size_t i=0; i<lenMixed; i++) {
-				folded[i] = mapping[static_cast<unsigned char>(mixed[i])];
-			}
-			return lenMixed;
-		}
-	}
 };
 
 
@@ -5717,6 +5720,19 @@ void Editor::SearchAnchor() {
 	searchAnchor = SelectionStart().Position();
 }
 
+// Simple RAII wrapper for CaseFolder as std::auto_ptr is now deprecated
+class ScopedCaseFolder {
+	CaseFolder *pcf;
+public:
+	ScopedCaseFolder(CaseFolder *pcf_) : pcf(pcf_) {
+	}
+	~ScopedCaseFolder() {
+		delete pcf;
+		pcf = 0;
+	}
+	CaseFolder *get() const { return pcf; }
+};
+
 /**
  * Find text from current search anchor: Must call @c SearchAnchor first.
  * Used for next text and previous text requests.
@@ -5731,7 +5747,7 @@ long Editor::SearchText(
 	const char *txt = reinterpret_cast<char *>(lParam);
 	int pos;
 	int lengthFound = istrlen(txt);
-	std::auto_ptr<CaseFolder> pcf(CaseFolderForEncoding());
+	ScopedCaseFolder pcf(CaseFolderForEncoding());
 	if (iMessage == SCI_SEARCHNEXT) {
 		pos = pdoc->FindText(searchAnchor, pdoc->Length(), txt,
 		        (wParam & SCFIND_MATCHCASE) != 0,
@@ -5782,7 +5798,7 @@ std::string Editor::CaseMapString(const std::string &s, int caseMapping) {
 long Editor::SearchInTarget(const char *text, int length) {
 	int lengthFound = length;
 
-	std::auto_ptr<CaseFolder> pcf(CaseFolderForEncoding());
+	ScopedCaseFolder pcf(CaseFolderForEncoding());
 	int pos = pdoc->FindText(targetStart, targetEnd, text,
 	        (searchFlags & SCFIND_MATCHCASE) != 0,
 	        (searchFlags & SCFIND_WHOLEWORD) != 0,
@@ -6056,6 +6072,11 @@ Window::Cursor Editor::GetMarginCursor(Point pt) {
 	return Window::cursorReverseArrow;
 }
 
+void Editor::TrimAndSetSelection(int currentPos_, int anchor_) {
+	sel.TrimSelection(SelectionRange(currentPos_, anchor_));
+	SetSelection(currentPos_, anchor_);
+}
+
 void Editor::LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLine) {
 	int selCurrentPos, selAnchorPos;
 	if (wholeLine) {
@@ -6086,7 +6107,7 @@ void Editor::LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLi
 			selAnchorPos = StartEndDisplayLine(lineAnchorPos_, true);
 		}
 	}
-	SetSelection(selCurrentPos, selAnchorPos);
+	TrimAndSetSelection(selCurrentPos, selAnchorPos);
 }
 
 void Editor::WordSelection(int pos) {
@@ -6096,20 +6117,20 @@ void Editor::WordSelection(int pos) {
 		// This ensures that a series of empty lines isn't counted as a single "word".
 		if (!pdoc->IsLineEndPosition(pos))
 			pos = pdoc->ExtendWordSelect(pdoc->MovePositionOutsideChar(pos + 1, 1), -1);
-		SetSelection(pos, wordSelectAnchorEndPos);
+		TrimAndSetSelection(pos, wordSelectAnchorEndPos);
 	} else if (pos > wordSelectAnchorEndPos) {
 		// Extend forward to the word containing the character to the left of pos.
 		// Skip ExtendWordSelect if the line is empty or if pos is the first position on the line.
 		// This ensures that a series of empty lines isn't counted as a single "word".
 		if (pos > pdoc->LineStart(pdoc->LineFromPosition(pos)))
 			pos = pdoc->ExtendWordSelect(pdoc->MovePositionOutsideChar(pos - 1, -1), 1);
-		SetSelection(pos, wordSelectAnchorStartPos);
+		TrimAndSetSelection(pos, wordSelectAnchorStartPos);
 	} else {
 		// Select only the anchored word
 		if (pos >= originalAnchorPos)
-			SetSelection(wordSelectAnchorEndPos, wordSelectAnchorStartPos);
+			TrimAndSetSelection(wordSelectAnchorEndPos, wordSelectAnchorStartPos);
 		else
-			SetSelection(wordSelectAnchorStartPos, wordSelectAnchorEndPos);
+			TrimAndSetSelection(wordSelectAnchorStartPos, wordSelectAnchorEndPos);
 	}
 }
 
@@ -6133,7 +6154,7 @@ void Editor::MouseLeave() {
 }
 
 static bool AllowVirtualSpace(int virtualSpaceOptions, bool rectangular) {
-	return ((virtualSpaceOptions & SCVS_USERACCESSIBLE) != 0)
+	return (!rectangular && ((virtualSpaceOptions & SCVS_USERACCESSIBLE) != 0))
 		|| (rectangular && ((virtualSpaceOptions & SCVS_RECTANGULARSELECTION) != 0));
 }
 
@@ -6145,37 +6166,48 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
 	inDragDrop = ddNone;
 	sel.SetMoveExtends(false);
 
-	bool processed = NotifyMarginClick(pt, shift, ctrl, alt);
-	if (processed)
+	if (NotifyMarginClick(pt, shift, ctrl, alt))
 		return;
 
 	NotifyIndicatorClick(true, newPos.Position(), shift, ctrl, alt);
 
 	bool inSelMargin = PointInSelMargin(pt);
-	if (shift & !inSelMargin) {
-		SetSelection(newPos.Position());
+	// In margin ctrl+(double)click should always select everything
+	if (ctrl && inSelMargin) {
+		SelectAll();
+		lastClickTime = curTime;
+		lastClick = pt;
+		return;
+	}
+	if (shift && !inSelMargin) {
+		SetSelection(newPos);
 	}
 	if (((curTime - lastClickTime) < Platform::DoubleClickTime()) && Close(pt, lastClick)) {
 		//Platform::DebugPrintf("Double click %d %d = %d\n", curTime, lastClickTime, curTime - lastClickTime);
 		SetMouseCapture(true);
-		SetEmptySelection(newPos.Position());
+		if (!ctrl || !multipleSelection || (selectionType != selChar && selectionType != selWord))
+			SetEmptySelection(newPos.Position());
 		bool doubleClick = false;
 		// Stop mouse button bounce changing selection type
 		if (!Platform::MouseButtonBounce() || curTime != lastClickTime) {
-			if (selectionType == selChar) {
-				selectionType = selWord;
-				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.
-				selectionType = selWholeLine;
-			} else {
-				if (inSelMargin) {
-					// Selection type is either selSubLine or selWholeLine here and we're inside margin.
+			if (inSelMargin) {
+				// Inside margin selection type should be either selSubLine or selWholeLine.
+				if (selectionType == selSubLine) {
 					// If it is selSubLine, we're inside a *double* click and word wrap is enabled, 
 					// so we switch to selWholeLine in order to select whole line.
-					if (selectionType == selSubLine)
-						selectionType = selWholeLine;
+					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;
+				}
+			} else {
+				if (selectionType == selChar) {
+					selectionType = selWord;
+					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.
+					selectionType = selWholeLine;
 				} else {
 					selectionType = selChar;
 					originalAnchorPos = sel.MainCaret();
@@ -6227,11 +6259,6 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
 	} else {	// Single click
 		if (inSelMargin) {
 			sel.selType = Selection::selStream;
-			if (ctrl) {
-				SelectAll();
-				lastClickTime = curTime;
-				return;
-			}
 			if (!shift) {
 				// Single click in margin: select whole line or only subline if word wrap is enabled
 				lineAnchorPos = newPos.Position();
@@ -6247,7 +6274,7 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
 				// This ensures that we don't end up stuck in previous selection mode, which is no longer valid.
 				// 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))
+				if (sel.Empty() || (selectionType != selSubLine && selectionType != selWholeLine))
 					selectionType = ((wrapState != eWrapNone) && (marginOptions & SC_MARGINOPTION_SUBLINESELECT)) ? selSubLine : selWholeLine;
 				LineSelection(newPos.Position(), lineAnchorPos, selectionType == selWholeLine);
 			}
@@ -6296,6 +6323,7 @@ void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, b
 		}
 	}
 	lastClickTime = curTime;
+	lastClick = pt;
 	lastXChosen = pt.x + xOffset;
 	ShowCaretAtCurrentPosition();
 }
@@ -6465,7 +6493,7 @@ void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) {
 	newPos = MovePositionOutsideChar(newPos, sel.MainCaret() - newPos.Position());
 	if (inDragDrop == ddInitial) {
 		inDragDrop = ddNone;
-		SetEmptySelection(newPos.Position());
+		SetEmptySelection(newPos);
 		selectionType = selChar;
 		originalAnchorPos = sel.MainCaret();
 	}
@@ -6846,7 +6874,8 @@ int Editor::ContractedFoldNext(int lineStart) {
 void Editor::EnsureLineVisible(int lineDoc, bool enforcePolicy) {
 
 	// In case in need of wrapping to ensure DisplayFromDoc works.
-	WrapLines(true, -1);
+	if (lineDoc >= wrapStart)
+		WrapLines(true, -1);
 
 	if (!cs.GetVisible(lineDoc)) {
 		int lookLine = lineDoc;
@@ -7451,6 +7480,10 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 		ClearAll();
 		return 0;
 
+	case SCI_DELETERANGE:
+		pdoc->DeleteChars(wParam, lParam);
+		return 0;
+
 	case SCI_CLEARDOCUMENTSTYLE:
 		ClearDocumentStyle();
 		return 0;
@@ -7991,8 +8024,10 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 
 		// Marker definition and setting
 	case SCI_MARKERDEFINE:
-		if (wParam <= MARKER_MAX)
+		if (wParam <= MARKER_MAX) {
 			vs.markers[wParam].markType = lParam;
+			vs.CalcLargestMarkerHeight();
+		}
 		InvalidateStyleData();
 		RedrawSelMargin();
 		break;
@@ -8012,11 +8047,12 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 	case SCI_MARKERSETBACKSELECTED:
 		if (wParam <= MARKER_MAX)
 			vs.markers[wParam].backSelected = ColourDesired(lParam);
-		InvalidateStyleRedraw();
+		InvalidateStyleData();
+		RedrawSelMargin();
 		break;
 	case SCI_MARKERENABLEHIGHLIGHT:
 		highlightDelimiter.isEnabled = wParam == 1;
-		InvalidateStyleRedraw();
+		RedrawSelMargin();
 		break;
 	case SCI_MARKERSETBACK:
 		if (wParam <= MARKER_MAX)
@@ -8063,6 +8099,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 	case SCI_MARKERDEFINEPIXMAP:
 		if (wParam <= MARKER_MAX) {
 			vs.markers[wParam].SetXPM(CharPtrFromSPtr(lParam));
+			vs.CalcLargestMarkerHeight();
 		};
 		InvalidateStyleData();
 		RedrawSelMargin();
@@ -8079,6 +8116,7 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 	case SCI_MARKERDEFINERGBAIMAGE:
 		if (wParam <= MARKER_MAX) {
 			vs.markers[wParam].SetRGBAImage(sizeRGBAImage, reinterpret_cast<unsigned char *>(lParam));
+			vs.CalcLargestMarkerHeight();
 		};
 		InvalidateStyleData();
 		RedrawSelMargin();
@@ -8876,6 +8914,12 @@ sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
 	case SCI_GETCHARACTERPOINTER:
 		return reinterpret_cast<sptr_t>(pdoc->BufferPointer());
 
+	case SCI_GETRANGEPOINTER:
+		return reinterpret_cast<sptr_t>(pdoc->RangePointer(wParam, lParam));
+
+	case SCI_GETGAPPOSITION:
+		return pdoc->GapPosition();
+
 	case SCI_SETEXTRAASCENT:
 		vs.extraAscent = wParam;
 		InvalidateStyleRedraw();
diff --git a/plugins/scintilla/scintilla/src/Editor.h b/plugins/scintilla/scintilla/src/Editor.h
index 0923f40..f8ab19d 100644
--- a/plugins/scintilla/scintilla/src/Editor.h
+++ b/plugins/scintilla/scintilla/src/Editor.h
@@ -264,7 +264,6 @@ protected:	// ScintillaBase subclass needs access to much of Editor
 	int wrapVisualFlags;
 	int wrapVisualFlagsLocation;
 	int wrapVisualStartIndent;
-	XYPOSITION wrapAddIndent; // This will be added to initial indent of line
 	int wrapIndentMode; // SC_WRAPINDENT_FIXED, _SAME, _INDENT
 
 	bool convertPastes;
@@ -470,9 +469,6 @@ protected:	// ScintillaBase subclass needs access to much of Editor
 	int KeyDownWithModifiers(int key, int modifiers, bool *consumed);
 	int KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed=0);
 
-	int GetWhitespaceVisible();
-	void SetWhitespaceVisible(int view);
-
 	void Indent(bool forwards);
 
 	virtual CaseFolder *CaseFolderForEncoding();
@@ -497,6 +493,7 @@ protected:	// ScintillaBase subclass needs access to much of Editor
 	bool PointInSelection(Point pt);
 	bool PointInSelMargin(Point pt);
 	Window::Cursor GetMarginCursor(Point pt);
+	void TrimAndSetSelection(int currentPos_, int anchor_);
 	void LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLine);
 	void WordSelection(int pos);
 	void DwellEnd(bool mouseMoved);
@@ -573,9 +570,9 @@ class AutoSurface {
 private:
 	Surface *surf;
 public:
-	AutoSurface(Editor *ed) : surf(0) {
+	AutoSurface(Editor *ed, int technology = -1) : surf(0) {
 		if (ed->wMain.GetID()) {
-			surf = Surface::Allocate(ed->technology);
+			surf = Surface::Allocate(technology != -1 ? technology : ed->technology);
 			if (surf) {
 				surf->Init(ed->wMain.GetID());
 				surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
@@ -583,9 +580,9 @@ public:
 			}
 		}
 	}
-	AutoSurface(SurfaceID sid, Editor *ed) : surf(0) {
+	AutoSurface(SurfaceID sid, Editor *ed, int technology = -1) : surf(0) {
 		if (ed->wMain.GetID()) {
-			surf = Surface::Allocate(ed->technology);
+			surf = Surface::Allocate(technology != -1 ? technology : ed->technology);
 			if (surf) {
 				surf->Init(sid, ed->wMain.GetID());
 				surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
diff --git a/plugins/scintilla/scintilla/src/LineMarker.cxx b/plugins/scintilla/scintilla/src/LineMarker.cxx
index a14e4e4..99e8326 100644
--- a/plugins/scintilla/scintilla/src/LineMarker.cxx
+++ b/plugins/scintilla/scintilla/src/LineMarker.cxx
@@ -68,7 +68,7 @@ static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, C
 	surface->FillRectangle(rcH, fore);
 }
 
-void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter, typeOfFold tFold) {
+void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter, typeOfFold tFold, int marginStyle) {
 	ColourDesired head = back;
 	ColourDesired body = back;
 	ColourDesired tail = back;
@@ -92,13 +92,18 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
 		break;
 	}
 
-
 	if ((markType == SC_MARK_PIXMAP) && (pxpm)) {
 		pxpm->Draw(surface, rcWhole);
 		return;
 	}
 	if ((markType == SC_MARK_RGBAIMAGE) && (image)) {
-		surface->DrawRGBAImage(rcWhole, image->GetWidth(), image->GetHeight(), image->Pixels());
+		// 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->GetHeight()) / 2);
+		rcImage.bottom = rcImage.top + image->GetHeight();
+		rcImage.left = static_cast<int>(((rcWhole.left + rcWhole.right) - image->GetWidth()) / 2);
+		rcImage.right = rcImage.left + image->GetWidth();
+		surface->DrawRGBAImage(rcImage, image->GetWidth(), image->GetHeight(), image->Pixels());
 		return;
 	}
 	// Restrict most shapes a bit
@@ -113,8 +118,8 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
 	int dimOn4 = minDim / 4;
 	int blobSize = dimOn2-1;
 	int armSize = dimOn2-2;
-	if (rc.Width() > (rc.Height() * 2)) {
-		// Wide column is line number so move to left to try to avoid overlapping number
+	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;
 	}
 	if (markType == SC_MARK_ROUNDRECT) {
@@ -195,17 +200,17 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
 	} else if (markType == SC_MARK_LCORNER) {
 		surface->PenColour(tail);
 		surface->MoveTo(centreX, rcWhole.top);
-		surface->LineTo(centreX, rc.top + dimOn2);
-		surface->LineTo(rc.right - 2, rc.top + dimOn2);
+		surface->LineTo(centreX, centreY);
+		surface->LineTo(rc.right - 1, centreY);
 
 	} else if (markType == SC_MARK_TCORNER) {
 		surface->PenColour(tail);
-		surface->MoveTo(centreX, rc.top + dimOn2);
-		surface->LineTo(rc.right - 2, rc.top + dimOn2);
+		surface->MoveTo(centreX, centreY);
+		surface->LineTo(rc.right - 1, centreY);
 
 		surface->PenColour(body);
 		surface->MoveTo(centreX, rcWhole.top);
-		surface->LineTo(centreX, rc.top + dimOn2 + 1);
+		surface->LineTo(centreX, centreY + 1);
 
 		surface->PenColour(head);
 		surface->LineTo(centreX, rcWhole.bottom);
@@ -213,19 +218,19 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
 	} else if (markType == SC_MARK_LCORNERCURVE) {
 		surface->PenColour(tail);
 		surface->MoveTo(centreX, rcWhole.top);
-		surface->LineTo(centreX, rc.top + dimOn2-3);
-		surface->LineTo(centreX+3, rc.top + dimOn2);
-		surface->LineTo(rc.right - 1, rc.top + dimOn2);
+		surface->LineTo(centreX, centreY-3);
+		surface->LineTo(centreX+3, centreY);
+		surface->LineTo(rc.right - 1, centreY);
 
 	} else if (markType == SC_MARK_TCORNERCURVE) {
 		surface->PenColour(tail);
-		surface->MoveTo(centreX, rc.top + dimOn2-3);
-		surface->LineTo(centreX+3, rc.top + dimOn2);
-		surface->LineTo(rc.right - 1, rc.top + dimOn2);
+		surface->MoveTo(centreX, centreY-3);
+		surface->LineTo(centreX+3, centreY);
+		surface->LineTo(rc.right - 1, centreY);
 
 		surface->PenColour(body);
 		surface->MoveTo(centreX, rcWhole.top);
-		surface->LineTo(centreX, rc.top + dimOn2-2);
+		surface->LineTo(centreX, centreY-2);
 
 		surface->PenColour(head);
 		surface->LineTo(centreX, rcWhole.bottom);
@@ -333,7 +338,7 @@ void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharac
 	} else if (markType >= SC_MARK_CHARACTER) {
 		char character[1];
 		character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
-		int width = surface->WidthText(fontForCharacter, character, 1);
+		XYPOSITION width = surface->WidthText(fontForCharacter, character, 1);
 		rc.left += (rc.Width() - width) / 2;
 		rc.right = rc.left + width;
 		surface->DrawTextClipped(rc, fontForCharacter, rc.bottom - 2,
diff --git a/plugins/scintilla/scintilla/src/LineMarker.h b/plugins/scintilla/scintilla/src/LineMarker.h
index ccf4104..5c73a62 100644
--- a/plugins/scintilla/scintilla/src/LineMarker.h
+++ b/plugins/scintilla/scintilla/src/LineMarker.h
@@ -36,7 +36,7 @@ public:
 		image = NULL;
 	}
 	LineMarker(const LineMarker &) {
-		// Defined to avoid pxpm being blindly copied, not as real copy constructor
+		// Defined to avoid pxpm being blindly copied, not as a complete copy constructor
 		markType = SC_MARK_CIRCLE;
 		fore = ColourDesired(0,0,0);
 		back = ColourDesired(0xff,0xff,0xff);
@@ -49,23 +49,25 @@ public:
 		delete pxpm;
 		delete image;
 	}
-	LineMarker &operator=(const LineMarker &) {
-		// Defined to avoid pxpm being blindly copied, not as real assignment operator
-		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;
+	LineMarker &operator=(const LineMarker &other) {
+		// Defined to avoid pxpm 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;
+		}
 		return *this;
 	}
 	void SetXPM(const char *textForm);
 	void SetXPM(const char *const *linesForm);
 	void SetRGBAImage(Point sizeRGBAImage, const unsigned char *pixelsRGBAImage);
-	void Draw(Surface *surface, PRectangle &rc, Font &fontForCharacter, typeOfFold tFold);
+	void Draw(Surface *surface, PRectangle &rc, Font &fontForCharacter, typeOfFold tFold, int marginStyle);
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/PerLine.cxx b/plugins/scintilla/scintilla/src/PerLine.cxx
index 7e716cc..0bdb602 100644
--- a/plugins/scintilla/scintilla/src/PerLine.cxx
+++ b/plugins/scintilla/scintilla/src/PerLine.cxx
@@ -397,28 +397,28 @@ bool LineAnnotation::AnySet() const {
 }
 
 bool LineAnnotation::MultipleStyles(int line) const {
-	if (annotations.Length() && (line < annotations.Length()) && annotations[line])
+	if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
 		return reinterpret_cast<AnnotationHeader *>(annotations[line])->style == IndividualStyles;
 	else
 		return 0;
 }
 
 int LineAnnotation::Style(int line) {
-	if (annotations.Length() && (line < annotations.Length()) && annotations[line])
+	if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
 		return reinterpret_cast<AnnotationHeader *>(annotations[line])->style;
 	else
 		return 0;
 }
 
 const char *LineAnnotation::Text(int line) const {
-	if (annotations.Length() && (line < annotations.Length()) && annotations[line])
+	if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
 		return annotations[line]+sizeof(AnnotationHeader);
 	else
 		return 0;
 }
 
 const unsigned char *LineAnnotation::Styles(int line) const {
-	if (annotations.Length() && (line < annotations.Length()) && annotations[line] && MultipleStyles(line))
+	if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line] && MultipleStyles(line))
 		return reinterpret_cast<unsigned char *>(annotations[line] + sizeof(AnnotationHeader) + Length(line));
 	else
 		return 0;
@@ -432,7 +432,7 @@ static char *AllocateAnnotation(int length, int style) {
 }
 
 void LineAnnotation::SetText(int line, const char *text) {
-	if (text) {
+	if (text && (line >= 0)) {
 		annotations.EnsureLength(line+1);
 		int style = Style(line);
 		if (annotations[line]) {
@@ -445,7 +445,7 @@ void LineAnnotation::SetText(int line, const char *text) {
 		pah->lines = static_cast<short>(NumberLines(text));
 		memcpy(annotations[line]+sizeof(AnnotationHeader), text, pah->length);
 	} else {
-		if (annotations.Length() && (line < annotations.Length()) && annotations[line]) {
+		if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) {
 			delete []annotations[line];
 			annotations[line] = 0;
 		}
@@ -469,35 +469,37 @@ void LineAnnotation::SetStyle(int line, int style) {
 }
 
 void LineAnnotation::SetStyles(int line, const unsigned char *styles) {
-	annotations.EnsureLength(line+1);
-	if (!annotations[line]) {
-		annotations[line] = AllocateAnnotation(0, IndividualStyles);
-	} else {
-		AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader *>(annotations[line]);
-		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;
+	if (line >= 0) {
+		annotations.EnsureLength(line+1);
+		if (!annotations[line]) {
+			annotations[line] = AllocateAnnotation(0, IndividualStyles);
+		} else {
+			AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader *>(annotations[line]);
+			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;
+			}
 		}
+		AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]);
+		pah->style = IndividualStyles;
+		memcpy(annotations[line] + sizeof(AnnotationHeader) + pah->length, styles, pah->length);
 	}
-	AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]);
-	pah->style = IndividualStyles;
-	memcpy(annotations[line] + sizeof(AnnotationHeader) + pah->length, styles, pah->length);
 }
 
 int LineAnnotation::Length(int line) const {
-	if (annotations.Length() && (line < annotations.Length()) && annotations[line])
+	if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
 		return reinterpret_cast<AnnotationHeader *>(annotations[line])->length;
 	else
 		return 0;
 }
 
 int LineAnnotation::Lines(int line) const {
-	if (annotations.Length() && (line < annotations.Length()) && annotations[line])
+	if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line])
 		return reinterpret_cast<AnnotationHeader *>(annotations[line])->lines;
 	else
 		return 0;
diff --git a/plugins/scintilla/scintilla/src/ScintillaBase.cxx b/plugins/scintilla/scintilla/src/ScintillaBase.cxx
index f78d0fb..9d4f93c 100644
--- a/plugins/scintilla/scintilla/src/ScintillaBase.cxx
+++ b/plugins/scintilla/scintilla/src/ScintillaBase.cxx
@@ -727,6 +727,13 @@ sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lPara
 	case SCI_AUTOCGETIGNORECASE:
 		return ac.ignoreCase;
 
+	case SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR:
+		ac.ignoreCaseBehaviour = wParam;
+		break;
+
+	case SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR:
+		return ac.ignoreCaseBehaviour;
+
 	case SCI_USERLISTSHOW:
 		listType = wParam;
 		AutoCompleteStart(0, reinterpret_cast<const char *>(lParam));
diff --git a/plugins/scintilla/scintilla/src/SplitVector.h b/plugins/scintilla/scintilla/src/SplitVector.h
index 44d5ddc..0ccf6c9 100644
--- a/plugins/scintilla/scintilla/src/SplitVector.h
+++ b/plugins/scintilla/scintilla/src/SplitVector.h
@@ -261,6 +261,24 @@ public:
 		body[lengthBody] = 0;
 		return body;
 	}
+
+	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;
+			} else {
+				return body + position ;
+			}
+		} else {
+			return body + position + gapLength;
+		}
+	}
+
+	int GapPosition() const {
+		return part1Length; 
+	}
 };
 
 #endif
diff --git a/plugins/scintilla/scintilla/src/Style.cxx b/plugins/scintilla/scintilla/src/Style.cxx
index ed30f55..375738c 100644
--- a/plugins/scintilla/scintilla/src/Style.cxx
+++ b/plugins/scintilla/scintilla/src/Style.cxx
@@ -45,10 +45,8 @@ FontMeasurements::FontMeasurements() {
 }
 
 void FontMeasurements::Clear() {
-	lineHeight = 2;
 	ascent = 1;
 	descent = 1;
-	externalLeading = 0;
 	aveCharWidth = 1;
 	spaceWidth = 1;
 	sizeZoomed = 2;
diff --git a/plugins/scintilla/scintilla/src/Style.h b/plugins/scintilla/scintilla/src/Style.h
index 018ab70..85663ac 100644
--- a/plugins/scintilla/scintilla/src/Style.h
+++ b/plugins/scintilla/scintilla/src/Style.h
@@ -43,11 +43,9 @@ public:
 };
 
 struct FontMeasurements {
-	unsigned int lineHeight;
 	unsigned int ascent;
 	unsigned int descent;
-	unsigned int externalLeading;
-	unsigned int aveCharWidth;
+	XYPOSITION aveCharWidth;
 	XYPOSITION spaceWidth;
 	int sizeZoomed;
 	FontMeasurements();
diff --git a/plugins/scintilla/scintilla/src/UniConversion.cxx b/plugins/scintilla/scintilla/src/UniConversion.cxx
index 2ef7584..ffe67f7 100644
--- a/plugins/scintilla/scintilla/src/UniConversion.cxx
+++ b/plugins/scintilla/scintilla/src/UniConversion.cxx
@@ -129,3 +129,120 @@ unsigned int UTF16FromUTF8(const char *s, unsigned int len, wchar_t *tbuf, unsig
 	}
 	return ui;
 }
+
+int UTF8BytesOfLead[256];
+static bool initialisedBytesOfLead = false;
+
+static int BytesFromLead(int leadByte) {
+	if (leadByte < 0xC2) {
+		// Single byte or invalid
+		return 1;
+	} else if (leadByte < 0xE0) {
+		return 2;
+	} else if (leadByte < 0xF0) {
+		return 3;
+	} else if (leadByte < 0xF5) {
+		return 4;
+	} else {
+		// Characters longer than 4 bytes not possible in current UTF-8
+		return 1;
+	}
+}
+
+void UTF8BytesOfLeadInitialise() {
+	if (!initialisedBytesOfLead) {
+		for (int i=0;i<256;i++) {
+			UTF8BytesOfLead[i] = BytesFromLead(i);
+		}
+		initialisedBytesOfLead = true;
+	}
+}
+
+// Return both the width of the first character in the string and a status
+// saying whether it is valid or invalid.
+// Most invalid sequences return a width of 1 so are treated as isolated bytes but
+// the non-characters *FFFE, *FFFF and FDD0 .. FDEF return 3 or 4 as they can be
+// reasonably treated as code points in some circumstances. They will, however,
+// not have associated glyphs.
+int UTF8Classify(const unsigned char *us, int len) {
+	// For the rules: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
+	if (*us < 0x80) {
+		// Single bytes easy
+		return 1;
+	} else if (*us > 0xf4) {
+		// Characters longer than 4 bytes not possible in current UTF-8
+		return UTF8MaskInvalid | 1;
+	} else if (*us >= 0xf0) {
+		// 4 bytes
+		if (len < 4)
+			return UTF8MaskInvalid | 1;
+		if (UTF8IsTrailByte(us[1]) && UTF8IsTrailByte(us[2]) && UTF8IsTrailByte(us[3])) {
+			if (((us[1] & 0xf) == 0xf) && (us[2] == 0xbf) && ((us[3] == 0xbe) || (us[3] == 0xbf))) {
+				// *FFFE or *FFFF non-character
+				return UTF8MaskInvalid | 4;
+			}
+			if (*us == 0xf4) {
+				// Check if encoding a value beyond the last Unicode character 10FFFF
+				if (us[1] > 0x8f) {
+					return UTF8MaskInvalid | 1;
+				} else if (us[1] == 0x8f) {
+					if (us[2] > 0xbf) {
+						return UTF8MaskInvalid | 1;
+					} else if (us[2] == 0xbf) {
+						if (us[3] > 0xbf) {
+							return UTF8MaskInvalid | 1;
+						}
+					}
+				}
+			} else if ((*us == 0xf0) && ((us[1] & 0xf0) == 0x80)) {
+				// Overlong
+				return UTF8MaskInvalid | 1;
+			}
+			return 4;
+		} else {
+			return UTF8MaskInvalid | 1;
+		}
+	} else if (*us >= 0xe0) {
+		// 3 bytes
+		if (len < 3)
+			return UTF8MaskInvalid | 1;
+		if (UTF8IsTrailByte(us[1]) && UTF8IsTrailByte(us[2])) {
+			if ((*us == 0xe0) && ((us[1] & 0xe0) == 0x80)) {
+				// Overlong
+				return UTF8MaskInvalid | 1;
+			}
+			if ((*us == 0xed) && ((us[1] & 0xe0) == 0xa0)) {
+				// Surrogate
+				return UTF8MaskInvalid | 1;
+			}
+			if ((*us == 0xef) && (us[1] == 0xbf) && (us[2] == 0xbe)) {
+				// U+FFFE non-character - 3 bytes long
+				return UTF8MaskInvalid | 3;
+			}
+			if ((*us == 0xef) && (us[1] == 0xbf) && (us[2] == 0xbf)) {
+				// U+FFFF non-character - 3 bytes long
+				return UTF8MaskInvalid | 3;
+			}
+			if ((*us == 0xef) && (us[1] == 0xb7) && (((us[2] & 0xf0) == 0x90) || ((us[2] & 0xf0) == 0xa0))) {
+				// U+FDD0 .. U+FDEF
+				return UTF8MaskInvalid | 3;
+			}
+			return 3;
+		} else {
+			return UTF8MaskInvalid | 1;
+		}
+	} else if (*us >= 0xc2) {
+		// 2 bytes
+		if (len < 2)
+			return UTF8MaskInvalid | 1;
+		if (UTF8IsTrailByte(us[1])) {
+			return 2;
+		} else {
+			return UTF8MaskInvalid | 1;
+		}
+	} else {
+		// 0xc0 .. 0xc1 is overlong encoding
+		// 0x80 .. 0xbf is trail byte
+		return UTF8MaskInvalid | 1;
+	}
+}
diff --git a/plugins/scintilla/scintilla/src/UniConversion.h b/plugins/scintilla/scintilla/src/UniConversion.h
index 2de2ef3..704f162 100644
--- a/plugins/scintilla/scintilla/src/UniConversion.h
+++ b/plugins/scintilla/scintilla/src/UniConversion.h
@@ -5,9 +5,24 @@
 // Copyright 1998-2001 by Neil Hodgson <neilh scintilla org>
 // The License.txt file describes the conditions under which this software may be distributed.
 
+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);
 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);
 
+extern int UTF8BytesOfLead[256];
+void UTF8BytesOfLeadInitialise();
+
+inline bool UTF8IsTrailByte(int ch) {
+	return (ch >= 0x80) && (ch < 0xc0);
+}
+
+inline bool UTF8IsAscii(int ch) {
+	return ch < 0x80;
+}
+
+enum { UTF8MaskWidth=0x7, UTF8MaskInvalid=0x8 };
+int UTF8Classify(const unsigned char *us, int len);
diff --git a/plugins/scintilla/scintilla/src/ViewStyle.cxx b/plugins/scintilla/scintilla/src/ViewStyle.cxx
index ab3c689..a4894ef 100644
--- a/plugins/scintilla/scintilla/src/ViewStyle.cxx
+++ b/plugins/scintilla/scintilla/src/ViewStyle.cxx
@@ -98,8 +98,6 @@ void FontRealised::Realise(Surface &surface, int zoomLevel, int technology) {
 
 	ascent = surface.Ascent(font);
 	descent = surface.Descent(font);
-	externalLeading = surface.ExternalLeading(font);
-	lineHeight = surface.Height(font);
 	aveCharWidth = surface.AverageCharWidth(font);
 	spaceWidth = surface.WidthChar(font, ' ');
 	if (frNext) {
@@ -145,6 +143,7 @@ ViewStyle::ViewStyle(const ViewStyle &source) {
 	for (int mrk=0; mrk<=MARKER_MAX; mrk++) {
 		markers[mrk] = source.markers[mrk];
 	}
+	CalcLargestMarkerHeight();
 	for (int ind=0; ind<=INDIC_MAX; ind++) {
 		indicators[ind] = source.indicators[ind];
 	}
@@ -194,7 +193,6 @@ ViewStyle::ViewStyle(const ViewStyle &source) {
 	for (int i=0; i < margins; i++) {
 		ms[i] = source.ms[i];
 	}
-	symbolMargin = source.symbolMargin;
 	maskInLine = source.maskInLine;
 	fixedColumnWidth = source.fixedColumnWidth;
 	zoomLevel = source.zoomLevel;
@@ -202,7 +200,6 @@ ViewStyle::ViewStyle(const ViewStyle &source) {
 	whitespaceSize = source.whitespaceSize;
 	viewIndentationGuides = source.viewIndentationGuides;
 	viewEOL = source.viewEOL;
-	showMarkedLines = source.showMarkedLines;
 	extraFontFlag = source.extraFontFlag;
 	extraAscent = source.extraAscent;
 	extraDescent = source.extraDescent;
@@ -230,6 +227,9 @@ void ViewStyle::Init(size_t stylesSize_) {
 	fontNames.Clear();
 	ResetDefaultStyle();
 
+	// 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);
@@ -302,11 +302,9 @@ void ViewStyle::Init(size_t stylesSize_) {
 	ms[2].width = 0;
 	ms[2].mask = 0;
 	fixedColumnWidth = leftMarginWidth;
-	symbolMargin = false;
 	maskInLine = 0xffffffff;
 	for (int margin=0; margin < margins; margin++) {
 		fixedColumnWidth += ms[margin].width;
-		symbolMargin = symbolMargin || (ms[margin].style != SC_MARGIN_NUMBER);
 		if (ms[margin].width > 0)
 			maskInLine &= ~ms[margin].mask;
 	}
@@ -315,7 +313,6 @@ void ViewStyle::Init(size_t stylesSize_) {
 	whitespaceSize = 1;
 	viewIndentationGuides = ivNone;
 	viewEOL = false;
-	showMarkedLines = true;
 	extraFontFlag = 0;
 	extraAscent = 0;
 	extraDescent = 0;
@@ -385,11 +382,9 @@ void ViewStyle::Refresh(Surface &surface) {
 	spaceWidth = styles[STYLE_DEFAULT].spaceWidth;
 
 	fixedColumnWidth = leftMarginWidth;
-	symbolMargin = false;
 	maskInLine = 0xffffffff;
 	for (int margin=0; margin < margins; margin++) {
 		fixedColumnWidth += ms[margin].width;
-		symbolMargin = symbolMargin || (ms[margin].style != SC_MARGIN_NUMBER);
 		if (ms[margin].width > 0)
 			maskInLine &= ~ms[margin].mask;
 	}
@@ -457,3 +452,19 @@ bool ViewStyle::ValidStyle(size_t styleIndex) const {
 	return styleIndex < stylesSize;
 }
 
+void ViewStyle::CalcLargestMarkerHeight() {
+	largestMarkerHeight = 0;
+	for (int m = 0; m <= MARKER_MAX; ++m) {
+		switch (markers[m].markType) {
+		case SC_MARK_PIXMAP:
+			if (markers[m].pxpm->GetHeight() > largestMarkerHeight)
+				largestMarkerHeight = markers[m].pxpm->GetHeight();
+			break;
+		case SC_MARK_RGBAIMAGE:
+			if (markers[m].image->GetHeight() > largestMarkerHeight)
+				largestMarkerHeight = markers[m].image->GetHeight();
+			break;
+		}
+	}
+}
+
diff --git a/plugins/scintilla/scintilla/src/ViewStyle.h b/plugins/scintilla/scintilla/src/ViewStyle.h
index 3803a6c..56d15d3 100644
--- a/plugins/scintilla/scintilla/src/ViewStyle.h
+++ b/plugins/scintilla/scintilla/src/ViewStyle.h
@@ -66,6 +66,7 @@ public:
 	size_t stylesSize;
 	Style *styles;
 	LineMarker markers[MARKER_MAX + 1];
+	int largestMarkerHeight;
 	Indicator indicators[INDIC_MAX + 1];
 	int technology;
 	int lineHeight;
@@ -103,7 +104,6 @@ public:
 	enum { margins=5 };
 	int leftMarginWidth;	///< Spacing margin on left of text
 	int rightMarginWidth;	///< Spacing margin on left of text
-	bool symbolMargin;
 	int maskInLine;	///< Mask for markers to be put into text because there is nowhere for them to go in margin
 	MarginStyle ms[margins];
 	int fixedColumnWidth;
@@ -112,7 +112,6 @@ public:
 	int whitespaceSize;
 	IndentView viewIndentationGuides;
 	bool viewEOL;
-	bool showMarkedLines;
 	ColourDesired caretcolour;
 	ColourDesired additionalCaretColour;
 	bool showCaretLineBackground;
@@ -148,6 +147,7 @@ public:
 	void SetStyleFontName(int styleIndex, const char *name);
 	bool ProtectionActive() const;
 	bool ValidStyle(size_t styleIndex) const;
+	void CalcLargestMarkerHeight();
 };
 
 #ifdef SCI_NAMESPACE
diff --git a/plugins/scintilla/scintilla/src/XPM.cxx b/plugins/scintilla/scintilla/src/XPM.cxx
index b63eb15..aeb94a9 100644
--- a/plugins/scintilla/scintilla/src/XPM.cxx
+++ b/plugins/scintilla/scintilla/src/XPM.cxx
@@ -47,14 +47,6 @@ ColourDesired XPM::ColourDesiredFromCode(int ch) const {
 
 ColourDesired XPM::ColourFromCode(int ch) const {
 	return *colourCodeTable[ch];
-#ifdef SLOW
-	for (int i=0; i<nColours; i++) {
-		if (codes[i] == ch) {
-			return colours[i].allocated;
-		}
-	}
-	return colours[0].allocated;
-#endif
 }
 
 void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) {



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